diff --git a/.github/skills/gh-stack/SKILL.md b/.github/skills/gh-stack/SKILL.md new file mode 100644 index 00000000..96aab643 --- /dev/null +++ b/.github/skills/gh-stack/SKILL.md @@ -0,0 +1,183 @@ +--- +name: gh-stack +description: > + Manages stacked PRs and splits multi-part work into reviewable branches with gh-stack. + Use for stack creation, viewing, edits, push, submit, sync, rebase, merge, or checkout; + when asked to split or isolate work for review; whenever a user mentions a stack, + branch layers, dependent PRs, or gh stack; or when a stack is checked out. +metadata: + author: github + version: "0.1.0" +--- + +# gh-stack + +`gh stack` is a [GitHub CLI](https://cli.github.com/) extension for stacked branches and pull +requests. A stack is an ordered chain of branches rooted on a trunk, where each branch has one PR +based on the branch below it, so a reviewer sees only that layer's diff. + +`gh stack` prints a stack trunk-first, left to right: + +``` +(main) <- auth <- api <- frontend +``` + +Left is the **bottom**, right is the **top**. `auth` is based on `main` and merges first; +`frontend` merges last. `up` moves toward the top, away from trunk; `down` moves toward it. +Foundational work belongs at the bottom, code that depends on it above. For how to choose the +layers, read `references/stack-design.md`. + +## Setup + +```bash +gh extension install github/gh-stack +git config rerere.enabled true # remember conflict resolutions +git config remote.pushDefault origin # required if the repo has more than one remote +``` + +## Non-interactive use + +`gh stack` branches on whether **stdout is a TTY**. Piped, most commands error cleanly or print +static text; under a PTY the same commands open a prompt or a full-screen TUI and block forever. +Agent harnesses differ, so always pass the flags below instead of relying on that detection. + +**Multiple remotes:** never run `push`, `submit`, `sync`, `rebase`, or `link` without +`--remote ` unless `remote.pushDefault` is configured. `checkout` and `trunk` have no +`--remote` flag and require the config. + +| Always run | Never run bare | Why | +|---|---|---| +| `gh stack view --json` | `gh stack view` | opens a TUI under a PTY | +| `gh stack submit --auto` | `gh stack submit` | prompts for a title per new PR | +| `gh stack merge --yes` | `gh pr merge` | `gh pr merge` cannot merge a stack | +| `gh stack init ...` | `gh stack init` | prompts for branch names | +| `gh stack add ` | `gh stack add` | prompts for a name, and fails even when piped | +| `gh stack checkout ` | `gh stack checkout` | opens a selection menu | +| `gh stack up` / `down` / `top` / `bottom` | `gh stack switch` | `switch` is menu-only | +| — | `gh stack modify` | TUI-only, no non-interactive path | + +- `view --short` is safe in both modes, but it is formatted for humans. Use `--json` to parse. +- **`checkout ` when a different local stack already covers those branches** cannot be forced. + Run `gh stack unstack --local` first (this keeps the stack on GitHub), then retry. + +## Branch placement + +- **Starting multi-part work:** create the stack before writing files. Do not implement every + concern on trunk and split it later. Put one dependent concern in each layer, bottom to top. +- **Editing an existing stack:** check out the layer that owns the change before editing. Never + commit a lower layer's concern on the current top branch. Run `gh stack view --json`; if + ownership is unclear, inspect `git log --all -- `. Then check out the owner, edit, commit, + rebase upstack, and return to top. + +```bash +gh stack down # or: gh stack checkout api +git add ... && git commit -m "Add get-user endpoint" +gh stack rebase --upstack # replay every branch above onto the change +gh stack top # return to where you were +gh stack push +``` + +## Core loop + +```bash +gh stack init auth # create the stack and check out its branch +git add ... && git commit -m "Add auth middleware" +gh stack add api # next layer, branched from the current one +git add ... && git commit -m "Add API routes" +gh stack submit --auto # push every branch and open draft PRs +gh stack view --json # confirm +``` + +Add `--open` to `submit` to create PRs ready for review instead of drafts. Branch names are +verbatim — `gh stack add refactor/foo` creates `refactor/foo`. + +## Staying in sync + +```bash +gh stack sync # fetch, reconcile with GitHub, rebase, push, refresh PR state +gh stack sync --prune # also delete local branches for merged PRs +``` + +Pruning never happens without `--prune` when non-interactive. If the local and remote stacks have +diverged, `sync` prints both chains, makes no changes, and exits 0 with `Sync aborted` — see +`references/troubleshooting.md`. + +## Merging + +Scope the merge with an argument: + +```bash +gh stack merge 42 --yes # PR #42 plus every unmerged PR below it +gh stack merge 7 --yes # every unmerged PR in stack #7 +gh stack merge 42 --yes --squash # or --merge, --rebase, --merge-method +``` + +Pass a PR number to merge that PR and every unmerged PR below it, or a stack number to merge every +unmerged PR in that stack. The operation is all-or-nothing: if any PR in that set cannot merge, +none do. + +Without a method flag the last-used method is reused. If the base branch uses a merge queue, the +stack is queued instead and the queue picks the method, ignoring any flag you passed with a +warning; queued PRs may land in separate groups. + +## Reading state + +`gh stack view --json` writes JSON to **stdout**. Status messages go to **stderr** — do not parse +them, branch on exit codes instead. + +``` +trunk string +currentBranch string +branches[] name, head, base, isCurrent, isMerged, isQueued, needsRebase +branches[].pr number, url, state ("OPEN" | "MERGED" | "QUEUED"); absent when no PR exists +``` + +`base` is the saved SHA of the parent branch that this branch was last known to contain. It may be +older than the parent's current tip. `needsRebase` is true when the current parent tip is no longer +an ancestor of the branch. + +## Exit codes + +| Code | Meaning | Recovery | +|---|---|---| +| 0 | Success | — | +| 1 | Generic error | Read stderr | +| 2 | Not in a stack | `gh stack init`, or `gh stack checkout ` | +| 3 | Rebase conflict | Follow the Exit 3 recovery below | +| 4 | GitHub API failure | Check `gh auth status`, retry | +| 5 | Invalid arguments | Fix the invocation; see ` --help` | +| 6 | Disambiguation required | Branch is in several stacks; check out a non-shared branch | +| 7 | Rebase already in progress | `gh stack rebase --continue` or `--abort` | +| 8 | Stack file locked | Another `gh stack` process is writing; retry after ~5s | +| 9 | Stacked PRs unavailable | Not enabled on the repository; tell the user | +| 10 | Modify recovery required | `gh stack modify --abort` | + +**Exit 3 recovery:** + +- After `gh stack rebase`: resolve the files, run `git add`, then + `gh stack rebase --continue`; use `gh stack rebase --abort` to restore the stack. +- After `gh stack sync`: the stack has already been restored. Run `gh stack rebase` to recreate the + conflict, then resolve and continue as above. + +## Constraints + +- Stacks are strictly linear: one parent, at most one child. Use separate stacks for parallel work. +- There is no non-interactive reorder or removal. Errors may suggest `gh stack modify`, but it is + TUI-only — restructure with `unstack` then `init` instead. +- PR titles and bodies are auto-generated. Use `gh pr edit` afterwards to change them. +- `checkout ` resolves against local stacks only. Use a stack or PR number to pull a + stack down from GitHub. + +## More detail + +`gh stack --help` is authoritative for flags and arguments. Note that +`gh stack help ` does **not** work — it prints the top-level help. + +Open the reference whose trigger matches the task; no need to preload all three. + +- `references/stack-design.md` — read before creating a stack, when deciding how many layers to + use, what belongs in each one, or whether work belongs in a new stack. +- `references/commands.md` — read when a command fails unexpectedly or you need its preconditions, + side effects, atomicity, or ordering guarantees. +- `references/troubleshooting.md` — read on a rebase conflict, after a squash-merge, on local and + remote divergence, when restructuring a stack, or when driving stacks from another tool. diff --git a/.github/skills/gh-stack/references/commands.md b/.github/skills/gh-stack/references/commands.md new file mode 100644 index 00000000..46e58336 --- /dev/null +++ b/.github/skills/gh-stack/references/commands.md @@ -0,0 +1,179 @@ +# Command behavior + +`gh stack --help` is authoritative for flags and arguments. (`gh stack help ` only prints the top-level help.) This file only covers behavior `--help` does not +explain: preconditions, side effects, atomicity, and failure modes. + +## Contents + +- [init](#init) +- [add](#add) +- [push](#push) +- [submit](#submit) +- [link](#link) +- [sync](#sync) +- [rebase](#rebase) +- [view](#view) +- [checkout](#checkout) +- [unstack](#unstack) +- [merge](#merge) +- [Navigation](#navigation) + +## init + +Creates the stack and checks out the **last** branch in the list, so a single `init` can lay down +the whole chain: `gh stack init auth api frontend`. + +`init` processes branch arguments from bottom to top. Existing branches are adopted. If the first +branch does not exist, it is created from the trunk; each later new branch is created from the +branch immediately before it. There is no separate adopt mode — existence decides. `--base` +selects a non-default trunk. + +`init` also enables `git rerere`. Under a TTY the first run in a repo asks for confirmation; set +`git config rerere.enabled true` beforehand to skip it. + +## add + +- **Must run from the top branch** of the stack (or the trunk when the stack is still empty). + Anywhere else it exits **5** with `can only add branches on top of the stack`. Run `gh stack top` + first. +- **Uncommitted changes carry over.** Without `-Am`, `add` does not touch the working tree, so + staged and unstaged changes follow you onto the new branch. Commit or stash first for a clean start. +- **`add -Am` commits in place when the current branch has no commits yet** — for example + immediately after `init` — instead of creating a branch. This is deliberate: the first layer + usually needs its content before a second layer exists. +- `-A` and `-u` are mutually exclusive, and both require `-m`. + +## push + +Pushes every active (non-merged, non-queued) branch in one multi-ref push with per-branch +`--force-with-lease`. + +**Not atomic.** Some branches may update while another is rejected. A rejection means that branch +moved on the remote; fix that branch and rerun — rerunning is safe and skips what already landed. + +`push` never creates or updates pull requests. Use `submit` for that. + +## submit + +Pushes each active branch, then creates a PR for every branch that lacks one, basing it on the +first non-merged ancestor, then links them into a Stack on GitHub. + +- **Not atomic.** Branches are pushed sequentially with per-branch `--force-with-lease`. If a later + push is rejected, earlier pushes and PR updates stand. Fix the rejection and rerun the same command. +- **A fully merged stack cannot be extended.** When every PR in the current stack is already merged, + `submit` forks the remaining unmerged branches into a **new** stack rooted at the trunk and creates + it on GitHub, leaving the merged stack untouched. +- **Title generation with `--auto`:** a branch with a single commit uses that commit's subject as + the title and its body as the PR body. A branch with multiple commits humanizes the branch name + (hyphens and underscores become spaces). There is no flag for a custom title or body; use + `gh pr edit` afterwards. +- `--open` marks new *and existing* PRs ready for review; without it new PRs are drafts. +- Requires stacked PRs to be enabled on the repository. If not, `submit` exits **9** when + non-interactive (under a TTY it offers to create ordinary unstacked PRs instead). + +## link + +Creates or updates a stack on GitHub **without any local tracking state**. This is the path for +branches managed by another tool or living in another worktree — see `troubleshooting.md`. + +- Arguments are given bottom to top. Each is a branch name or a PR number; a numeric argument is + tried as a PR number first and falls back to a branch name. +- **A numeric first argument is treated as a stack number only when a stack with that number + exists.** In that case the remaining arguments are appended to the top of that stack and you do + not re-list its current PRs: `gh stack link 7 feature-c`. Arguments already in the stack are + skipped; arguments belonging to a different stack are rejected. +- Branch arguments are pushed automatically (non-force, atomic). Missing PRs are created with + auto-generated titles and correctly chained bases; existing PRs with a wrong base are corrected. +- Stack membership is **additive only** — `link` never removes a PR from a stack. + +## sync + +The routine command. Steps, in order: + +1. **Fetch** from the remote. +2. **Reconcile with the GitHub stack.** PRs added to the stack on github.com are pulled down and + appended locally. On divergence, aborts when non-interactive (see `troubleshooting.md`). +3. **Fast-forward the trunk.** Skipped when already current; warns when diverged. +4. **Cascade rebase when needed.** This runs if the trunk moved, a stack branch was fast-forwarded + from its remote, or a branch no longer contains its expected parent. Merged PRs are handled + automatically. On conflict, **all branches are restored** to their pre-rebase state and the + command exits **3**. +5. **Push** all active branches, atomically. +6. **Refresh PR state** from GitHub. +7. **Sync the stack object** — link open PRs into a stack, additively. Only when two or more PRs + exist. `sync` never opens PRs; that is `submit`. +8. **Prune** local branches for merged PRs, only when `--prune` is passed in a non-interactive + environment. + +## rebase + +Pulls from the remote and cascade-rebases. Use it when `sync` reported a conflict or when you need +to rebase only part of the stack. + +- `--upstack` rebases from the current branch to the top. This is what you run after editing a + lower layer. +- `--downstack` rebases from the trunk to the current branch. +- `--no-trunk` skips fetching and the trunk rebase entirely, aligning stack branches with each + other only. +- `--continue` after staging resolutions; `--abort` restores every branch. +- A merged PR is detected automatically and replayed with `--onto` against the correct target, so a + squash-merged parent does not produce spurious conflicts. +- Starting a rebase while one is in progress exits **7**. + +## view + +- `--json` writes the machine-readable payload to stdout. Its schema is in `SKILL.md`. +- Bare `view` opens a full-screen TUI when stdout is a TTY, and prints static text when piped. +- `--short` prints a compact one-line-per-branch summary and never opens the TUI, but it is + formatted for humans; parse `--json` instead. +- `view` refreshes PR state from GitHub as a side effect, best-effort — it does not fail when the + API is unreachable. + +## checkout + +Accepts a stack number, PR number, PR URL, or branch name. + +- A bare number resolves as a **stack number first**, then a PR number, then a branch name. +- Stack numbers, PR numbers, and PR URLs fetch from GitHub, pull the branches down, and set the + stack up locally. +- A **branch name resolves against locally tracked stacks only** and never contacts GitHub. Use a + stack or PR number to pull a stack that is not tracked locally. +- If a local stack already exists over those branches with a different composition, `checkout` + cannot be forced past it. Run `gh stack unstack --local` first, then retry. +- `checkout` has no flags. It relies on `remote.pushDefault` when several remotes exist. + +## unstack + +Removes the stack **grouping** only. It never deletes pull requests or branches. + +- With no argument it targets the active stack — the one containing the current branch — removing + it on GitHub and locally. +- With a stack number it works from anywhere in the repository, tracked locally or not, via the API. + Local tracking is also removed when present. +- `--local` removes local tracking only and never contacts GitHub. Combining `--local` with a stack + number that is not tracked locally is an error. +- An unknown stack number exits **2**. + +## merge + +- Scope with an argument: pass a PR number to merge that PR and every unmerged PR below it in the + stack, or pass a stack number to merge every unmerged PR in that stack. +- **All-or-nothing.** If any PR in that exact merge set cannot be merged, none are, and the reason + is reported. +- The method comes from `--squash`, `--rebase`, `--merge`, or `--merge-method `. Without + one, the last-used method is reused. +- Only basic PR state is checked before merging: open and not a draft. Bypassing merge requirements + is not supported for stacks. +- **A merge queue on the base branch overrides everything.** The stack is added to the queue rather + than merged; the queue chooses the method and any method flag you passed is ignored with a + warning. Queued PRs are submitted together but land as the queue processes them, so they may merge + in separate groups rather than all at once. +- `gh pr merge` cannot merge a stack. Always use `gh stack merge`. + +## Navigation + +`up`, `down`, `top`, `bottom`, and `trunk` are always non-interactive. `up` and `down` accept a +count (`gh stack up 3`). Movement clamps at the stack bounds, and merged branches are skipped when +navigating from an active branch, so `bottom` lands on the lowest *unmerged* branch. + +`gh stack switch` is a selection menu with no non-interactive path. Use the commands above instead. diff --git a/.github/skills/gh-stack/references/stack-design.md b/.github/skills/gh-stack/references/stack-design.md new file mode 100644 index 00000000..f64543ac --- /dev/null +++ b/.github/skills/gh-stack/references/stack-design.md @@ -0,0 +1,97 @@ +# Designing a stack + +How to decide what goes in each layer. Read this before running `gh stack init`. + +## Contents + +- [Plan the layers before writing code](#plan-the-layers-before-writing-code) +- [Branch naming](#branch-naming) +- [Staging changes deliberately](#staging-changes-deliberately) +- [When to add a layer](#when-to-add-a-layer) +- [One stack, one story](#one-stack-one-story) + +## Plan the layers before writing code + +A stack is a dependency chain. If code in one layer depends on code in another, the dependency must +live in the same branch or a lower one. That constraint is much cheaper to satisfy by planning than +by restructuring later, because there is no non-interactive in-place reorder — fixing the order +means`unstack` and `init` again. + +Decide the layers first, then write code into them: + +``` +(main) <- todo-app/models <- todo-app/api <- todo-app/frontend <- todo-app/integration +``` + +- `todo-app/models` — shared types and schema +- `todo-app/api` — routes that use the models +- `todo-app/frontend` — components that call the routes +- `todo-app/integration` — tests exercising the whole feature + +This is illustrative. Infer the stack topic and layer names from the actual task; do not reuse +`todo-app` or these layer names literally. + +The failure mode to avoid is writing everything on one branch and trying to split it afterwards. +If a task is large enough to warrant a stack, create the stack at the start. + +## Branch naming + +Prefer a shared topic prefix plus the layer's concern: +`/` — for example, `billing/schema`, `billing/api`, `billing/ui`. +This keeps related branches recognizable without using generic names that could belong to any +stack. **User and repository branch naming conventions take precedence; follow them instead.** + +Names are used exactly as given — nothing is prepended or transformed, and slashes are kept, so +`gh stack add refactor/foo` creates a branch literally named `refactor/foo`. + +If you pass `-m` without a branch name, the name is generated from the commit message in +date-and-slug form (for example `03-24-add_api_routes`). Prefer naming the branch yourself. + +## Staging changes deliberately + +Use `git add` and `git commit` directly rather than the `add -Am` shortcut. The point is control +over which changes land in which branch. With several modified files in the working tree, stage the +subset that belongs to the current layer, commit it, then create the next branch and stage the rest +there: + +```bash +git add internal/models/user.go internal/models/session.go +git commit -m "Add user and session models" + +gh stack add api-routes +git add internal/api/routes.go internal/api/handlers.go +git commit -m "Add user API routes" +``` + +Multiple commits per branch are fine. What matters is that every commit in a branch serves the same +concern, and that a change belonging to a different concern goes in a different branch. + +Note that `gh stack add ` without `-Am` does not touch the working tree, so uncommitted +changes carry over to the new branch. Commit or stash first if you want the new layer to start clean. + +## When to add a layer + +Add a branch when you start a **different concern that depends on what you have built so far**. +Signals: + +- Moving from backend to frontend, or from core logic to tests or documentation +- The next changes have a different reviewer audience +- The current branch's diff is already large enough to review on its own + +A layer that cannot be described in one sentence is usually two layers. + +## One stack, one story + +A stack should read as a coherent progression: a reviewer walks the PRs bottom to top and sees the +feature being built. + +**Use a single stack** when every branch serves the same feature or project, even if the layers span +different concerns. + +**Start a separate stack** for unrelated work — a different feature, an unrelated bug fix, an +independent refactor. Do not mix efforts into one stack just because you happened to work on both. +Use `gh stack init` for the new effort, or `gh stack checkout ` to move between existing +stacks. + +A trivial incidental fix can ride along in the current stack. Once it grows into its own project, it +deserves its own stack. diff --git a/.github/skills/gh-stack/references/troubleshooting.md b/.github/skills/gh-stack/references/troubleshooting.md new file mode 100644 index 00000000..fc97b41a --- /dev/null +++ b/.github/skills/gh-stack/references/troubleshooting.md @@ -0,0 +1,159 @@ +# Troubleshooting and recovery + +## Contents + +- [Rebase conflicts (exit 3)](#rebase-conflicts-exit-3) +- [After a squash merge](#after-a-squash-merge) +- [Local and remote stacks have diverged](#local-and-remote-stacks-have-diverged) +- [Restructuring a stack](#restructuring-a-stack) +- [Branch belongs to several stacks (exit 6)](#branch-belongs-to-several-stacks-exit-6) +- [Driving stacks from another tool or worktree](#driving-stacks-from-another-tool-or-worktree) +- [Stack file is locked (exit 8)](#stack-file-is-locked-exit-8) +- [An interrupted modify session (exit 10)](#an-interrupted-modify-session-exit-10) + +## Rebase conflicts (exit 3) + +`rebase` and `sync` both exit 3 on conflict. `sync` restores every branch to its pre-rebase state +first, so a failed `sync` leaves nothing half-applied; a failed `rebase` stops mid-flight and waits. + +```bash +gh stack rebase +# exit 3 — conflicted paths are listed on stderr +git add +gh stack rebase --continue # repeat if the next branch also conflicts +``` + +`gh stack rebase --abort` restores every branch in the stack, not just the current one. + +Because `init` enables `git rerere`, a conflict you resolve once is replayed automatically the next +time the same conflict appears — which is common, since a change low in the stack is rebased through +every branch above it. Without `rerere`, repeated conflicts may need manual resolution on each +affected layer. + +## After a squash merge + +A squash merge replaces the branch's commits with one new commit, so the originals no longer exist +in the trunk's history and an ordinary rebase would try to replay them again. + +`gh stack sync` detects this and rebases with `--onto` against the correct target, skipping the +merged branch: + +```bash +gh stack sync +gh stack view --json # merged branch reports "isMerged": true, "state": "MERGED" +``` + +No manual action is needed. If the replay conflicts, `sync` restores all branches and exits 3. +Run `gh stack rebase` to rerun the rebase, which will stop at the conflict and allow you to resolve +and then `--continue` until complete. Use `gh stack sync --prune` to also delete local branches for +merged PRs. + +## Local and remote stacks have diverged + +Divergence means the local stack and the stack on GitHub changed in different ways — for example +branches were added locally while a PR was added to the stack on github.com. + +When non-interactive, `sync` prints both chains, changes nothing, and exits **0** with +`Sync aborted`. Success here does not mean the sync happened; check for that message, or re-run +`gh stack view --json` and compare. + +Two resolution paths: + +- **Keep the remote version.** Drop local tracking and pull the stack back down. + + ```bash + gh stack unstack --local # keeps the stack on GitHub + gh stack checkout # or a PR number + ``` + +- **Keep the local version.** Remove the grouping on GitHub, then recreate it from local state. + + ```bash + gh stack unstack # removes the grouping; PRs and branches survive + gh stack submit --auto + ``` + +Neither path deletes pull requests or branches. +Remote unstacking leaves PRs that are merging (auto-merge enabled) or are queued (in a merge queue) +stacked. If needed, clear that state before retrying. + +## Restructuring a stack + +There is no non-interactive reorder, rename, or removal. `add` run from the wrong branch suggests +`gh stack modify`, but that is TUI-only. Tear the stack down and rebuild it instead: + +```bash +gh stack unstack # removes local tracking and the GitHub grouping +# Rename or drop branches, and rewrite ancestry as needed. +gh stack init --base main branch-1 branch-2 branch-3 +gh stack submit --auto # re-link on GitHub +``` + +`init` adopts branches that already exist, so the rebuild reuses them rather than creating new ones. +Existing PRs survive. Once Git ancestry is correct, `submit` updates their base branches and +re-links the stack on GitHub. + +Changing metadata does **not** change Git ancestry. Reorder commits first, then rebuild the stack. +For example, to change `main <- models <- migration <- ui` into +`main <- migration <- models <- ui`: + +```bash +old_models=$(git rev-parse models) +old_migration=$(git rev-parse migration) +git rebase --onto main "$old_models" migration +git rebase --onto migration main models +git rebase --onto models "$old_migration" ui +gh stack unstack +gh stack init --base main migration models ui +``` + +The first rebase moves migration-only commits onto trunk, the second replays model commits above +them, and the third replays UI-only commits above models. Preserve the old boundary SHAs before +moving any branch. For a different reorder, identify each layer's range with +`git log ..`, then replay the ranges bottom to top. + +## Branch belongs to several stacks (exit 6) + +Commands exit 6 when the current branch cannot identify a single stack — typically because it is the +trunk of more than one stack. There is no flag to disambiguate. + +```bash +gh stack checkout +``` + +Then rerun. Commands that take an explicit stack number (`merge 7`, `unstack 7`) sidestep the +problem entirely, since they do not infer the stack from the current branch. + +## Driving stacks from another tool or worktree + +`gh stack link` creates and updates stacks purely through the API, with no local tracking state. +Use it when branches are managed by jj, Sapling, git-town, a separate worktree, or any workflow +where the local `.git/gh-stack` file would be wrong or absent. + +```bash +gh stack link branch-a branch-b branch-c # bottom to top +gh stack link --base develop --open a b c # non-default trunk, ready for review +gh stack link 10 20 30 # by PR number +gh stack link 7 feature-d # append to existing stack #7 +``` + +Because `link` writes no local state, the local navigation commands (`up`, `down`, `top`, `bottom`) +will not work on the result. Use `gh stack checkout ` if you later want local tracking. + +## Stack file is locked (exit 8) + +Another `gh stack` process holds the exclusive lock on `.git/gh-stack.lock`. The lock times out +after about five seconds, so wait and retry. A persistent exit 8 means another process still holds +the lock; identify and stop that process before retrying. + +## An interrupted modify session (exit 10) + +`gh stack modify` is TUI-only and should never be invoked by an agent. If a repository is left in +this state by someone else, restore it: + +```bash +gh stack modify --abort +``` + +Related: `submit` also detects a pending modify state, and under a TTY asks before overwriting the +stack on GitHub with local state. diff --git a/.github/workflows/validate-openspec.yaml b/.github/workflows/validate-openspec.yaml new file mode 100644 index 00000000..af8f0d2b --- /dev/null +++ b/.github/workflows/validate-openspec.yaml @@ -0,0 +1,74 @@ +# ------------------------------ tabstop = 4 ---------------------------------- +# +# If not stated otherwise in this file or this component's LICENSE file the +# following copyright and licenses apply: +# +# Copyright 2026 Comcast Cable Communications Management, LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# +# ------------------------------ tabstop = 4 ---------------------------------- + +# The goal of this workflow is to enforce that every OpenSpec spec conforms to +# the OpenSpec v4 structure by running `openspec validate --specs --strict` +# inside the builder image (which provides the pinned openspec CLI). + +name: Validate OpenSpec Specs + +on: + push: + branches: + - main + pull_request: + workflow_dispatch: + +jobs: + get-action-constants: + name: Get Action Constants + uses: ./.github/workflows/action-constants.yaml + secrets: inherit + + validate_openspec_specs: + name: Validate OpenSpec Specs + runs-on: ubuntu-latest + needs: get-action-constants + + steps: + - + name: Checkout code + uses: actions/checkout@v4 + with: + repository: ${{ github.repository }} + fetch-depth: 0 + fetch-tags: true + - + name: Log in to GitHub Container Registry + uses: docker/login-action@v2 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - + name: Try to pull barton_builder Docker image + continue-on-error: true + run: | + if docker pull ${{ needs.get-action-constants.outputs.image_repo }}:${{ needs.get-action-constants.outputs.image_tag }}; then + echo "Image pulled successfully" + else + echo "Could not pull image, will build locally via dockerw" + fi + - + name: Validate specs (strict) + run: ./dockerw -n openspec validate --specs --strict --no-interactive diff --git a/docker/Dockerfile b/docker/Dockerfile index 37fcb27c..acf1443b 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -344,6 +344,11 @@ RUN apt-get update && apt-get -y upgrade && DEBIAN_FRONTEND='noninteractive' apt apt-get update && \ apt-get install -y nodejs +############################################################################### +# OpenSpec CLI for spec validation (used by developers and by CI) +############################################################################### +RUN npm install -g openspec@1.4.1 + ############################################################################### # Development build stage # diff --git a/docker/version b/docker/version index e3d06964..5c6fb548 100644 --- a/docker/version +++ b/docker/version @@ -1 +1 @@ -2.15 +2.17 diff --git a/hooks/pre-commit b/hooks/pre-commit index 3842ae49..07db7af9 100755 --- a/hooks/pre-commit +++ b/hooks/pre-commit @@ -34,3 +34,12 @@ MY_DIR=$(realpath "$(dirname "$0")") # JavaScript: Prettier formats staged *.js files via lint-staged. "${MY_DIR}/pre-commit-lint-staged" + +# OpenSpec: enforce that every spec conforms to the v4 structure. The dev +# container provides the pinned openspec CLI; when it is absent (commits made +# outside the container), skip and rely on the CI gate. +if command -v openspec >/dev/null 2>&1; then + openspec validate --specs --strict --no-interactive +else + echo "pre-commit: openspec not found on PATH; skipping spec validation (CI will enforce)." >&2 +fi diff --git a/openspec/changes/migrate-specs-to-v4/.openspec.yaml b/openspec/changes/migrate-specs-to-v4/.openspec.yaml new file mode 100644 index 00000000..1b062d3a --- /dev/null +++ b/openspec/changes/migrate-specs-to-v4/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-08-04 diff --git a/openspec/changes/migrate-specs-to-v4/design.md b/openspec/changes/migrate-specs-to-v4/design.md new file mode 100644 index 00000000..e88e1ecf --- /dev/null +++ b/openspec/changes/migrate-specs-to-v4/design.md @@ -0,0 +1,86 @@ +## Context + +OpenSpec v4 (CLI `1.4.1`, schema `spec-driven`) validates the *structure* of spec documents, not code. All 35 specs under `openspec/specs/` fail `openspec validate --specs --strict`: + +| Bucket | Count | Symptom | +|--------|-------|---------| +| Delta-format (`## ADDED`/`## MODIFIED Requirements`) | 34 | No title, no `## Purpose`, no `## Requirements` | +| Structured but non-normative (`sbmd-runtime-observability`) | 1 | One requirement lacks `SHALL`/`MUST` | + +Root cause: these main specs were populated with the delta syntax that belongs *inside* a change proposal, instead of the flattened main-spec form that `openspec archive` normally produces. An audit of the 34 delta specs found 32 pure `ADDED` and 2 with a `MODIFIED` section (`sbmd-script-execution-limits`, `sbmd-system`); neither MODIFIED spec contains a duplicate requirement name, so flattening is a safe, lossless transform. + +``` + DELTA (authored form) MAIN SPEC (v4 validate expects) + ┌──────────────────────────┐ ┌────────────────────────────┐ + │ ## ADDED Requirements │ ──────▶ │ # │ + │ ### Requirement: Foo │ flatten │ ## Purpose │ + │ #### Scenario: … │ │ │ + │ ## MODIFIED Requirements │ │ ## Requirements │ + │ ### Requirement: Bar │ │ ### Requirement: Foo / Bar │ + └──────────────────────────┘ │ #### Scenario: … │ + └────────────────────────────┘ +``` + +Node.js 22 is already installed in the builder image, so the `openspec` npm CLI can be added there. `docker/version` is currently `2.14`. + +## Goals / Non-Goals + +**Goals:** +- Every spec passes `openspec validate --specs --strict` (green baseline). +- Validation is enforced automatically (build image + CI + pre-commit) so structure cannot silently regress. +- Preserve every existing requirement's meaning verbatim during the reformat. + +**Non-Goals:** +- Consolidating/renaming specs or reducing the flat directory count — deferred to a stacked follow-up (`consolidate-specs`). +- Subdirectory organization — unsupported by OpenSpec discovery. +- Any change to requirement semantics, runtime behavior, or the public API. + +## Decisions + +**D1. Flatten in place; treat `MODIFIED` and `ADDED` identically.** +Because these files are main specs (not deltas being archived), both `## ADDED Requirements` and `## MODIFIED Requirements` collapse into one `## Requirements` section. The audit confirmed no duplicate requirement names, so no content is lost. *Alternative considered:* run each spec back through a synthetic `openspec archive`; rejected as more complex and error-prone than a direct rewrite, and archive expects a change context these specs never had. + +**D2. Write `## Purpose` by hand per spec.** +A script can insert an empty `## Purpose` to satisfy the validator, but that defeats the intent. Each purpose is authored from the spec's existing content. *Alternative:* auto-generate from the first requirement — rejected as low-value boilerplate. + +**D3. Install `openspec` in the builder image, pinned; bump the image version.** +Provides one source of truth for the validation rules across dev and CI (mirrors how `cocogitto` is provisioned). Pin to the version used locally today (`1.4.1`). *Alternative:* `npx openspec` in CI only — rejected because dev and CI could drift and every run would re-download. + +``` + docker/Dockerfile (after Node 22 stage) + ┌──────────────────────────────────────────────┐ + │ RUN npm install -g openspec@ │ + └──────────────────────────────────────────────┘ + docker/version: 2.14 → 2.17 (2.15/2.16 taken by parallel branches) +``` + +**D4. CI validates all specs, strict, on pull_request.** +New workflow `.github/workflows/validate-openspec.yaml` runs `openspec validate --specs --strict --no-interactive` inside the builder image and fails on any error. Validate *all* specs (not just changed) to enforce the whole-repo invariant. *Alternative:* changed-specs-only — rejected; a full strict run is ~0.2s and whole-set validation catches cross-spec issues. + +**D5. Pre-commit hook runs the same command unconditionally.** +The full strict run of all 35 specs is ~190ms (dominated by Node startup); scoping to changed files would save ~5ms while adding path→spec-id mapping complexity and a correctness risk. Wire it through the existing `hooks/` mechanism. + +**D6. Vendor the `gh-stack` skill.** +`gh skill install` is unavailable here, so the skill (`SKILL.md` + `references/{commands,stack-design,troubleshooting}.md`, MIT-licensed) is copied from `github/gh-stack` into `.github/skills/gh-stack/`. It ships in this PR because it is the prerequisite tooling for the stacked follow-up PR. + +## Risks / Trade-offs + +- **Reformatting silently alters a requirement's wording.** → Diff each spec's requirement/scenario text before-and-after; only structural headers and the new `## Purpose` should change. Validation + review catch structural mistakes; a careful diff catches semantic ones. +- **Builder image version collision with parallel branches (2.15 webrtc, 2.16 testSpeedup).** → Bump to 2.17; reconcile at merge time if another branch also claims it. +- **CI depends on the new builder image being published.** → CI must reference the bumped image tag; if unpublished, the validate job fails fast with a clear "openspec: not found". +- **Pinned openspec drifts from the latest CLI.** → Acceptable; the pin is the source of truth and is bumped deliberately alongside the image version. + +## Migration Plan + +1. Vendor the `gh-stack` skill (already staged in the worktree). +2. Rewrite the 34 delta specs (flatten + title + `## Purpose`); reword the one non-normative requirement in `sbmd-runtime-observability`. +3. Add pinned `openspec` to `docker/Dockerfile`; bump `docker/version` to 2.17. +4. Add the CI validation workflow and the pre-commit hook. +5. Run `openspec validate --specs --strict` — must be fully green — then open PR #1. The `consolidate-specs` PR stacks on top via `gh stack`. + +Rollback is trivial: the change is documentation/tooling only; reverting the branch restores the prior specs and removes the workflow/hook with no runtime effect. + +## Open Questions + +- Final pinned `openspec` version — default to `1.4.1` (matches local) unless a newer release is preferred. +- Confirm the exact builder image tag CI should consume once `docker/version` is bumped. diff --git a/openspec/changes/migrate-specs-to-v4/proposal.md b/openspec/changes/migrate-specs-to-v4/proposal.md new file mode 100644 index 00000000..3edb515b --- /dev/null +++ b/openspec/changes/migrate-specs-to-v4/proposal.md @@ -0,0 +1,37 @@ +## Why + +OpenSpec v4's `openspec validate` enforces a structural contract for specs (a `## Purpose` section, a `## Requirements` section, and at least one `#### Scenario:` per requirement). All 35 checked-in specs under `openspec/specs/` were authored under the older delta format and currently fail `openspec validate --specs --strict` (35/35 failing). Without a green baseline and automated enforcement, spec structure silently drifts and validation provides no guardrail. + +## What Changes + +- Migrate all 35 specs in `openspec/specs/` to the v4 main-spec structure so `openspec validate --specs --strict` passes: + - Flatten 34 delta-format specs (`## ADDED Requirements` / `## MODIFIED Requirements` → a single `## Requirements`), and add a top-level title plus a `## Purpose` section to each. + - Reword the one requirement in `sbmd-runtime-observability` that lacks a `SHALL`/`MUST` keyword. +- Install the `openspec` CLI in the Docker builder image (pinned version) and bump the image version, so validation runs identically for developers and in CI. +- Add a CI workflow that runs `openspec validate --specs --strict` over all specs and fails the build on any error. +- Add a `pre-commit` hook that runs the same strict validation locally before each commit. +- Install the `gh-stack` agent skill under `.github/skills/gh-stack/` (the `gh skill install` command is unavailable in this environment), enabling the stacked-PR workflow this effort uses. + +## Capabilities + +### New Capabilities +- `spec-validation`: Specs MUST conform to the OpenSpec v4 structure and pass `openspec validate --specs --strict`. This invariant is enforced at three points: the Docker builder image ships a pinned `openspec` CLI, a CI workflow validates all specs on every pull request, and a pre-commit hook validates before each local commit. + +### Modified Capabilities + + +## Impact + +- **Specs**: all 35 `openspec/specs/*/spec.md` files rewritten (structure only; requirement text preserved). +- **Build image**: `docker/Dockerfile` gains a pinned `openspec` install (Node.js 22 is already present); `docker/version` bumped (2.14 → 2.17, chosen to avoid collision with in-flight builder bumps on parallel branches). Consumers must repull the builder image. +- **CI**: new `.github/workflows/validate-openspec.yaml`. +- **Hooks**: new strict-validation `pre-commit` hook wired through `hooks/`. +- **Tooling**: new `.github/skills/gh-stack/` skill (MIT-licensed, vendored from `github/gh-stack`). +- **No** C/C++/CMake code is affected and **no** CMake feature flags are relevant; there is no runtime, library, or public-API impact. + +## Non-goals + +- Consolidating or renaming specs to reduce the ever-growing flat list of varying-scope directories — deferred to a stacked follow-up PR (`consolidate-specs`) built on top of this change. +- Organizing specs into subdirectories — proven unsupported (OpenSpec spec discovery is flat, one directory level deep; nested `spec.md` files are silently ignored). +- Changing the meaning of any existing requirement, introducing new device/product functionality, or altering the public API. +- Scoping the pre-commit hook to only changed specs — unnecessary, since a full strict run of all specs completes in ~0.2s (Node startup dominated). diff --git a/openspec/changes/migrate-specs-to-v4/specs/spec-validation/spec.md b/openspec/changes/migrate-specs-to-v4/specs/spec-validation/spec.md new file mode 100644 index 00000000..8f8be756 --- /dev/null +++ b/openspec/changes/migrate-specs-to-v4/specs/spec-validation/spec.md @@ -0,0 +1,41 @@ +## ADDED Requirements + +### Requirement: Specs conform to OpenSpec v4 structure +Every specification under `openspec/specs/` SHALL conform to the OpenSpec v4 main-spec structure: a top-level title, a `## Purpose` section, a `## Requirements` section, and at least one `#### Scenario:` block per requirement. Delta-only headers (`## ADDED Requirements`, `## MODIFIED Requirements`, `## REMOVED Requirements`) SHALL NOT appear in a checked-in main spec. + +#### Scenario: All specs pass strict validation +- **WHEN** `openspec validate --specs --strict` is run at the repository root +- **THEN** every spec SHALL report valid and the command SHALL exit with status 0 + +#### Scenario: A malformed spec is rejected +- **WHEN** a spec is missing its `## Purpose` or `## Requirements` section, or a requirement has no `#### Scenario:` block +- **THEN** `openspec validate --specs --strict` SHALL report an ERROR for that spec and exit non-zero + +### Requirement: Build image provides a pinned openspec CLI +The Docker builder image SHALL install a pinned version of the `openspec` CLI so that spec validation runs identically for developers and in CI. The builder image version SHALL be bumped whenever the installed `openspec` version changes. + +#### Scenario: openspec available in the builder image +- **WHEN** a shell is opened inside the builder image +- **THEN** `openspec --version` SHALL succeed and report the pinned version + +### Requirement: CI enforces strict spec validation +A CI workflow SHALL run `openspec validate --specs --strict` over all specs on every pull request and SHALL fail the check when any spec is invalid. + +#### Scenario: Pull request with a valid spec set +- **WHEN** a pull request is opened and all specs conform to the v4 structure +- **THEN** the OpenSpec validation check SHALL pass + +#### Scenario: Pull request introduces a malformed spec +- **WHEN** a pull request adds or edits a spec so that it no longer conforms to the v4 structure +- **THEN** the OpenSpec validation check SHALL fail and block the pull request + +### Requirement: Pre-commit hook validates specs locally +The repository's pre-commit hook SHALL run `openspec validate --specs --strict` before each commit and SHALL abort the commit when any spec is invalid. + +#### Scenario: Commit with valid specs +- **WHEN** a developer commits with all specs conforming to the v4 structure +- **THEN** the pre-commit hook SHALL pass and the commit SHALL proceed + +#### Scenario: Commit with an invalid spec +- **WHEN** a developer attempts to commit a spec that fails strict validation +- **THEN** the pre-commit hook SHALL abort the commit and report the validation error diff --git a/openspec/changes/migrate-specs-to-v4/tasks.md b/openspec/changes/migrate-specs-to-v4/tasks.md new file mode 100644 index 00000000..7a06d263 --- /dev/null +++ b/openspec/changes/migrate-specs-to-v4/tasks.md @@ -0,0 +1,30 @@ +## 1. Tooling setup + +- [x] 1.1 Vendor the `gh-stack` agent skill into `.github/skills/gh-stack/` (`SKILL.md` + `references/{commands,stack-design,troubleshooting}.md`) from `github/gh-stack`, since `gh skill install` is unavailable in this environment + +## 2. Migrate specs to v4 structure + +- [x] 2.1 Flatten the `agent-skill-*` specs (build, debug, format-code, integration-tests, matter-devices, unit-tests, validate-sbmd): merge delta headers into `## Requirements`, add a `# Title` and a hand-written `## Purpose` +- [x] 2.2 Flatten the `sbmd-*` specs (sbmd-system, sbmd-resource-prerequisites, sbmd-script-execution-limits, sbmd-seed-from-attribute, sbmd-v4-light-driver, sbmd-v4-runtime); for `sbmd-script-execution-limits` and `sbmd-system`, collapse both `## MODIFIED` and `## ADDED` sections into one `## Requirements` +- [x] 2.3 Flatten the `matter*`/`matterjs-*` specs (matter-subsystem, matter-test-infrastructure, matter-thermostat-sbmd, matter-thermostat-testing, matterjs-door-lock-device, matterjs-virtual-device-framework) +- [x] 2.4 Flatten the remaining capability specs (build-system, changelog-generation, core-services, device-drivers, device-type-endpoint-resolution, endpoint-cluster-fallback, observability-metrics, public-api, python-sideband-client, release-workflow, resource-model, temperature-humidity-sbmd-drivers, thread-subsystem, vendor-product-claiming, zigbee-subsystem) +- [x] 2.5 Reword requirements that lack a `SHALL`/`MUST` keyword: `sbmd-runtime-observability` (Subsystem metrics initialization) and `device-drivers` (Config restore / System event / Additional driver callbacks); add missing scenarios to `device-drivers` and `public-api` requirements +- [x] 2.6 Verify no requirement or scenario text changed meaning during reformatting (structural-only diff review per spec) + +## 3. Build image provisioning + +- [x] 3.1 Add a pinned `openspec` CLI install to `docker/Dockerfile` after the Node.js 22 stage (`npm install -g openspec@1.4.1`) +- [x] 3.2 Bump `docker/version` (2.14 → 2.17) +- [ ] 3.3 Rebuild the builder image and confirm `openspec --version` reports the pinned version inside it + +## 4. Enforcement + +- [x] 4.1 Add `.github/workflows/validate-openspec.yaml` running `openspec validate --specs --strict --no-interactive` over all specs on `pull_request`, failing on any error (Apache-2.0 header, mirroring existing workflow style) +- [x] 4.2 Add a `pre-commit` hook (wired through `hooks/`) that runs `openspec validate --specs --strict` and aborts the commit on failure +- [x] 4.3 Confirm strict validation returns non-zero on a deliberately-malformed spec (the command the hook and CI both run) + +## 5. Verify + +- [x] 5.1 Run `openspec validate --specs --strict` at repo root — all 35 specs valid, exit 0 +- [x] 5.2 Run `openspec validate migrate-specs-to-v4 --type change --strict` to confirm this change's own artifacts validate +- [ ] 5.3 Open PR #1 (`gh stack`), leaving `consolidate-specs` as the stacked follow-up diff --git a/openspec/specs/agent-skill-build/spec.md b/openspec/specs/agent-skill-build/spec.md index 6ca29969..32bb6bcf 100644 --- a/openspec/specs/agent-skill-build/spec.md +++ b/openspec/specs/agent-skill-build/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Agent Skill: Build + +## Purpose + +Defines the structure and required content of the `build` agent skill (`.github/skills/build/SKILL.md`), which teaches an AI agent how to build BartonCore: the `build.sh` hierarchy, CMake configuration flags, the development build profile, and an error-recovery pattern. + +## Requirements ### Requirement: Build skill SKILL.md conforms to Agent Skills spec The `build` skill SHALL be located at `.github/skills/build/SKILL.md`. The frontmatter SHALL include `name: build`, a `description` field explaining the skill covers building BartonCore, and `compatibility` noting it requires the BartonCore Docker development container. The `name` field SHALL match the parent directory name. diff --git a/openspec/specs/agent-skill-debug/spec.md b/openspec/specs/agent-skill-debug/spec.md index bacfb102..bc1825d7 100644 --- a/openspec/specs/agent-skill-debug/spec.md +++ b/openspec/specs/agent-skill-debug/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Agent Skill: Debug + +## Purpose + +Defines the structure and required content of the `debug` agent skill, covering the three debugging workflows — gdb for the reference app and unit tests, pdb for Python integration tests, and gdb with `python3-gdb` for native visibility from Python — plus ASAN considerations and an error-recovery pattern. + +## Requirements ### Requirement: Debug skill SKILL.md conforms to Agent Skills spec The `debug` skill SHALL be located at `.github/skills/debug/SKILL.md`. The frontmatter SHALL include `name: debug`, a `description` field explaining the skill covers debugging BartonCore with gdb and pdb, and `compatibility` noting the BartonCore Docker development container. diff --git a/openspec/specs/agent-skill-format-code/spec.md b/openspec/specs/agent-skill-format-code/spec.md index 31f5b99e..8972c66f 100644 --- a/openspec/specs/agent-skill-format-code/spec.md +++ b/openspec/specs/agent-skill-format-code/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Agent Skill: Format Code + +## Purpose + +Defines the structure and required content of the `format-code` agent skill, covering `clang-format` usage, the diff-only formatting rule, the manual blank-line conventions `clang-format` cannot enforce, and the pre-commit hook. + +## Requirements ### Requirement: Format code skill SKILL.md conforms to Agent Skills spec The `format-code` skill SHALL be located at `.github/skills/format-code/SKILL.md`. The frontmatter SHALL include `name: format-code`, a `description` field explaining the skill covers C/C++ code formatting, and `compatibility` noting the BartonCore Docker development container. diff --git a/openspec/specs/agent-skill-integration-tests/spec.md b/openspec/specs/agent-skill-integration-tests/spec.md index c55f616c..c7a7aa67 100644 --- a/openspec/specs/agent-skill-integration-tests/spec.md +++ b/openspec/specs/agent-skill-integration-tests/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Agent Skill: Integration Tests + +## Purpose + +Defines the structure and required content of the `run-integration-tests` agent skill, covering pytest execution via `py_test.sh`, test filtering, prerequisites, and pytest configuration for BartonCore's Python integration tests. + +## Requirements ### Requirement: Integration test skill SKILL.md conforms to Agent Skills spec The `run-integration-tests` skill SHALL be located at `.github/skills/run-integration-tests/SKILL.md`. The frontmatter SHALL include `name: run-integration-tests`, a `description` field explaining the skill covers running Python integration tests, and `compatibility` noting the BartonCore Docker development container. diff --git a/openspec/specs/agent-skill-matter-devices/spec.md b/openspec/specs/agent-skill-matter-devices/spec.md index af95dec1..d791ba53 100644 --- a/openspec/specs/agent-skill-matter-devices/spec.md +++ b/openspec/specs/agent-skill-matter-devices/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Agent Skill: Matter Virtual Devices + +## Purpose + +Defines the structure and required content of the `matter-virtual-devices` agent skill, covering pre-built Matter sample apps, `chip-tool`, matter.js virtual devices, and authoring custom virtual device types. + +## Requirements ### Requirement: Matter virtual devices skill SKILL.md conforms to Agent Skills spec The `matter-virtual-devices` skill SHALL be located at `.github/skills/matter-virtual-devices/SKILL.md`. The frontmatter SHALL include `name: matter-virtual-devices`, a `description` field explaining the skill covers working with Matter test devices, and `compatibility` noting the BartonCore Docker development container. diff --git a/openspec/specs/agent-skill-unit-tests/spec.md b/openspec/specs/agent-skill-unit-tests/spec.md index e603cd7f..40f9d13e 100644 --- a/openspec/specs/agent-skill-unit-tests/spec.md +++ b/openspec/specs/agent-skill-unit-tests/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Agent Skill: Unit Tests + +## Purpose + +Defines the structure and required content of the `run-unit-tests` agent skill, covering `ctest` execution, test filtering, and the CMocka and Google Test frameworks used by BartonCore's C/C++ unit tests. + +## Requirements ### Requirement: Unit test skill SKILL.md conforms to Agent Skills spec The `run-unit-tests` skill SHALL be located at `.github/skills/run-unit-tests/SKILL.md`. The frontmatter SHALL include `name: run-unit-tests`, a `description` field explaining the skill covers running C/C++ unit tests, and `compatibility` noting the BartonCore Docker development container. diff --git a/openspec/specs/agent-skill-validate-sbmd/spec.md b/openspec/specs/agent-skill-validate-sbmd/spec.md index 246c5204..5f7c3bf8 100644 --- a/openspec/specs/agent-skill-validate-sbmd/spec.md +++ b/openspec/specs/agent-skill-validate-sbmd/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Agent Skill: Validate SBMD + +## Purpose + +Defines the structure and required content of the `validate-sbmd` agent skill, covering SBMD spec validation, stub generation, and spec file locations. + +## Requirements ### Requirement: SBMD validation skill SKILL.md conforms to Agent Skills spec The `validate-sbmd` skill SHALL be located at `.github/skills/validate-sbmd/SKILL.md`. The frontmatter SHALL include `name: validate-sbmd`, a `description` field explaining the skill covers validating SBMD specification files, and `compatibility` noting the BartonCore Docker development container. diff --git a/openspec/specs/build-system/spec.md b/openspec/specs/build-system/spec.md index 048bdc02..865d1adc 100644 --- a/openspec/specs/build-system/spec.md +++ b/openspec/specs/build-system/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Build System + +## Purpose + +Specifies BartonCore's CMake-based build system: project configuration, build targets, the modular feature-flag catalog, string and integer configuration options, dependency version constraints, sanitizer and coverage support, CTest and GObject Introspection integration, Docker builds, and Git-derived versioning. + +## Requirements ### Requirement: CMake project configuration The build system SHALL use CMake (minimum 3.16.5) with the project name `barton-core`. It SHALL use C99 and C++17 standards, both set as required. Position-independent code SHALL be enabled globally. diff --git a/openspec/specs/changelog-generation/spec.md b/openspec/specs/changelog-generation/spec.md index deac5d81..620f1241 100644 --- a/openspec/specs/changelog-generation/spec.md +++ b/openspec/specs/changelog-generation/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Changelog Generation + +## Purpose + +Specifies how the project's changelog is generated and maintained across releases, ensuring new entries are prepended and a full historical changelog is preserved. + +## Requirements ### Requirement: Changelog entries are prepended across releases The release workflow SHALL produce a `CHANGELOG.md` where each new release entry is prepended diff --git a/openspec/specs/core-services/spec.md b/openspec/specs/core-services/spec.md index 7bb40c09..d1b3931f 100644 --- a/openspec/specs/core-services/spec.md +++ b/openspec/specs/core-services/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Core Services + +## Purpose + +Specifies the core device service orchestration layer: the two-phase `deviceService` lifecycle, driver manager, subsystem manager, communication watchdog, JSON file-based database, event producer and handler, discovery filters, storage monitor, and device scrubbing. + +## Requirements ### Requirement: DeviceService orchestrator lifecycle The `deviceService` SHALL orchestrate the complete service lifecycle in two phases: `deviceServiceInitialize()` (configuration, database init) and `deviceServiceStart()` (event system, drivers, subsystems). Shutdown SHALL follow a defined teardown order (event handler → storage monitor → comm-fail → drivers → subsystems → event producer → database). diff --git a/openspec/specs/device-drivers/spec.md b/openspec/specs/device-drivers/spec.md index c9d9cde0..f9f54c76 100644 --- a/openspec/specs/device-drivers/spec.md +++ b/openspec/specs/device-drivers/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Device Drivers + +## Purpose + +Specifies the `DeviceDriver` interface and the contract native and SBMD drivers implement: identification, startup/shutdown lifecycle, discovery, configuration, resource operations, communication-failure handling, synchronization, migration, and the native Zigbee and Philips Hue driver catalog. + +## Requirements ### Requirement: DeviceDriver interface The system SHALL define a `DeviceDriver` C struct with function pointers for all driver lifecycle and operational callbacks. Drivers SHALL be registered via `deviceDriverManagerRegisterDriver()`. @@ -131,21 +137,21 @@ The system SHALL include a `philipsHue` IP-based device driver when `BCORE_PHILI - **THEN** the Philips Hue driver SHALL be compiled and available for registration ### Requirement: Config restore callbacks -Drivers MAY implement `restoreConfig()`, `preRestoreConfig()`, and `postRestoreConfig()` callbacks for backup/restore scenarios. +The device driver contract SHALL allow drivers to optionally implement `restoreConfig()`, `preRestoreConfig()`, and `postRestoreConfig()` callbacks for backup/restore scenarios. #### Scenario: Restore driver config - **WHEN** `b_core_client_config_restore()` is called - **THEN** the driver manager SHALL invoke `preRestoreConfig()` on all drivers, then `restoreConfig()` with the backup directory, then `postRestoreConfig()` ### Requirement: System event callbacks -Drivers MAY implement `systemPowerEvent()` and `propertyChanged()` callbacks to react to system-wide events. +The device driver contract SHALL allow drivers to optionally implement `systemPowerEvent()` and `propertyChanged()` callbacks to react to system-wide events. #### Scenario: Property change notification to driver - **WHEN** a system property changes - **THEN** all drivers with `propertyChanged` callbacks SHALL be notified with the property key and new value ### Requirement: Additional driver callbacks -Drivers MAY implement these additional callbacks: +The device driver contract SHALL allow drivers to optionally implement these additional callbacks: - `processDeviceDescriptor(ctx, device, dd)` — examine device against its descriptor for firmware upgrades or changes - `endpointDisabled(ctx, endpoint)` — notification when an endpoint is disabled - `fetchRuntimeStats(ctx, output)` — collect device-specific runtime statistics @@ -154,3 +160,7 @@ Drivers MAY implement these additional callbacks: - `serviceStatusChanged(ctx, status)` — notification when the device service status changes - `commFailTimeoutSecsChanged(driver, device, commFailTimeoutSecs)` — notification when the comm-fail timeout has changed - `metadataUpdated(driver, device, key, value)` — notification when a metadata key is persisted for a device managed by this driver; called synchronously from `setMetadata()` after each persisted change + +#### Scenario: Metadata update notification +- **WHEN** `setMetadata()` persists a metadata key for a device managed by a driver +- **THEN** the driver's `metadataUpdated` callback SHALL be invoked synchronously with the metadata key and value diff --git a/openspec/specs/device-type-endpoint-resolution/spec.md b/openspec/specs/device-type-endpoint-resolution/spec.md index 7906e458..82de725f 100644 --- a/openspec/specs/device-type-endpoint-resolution/spec.md +++ b/openspec/specs/device-type-endpoint-resolution/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Device Type Endpoint Resolution + +## Purpose + +Specifies how SBMD device drivers resolve Matter endpoints by device-type matching, building an endpoint map during device initialization and binding resources to the Nth matching endpoint. + +## Requirements ### Requirement: Endpoint resolution by device type matching The system SHALL resolve Matter endpoint IDs for SBMD endpoints by matching the endpoint's Descriptor device type list against the driver's `matterMeta.deviceTypes` list, rather than searching for the first endpoint that hosts a specific cluster. diff --git a/openspec/specs/endpoint-cluster-fallback/spec.md b/openspec/specs/endpoint-cluster-fallback/spec.md index 3dc2024f..53034b97 100644 --- a/openspec/specs/endpoint-cluster-fallback/spec.md +++ b/openspec/specs/endpoint-cluster-fallback/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Endpoint Cluster Fallback + +## Purpose + +Specifies cluster-based fallback for endpoint resolution, ensuring all resource and event binding routes through `ResolveEndpointForCluster` when device-type matching alone is insufficient. + +## Requirements ### Requirement: Endpoint resolution with cluster-based fallback `MatterDevice` SHALL provide a `ResolveEndpointForCluster` method that resolves a Matter endpoint for a given cluster ID. When an SBMD endpoint index is provided, it SHALL first try the SBMD-mapped endpoint. If that endpoint does not host the required cluster (verified via `DeviceDataCache::EndpointHasServerCluster`), it SHALL fall back to cluster-based lookup via `GetEndpointForCluster`. diff --git a/openspec/specs/matter-subsystem/spec.md b/openspec/specs/matter-subsystem/spec.md index 8640d208..2ade9a01 100644 --- a/openspec/specs/matter-subsystem/spec.md +++ b/openspec/specs/matter-subsystem/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Matter Subsystem + +## Purpose + +Specifies the Matter subsystem that wraps the CHIP SDK: SDK initialization, commissioning orchestration, device discovery, the device data cache, storage/access-control/attestation delegates, pluggable credential and commissionable-data providers, and the Matter driver factory and device abstractions. + +## Requirements ### Requirement: Matter SDK initialization The Matter subsystem SHALL initialize the CHIP SDK, set up the GLib main loop integration, and configure operational parameters. Initialization SHALL be triggered via an `initialize` callback registered with `subsystemManagerRegister()` and SHALL report readiness via `notifySubsystemInitialized()`. diff --git a/openspec/specs/matter-test-infrastructure/spec.md b/openspec/specs/matter-test-infrastructure/spec.md index 251227cb..3e91ec3d 100644 --- a/openspec/specs/matter-test-infrastructure/spec.md +++ b/openspec/specs/matter-test-infrastructure/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Matter Test Infrastructure + +## Purpose + +Specifies the matter.js-based Matter test infrastructure: the refactored `MatterDevice` backend, device classes (light, door lock) migrated to matter.js side-band control, test fixtures, conditional execution markers, and Docker environment setup. + +## Requirements ### Requirement: MatterDevice refactored for matter.js-only backend The `MatterDevice` base class SHALL exclusively use matter.js virtual devices. The `_app_name` attribute and all CHIP SDK sample app subprocess code SHALL be removed. `MatterDevice.__init__()` SHALL require a `matterjs_entry_point` parameter specifying the JavaScript file to run. `MatterDevice.start()` SHALL spawn a Node.js subprocess, wait for the JSON ready signal on stdout, and configure the `SidebandClient`. diff --git a/openspec/specs/matter-thermostat-sbmd/spec.md b/openspec/specs/matter-thermostat-sbmd/spec.md index ed9f8b04..236c5060 100644 --- a/openspec/specs/matter-thermostat-sbmd/spec.md +++ b/openspec/specs/matter-thermostat-sbmd/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Matter Thermostat SBMD Driver + +## Purpose + +Specifies the SBMD driver that claims the Matter Thermostat device type and maps its cluster attributes — setpoints, absolute limits, system mode, running state, and optional fan controls — to Barton resources with subscription reporting. + +## Requirements ### Requirement: Matter Thermostat device type claiming The SBMD driver SHALL claim Matter devices with device type ID 0x0301 (Thermostat) and register them under the Barton `thermostat` device class. diff --git a/openspec/specs/matter-thermostat-testing/spec.md b/openspec/specs/matter-thermostat-testing/spec.md index 40195fcc..65edf17f 100644 --- a/openspec/specs/matter-thermostat-testing/spec.md +++ b/openspec/specs/matter-thermostat-testing/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Matter Thermostat Testing + +## Purpose + +Specifies the matter.js virtual thermostat devices (with and without fan control) and the Python integration tests covering commissioning, setpoint and system-mode read/write, side-band temperature changes, and fan resources. + +## Requirements ### Requirement: matter.js virtual thermostat device A matter.js virtual thermostat device (`ThermostatDevice.js`) SHALL be created extending `VirtualDevice` with: diff --git a/openspec/specs/matterjs-door-lock-device/spec.md b/openspec/specs/matterjs-door-lock-device/spec.md index f4703dc6..98c994db 100644 --- a/openspec/specs/matterjs-door-lock-device/spec.md +++ b/openspec/specs/matterjs-door-lock-device/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# matter.js Door Lock Device + +## Purpose + +Specifies the matter.js virtual door lock: its device type, Matter lock/unlock commands, side-band lock/unlock/getState operations, `LockOperation` event emission, initial lock state, and user and PIN-code management. + +## Requirements ### Requirement: Door lock device type The matter.js door lock virtual device SHALL present itself as a Matter Door Lock device type (Device Type ID `0x000A`) with a DoorLock cluster (Cluster ID `0x0101`) on endpoint 1. diff --git a/openspec/specs/matterjs-virtual-device-framework/spec.md b/openspec/specs/matterjs-virtual-device-framework/spec.md index 1c27c8c1..31c832f1 100644 --- a/openspec/specs/matterjs-virtual-device-framework/spec.md +++ b/openspec/specs/matterjs-virtual-device-framework/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# matter.js Virtual Device Framework + +## Purpose + +Specifies the matter.js virtual device framework used for integration testing: the base class, the side-band HTTP server and operation registration, the stdout ready signal, graceful shutdown, and package configuration. + +## Requirements ### Requirement: Virtual device base class initialization The matter.js virtual device base class (`VirtualDevice`) SHALL initialize a Matter `ServerNode` with configurable vendor ID, product ID, device name, passcode, discriminator, and port. The class SHALL handle all common Matter device setup so that subclasses only need to define their device type and side-band operations. diff --git a/openspec/specs/observability-metrics/spec.md b/openspec/specs/observability-metrics/spec.md index 5bb43f3b..cbb3b874 100644 --- a/openspec/specs/observability-metrics/spec.md +++ b/openspec/specs/observability-metrics/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Observability Metrics + +## Purpose + +Specifies BartonCore's metrics instruments — counters, gauges, and histograms — along with the telemetry JSON dump command and conditional compilation of the observability subsystem. + +## Requirements ### Requirement: Counter metric instrument The system SHALL provide an `ObservabilityCounter` opaque type that tracks a monotonically increasing uint64 value. The API SHALL support `observabilityCounterCreate(name)`, `observabilityCounterAdd(counter, value)`, and `observabilityCounterAddWithAttrs(counter, value, ...)` with NULL-terminated key-value attribute pairs. diff --git a/openspec/specs/public-api/spec.md b/openspec/specs/public-api/spec.md index 8537bb30..820f1854 100644 --- a/openspec/specs/public-api/spec.md +++ b/openspec/specs/public-api/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Public API + +## Purpose + +Specifies the GObject-based public C API: `BCoreClient` lifecycle and operations, device/endpoint/resource CRUD and access, Matter commissioning, provider interfaces, the `BCoreEvent` hierarchy, GObject Introspection compatibility, and well-known property constants. + +## Requirements ### Requirement: BCoreClient lifecycle management The system SHALL provide a `BCoreClient` GObject type that manages the complete device service lifecycle. A client SHALL be created with `b_core_client_new()` accepting a `BCoreInitializeParamsContainer`, started with `b_core_client_start()`, and stopped with `b_core_client_stop()`. @@ -221,11 +227,19 @@ The system SHALL provide additional client functions: - `b_core_process_device_descriptors()` — process device descriptor list - `b_core_client_set_account_id()` — set the account ID +#### Scenario: Query current service status +- **WHEN** a client calls `b_core_client_get_status()` +- **THEN** the current service status SHALL be returned as a `BCoreStatus` + ### Requirement: Additional event types The system SHALL provide intermediate event base types: - `BCoreDiscoverySessionInfoEvent` with `session-discovery-type` property - `BCoreDeviceConfigurationEvent` with `uuid` and `device-class` properties +#### Scenario: Discovery session event carries discovery type +- **WHEN** a `BCoreDiscoverySessionInfoEvent` is emitted +- **THEN** it SHALL expose the `session-discovery-type` property + ### Requirement: Well-known property constants The system SHALL define string constants for all Matter and device properties: vendor name/ID, product name/ID, hardware version, serial number, manufacturing date, setup discriminator, setup passcode, SPAKE2+ parameters, 802.15.4 EUI64, Matter part number, Matter product URL, Matter product label, Matter hardware version string, and default Thread network name. These SHALL be defined as C macros with the `B_CORE_BARTON_` prefix. diff --git a/openspec/specs/python-sideband-client/spec.md b/openspec/specs/python-sideband-client/spec.md index fcb65bef..0394455c 100644 --- a/openspec/specs/python-sideband-client/spec.md +++ b/openspec/specs/python-sideband-client/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Python Side-band Client + +## Purpose + +Specifies the Python side-band client used by integration tests to drive virtual devices: the client class, convenience methods, error handling, and timeout support. + +## Requirements ### Requirement: Sideband client class A Python `SidebandClient` class SHALL provide a simple interface for sending side-band operations to matter.js virtual devices over HTTP. The client SHALL be initialized with the device's side-band host and port. diff --git a/openspec/specs/release-workflow/spec.md b/openspec/specs/release-workflow/spec.md index 019919d2..38db122f 100644 --- a/openspec/specs/release-workflow/spec.md +++ b/openspec/specs/release-workflow/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Release Workflow + +## Purpose + +Specifies release safety and mechanics: the branch guard that prevents non-main releases, annotated tagging, and pushing the version commit to main. + +## Requirements ### Requirement: Branch guard prevents non-main releases The release workflow SHALL refuse to run when triggered on any branch other than `main`. diff --git a/openspec/specs/resource-model/spec.md b/openspec/specs/resource-model/spec.md index 196a279f..b5ea7925 100644 --- a/openspec/specs/resource-model/spec.md +++ b/openspec/specs/resource-model/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Resource Model + +## Purpose + +Specifies the URI-based, protocol-agnostic resource model: resource addressing, string-serialized values, the type system, the mode bitmask, caching and lazy-save policy, the device-class and endpoint-profile contracts, device-class versioning, and common device-level resources. + +## Requirements ### Requirement: URI-based resource addressing The system SHALL address all device data using a hierarchical URI scheme: `/` for devices, `//ep/` for endpoints, `//ep//r/` for endpoint resources, `//r/` for device-level resources, and `//ep//m/` or `//m/` for metadata. diff --git a/openspec/specs/sbmd-resource-prerequisites/spec.md b/openspec/specs/sbmd-resource-prerequisites/spec.md index fe341e96..0667a2f0 100644 --- a/openspec/specs/sbmd-resource-prerequisites/spec.md +++ b/openspec/specs/sbmd-resource-prerequisites/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# SBMD Resource Prerequisites + +## Purpose + +Specifies prerequisite gating for SBMD resources: alias definitions in `matterMeta`, prerequisite declarations on resources, alias-based mapper metadata, parser enforcement, and commissioning-time evaluation that leaves unsatisfied resources unregistered. + +## Requirements ### Requirement: Alias definitions in `matterMeta` Each SBMD driver spec MAY declare a `matterMeta.aliases` list. Each alias SHALL have a `name` (unique within the spec) and exactly one of `attribute` (with `clusterId`, `attributeId`, `name`, `type`) or `event` (with `clusterId`, `eventId`, `name`). An alias name referenced in `prerequisites` or mapper metadata that does not exist in `matterMeta.aliases` SHALL be a parse-time error. diff --git a/openspec/specs/sbmd-runtime-observability/spec.md b/openspec/specs/sbmd-runtime-observability/spec.md index d9a5f1e6..d7e82497 100644 --- a/openspec/specs/sbmd-runtime-observability/spec.md +++ b/openspec/specs/sbmd-runtime-observability/spec.md @@ -179,7 +179,7 @@ The SBMD runtime SHALL count deferred operations terminated because they reached > **Note:** Integration test coverage for this scenario is planned as future work (task 9.7). It requires a test-only driver whose response handler unconditionally re-arms with another `requestCommand`, which in turn requires new test infrastructure (a new `.sbmd.js` spec file and a fixture whose virtual device responds at least 11 times). ### Requirement: Subsystem metrics initialization -Each SBMD metrics class (`MQuickJsRuntimeMetrics`, `SbmdHandlerInvokerMetrics`, `SbmdFactoryMetrics`, `SpecBasedMatterDeviceDriverMetrics`) initializes its metric handles in its constructor. No explicit `InitializeMetrics()` / `ShutdownMetrics()` lifecycle calls are needed: handles are created when the owning object is constructed and persist for the process lifetime. `MQuickJsRuntimeMetrics` is constructed as an `inline static` member of `MQuickJsRuntime`; `SbmdHandlerInvokerMetrics` as a `static` member of `SbmdHandlerInvoker`; `SbmdFactoryMetrics` as a non-static member of the `SbmdFactory` singleton; `SpecBasedMatterDeviceDriverMetrics` as a `static` member of `SpecBasedMatterDeviceDriver`. No `MetricsRegistry` or centralized initialization sequence is required. +Each SBMD metrics class (`MQuickJsRuntimeMetrics`, `SbmdHandlerInvokerMetrics`, `SbmdFactoryMetrics`, `SpecBasedMatterDeviceDriverMetrics`) SHALL initialize its metric handles in its constructor. No explicit `InitializeMetrics()` / `ShutdownMetrics()` lifecycle calls are needed: handles are created when the owning object is constructed and persist for the process lifetime. `MQuickJsRuntimeMetrics` is constructed as an `inline static` member of `MQuickJsRuntime`; `SbmdHandlerInvokerMetrics` as a `static` member of `SbmdHandlerInvoker`; `SbmdFactoryMetrics` as a non-static member of the `SbmdFactory` singleton; `SpecBasedMatterDeviceDriverMetrics` as a `static` member of `SpecBasedMatterDeviceDriver`. No `MetricsRegistry` or centralized initialization sequence is required. #### Scenario: Metrics available after first use - **WHEN** any SBMD recording method is called diff --git a/openspec/specs/sbmd-script-execution-limits/spec.md b/openspec/specs/sbmd-script-execution-limits/spec.md index 21bb16de..0434e9c3 100644 --- a/openspec/specs/sbmd-script-execution-limits/spec.md +++ b/openspec/specs/sbmd-script-execution-limits/spec.md @@ -1,4 +1,10 @@ -## MODIFIED Requirements +# SBMD Script Execution Limits + +## Purpose + +Specifies safety limits for SBMD embedded-JavaScript execution: per-invocation script timeouts, an overall operation timeout for deferred chains, and a maximum deferral depth. + +## Requirements ### Requirement: Script timeout enforcement for handler invocations The mquickjs interrupt handler SHALL enforce per-invocation timeouts for v4 handler function calls, using the same `BARTON_CONFIG_SBMD_SCRIPT_TIMEOUT_MS` configuration as v3 mapper scripts. The deadline SHALL be set before each handler call and cleared immediately after. @@ -7,7 +13,6 @@ The mquickjs interrupt handler SHALL enforce per-invocation timeouts for v4 hand - **WHEN** a handler function runs longer than `BARTON_CONFIG_SBMD_SCRIPT_TIMEOUT_MS` - **THEN** the mquickjs interrupt handler terminates execution and the runtime reports the operation as failed -## ADDED Requirements ### Requirement: Overall operation timeout for deferred chains The runtime SHALL enforce an overall operation deadline for resource operations that involve deferred chains. The deadline SHALL be set when the first deferral occurs (from `matter.defaultTimeoutMs` or a system default) and SHALL NOT reset on subsequent deferrals. Per-hop `timeoutMs` values SHALL be capped at the remaining overall budget. diff --git a/openspec/specs/sbmd-seed-from-attribute/spec.md b/openspec/specs/sbmd-seed-from-attribute/spec.md index dbd69bd6..e91df7e8 100644 --- a/openspec/specs/sbmd-seed-from-attribute/spec.md +++ b/openspec/specs/sbmd-seed-from-attribute/spec.md @@ -1,3 +1,11 @@ +# SBMD seedFrom Attribute + +## Purpose + +Specifies the SBMD `seedFrom` mapper that seeds an event-backed resource from a Matter attribute at configure and synchronize time: its schema and structure, mutual exclusion with `read`, event requirement, non-subscription semantics, script interface, and JSON schema entry. + +## Requirements + ### Requirement: seedFrom mapper — schema and structure A resource's mapper MAY contain a `seedFrom` section with an `alias` (a string naming an **attribute** alias defined in `matterMeta.aliases`) and a `script` (JavaScript string). The `seedFrom` mapper SHALL only appear when the same resource also declares a `mapper.event` section. The `alias` SHALL resolve to an attribute alias; event aliases SHALL NOT be accepted. The `script` SHALL be required; absence of `script` SHALL be a parse error. diff --git a/openspec/specs/sbmd-system/spec.md b/openspec/specs/sbmd-system/spec.md index 3b63b938..2a6bfa90 100644 --- a/openspec/specs/sbmd-system/spec.md +++ b/openspec/specs/sbmd-system/spec.md @@ -1,4 +1,10 @@ -## MODIFIED Requirements +# SBMD System + +## Purpose + +Specifies the Spec-Based Matter Driver system: how the factory loads driver files, claims devices using C++ metadata, and supports the v4 handler model in `SpecBasedMatterDeviceDriver`. + +## Requirements ### Requirement: SBMD factory loads driver files The SBMD factory SHALL scan configured directories for `.sbmd.js` files (instead of `.sbmd` YAML files). For each file, the factory SHALL evaluate it in the mquickjs context, extract metadata to C++ structures, and register the driver with `MatterDriverFactory`. The factory SHALL no longer use `SbmdParser` or yaml-cpp for driver loading. diff --git a/openspec/specs/sbmd-v4-light-driver/spec.md b/openspec/specs/sbmd-v4-light-driver/spec.md index 2d66535e..b3f35ee7 100644 --- a/openspec/specs/sbmd-v4-light-driver/spec.md +++ b/openspec/specs/sbmd-v4-light-driver/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# SBMD v4 Light Driver + +## Purpose + +Specifies the v4 JavaScript SBMD light driver: on/off via attribute and write handlers, the optional current-level resource, and continued unchanged passing of existing integration tests. + +## Requirements ### Requirement: Light driver as v4 JavaScript file The light driver SHALL be implemented as a single `light.sbmd.js` file using the v4 `SbmdDriver({...})` registration format. It SHALL declare constants for all cluster, attribute, command, and resource IDs. It SHALL support the same device types as the v3 `light.sbmd` driver. diff --git a/openspec/specs/sbmd-v4-runtime/spec.md b/openspec/specs/sbmd-v4-runtime/spec.md index 10ab1617..272f53fd 100644 --- a/openspec/specs/sbmd-v4-runtime/spec.md +++ b/openspec/specs/sbmd-v4-runtime/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# SBMD v4 Runtime + +## Purpose + +Specifies the SBMD v4 embedded-JavaScript runtime: two-pass file evaluation with constants injection, the `SbmdDriver` capture function and registration extraction, result building, handler dispatch, supplements pre-loading, resource handler invocation, result-chain execution, deferred operations, driver lifecycle, and alias resolution. + +## Requirements ### Requirement: Two-pass file evaluation with constants injection The runtime SHALL evaluate `.sbmd.js` files using a two-pass process. Pass 1 SHALL extract the `constants:` block from the source text by brace-matching, evaluate it as a JavaScript object literal, and produce a set of name→primitive-value pairs. Pass 2 SHALL prepend `var` declarations for each constant, wrap the entire file in an IIFE, and evaluate the result using `JS_EVAL_REPL`. diff --git a/openspec/specs/temperature-humidity-sbmd-drivers/spec.md b/openspec/specs/temperature-humidity-sbmd-drivers/spec.md index 2712128f..22f4be54 100644 --- a/openspec/specs/temperature-humidity-sbmd-drivers/spec.md +++ b/openspec/specs/temperature-humidity-sbmd-drivers/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Temperature and Humidity SBMD Drivers + +## Purpose + +Specifies the SBMD specs and tests for temperature and humidity sensors: the IKEA TIMMERFLOTTE spec and its resources, generic temperature and humidity sensor specs, virtual test devices, and integration tests. + +## Requirements ### Requirement: IKEA TIMMERFLOTTE SBMD spec The system SHALL include an SBMD spec file `ikea-timmerflotte.sbmd` that defines a TIMMERFLOTTE-specific driver claiming by vendor ID and product ID. The spec SHALL also list device types `0x0302` (Temperature Sensor) and `0x0307` (Humidity Sensor) for endpoint mapping purposes. diff --git a/openspec/specs/thread-subsystem/spec.md b/openspec/specs/thread-subsystem/spec.md index eb188a8d..d29f1d3f 100644 --- a/openspec/specs/thread-subsystem/spec.md +++ b/openspec/specs/thread-subsystem/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Thread Subsystem + +## Purpose + +Specifies the Thread subsystem's OTBR D-Bus integration: network backup and restore, Thread credentials for Matter commissioning, NAT64 support, ephemeral-key commissioning, border-router status monitoring, the default network name, and conditional compilation. + +## Requirements ### Requirement: OTBR D-Bus integration The Thread subsystem SHALL communicate with the OpenThread Border Router (OTBR) agent via D-Bus (using the `io.openthread.BorderRouter` interface on `DBUS_BUS_SYSTEM`). It SHALL wrap D-Bus access via an `OpenThreadClient` class that provides methods for `CreateNetwork()`, `RestoreNetwork()`, `GetChannel()`, `GetPanId()`, `GetExtPanId()`, `GetNetworkKey()`, `GetNetworkName()`, `GetDeviceRole()`, `SetNat64Enabled()`, and `ActivateEphemeralKeyMode()`. The `DeviceRole` enum SHALL include: UNKNOWN, DISABLED, DETACHED, CHILD, ROUTER, LEADER. diff --git a/openspec/specs/vendor-product-claiming/spec.md b/openspec/specs/vendor-product-claiming/spec.md index d22b8b69..3d71177a 100644 --- a/openspec/specs/vendor-product-claiming/spec.md +++ b/openspec/specs/vendor-product-claiming/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Vendor and Product Claiming + +## Purpose + +Specifies vendor and product ID claiming for SBMD drivers: declaring vendor/product IDs in specs, `DeviceDataCache` accessors, claim semantics, and vendor-specific driver priority. + +## Requirements ### Requirement: Vendor ID and product ID in SBMD specs The `matterMeta` section of an SBMD spec SHALL support optional `vendorId` and `productId` fields (unsigned 16-bit integers). When omitted, the driver SHALL use device-type matching as before. diff --git a/openspec/specs/zigbee-subsystem/spec.md b/openspec/specs/zigbee-subsystem/spec.md index 9961d9aa..14392b1b 100644 --- a/openspec/specs/zigbee-subsystem/spec.md +++ b/openspec/specs/zigbee-subsystem/spec.md @@ -1,4 +1,10 @@ -## ADDED Requirements +# Zigbee Subsystem + +## Purpose + +Specifies the Zigbee subsystem built on the ZHAL abstraction layer: device lifecycle and message-reception callbacks, communication tracking, network management and security events, OTA support, attribute-reporting configuration, DDL processing, network monitoring, energy scan, and channel change. + +## Requirements ### Requirement: ZHAL abstraction layer The system SHALL define a Zigbee Hardware Abstraction Layer (ZHAL) as a C API that abstracts the underlying Zigbee radio and stack. ZHAL SHALL support device lifecycle callbacks, attribute report reception, cluster command reception, and network management operations.