opencode-work-context 0.11.2 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -151,11 +151,12 @@ Avoid editing configuration by hand:
151
151
  /wc profiles reset
152
152
  ```
153
153
 
154
- `profiles setup` asks for advisory/off mode and the local model label for each
155
- depth, then offers to refresh unfinished stages. Profiles are advisory by
156
- default. Off mode hides and skips resolution while preserving stage metadata.
157
- The resulting user-local mappings live only in the ignored
158
- `.work-context/local/capability-profiles.json` file:
154
+ `profiles setup` asks for advisory/off mode, global or project scope, and the
155
+ model label for each depth, then offers to refresh unfinished stages. Profiles
156
+ are advisory by default. Off mode hides and skips resolution while preserving
157
+ stage metadata. Global user mappings live at
158
+ `~/.config/opencode/capability-profiles.json`. Optional project overrides live
159
+ at `.opencode/capability-profiles.json` and are tracked by default:
159
160
 
160
161
  ```json
161
162
  {
@@ -173,10 +174,17 @@ Sol`. Without a mapping, the TUI shows the actual model name for the current
173
174
  OpenCode session; other stages show only capability and depth rather than an
174
175
  ambiguous `current model` label. Optional `review_profile` metadata neither
175
176
  resolves a model nor controls separately configured subagents.
176
- Targets are bounded opaque labels and never enter tracked data. Invalid entries
177
- produce bounded warnings. The plugin never changes an active model or agent,
178
- invokes a reviewer, creates a replacement session, or blocks resume. `init`,
179
- `activate`, and `sync-command` preserve files below `.work-context/local/`.
177
+ Resolution precedence is explicit invocation override, project mapping, global
178
+ mapping, then current model. Targets are bounded opaque advisory labels and
179
+ never enter tracked work-context data. Invalid entries produce bounded warnings.
180
+ The plugin never changes an active model or agent, invokes a reviewer, creates a
181
+ replacement session, or blocks resume.
182
+
183
+ Existing `.work-context/local/capability-profiles.json` files remain a temporary
184
+ lowest-precedence compatibility fallback and produce a migration warning. Use
185
+ the shared `opencode-capability-profiles migrate --project` flow to preview
186
+ additions and conflicts and explicitly import legacy values into global config.
187
+ Migration never modifies or deletes the legacy file.
180
188
 
181
189
  Long-running stages may keep a bounded execution ledger separate from the
182
190
  original prompt, workspace knowledge, session summaries, and final result. It
@@ -195,9 +203,15 @@ atomically adds and removes exact normalized items. Mutations require the active
195
203
  stage session. A stale revision fails with `EXECUTION_REVISION_CONFLICT` rather
196
204
  than overwriting newer work. Each section is limited to 50 items, the complete
197
205
  state to 200 items and 32,768 serialized bytes, and each item to 500 characters.
198
- Update the ledger at meaningful boundaries, not after every edit. Checklist
199
- state never completes a stage: explicit stage finish reports unfinished ledger
200
- entries as warnings and preserves the final record.
206
+ The first Remaining item is `Current`; later items are `Queued`. Agents work only
207
+ on Current by default and do not combine Queued work into the same change set
208
+ unless the user explicitly requests it. The read model includes stable item IDs,
209
+ so Current and Queued remain unambiguous even when text is duplicated or revised.
210
+ After completing Current, read the latest revision and use `complete-current` to
211
+ move it to Completed and promote the next Queued item. Update the ledger at
212
+ meaningful boundaries, not after every edit. Checklist state never completes a
213
+ stage: explicit stage finish reports unfinished ledger entries as warnings and
214
+ preserves the final record.
201
215
 
202
216
  After updating the npm package, refresh the generated slash-command contract
203
217
  without touching project configuration or loaders:
@@ -285,9 +299,9 @@ For an existing JSONC configuration, add the equivalent entry manually:
285
299
  }
286
300
  ```
287
301
 
288
- Re-running `activate` also migrates work-context entries previously generated
289
- under the unsupported legacy `plugins` field. Unrelated legacy entries are
290
- preserved rather than activated or removed implicitly.
302
+ Re-running `activate` or `deactivate` migrates every entry from the unsupported
303
+ legacy `plugins` field into the canonical `plugin` array, preserves entry order,
304
+ removes exact duplicates, and deletes `plugins`.
291
305
 
292
306
  Update managed activation from one activated project with an exact version:
293
307
 
@@ -639,6 +653,45 @@ separate those edits by provenance. Use an integration candidate only when the
639
653
  combined patch is coherent and verified; otherwise stop and establish a safe
640
654
  candidate boundary before publication.
641
655
 
656
+ ### Repository-local commit all
657
+
658
+ `commit all` is the explicit fast path for one coherent repository-wide
659
+ integration commit. It is available in both standard and startup workspaces and
660
+ uses the same temporary-index capture, preview verification, Git lock, and
661
+ compare-and-swap publication as an integration candidate. Ordinary candidate
662
+ lifecycle commands remain startup-only.
663
+
664
+ The flow is deliberately two-phase:
665
+
666
+ ```text
667
+ /wc commit all 000123 stages 02 04 exclude scratch.txt
668
+ /wc commit all confirm 000123 <fingerprint> COMMIT_ALL_CONFIRMED stages 02 04 exclude scratch.txt
669
+ ```
670
+
671
+ Inspection is read-only. It returns the repository root, included and excluded
672
+ paths, unattributed paths, related stage titles, a diff-derived message proposal,
673
+ recent subjects used to match repository message style, a patch summary, and a
674
+ SHA-256 fingerprint. An explicit message on both commands overrides the proposal.
675
+ Selected stages provide traceability only and never assign files or lines. When
676
+ stage evidence is unavailable, the operation keeps paths explicitly unattributed
677
+ instead of inventing provenance.
678
+
679
+ Publication requires the exact `COMMIT_ALL_CONFIRMED` token and the inspection
680
+ fingerprint. Under the Git lock it repeats inspection with the same message,
681
+ stages, and exclusions. Any changed `HEAD`, patch, selection, attribution, or
682
+ message returns `COMMIT_ALL_STALE_PLAN` without creating a commit. A matching
683
+ active integration candidate is reused only when its exact patch matches;
684
+ otherwise a new candidate is created inside the atomic publication transaction.
685
+
686
+ The repository boundary is the current Git root. Sibling and external
687
+ repositories are never inspected. Nested repositories, submodules, local
688
+ operational state, suspicious generated paths, probable secrets, and explicitly
689
+ excluded unrelated paths remain outside the patch and are reported. Work in
690
+ another repository must be committed independently there. Active Git operations,
691
+ unsupported binary boundaries, detached `HEAD`, verification failures, and ref
692
+ races stop publication. Hooks and signing remain bypassed because publication
693
+ uses `git commit-tree`.
694
+
642
695
  ### Delivery context
643
696
 
644
697
  Committing or pushing does not prove that an environment was updated. Delivery is
@@ -769,6 +822,23 @@ descriptor hash, version, and module-origin drift produce findings with repair
769
822
  guidance. The current OpenCode host may report authoritative attestation as
770
823
  unavailable; doctor does not guess or repair automatically.
771
824
 
825
+ For automation outside a loaded OpenCode runtime, use the standalone JSON doctor:
826
+
827
+ ```sh
828
+ opencode-work-context doctor --json [--project <path>]
829
+ ```
830
+
831
+ `--json` is required and options may be ordered either way. The project defaults
832
+ to the current working directory and must be an existing directory. A valid
833
+ invocation emits exactly one JSON object with `schema: 1`, component and package
834
+ version metadata, aggregate `status`, canonical absolute `project`, the existing
835
+ `diagnostic` envelope, and `complete: true`. It exits `0` only when status is
836
+ `ok`; findings at warning or error severity exit `1`. Invalid arguments or a
837
+ missing project use the CLI error output and do not emit a health envelope. The
838
+ standalone process has no loaded-plugin runtime attestation, so its diagnostic
839
+ truthfully reports that evidence as unavailable rather than claiming the CLI
840
+ package is loaded by OpenCode.
841
+
772
842
  For a pinned local installation, repair with:
773
843
 
774
844
  ```sh
@@ -6,6 +6,7 @@ import { spawnSync } from "node:child_process";
6
6
  import { randomUUID } from "node:crypto";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { defaultConfig } from "../src/storage.js";
9
+ import { doctorDelivery, validateDeliveryDoctorEnvelope } from "../src/delivery-doctor.js";
9
10
 
10
11
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
11
12
  const packageManifest = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"));
@@ -81,6 +82,24 @@ const hasSymlinkParent = (file) => {
81
82
  };
82
83
 
83
84
  function parseArgs(args) {
85
+ if (args[0] === "doctor") {
86
+ let project;
87
+ let json = false;
88
+ for (let index = 1; index < args.length; index += 1) {
89
+ const arg = args[index];
90
+ if (arg === "--json") {
91
+ if (json) return fail("duplicate option: --json");
92
+ json = true;
93
+ } else if (arg === "--project") {
94
+ if (project !== undefined) return fail("duplicate option: --project");
95
+ project = args[index + 1];
96
+ if (!project || project.startsWith("--")) return fail("--project requires a path");
97
+ index += 1;
98
+ } else return fail(`unknown option: ${arg}`);
99
+ }
100
+ if (!json) return fail("doctor requires --json");
101
+ return { doctor: true, project };
102
+ }
84
103
  if (args[0] === "sync-command") {
85
104
  const unknown = args.slice(1).filter((arg) => arg !== "--force");
86
105
  if (unknown.length) return fail(`unknown option: ${unknown[0]}`);
@@ -91,12 +110,43 @@ function parseArgs(args) {
91
110
  if (unknown.length) return fail(`unknown option: ${unknown[0]}`);
92
111
  return { activation: args[0] === "activate", force: args.includes("--force") };
93
112
  }
94
- if (args[0] !== "init") return fail("usage: opencode-work-context init [--force] | activate [--force] | deactivate [--force] | sync-command");
113
+ if (args[0] !== "init") return fail("usage: opencode-work-context init [--force] | activate [--force] | deactivate [--force] | sync-command | doctor --json [--project <path>]");
95
114
  const unknown = args.slice(1).filter((arg) => arg !== "--force");
96
115
  if (unknown.length) return fail(`unknown option: ${unknown[0]}`);
97
116
  return { force: args.includes("--force") };
98
117
  }
99
118
 
119
+ function runDoctor(project) {
120
+ let root;
121
+ try {
122
+ root = fs.realpathSync(path.resolve(project || process.cwd()));
123
+ if (!fs.statSync(root).isDirectory()) throw new Error("path is not a directory");
124
+ } catch {
125
+ fail("doctor project must be an existing directory");
126
+ return;
127
+ }
128
+ try {
129
+ const diagnostic = validateDeliveryDoctorEnvelope(doctorDelivery(root));
130
+ const status = diagnostic.findings.some((finding) => finding.severity === "error")
131
+ ? "error"
132
+ : diagnostic.findings.some((finding) => finding.severity === "warning")
133
+ ? "warning"
134
+ : "ok";
135
+ console.log(JSON.stringify({
136
+ schema: 1,
137
+ component: packageManifest.name,
138
+ package_version: packageManifest.version,
139
+ status,
140
+ project: root,
141
+ diagnostic,
142
+ complete: true,
143
+ }));
144
+ if (status !== "ok") process.exitCode = 1;
145
+ } catch {
146
+ fail("doctor could not inspect project safely");
147
+ }
148
+ }
149
+
100
150
  function activate(enabled, force) {
101
151
  const localLoader = path.join(projectRoot, ".opencode", "plugins", "work-context.js");
102
152
  if (exists(localLoader)) {
@@ -147,11 +197,17 @@ function activate(enabled, force) {
147
197
  || item.startsWith(`${packageManifest.name}@`)
148
198
  || item === "-work-context"
149
199
  );
150
- config.plugin = [...(config.plugin || []).filter((item) => !isWorkContextEntry(item)), entry];
151
- if (config.plugins) {
152
- config.plugins = config.plugins.filter((item) => !isWorkContextEntry(item));
153
- if (config.plugins.length === 0) delete config.plugins;
154
- }
200
+ const seenPluginEntries = new Set();
201
+ config.plugin = [...(config.plugin || []), ...(config.plugins || [])]
202
+ .filter((item) => !isWorkContextEntry(item))
203
+ .filter((item) => {
204
+ const key = JSON.stringify(item);
205
+ if (seenPluginEntries.has(key)) return false;
206
+ seenPluginEntries.add(key);
207
+ return true;
208
+ });
209
+ config.plugin.push(entry);
210
+ delete config.plugins;
155
211
  managedTuiConfig.plugin = [...(managedTuiConfig.plugin || []).filter((item) => !isWorkContextEntry(item)), entry];
156
212
  const files = new Map([
157
213
  [configRelative, JSON.stringify(config, null, 2) + "\n"],
@@ -410,7 +466,9 @@ function writeGenerated() {
410
466
  }
411
467
 
412
468
  const options = parseArgs(process.argv.slice(2));
413
- if (options?.syncCommand) {
469
+ if (options?.doctor) {
470
+ runDoctor(options.project);
471
+ } else if (options?.syncCommand) {
414
472
  const initLock = acquireInitLock();
415
473
  if (initLock.failed) process.exitCode = 1;
416
474
  else {
package/commands/wc.md CHANGED
@@ -3,7 +3,7 @@ description: Explicit work-context lifecycle commands backed by structured tools
3
3
  subtask: false
4
4
  ---
5
5
 
6
- <!-- opencode-work-context-protocol: {"schema":1,"major":1,"minor":1,"descriptor_hash":"sha256:d1320820ace2e9a56f35ab279dace8ae2c59cc2c73f03b73f30068adbfd6e734"} -->
6
+ <!-- opencode-work-context-protocol: {"schema":1,"major":1,"minor":3,"descriptor_hash":"sha256:08ec85ffd42546b86bd07ce8f924ddc3f1e671c54211c161751e4af8b91fae32"} -->
7
7
 
8
8
  Interpret `/wc $ARGUMENTS` as an explicit work-context operation. Use the matching
9
9
  `work_context_*` custom tool registered by the installed package plugin with structured arguments. Never edit work-context
@@ -39,6 +39,8 @@ Use these exact tool mappings; do not invent shortened tool names:
39
39
  - `candidate ready <workspace> <candidateId>` -> `work_context_ready_candidate`
40
40
  - `candidate commit <workspace> <candidateId> ["message"]` -> `work_context_commit_candidate`
41
41
  - `candidate discard <workspace> <candidateId>` -> `work_context_discard_candidate`
42
+ - `commit all <workspace> ["message"] [stages <stage>...] [exclude <path>...]` -> `work_context_inspect_commit_all`
43
+ - `commit all confirm <workspace> <fingerprint> COMMIT_ALL_CONFIRMED ["message"] [stages <stage>...] [exclude <path>...]` -> `work_context_commit_all`
42
44
  - `delivery read <workspace> [<environment>] [range <from> <to>]` -> `work_context_read_delivery`
43
45
  - `delivery explain <workspace> <from> <to> [findings JSON]` -> `work_context_explain_delivery`
44
46
  - `delivery doctor` -> `work_context_doctor_delivery`
@@ -49,8 +51,8 @@ Use these exact tool mappings; do not invent shortened tool names:
49
51
  - `commited <short-or-full-SHA>` -> `work_context_acknowledge_commit`
50
52
  - `stage force-close <workspace> <stage> <sessionId> "reason" FORCE_CLOSE` -> `work_context_force_close_session`
51
53
  - `profiles show` -> `work_context_show_capability_profiles`
52
- - `profiles setup` -> ask the user questions, then `work_context_configure_capability_profiles`
53
- - `profiles reset` -> ask for confirmation, then `work_context_reset_capability_profiles`
54
+ - `profiles setup` -> ask for global or project scope and mapping values, then `work_context_configure_capability_profiles`
55
+ - `profiles reset` -> ask for global or project scope and confirmation, then `work_context_reset_capability_profiles`
54
56
  - `stage add [<workspace>] ...` -> `work_context_add_stage` (optional `prompt`; infer missing execution capability and depth from the complete stage context before calling the tool)
55
57
  - `stage profiles [<workspace>] [<stage>] [execution <routine|implementation|architecture|security|review> depth <light|standard|deep>|clear] [review <routine|implementation|architecture|security|review|clear>]` -> `work_context_set_stage_profiles`
56
58
  - `stage profiles refresh <workspace> [<stage>] [--include-explicit]` -> inspect current stage context, infer classifications, then `work_context_refresh_stage_profiles`
@@ -63,6 +65,7 @@ Use these exact tool mappings; do not invent shortened tool names:
63
65
  - `stage execution read [<workspace>] [<stage>]` -> `work_context_read_stage_execution`
64
66
  - `stage execution replace [<workspace>] [<stage>] <expectedRevision> "state JSON"` -> `work_context_replace_stage_execution`
65
67
  - `stage execution update [<workspace>] [<stage>] <expectedRevision> "changes JSON"` -> `work_context_update_stage_execution`
68
+ - `stage execution complete-current [<workspace>] [<stage>] <expectedRevision>` -> `work_context_complete_current`
66
69
  - `stage archive [<workspace>] [<stage>]` -> `work_context_archive_stage`
67
70
  - `stage handoff [<workspace>] [<stage>]` -> `work_context_handoff_stage`
68
71
  - `stage abandon [<workspace>] [<stage>]` -> `work_context_abandon_stage`
@@ -86,6 +89,8 @@ Supported syntax:
86
89
  - `candidate ready <workspace> <candidateId>`
87
90
  - `candidate commit <workspace> <candidateId> ["message"]`
88
91
  - `candidate discard <workspace> <candidateId>`
92
+ - `commit all <workspace> ["message"] [stages <stage>...] [exclude <path>...]`
93
+ - `commit all confirm <workspace> <fingerprint> COMMIT_ALL_CONFIRMED ["message"] [stages <stage>...] [exclude <path>...]`
89
94
  - `delivery read <workspace> [<environment>] [range <from> <to>]`
90
95
  - `delivery explain <workspace> <from> <to> [findings JSON]`
91
96
  - `delivery doctor`
@@ -110,6 +115,7 @@ Supported syntax:
110
115
  - `stage execution read [<workspace>] [<stage>]`
111
116
  - `stage execution replace [<workspace>] [<stage>] <expectedRevision> "state JSON"`
112
117
  - `stage execution update [<workspace>] [<stage>] <expectedRevision> "changes JSON"`
118
+ - `stage execution complete-current [<workspace>] [<stage>] <expectedRevision>`
113
119
  - `stage archive [<workspace>] [<stage>]`
114
120
  - `stage handoff [<workspace>] [<stage>]`
115
121
  - `stage abandon [<workspace>] [<stage>]`
@@ -131,20 +137,21 @@ Supported syntax:
131
137
  - `stage profiles` makes an explicit assignment; execution capability and depth are set or cleared together, omitted fields remain unchanged, and review remains optional metadata that does not control subagents or resolve a model
132
138
  - `stage profiles refresh` re-evaluates actionable missing/inferred stages from their complete current context and applies all computed recommendations in one structured call; skip completed/archived stages and preserve explicit assignments unless `--include-explicit` was requested
133
139
  - `capability_profiles.mode` in `.work-context/config.yaml` is `advisory` by default or `off`; off mode preserves metadata but omits profile presentation, resolution, and mapping warnings
134
- - advisory mappings are local depth-to-model labels, for example `{ "schema": 1, "mappings": { "light": "Luna", "standard": "Terra", "deep": "Sol" } }`; invalid entries are ignored with bounded warnings and missing mappings resolve to `current model`
140
+ - advisory mappings are layered depth-to-model labels: tracked project mappings in `.opencode/capability-profiles.json` override global mappings in `~/.config/opencode/capability-profiles.json`; invalid entries are ignored with bounded warnings and missing mappings resolve to `current model`
135
141
  - `profiles setup` must use interactive questions for mode and light/standard/deep labels, apply mode and mappings in separate atomic structured calls, then offer to refresh unfinished stages; `profiles reset` requires explicit confirmation and removes mappings without changing stage metadata or mode
136
142
  - expanded stage details show one unlabeled line `<capability> · <depth> · <model>`; review metadata is not displayed as a model recommendation
137
143
  - capability recommendations never select a model or agent, create a replacement session, block resume, or persist mapping targets in tracked workspace data
138
- - stage execution state has `scope`, `completed`, `remaining`, `decisions`, `blockers`, and `verification` string-array sections; `replace` accepts the complete state object, while `update` accepts an object with `add` and/or `remove` section objects
144
+ - stage execution state preserves string-array section compatibility while exposing stable `{ id, text }` identities in `items`; `current` is the first remaining item and `queued` contains later remaining items in order. `replace` accepts strings or structured items, while `update` accepts `add`, `remove`, and `edit` changes; use IDs for duplicate or reworded text
139
145
  - read stage execution state first and pass its revision as `expectedRevision`; absent legacy state has revision `0`, and a stale mutation returns `EXECUTION_REVISION_CONFLICT` without changing newer state
140
146
  - execution mutations require the active stage session, trim and deduplicate items, reject overlap between `completed` and `remaining`, and enforce bounded item counts, lengths, and serialized size
141
147
  - update execution state after meaningful scope changes, decisions, substantial work, blockers, or verification changes and before handoff; do not update it for every trivial edit or tool call
142
- - after completing a meaningful remaining checklist item, read the latest revision and atomically remove that exact item from `remaining` while adding it to `completed` in one execution update; retain ordering and briefly report the transition in normal output
148
+ - work only on Current by default. Do not combine Queued items into one change set unless the user explicitly asks to batch them
149
+ - after completing a meaningful Current item, read the latest revision and call `stage execution complete-current`; it atomically moves only Current to Completed and promotes the next queued item. Retain ordering and briefly report the transition in normal output
143
150
  - `resume` returns `resume.presentation` and `resume.context`; before doing any work, report a concise human-oriented summary in the user's language with the stage title, a plain-language Goal, previous progress when useful, and the immediate next action
144
151
  - when the saved prompt contains several clear deliverables, add `In this stage we will` with 2-5 short outcome-oriented bullets derived only from the prompt, previous result, and workspace knowledge; do not invent scope, and omit this block for a small stage
145
152
  - do not expose raw workspace/stage/session identifiers, ordinals, `ok` flags, or absent error codes in the user-facing resume summary
146
153
  - `resume.context.workspace_knowledge` contains every active durable knowledge entry for the workspace; treat it as established shared context, and do not repeat earlier analysis unless an entry is incomplete, contradicted, or needs verification
147
- - when stage execution state exists, `resume.context.execution_state` is the current stage-local operational checkpoint; continue from it without rewriting the original prompt, and never copy it automatically into workspace knowledge or unrelated stages
154
+ - when stage execution state exists, `resume.context.execution_state` is the current stage-local operational checkpoint. Its structured `current` and `queued` fields identify the active item and its ordered backlog; continue from it without rewriting the original prompt, and never copy it automatically into workspace knowledge or unrelated stages
148
155
  - Planning-stage resume may include `resume.context.delivery_context`, a bounded workspace-level summary of committed candidates and environment checkpoints; it is release coordination context, not stage ownership
149
156
  - when the user asks how to deploy from Planning, inspect the exact commit range and the repository's own deployment documentation, scripts, infrastructure, migrations, container definitions, configuration examples, and CI; produce ordered prerequisites, deployment, verification, rollback, and unresolved blockers instead of assuming that push or one generic command is sufficient
150
157
  - delivery planning must never persist secret values; mention only required secret or configuration names, ask one focused question when environment or baseline is ambiguous, and never mark delivery merely because commit, push, or CI succeeded
@@ -168,6 +175,10 @@ Supported syntax:
168
175
  - `stage restore <workspace> <stage> "reason"` applies only to an archived stage and restores its saved pre-archive status. New archives preserve that status; legacy archives restore to `in_progress`. It records the reason, preserves stage content and results, does not start a session, and requires explicit separate-session `resume` when restored to `planned` or `in_progress`.
169
176
  - `workspace reopen <workspace> "reason"` applies only to a completed workspace, changes it to `in_progress`, and records durable recovery history. Cancelled workspaces cannot be reopened.
170
177
  - candidate operations require `startup` workflow mode and store metadata and patch payloads only under `.work-context/local/`; create accepts an optional strategy and related stages, which are normalized references for traceability only and never ownership or lifecycle; active candidates explicitly related to the resumed stage appear as bounded metadata in `resume.context.pending_candidates` and in expanded sidebar details; capture requires exactly one explicit list of complete paths or one Git unified patch and never infers stage ownership; commit requires a ready candidate, uses its stored message unless a non-empty override is supplied, serializes Git publication, bypasses hooks and signing, and never uses the ordinary Git index
178
+ - `commit all` is an explicit two-phase repository-local integration operation available in standard and startup workspaces: first call inspection, report its included and excluded paths, traceability, proposed message, verification summary, and fingerprint, then wait for the user's exact `COMMIT_ALL_CONFIRMED` confirmation before calling publication with the same message, stages, exclusions, and fingerprint
179
+ - commit-all inspection is read-only and never treats stages as file ownership; user-selected stages are traceability and message context, paths without defensible attribution remain explicit, `exclude` leaves known unrelated work outside the patch, and an omitted message uses the diff-derived proposal
180
+ - commit-all publication re-inspects under the Git lock and returns `COMMIT_ALL_STALE_PLAN` when HEAD, patch content, exclusions, traceability, or message no longer match the confirmed fingerprint; never infer confirmation from tests, candidate readiness, preview success, or lifecycle state
181
+ - commit-all is bounded to the current Git root and never includes sibling or external repositories, nested repositories, submodules, local operational state, suspicious generated paths, or probable secrets; those exclusions remain visible in the structured result and work in another repository must be committed there independently
171
182
  - delivery operations are mode-neutral local operational state and never execute deployment; `delivery read` without a range returns metadata only, exact Git inspection requires both immutable `from` and `to` hashes, and `delivery mark` requires the exact `DELIVERY_CONFIRMED` token only after the user confirms successful delivery to that environment
172
183
  - `delivery explain` is strictly read-only, accepts findings as structured JSON data, inspects only the explicit immutable range, and preserves stable errors, contract version, completeness, and omission of recommendations when incomplete
173
184
  - `delivery doctor` is strictly read-only, compares generated-command, declared, installed, self-reported, and host-attested or unavailable runtime evidence, and fails fast only when command and loaded-plugin protocol majors differ
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-work-context",
3
3
  "type": "module",
4
- "version": "0.11.2",
4
+ "version": "0.12.1",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -46,6 +46,7 @@
46
46
  ],
47
47
  "dependencies": {
48
48
  "@opentui/solid": "^0.4.5",
49
+ "opencode-capability-profiles": "0.1.0",
49
50
  "solid-js": "1.9.12",
50
51
  "zod": "^4.6.7"
51
52
  },
@@ -117,7 +117,7 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
117
117
  flexShrink: 0,
118
118
  marginRight: 1,
119
119
  fg: working || current ? theme?.current?.warning : theme?.current?.textMuted,
120
- children: working ? activityFrame() : attentionSignal ? runtime.jsx("b", { children: attentionSignal }) : " ",
120
+ children: attentionSignal ? runtime.jsx("b", { children: attentionSignal }) : working ? activityFrame() : " ",
121
121
  }),
122
122
  runtime.jsx("text", { flexShrink: 0, marginRight: 1, fg: current ? theme?.current?.warning : theme?.current?.textMuted, children: statusMarker(stage.status) }),
123
123
  runtime.jsx("box", {
@@ -126,7 +126,7 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
126
126
  flexDirection: "column",
127
127
  children: [
128
128
  runtime.jsx("text", { wrapMode: "word", fg: current ? theme?.current?.warning : theme?.current?.text, children: `${stage.id}. ${stage.title}` }),
129
- metadata && runtime.jsx("text", { wrapMode: "none", fg: theme?.current?.textMuted, children: metadata }),
129
+ metadata && runtime.jsx("text", { wrapMode: "word", fg: theme?.current?.textMuted, children: metadata }),
130
130
  ].filter(Boolean),
131
131
  }),
132
132
  ],
@@ -375,14 +375,24 @@ export const checklistOptions = (execution, width = 80) => {
375
375
  if (!execution) return [{ title: "No checklist is available for the current stage.", value: "empty", disabled: true }];
376
376
  const compact = width < 50;
377
377
  const truncate = (text) => compact && text.length > Math.max(12, width - 12) ? `${text.slice(0, Math.max(9, width - 15))}...` : text;
378
+ const structuredItems = (section) => execution.items?.[section] || execution[section] || [];
379
+ const item = (value, section, index) => typeof value === "string"
380
+ ? { id: `${section}-${index}`, text: value }
381
+ : value;
382
+ const option = (value, section, index, title, category) => {
383
+ const entry = item(value, section, index);
384
+ return { title: title(entry.text), value: `execution-${entry.id}`, category };
385
+ };
378
386
  const options = [];
379
- if (execution.remaining?.[0]) options.push({ title: `[•] ${truncate(execution.remaining[0])}`, value: "current", category: "Current" });
380
- for (const item of execution.remaining?.slice(1) || []) options.push({ title: `[ ] ${truncate(item)}`, value: `queued-${item}`, category: "Queued" });
381
- for (const item of execution.completed || []) options.push({ title: `[✓] ${truncate(item)}`, value: `completed-${item}`, category: "Completed" });
382
- for (const item of execution.blockers || []) options.push({ title: `[!] ${truncate(item)}`, value: `blocker-${item}`, category: "Blockers" });
383
- for (const item of execution.verification || []) options.push({ title: `[ ] ${truncate(item)}`, value: `verification-${item}`, category: "Verification" });
384
- if (execution.scope?.length) options.push(...execution.scope.map((item) => ({ title: truncate(item), value: `scope-${item}`, category: "Scope" })));
385
- if (execution.decisions?.length) options.push(...execution.decisions.map((item) => ({ title: truncate(item), value: `decision-${item}`, category: "Decisions" })));
387
+ const current = execution.current || structuredItems("remaining")[0];
388
+ const queued = execution.queued || structuredItems("remaining").slice(1);
389
+ if (current) options.push(option(current, "remaining", 0, (text) => `[•] ${truncate(text)}`, "Current"));
390
+ queued.forEach((entry, index) => options.push(option(entry, "remaining", index + 1, (text) => `[ ] ${truncate(text)}`, "Queued")));
391
+ structuredItems("completed").forEach((entry, index) => options.push(option(entry, "completed", index, (text) => `[✓] ${truncate(text)}`, "Completed")));
392
+ structuredItems("blockers").forEach((entry, index) => options.push(option(entry, "blockers", index, (text) => `[!] ${truncate(text)}`, "Blockers")));
393
+ structuredItems("verification").forEach((entry, index) => options.push(option(entry, "verification", index, (text) => `[ ] ${truncate(text)}`, "Verification")));
394
+ structuredItems("scope").forEach((entry, index) => options.push(option(entry, "scope", index, truncate, "Scope")));
395
+ structuredItems("decisions").forEach((entry, index) => options.push(option(entry, "decisions", index, truncate, "Decisions")));
386
396
  return options.length ? [{ title: "Close", value: "close", category: "Checklist" }, ...options] : [{ title: "Checklist is empty.", value: "empty", disabled: true }];
387
397
  };
388
398
 
package/src/candidates.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { createHash } from "node:crypto";
3
4
  import { atomicWrite } from "./storage.js";
4
5
  import { ERROR_CODES, fail } from "./errors.js";
5
6
  import { normalizeStageId, normalizeWorkspaceId } from "./identifiers.js";
6
- import { capturePatch, capturePaths, commitPatch, previewPatch, repositoryState } from "./git-candidates.js";
7
+ import { capturePatch, capturePaths, commitPatch, inspectCommitAll, previewPatch, repositoryState } from "./git-candidates.js";
7
8
 
8
9
  const candidatePattern = /^CC-(\d{6})$/;
9
10
  const statuses = new Set(["draft", "ready", "discarded", "committed"]);
@@ -52,6 +53,13 @@ export class CandidateStore {
52
53
  return workspace;
53
54
  }
54
55
 
56
+ assertWorkspace(workspace) {
57
+ this.context.storage.assertNoSymlinks();
58
+ workspace = normalizeWorkspaceId(workspace);
59
+ this.context.storage.readWorkspace(workspace);
60
+ return workspace;
61
+ }
62
+
55
63
  metadataFile(id) { return path.join(this.directory, `${id}.json`); }
56
64
  patchFile(id) { return path.join(this.directory, `${id}.patch`); }
57
65
 
@@ -84,7 +92,7 @@ export class CandidateStore {
84
92
  }
85
93
 
86
94
  create(workspace, title, message = null, options = {}) {
87
- workspace = this.assertStartup(workspace);
95
+ workspace = options.allowStandard ? this.assertWorkspace(workspace) : this.assertStartup(workspace);
88
96
  if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Candidate title is required");
89
97
  const strategy = options.strategy ?? "exact";
90
98
  if (!strategies.has(strategy)) fail(ERROR_CODES.INVALID_ARGUMENT, "Candidate strategy must be 'exact', 'shared_foundation' or 'integration'");
@@ -168,8 +176,8 @@ export class CandidateStore {
168
176
  };
169
177
  }
170
178
 
171
- capture(workspace, id, input) {
172
- workspace = this.assertStartup(workspace);
179
+ capture(workspace, id, input, options = {}) {
180
+ workspace = options.allowStandard ? this.assertWorkspace(workspace) : this.assertStartup(workspace);
173
181
  const data = this.read(id, workspace);
174
182
  if (data.status !== "draft") fail(ERROR_CODES.INVALID_STATE, "Only draft candidates can be captured", { status: data.status });
175
183
  const hasPaths = Array.isArray(input.paths);
@@ -185,15 +193,15 @@ export class CandidateStore {
185
193
  return { ...data, patch: captured.patch };
186
194
  }
187
195
 
188
- preview(workspace, id) {
189
- workspace = this.assertStartup(workspace);
196
+ preview(workspace, id, options = {}) {
197
+ workspace = options.allowStandard ? this.assertWorkspace(workspace) : this.assertStartup(workspace);
190
198
  const data = this.read(id, workspace, true);
191
199
  if (!data.patch) fail(ERROR_CODES.INVALID_STATE, "Commit candidate has not captured a patch");
192
200
  return { candidate: data, preview: previewPatch(this.context.storage.projectRoot, data.base_head, data.patch) };
193
201
  }
194
202
 
195
- setStatus(workspace, id, status) {
196
- workspace = this.assertStartup(workspace);
203
+ setStatus(workspace, id, status, options = {}) {
204
+ workspace = options.allowStandard ? this.assertWorkspace(workspace) : this.assertStartup(workspace);
197
205
  const data = this.read(id, workspace, true);
198
206
  if (status === "ready" && data.status !== "draft") fail(ERROR_CODES.INVALID_STATE, "Only draft candidates can become ready", { status: data.status });
199
207
  if (status === "discarded" && data.status === "discarded") return data;
@@ -207,13 +215,14 @@ export class CandidateStore {
207
215
  }
208
216
 
209
217
  commit(workspace, id, message = undefined, options = {}) {
210
- workspace = this.assertStartup(workspace);
218
+ workspace = options.allowStandard ? this.assertWorkspace(workspace) : this.assertStartup(workspace);
211
219
  const data = this.read(id, workspace, true);
212
220
  if (data.status !== "ready") fail(ERROR_CODES.INVALID_STATE, "Only ready candidates can be committed", { status: data.status });
213
221
  if (message !== undefined && (typeof message !== "string" || !message.trim())) fail(ERROR_CODES.INVALID_ARGUMENT, "Commit message must be a non-empty string");
214
222
  const commitMessage = message === undefined ? data.message : message.trim();
215
223
  let metadata;
216
224
  const published = commitPatch(this.context.storage.projectRoot, data.base_head, data.patch, commitMessage, {
225
+ expectedHead: options.expectedHead,
217
226
  beforeUpdateRef: (pending) => {
218
227
  const committedAt = new Date().toISOString();
219
228
  data.message = commitMessage;
@@ -226,7 +235,105 @@ export class CandidateStore {
226
235
  this.write(metadata);
227
236
  options.beforeUpdateRef?.(pending);
228
237
  },
238
+ afterUpdateRef: (publication) => options.afterUpdateRef?.({ ...publication, candidate_record: metadata, patch: data.patch }),
229
239
  });
230
240
  return { ...metadata, branch: published.branch, previous_head: published.previous_head, stale: published.stale };
231
241
  }
242
+
243
+ normalizeRelatedStages(workspace, values = []) {
244
+ if (!Array.isArray(values)) fail(ERROR_CODES.INVALID_ARGUMENT, "Related stages must be an array");
245
+ const stages = values.map(normalizeStageId);
246
+ if (new Set(stages).size !== stages.length) fail(ERROR_CODES.INVALID_ARGUMENT, "Related stages must be unique");
247
+ return stages.map((stage) => {
248
+ const record = this.context.storage.readStage(workspace, stage);
249
+ return { stage, title: record.data.title };
250
+ });
251
+ }
252
+
253
+ generatedMessage(audit, stages) {
254
+ const paths = audit.included_paths;
255
+ let subject;
256
+ let conventionalType = "chore";
257
+ if (paths.every((item) => /^(?:docs\/|README(?:\.|$)|[^/]+\.md$)/i.test(item))) { subject = "Update documentation"; conventionalType = "docs"; }
258
+ else if (paths.every((item) => /(?:^|\/)(?:test|tests|__tests__)(?:\/|$)|\.test\.[^/]+$/.test(item))) { subject = "Expand test coverage"; conventionalType = "test"; }
259
+ else if (paths.some((item) => /candidate|git-candidate/.test(item)) || (stages.length === 1 && /commit[- ]all/i.test(stages[0].title))) { subject = "Add repository-local commit-all flow"; conventionalType = "feat"; }
260
+ else subject = paths.length === 1 ? `Update ${path.basename(paths[0])}` : "Integrate repository changes";
261
+ const conventional = audit.recent_subjects.filter((item) => /^[a-z]+(?:\([^)]+\))?!?:\s/.test(item)).length > audit.recent_subjects.length / 2;
262
+ return conventional ? `${conventionalType}: ${subject[0].toLowerCase()}${subject.slice(1)}` : subject;
263
+ }
264
+
265
+ inspectAll(workspace, options = {}) {
266
+ workspace = this.assertWorkspace(workspace);
267
+ if (options.message !== undefined && (typeof options.message !== "string" || !options.message.trim())) fail(ERROR_CODES.INVALID_ARGUMENT, "Commit message must be a non-empty string");
268
+ const audit = inspectCommitAll(this.context.storage.projectRoot, this.context.storage.personalRoot, { excludePaths: options.excludePaths });
269
+ if (!audit.included_paths.length) fail(ERROR_CODES.COMMIT_ALL_NO_CHANGES, "No eligible repository changes are available to commit", { excluded_paths: audit.excluded_paths });
270
+ let relatedStages = options.relatedStages;
271
+ let attributionBasis = relatedStages === undefined ? "workspace_integration" : "user_selected";
272
+ if (relatedStages === undefined) {
273
+ relatedStages = this.projectionRecords(workspace).filter((candidate) => ["draft", "ready"].includes(candidate.status) && candidate.strategy === "integration")
274
+ .flatMap((candidate) => {
275
+ try {
276
+ const patch = this.read(candidate.candidate, workspace, true).patch;
277
+ return createHash("sha256").update(patch).digest("hex") === audit.patch_fingerprint ? (candidate.related_stages || []) : [];
278
+ } catch { return []; }
279
+ });
280
+ relatedStages = [...new Set(relatedStages)].sort();
281
+ if (relatedStages.length) attributionBasis = "exact_candidate_relation";
282
+ }
283
+ const stages = this.normalizeRelatedStages(workspace, relatedStages).map((stage) => ({ ...stage, evidence: attributionBasis }));
284
+ const message = options.message?.trim() || this.generatedMessage(audit, stages);
285
+ const plan = {
286
+ workspace,
287
+ base_head: audit.base_head,
288
+ patch_fingerprint: audit.patch_fingerprint,
289
+ included_paths: audit.included_paths,
290
+ excluded_paths: audit.excluded_paths,
291
+ related_stages: stages.map((item) => item.stage),
292
+ message,
293
+ };
294
+ const fingerprint = createHash("sha256").update(JSON.stringify(plan)).digest("hex");
295
+ const result = {
296
+ workspace,
297
+ repository_root: audit.repository_root,
298
+ strategy: "integration",
299
+ fingerprint,
300
+ base_head: audit.base_head,
301
+ included_paths: audit.included_paths,
302
+ excluded_paths: audit.excluded_paths,
303
+ unattributed_paths: audit.included_paths,
304
+ contributing_stages: stages,
305
+ attribution: { basis: attributionBasis, complete: false },
306
+ message,
307
+ message_source: options.message === undefined ? "generated" : "user",
308
+ verification: { patch_fingerprint: audit.patch_fingerprint, stat: audit.stat, recent_subjects: audit.recent_subjects, included_path_count: audit.included_paths.length, excluded_path_count: audit.excluded_paths.length },
309
+ policy_exclusions: [".work-context/local/**", ".work-context/.locks/**", ".work-context/.transactions/**"],
310
+ };
311
+ return options.includePatch ? { ...result, patch: audit.patch } : result;
312
+ }
313
+
314
+ commitAll(workspace, expectedFingerprint, confirmation, options = {}) {
315
+ if (confirmation !== "COMMIT_ALL_CONFIRMED") fail(ERROR_CODES.COMMIT_ALL_CONFIRMATION_REQUIRED, "Commit all requires the exact COMMIT_ALL_CONFIRMED confirmation");
316
+ if (typeof expectedFingerprint !== "string" || !/^[a-f0-9]{64}$/.test(expectedFingerprint)) fail(ERROR_CODES.INVALID_ARGUMENT, "Expected fingerprint must be a SHA-256 hash");
317
+ const inspection = this.inspectAll(workspace, { ...options, includePatch: true });
318
+ if (inspection.fingerprint !== expectedFingerprint) fail(ERROR_CODES.COMMIT_ALL_STALE_PLAN, "Repository changes no longer match the inspected commit-all plan", { expected_fingerprint: expectedFingerprint, actual_fingerprint: inspection.fingerprint });
319
+ options.beforeCandidate?.(inspection);
320
+ if (repositoryState(this.context.storage.projectRoot).head !== inspection.base_head) fail(ERROR_CODES.COMMIT_ALL_STALE_PLAN, "Git HEAD no longer matches the confirmed commit-all plan", { expected_head: inspection.base_head });
321
+ const patchHash = (value) => createHash("sha256").update(value).digest("hex");
322
+ const duplicate = this.projectionRecords(workspace).filter((candidate) => ["draft", "ready"].includes(candidate.status)
323
+ && candidate.strategy === "integration" && candidate.base_head === inspection.base_head
324
+ && candidate.message === inspection.message && JSON.stringify(candidate.related_stages || []) === JSON.stringify(inspection.contributing_stages.map((item) => item.stage)))
325
+ .find((candidate) => {
326
+ try { return patchHash(this.read(candidate.candidate, workspace, true).patch) === inspection.verification.patch_fingerprint; } catch { return false; }
327
+ });
328
+ const allowStandard = { allowStandard: true };
329
+ let candidate = duplicate || this.create(workspace, inspection.message.split("\n", 1)[0], inspection.message, { ...allowStandard, strategy: "integration", relatedStages: inspection.contributing_stages.map((item) => item.stage) });
330
+ if (candidate.base_head !== inspection.base_head) fail(ERROR_CODES.COMMIT_ALL_STALE_PLAN, "Git HEAD changed while constructing the confirmed commit-all candidate", { expected_head: inspection.base_head, actual_head: candidate.base_head });
331
+ if (!duplicate) candidate = this.capture(workspace, candidate.candidate, { paths: inspection.included_paths }, allowStandard);
332
+ const preview = this.preview(workspace, candidate.candidate, allowStandard).preview;
333
+ if (patchHash(preview.patch) !== inspection.verification.patch_fingerprint) fail(ERROR_CODES.COMMIT_ALL_VERIFICATION_FAILED, "Candidate preview does not match the confirmed commit-all patch");
334
+ if (candidate.status === "draft") candidate = this.setStatus(workspace, candidate.candidate, "ready", allowStandard);
335
+ const committed = this.commit(workspace, candidate.candidate, undefined, { ...allowStandard, expectedHead: inspection.base_head, afterUpdateRef: options.afterUpdateRef });
336
+ const { patch, ...audit } = inspection;
337
+ return { ...audit, candidate: committed.candidate, candidate_reused: Boolean(duplicate), commit: { sha: committed.commit_hash, branch: committed.branch, previous_head: committed.previous_head } };
338
+ }
232
339
  }