opencode-work-context 0.11.2 → 0.12.0

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.
@@ -1,62 +1,67 @@
1
- import fs from "node:fs";
2
1
  import path from "node:path";
2
+ import {
3
+ CAPABILITY_DEPTHS,
4
+ CONFIG_FILE_NAME,
5
+ assertValidMappings,
6
+ configureGlobal,
7
+ configureProject,
8
+ globalConfigPath,
9
+ projectConfigPath,
10
+ readConfigFile,
11
+ readProfiles,
12
+ resetConfigFile,
13
+ resetGlobal,
14
+ resetProject,
15
+ resolveDepth,
16
+ writeConfigFile,
17
+ } from "opencode-capability-profiles";
3
18
 
4
19
  export const CAPABILITY_PROFILES = Object.freeze(["routine", "implementation", "architecture", "security", "review"]);
5
- export const CAPABILITY_DEPTHS = Object.freeze(["light", "standard", "deep"]);
20
+ export { CAPABILITY_DEPTHS };
6
21
  export const CAPABILITY_CLASSIFICATIONS = Object.freeze(["inferred", "explicit"]);
7
22
  export const CAPABILITY_PROFILE_MODES = Object.freeze(["advisory", "off"]);
8
- export const CAPABILITY_MAPPINGS_FILE = "capability-profiles.json";
9
- const MAX_MAPPING_BYTES = 16 * 1024;
10
- const MAX_WARNINGS = 5;
23
+ export const CAPABILITY_MAPPINGS_FILE = CONFIG_FILE_NAME;
11
24
 
12
25
  export const capabilityProfileMode = (storage) => storage.config.capability_profiles?.mode || "advisory";
13
26
 
14
- const warning = (message) => ({ code: "INVALID_CAPABILITY_MAPPING", message });
15
- const validTarget = (value) => typeof value === "string"
16
- && value.length <= 200
17
- && value.trim() === value
18
- && value.length > 0
19
- && !/[\u0000-\u001f\u007f]/.test(value);
27
+ const legacyWarning = (file) => ({
28
+ code: "LEGACY_CAPABILITY_MAPPING",
29
+ message: `Legacy capability mappings detected at ${file}; migrate them to the shared global or project configuration.`,
30
+ path: file,
31
+ });
20
32
 
21
- export function readCapabilityMappings(storage) {
22
- const file = path.join(storage.personalRoot, CAPABILITY_MAPPINGS_FILE);
23
- if (!fs.existsSync(file)) return { mappings: {}, warnings: [] };
24
- try {
25
- const stat = fs.lstatSync(file);
26
- if (!stat.isFile() || stat.size > MAX_MAPPING_BYTES) return { mappings: {}, warnings: [warning(`Ignoring ${CAPABILITY_MAPPINGS_FILE}; expected a regular file no larger than ${MAX_MAPPING_BYTES} bytes.`)] };
27
- } catch { return { mappings: {}, warnings: [warning(`Cannot inspect ${CAPABILITY_MAPPINGS_FILE}; continuing without local mappings.`)] }; }
28
- let input;
29
- try { input = JSON.parse(fs.readFileSync(file, "utf8")); }
30
- catch { return { mappings: {}, warnings: [warning(`Invalid ${CAPABILITY_MAPPINGS_FILE}; expected JSON with schema and mappings.`)] }; }
31
-
32
- if (!input || typeof input !== "object" || Array.isArray(input) || input.schema !== 1 || !input.mappings || typeof input.mappings !== "object" || Array.isArray(input.mappings)) {
33
- return { mappings: {}, warnings: [warning(`Invalid ${CAPABILITY_MAPPINGS_FILE}; expected { "schema": 1, "mappings": { ... } }.`)] };
34
- }
35
- const warnings = [];
36
- const addWarning = (message) => { if (warnings.length < MAX_WARNINGS) warnings.push(warning(message)); };
37
- if (Object.keys(input).some((key) => !["schema", "mappings"].includes(key))) addWarning(`Ignoring unknown top-level keys in ${CAPABILITY_MAPPINGS_FILE}.`);
38
- const mappings = {};
39
- for (const [depth, target] of Object.entries(input.mappings)) {
40
- const safeDepth = depth.replace(/[\u0000-\u001f\u007f]/g, "?").slice(0, 40);
41
- if (!CAPABILITY_DEPTHS.includes(depth)) addWarning(`Ignoring unknown capability depth mapping: ${safeDepth}.`);
42
- else if (!validTarget(target)) addWarning(`Ignoring invalid target for capability depth mapping: ${depth}.`);
43
- else mappings[depth] = target;
44
- }
45
- return { mappings, warnings };
33
+ export function readCapabilityMappings(storage, options = {}) {
34
+ const profiles = readProfiles({
35
+ projectRoot: storage.projectRoot,
36
+ ...(options.homeDir ? { homeDir: options.homeDir } : {}),
37
+ });
38
+ const legacyFile = path.join(storage.personalRoot, CAPABILITY_MAPPINGS_FILE);
39
+ const legacy = readConfigFile(legacyFile);
40
+ return {
41
+ mappings: { ...legacy.mappings, ...profiles.global.mappings, ...(profiles.project?.mappings || {}) },
42
+ warnings: [
43
+ ...profiles.warnings,
44
+ ...legacy.warnings,
45
+ ...(legacy.exists && legacy.warnings.length === 0 ? [legacyWarning(legacyFile)] : []),
46
+ ],
47
+ global: profiles.global,
48
+ project: profiles.project,
49
+ legacy,
50
+ };
46
51
  }
47
52
 
48
53
  export function capabilityRecommendations(storage, stage, localMappings) {
49
54
  if (capabilityProfileMode(storage) === "off") return null;
50
55
  if (!stage.execution_profile || !stage.execution_depth) return null;
51
- const { mappings, warnings } = localMappings || readCapabilityMappings(storage);
52
- const target = mappings[stage.execution_depth];
56
+ const loaded = localMappings || readCapabilityMappings(storage);
57
+ const resolution = resolveDepth({ depth: stage.execution_depth, projectMappings: loaded.mappings });
53
58
  return {
54
59
  mode: "advisory",
55
- execution: target
56
- ? { profile: stage.execution_profile, depth: stage.execution_depth, classification: stage.execution_classification || "explicit", source: "mapping", target }
60
+ execution: resolution.target
61
+ ? { profile: stage.execution_profile, depth: stage.execution_depth, classification: stage.execution_classification || "explicit", source: "mapping", target: resolution.target }
57
62
  : { profile: stage.execution_profile, depth: stage.execution_depth, classification: stage.execution_classification || "explicit", source: "current", message: "No mapping configured; continuing with the current model." },
58
63
  ...(stage.review_profile ? { review: { profile: stage.review_profile } } : {}),
59
- ...(warnings.length ? { warnings } : {}),
64
+ ...(loaded.warnings.length ? { warnings: loaded.warnings } : {}),
60
65
  };
61
66
  }
62
67
 
@@ -73,6 +78,33 @@ export const stageCapabilityProfiles = (storage, stage, localMappings) => {
73
78
  };
74
79
 
75
80
  export function validateCapabilityMappings(mappings) {
76
- if (!mappings || typeof mappings !== "object" || Array.isArray(mappings) || Object.keys(mappings).some((key) => !CAPABILITY_DEPTHS.includes(key))) return false;
77
- return Object.values(mappings).every(validTarget);
81
+ try {
82
+ assertValidMappings(mappings);
83
+ return true;
84
+ } catch {
85
+ return false;
86
+ }
87
+ }
88
+
89
+ export function configureCapabilityMappings(storage, mappings, options = {}) {
90
+ if (options.scope === "global") {
91
+ configureGlobal(mappings, options.homeDir ? { homeDir: options.homeDir } : {});
92
+ return globalConfigPath(options.homeDir);
93
+ }
94
+ if (options.scope === "project") {
95
+ configureProject(storage.projectRoot, mappings);
96
+ return projectConfigPath(storage.projectRoot);
97
+ }
98
+ const legacyFile = path.join(storage.personalRoot, CAPABILITY_MAPPINGS_FILE);
99
+ writeConfigFile(legacyFile, mappings, { mode: 0o600 });
100
+ return legacyFile;
101
+ }
102
+
103
+ export function resetCapabilityMappings(storage, options = {}) {
104
+ if (options.scope === "global") {
105
+ return { removed: resetGlobal(options.homeDir ? { homeDir: options.homeDir } : {}), file: globalConfigPath(options.homeDir) };
106
+ }
107
+ if (options.scope === "project") return { removed: resetProject(storage.projectRoot), file: projectConfigPath(storage.projectRoot) };
108
+ const legacyFile = path.join(storage.personalRoot, CAPABILITY_MAPPINGS_FILE);
109
+ return { removed: resetConfigFile(legacyFile), file: legacyFile };
78
110
  }
package/src/core.js CHANGED
@@ -11,9 +11,10 @@ import { isDependencySatisfied } from "./stage-status.js";
11
11
  import { CandidateStore } from "./candidates.js";
12
12
  import { DeliveryStore } from "./delivery.js";
13
13
  import { doctorDelivery as runDeliveryDoctor } from "./delivery-doctor.js";
14
- import { applyExecutionPatch, assertExecutionSize, executionState, normalizeExecutionState } from "./stage-execution.js";
15
- import { CAPABILITY_CLASSIFICATIONS, CAPABILITY_DEPTHS, CAPABILITY_MAPPINGS_FILE, CAPABILITY_PROFILES, capabilityProfileMode, capabilityRecommendations, readCapabilityMappings, validateCapabilityMappings } from "./capability-profiles.js";
14
+ import { applyExecutionItemPatch, applyExecutionTextPatchItems, assertExecutionSize, EXECUTION_SECTIONS, executionInputUsesItems, executionItems, executionItemsFromState, executionPatchUsesItems, executionReadModel, normalizeExecutionItemState, normalizeExecutionState } from "./stage-execution.js";
15
+ import { CAPABILITY_CLASSIFICATIONS, CAPABILITY_DEPTHS, CAPABILITY_PROFILES, capabilityProfileMode, capabilityRecommendations, configureCapabilityMappings, readCapabilityMappings, resetCapabilityMappings, validateCapabilityMappings } from "./capability-profiles.js";
16
16
  import { acknowledgeGitCommit, initializeGitCheckpoint } from "./git-acknowledgement.js";
17
+ import { rollbackCommitRef } from "./git-candidates.js";
17
18
 
18
19
  const actor = (options) => options.actor || "OpenCode";
19
20
  const workspaceMode = (data) => data.mode || "standard";
@@ -65,7 +66,15 @@ const resumePresentationInstruction = ({ confirmationRequired }) => `Before doin
65
66
  - Mention previous progress only when presentation.previous_result or presentation.previous_session_summary contains useful information.
66
67
  - State the immediate next action in one sentence.
67
68
  ${confirmationRequired ? "- Ask for the explicitly required confirmation and wait before inspecting or changing application code." : "- Then continue with the work immediately. Do not ask for generic confirmation; ask a focused question only when an unresolved decision genuinely blocks progress."}`;
68
- const executionInstruction = (record) => record ? `\n\nCurrent stage execution state:\n${JSON.stringify(record, null, 2)}\nTreat this bounded stage-local ledger as the current operational checkpoint. Update it after meaningful scope changes, decisions, substantial work, blockers, or verification changes, and before handoff; do not update it for trivial tool calls.` : "";
69
+ const executionInstruction = (record) => {
70
+ if (!record) return "";
71
+ const execution = executionReadModel(record);
72
+ const current = execution.current ? `\nCurrent checklist item: ${execution.current.text}` : "\nCurrent checklist item: none";
73
+ const queued = execution.queued.length
74
+ ? `\nQueued checklist items: ${execution.queued.map((item) => item.text).join(" | ")}`
75
+ : "\nQueued checklist items: none";
76
+ return `\n\nCurrent stage execution state:${current}${queued}\n${JSON.stringify(execution, null, 2)}\nTreat this bounded stage-local ledger as the current operational checkpoint. Work only on the Current checklist item by default. Do not combine Queued items into the same change set unless the user explicitly asks. Update it after meaningful scope changes, decisions, substantial work, blockers, or verification changes, and before handoff; do not update it for trivial tool calls.`;
77
+ };
69
78
  const deliveryPlanningInstruction = `\n\nDelivery planning policy:\n- When the user asks how to deploy, treat this as workspace-level delivery planning across all relevant committed changes, not as ownership by the current stage.\n- Inspect the exact commit range and the repository's own deployment documentation, scripts, infrastructure, migrations, container definitions, configuration examples, and CI before proposing commands.\n- Produce an ordered plan covering prerequisites, deployment, verification, rollback, and unresolved blockers. Ask one focused question when the target environment or baseline is genuinely ambiguous.\n- Never persist secret values. Mention only required secret or configuration names.\n- Never mark delivery from a successful commit or push alone. Use explicit delivery confirmation only after the user confirms that the target environment was updated successfully.`;
70
79
  const assertNoSymlinkPath = (file) => { let current = path.parse(file).root; for (const part of file.slice(current.length).split(path.sep).filter(Boolean)) { current = path.join(current, part); try { if (fs.lstatSync(current).isSymbolicLink()) fail(ERROR_CODES.STORAGE_ERROR, `Symlink path component is not supported: ${current}`); } catch (error) { if (error.code !== "ENOENT") throw error; break; } } };
71
80
 
@@ -342,6 +351,30 @@ export class WorkContext {
342
351
  ), { session: this.options.sessionId, owner: actor(this.options) });
343
352
  }
344
353
 
354
+ inspectCommitAll(workspace, options = {}) { return { ok: true, data: this.candidates().inspectAll(workspace, options) }; }
355
+
356
+ commitAll(workspace, expectedFingerprint, confirmation, options = {}) {
357
+ this.storage.assertSafeRoots();
358
+ return withLock(this.storage.lockPath("candidate-git"), () => {
359
+ let publication;
360
+ try {
361
+ return this.transact("commit-all", () => this.result(this.candidates().commitAll(workspace, expectedFingerprint, confirmation, {
362
+ ...options,
363
+ afterUpdateRef: (published) => { publication = published; options.afterUpdateRef?.(published); },
364
+ }), ["local:candidates"]));
365
+ } catch (error) {
366
+ if (publication) {
367
+ try { rollbackCommitRef(this.storage.projectRoot, publication); }
368
+ catch (rollbackError) {
369
+ this.candidates().write(publication.candidate_record, publication.patch);
370
+ throw rollbackError;
371
+ }
372
+ }
373
+ throw error;
374
+ }
375
+ }, { session: this.options.sessionId, owner: actor(this.options) });
376
+ }
377
+
345
378
  readDelivery(workspace, options = {}) { return { ok: true, data: this.deliveries().readContext(workspace, options) }; }
346
379
 
347
380
  explainDelivery(workspace, from, to, findings = []) {
@@ -409,7 +442,7 @@ export class WorkContext {
409
442
  const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
410
443
  const execution = this.storage.readStageExecution(workspace, stage);
411
444
  const automaticFinish = automaticFinishAllowed(this.storage, workspace);
412
- const recommendations = capabilityRecommendations(this.storage, stageRecord.data);
445
+ const recommendations = capabilityRecommendations(this.storage, stageRecord.data, readCapabilityMappings(this.storage, { homeDir: this.options.capabilityProfilesHome }));
413
446
  return this.result({
414
447
  workspace,
415
448
  stage,
@@ -431,7 +464,7 @@ export class WorkContext {
431
464
  scope: stageRecord.data.prompt || null,
432
465
  previous_result: previousResult,
433
466
  previous_session_summary: previousSessionSummary,
434
- ...(execution ? { execution_state: execution } : {}),
467
+ ...(execution ? { execution_state: executionReadModel(execution) } : {}),
435
468
  ...(recommendations ? { capability_profiles: recommendations } : {}),
436
469
  },
437
470
  context: {
@@ -439,7 +472,7 @@ export class WorkContext {
439
472
  previous: previousSessionSummary || previousResult || "No previous progress was recorded.",
440
473
  now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
441
474
  workspace_knowledge: workspaceKnowledge,
442
- ...(execution ? { execution_state: execution } : {}),
475
+ ...(execution ? { execution_state: executionReadModel(execution) } : {}),
443
476
  ...(recommendations ? { capability_profiles: recommendations } : {}),
444
477
  ...(pendingCandidates ? { pending_candidates: pendingCandidates } : {}),
445
478
  ...(hasDeliveryContext ? { delivery_context: deliveryContext } : {}),
@@ -562,8 +595,8 @@ export class WorkContext {
562
595
  }
563
596
 
564
597
  showCapabilityProfiles() {
565
- const local = readCapabilityMappings(this.storage);
566
- return this.result({ mode: capabilityProfileMode(this.storage), mappings: local.mappings, warnings: local.warnings }, []);
598
+ const local = readCapabilityMappings(this.storage, { homeDir: this.options.capabilityProfilesHome });
599
+ return this.result({ mode: capabilityProfileMode(this.storage), mappings: local.mappings, global: local.global.mappings, project: local.project?.mappings || {}, legacy: local.legacy.mappings, warnings: local.warnings }, []);
567
600
  }
568
601
 
569
602
  configureCapabilityProfiles(options = {}) {
@@ -575,13 +608,7 @@ export class WorkContext {
575
608
  this.storage.assertNoSymlinks();
576
609
  const changed = [];
577
610
  const configFile = path.join(this.storage.projectRoot, ".work-context", "config.yaml");
578
- const mappingFile = path.join(this.storage.personalRoot, CAPABILITY_MAPPINGS_FILE);
579
611
  const previousConfig = fs.readFileSync(configFile);
580
- let previousMapping = null;
581
- if (fs.existsSync(mappingFile)) {
582
- if (!fs.lstatSync(mappingFile).isFile()) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${CAPABILITY_MAPPINGS_FILE} path`);
583
- previousMapping = fs.readFileSync(mappingFile);
584
- }
585
612
  try {
586
613
  if (options.mode !== undefined && options.mode !== capabilityProfileMode(this.storage)) {
587
614
  const current = fs.readFileSync(configFile, "utf8");
@@ -593,30 +620,25 @@ export class WorkContext {
593
620
  changed.push(configFile);
594
621
  }
595
622
  if (options.mappings !== undefined) {
596
- atomicWrite(mappingFile, `${JSON.stringify({ schema: 1, mappings: options.mappings }, null, 2)}\n`);
623
+ const mappingFile = configureCapabilityMappings(this.storage, options.mappings, { scope: options.scope, homeDir: this.options.capabilityProfilesHome });
597
624
  changed.push(mappingFile);
598
625
  }
599
626
  } catch (error) {
600
627
  try { atomicWrite(configFile, previousConfig.toString("utf8")); } catch {}
601
- try {
602
- if (previousMapping) atomicWrite(mappingFile, previousMapping.toString("utf8"));
603
- else fs.rmSync(mappingFile, { force: true });
604
- } catch {}
605
628
  throw error;
606
629
  }
607
630
  if (options.mode !== undefined) this.storage.config.capability_profiles.mode = options.mode;
608
- const local = readCapabilityMappings(this.storage);
609
- return this.result({ mode: capabilityProfileMode(this.storage), mappings: local.mappings, warnings: local.warnings }, changed);
631
+ const local = readCapabilityMappings(this.storage, { homeDir: this.options.capabilityProfilesHome });
632
+ return this.result({ mode: capabilityProfileMode(this.storage), mappings: local.mappings, global: local.global.mappings, project: local.project?.mappings || {}, legacy: local.legacy.mappings, warnings: local.warnings }, changed);
610
633
  }, { owner: actor(this.options), session: this.options.sessionId || null });
611
634
  }
612
635
 
613
- resetCapabilityProfiles(confirmation) {
636
+ resetCapabilityProfiles(confirmation, options = {}) {
614
637
  if (confirmation !== "RESET_PROFILES") fail(ERROR_CODES.CONFIRMATION_REQUIRED, "Reset requires RESET_PROFILES confirmation");
615
638
  return this.transact("capability-profiles", () => {
616
- const file = path.join(this.storage.personalRoot, CAPABILITY_MAPPINGS_FILE);
617
- const existed = fs.existsSync(file);
618
- if (existed) fs.rmSync(file);
619
- return this.result({ mode: capabilityProfileMode(this.storage), mappings: {} }, existed ? [file] : []);
639
+ const reset = resetCapabilityMappings(this.storage, { scope: options.scope, homeDir: this.options.capabilityProfilesHome });
640
+ const local = readCapabilityMappings(this.storage, { homeDir: this.options.capabilityProfilesHome });
641
+ return this.result({ mode: capabilityProfileMode(this.storage), mappings: local.mappings, global: local.global.mappings, project: local.project?.mappings || {}, legacy: local.legacy.mappings, warnings: local.warnings }, reset.removed ? [reset.file] : []);
620
642
  });
621
643
  }
622
644
 
@@ -695,14 +717,13 @@ export class WorkContext {
695
717
  this.storage.assertNoSymlinks();
696
718
  this.storage.readStage(workspace, stage);
697
719
  const record = this.storage.readStageExecution(workspace, stage);
698
- return { ok: true, data: record || { schema: 1, workspace, stage, revision: 0, exists: false, ...normalizeExecutionState({}) } };
720
+ return { ok: true, data: record ? executionReadModel(record) : { schema: 1, workspace, stage, revision: 0, exists: false, ...normalizeExecutionState({}), items: Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, []])), current: null, queued: [] } };
699
721
  }
700
722
 
701
723
  replaceStageExecution(workspace, stage, sessionId, expectedRevision, input) {
702
724
  workspace = normalizeWorkspaceId(workspace);
703
725
  stage = normalizeStageId(stage);
704
726
  if (!Number.isInteger(expectedRevision) || expectedRevision < 0) fail(ERROR_CODES.INVALID_ARGUMENT, "expectedRevision must be a non-negative integer");
705
- const state = normalizeExecutionState(input);
706
727
  return this.transact(`stage-execution-${workspace}-${stage}`, () => {
707
728
  const stageRecord = this.storage.readStage(workspace, stage);
708
729
  if (!["planned", "in_progress"].includes(stageRecord.data.status)) fail(ERROR_CODES.INVALID_STATE, "Execution state can only change for an actionable stage", { status: stageRecord.data.status });
@@ -710,12 +731,15 @@ export class WorkContext {
710
731
  const current = this.storage.readStageExecution(workspace, stage);
711
732
  const revision = current?.revision || 0;
712
733
  if (revision !== expectedRevision) fail(ERROR_CODES.EXECUTION_REVISION_CONFLICT, "Stage execution state changed since it was read", { expectedRevision, actualRevision: revision });
713
- if (current && JSON.stringify(executionState(current)) === JSON.stringify(state)) return this.result(current, []);
734
+ const structured = executionInputUsesItems(input);
735
+ const state = structured ? null : normalizeExecutionState(input);
736
+ const items = structured ? normalizeExecutionItemState(input, current) : executionItemsFromState(state, current);
737
+ if (current && JSON.stringify(executionItems(current)) === JSON.stringify(items)) return this.result(executionReadModel(current), []);
714
738
  const timestamp = new Date().toISOString();
715
- const record = { schema: 1, workspace, stage, revision: revision + 1, created_at: current?.created_at || timestamp, updated_at: timestamp, updated_by: actor(this.options), ...state };
739
+ const record = { schema: 2, workspace, stage, revision: revision + 1, created_at: current?.created_at || timestamp, updated_at: timestamp, updated_by: actor(this.options), items };
716
740
  assertExecutionSize(record);
717
741
  this.storage.writeStageExecution(workspace, stage, record);
718
- return this.result(record, [this.storage.stageExecutionFile(workspace, stage)]);
742
+ return this.result(executionReadModel(record), [this.storage.stageExecutionFile(workspace, stage)]);
719
743
  });
720
744
  }
721
745
 
@@ -730,13 +754,39 @@ export class WorkContext {
730
754
  const current = this.storage.readStageExecution(workspace, stage);
731
755
  const revision = current?.revision || 0;
732
756
  if (revision !== expectedRevision) fail(ERROR_CODES.EXECUTION_REVISION_CONFLICT, "Stage execution state changed since it was read", { expectedRevision, actualRevision: revision });
733
- const state = applyExecutionPatch(current ? executionState(current) : normalizeExecutionState({}), patch);
734
- if (current && JSON.stringify(executionState(current)) === JSON.stringify(state)) return this.result(current, []);
757
+ const structured = executionPatchUsesItems(patch);
758
+ const empty = { schema: 2, items: Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, []])) };
759
+ const items = structured ? applyExecutionItemPatch(current || empty, patch) : applyExecutionTextPatchItems(current || empty, patch);
760
+ if (current && JSON.stringify(executionItems(current)) === JSON.stringify(items)) return this.result(executionReadModel(current), []);
761
+ const timestamp = new Date().toISOString();
762
+ const record = { schema: 2, workspace, stage, revision: revision + 1, created_at: current?.created_at || timestamp, updated_at: timestamp, updated_by: actor(this.options), items };
763
+ assertExecutionSize(record);
764
+ this.storage.writeStageExecution(workspace, stage, record);
765
+ return this.result(executionReadModel(record), [this.storage.stageExecutionFile(workspace, stage)]);
766
+ });
767
+ }
768
+
769
+ completeCurrentExecution(workspace, stage, sessionId, expectedRevision) {
770
+ workspace = normalizeWorkspaceId(workspace);
771
+ stage = normalizeStageId(stage);
772
+ if (!Number.isInteger(expectedRevision) || expectedRevision < 0) fail(ERROR_CODES.INVALID_ARGUMENT, "expectedRevision must be a non-negative integer");
773
+ return this.transact(`stage-execution-${workspace}-${stage}`, () => {
774
+ const stageRecord = this.storage.readStage(workspace, stage);
775
+ if (!["planned", "in_progress"].includes(stageRecord.data.status)) fail(ERROR_CODES.INVALID_STATE, "Execution state can only change for an actionable stage", { status: stageRecord.data.status });
776
+ assertActive(this.storage.readEvents(), workspace, stage, sessionId);
777
+ const current = this.storage.readStageExecution(workspace, stage);
778
+ const revision = current?.revision || 0;
779
+ if (revision !== expectedRevision) fail(ERROR_CODES.EXECUTION_REVISION_CONFLICT, "Stage execution state changed since it was read", { expectedRevision, actualRevision: revision });
780
+ const items = current && executionItems(current);
781
+ const currentItem = items?.remaining.shift();
782
+ if (!currentItem) fail(ERROR_CODES.INVALID_STATE, "No current execution item to complete");
783
+ items.completed.push(currentItem);
784
+ const nextItems = normalizeExecutionItemState(items, current);
735
785
  const timestamp = new Date().toISOString();
736
- const record = { schema: 1, workspace, stage, revision: revision + 1, created_at: current?.created_at || timestamp, updated_at: timestamp, updated_by: actor(this.options), ...state };
786
+ const record = { schema: 2, workspace, stage, revision: revision + 1, created_at: current.created_at, updated_at: timestamp, updated_by: actor(this.options), items: nextItems };
737
787
  assertExecutionSize(record);
738
788
  this.storage.writeStageExecution(workspace, stage, record);
739
- return this.result(record, [this.storage.stageExecutionFile(workspace, stage)]);
789
+ return this.result(executionReadModel(record), [this.storage.stageExecutionFile(workspace, stage)]);
740
790
  });
741
791
  }
742
792
 
@@ -968,10 +1018,11 @@ export class WorkContext {
968
1018
  if (!['auto', 'added', 'none'].includes(knowledgeReview)) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge review must be 'auto', 'added' or 'none'");
969
1019
  const knowledgeEntries = this.listKnowledge(workspace).data;
970
1020
  const execution = this.storage.readStageExecution(workspace, stage);
971
- const executionWarnings = execution ? [
972
- ...(execution.remaining.length ? [`${execution.remaining.length} remaining item(s)`] : []),
973
- ...(execution.blockers.length ? [`${execution.blockers.length} blocker(s) or open question(s)`] : []),
974
- ...(execution.verification.length ? [`${execution.verification.length} pending verification item(s)`] : []),
1021
+ const executionData = execution ? executionReadModel(execution) : null;
1022
+ const executionWarnings = executionData ? [
1023
+ ...(executionData.remaining.length ? [`${executionData.remaining.length} remaining item(s)`] : []),
1024
+ ...(executionData.blockers.length ? [`${executionData.blockers.length} blocker(s) or open question(s)`] : []),
1025
+ ...(executionData.verification.length ? [`${executionData.verification.length} pending verification item(s)`] : []),
975
1026
  ] : [];
976
1027
  const active = activeSession(events, workspace, stage);
977
1028
  if (!active || active.session_id !== sessionId) fail(active ? ERROR_CODES.ACTIVE_SESSION_EXISTS : ERROR_CODES.SESSION_NOT_ACTIVE, active ? "Another active session owns this stage" : "Session is not active");
@@ -983,7 +1034,7 @@ export class WorkContext {
983
1034
  const promptReview = this.listStages(workspace).data.stages
984
1035
  .filter((item) => Number(item.stage) > Number(stage) && !["completed", "archived"].includes(item.status))
985
1036
  .map(({ stage: id, title, description, prompt, status }) => ({ stage: id, title, description, prompt: prompt || null, status }));
986
- const data = { session_id: sessionId, workspace, stage, state: "closed", status: "completed", next_stage_started: false, knowledge_review: knowledgeReview, knowledge_entries: knowledgeEntries.length, active_knowledge_entries: activeKnowledge(knowledgeEntries).length, prompt_review: promptReview, ...(execution ? { execution_state: execution, execution_warnings: executionWarnings } : {}) };
1037
+ const data = { session_id: sessionId, workspace, stage, state: "closed", status: "completed", next_stage_started: false, knowledge_review: knowledgeReview, knowledge_entries: knowledgeEntries.length, active_knowledge_entries: activeKnowledge(knowledgeEntries).length, prompt_review: promptReview, ...(executionData ? { execution_state: executionData, execution_warnings: executionWarnings } : {}) };
987
1038
  const incompleteStages = this.listStages(workspace).data.stages.filter((item) => !["completed", "archived"].includes(item.status));
988
1039
  const next = incompleteStages.length ? null : {
989
1040
  action: "workspace_finish",
@@ -998,7 +1049,7 @@ export class WorkContext {
998
1049
  help(command = "") {
999
1050
  return this.result({
1000
1051
  command,
1001
- syntax: "/wc [create|list|workspace list|workspace rename|workspace mode|candidate create|candidate capture|candidate preview|candidate show|candidate list|candidate ready|candidate commit|candidate discard|delivery read|delivery explain|delivery doctor|delivery mark|profiles show|profiles setup|profiles reset|workspace finish|workspace reopen|resume|stage add|stage profiles|stage profiles refresh|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage execution read|stage execution replace|stage execution update|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|unlink-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
1052
+ syntax: "/wc [create|list|workspace list|workspace rename|workspace mode|candidate create|candidate capture|candidate preview|candidate show|candidate list|candidate ready|candidate commit|candidate discard|commit all|commit all confirm|delivery read|delivery explain|delivery doctor|delivery mark|profiles show|profiles setup|profiles reset|workspace finish|workspace reopen|resume|stage add|stage profiles|stage profiles refresh|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage execution read|stage execution replace|stage execution update|stage execution complete-current|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|unlink-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
1002
1053
  note: "execution recommendations combine a vendor-neutral capability with light, standard, or deep depth; Planning agents infer missing values before stage creation, ordinary refresh updates missing/inferred classifications while preserving explicit assignments, and local depth mappings resolve only an advisory model label; profiles setup gathers mode and mappings through questions, off mode suppresses presentation and resolution, and no profile operation changes a model, agent, reviewer, or session; delivery context is workspace-level local operational state; exact Git range inspection runs only for explicit immutable hashes; stage execution state is a bounded stage-local operational checkpoint; associated startup sessions receive the shared-worktree candidate policy; stage finish requires an explicit user lifecycle request unless Planning contains AUTO_STAGE_FINISH: allowed; recovery operations preserve lifecycle history.",
1003
1054
  }, []);
1004
1055
  }
package/src/errors.js CHANGED
@@ -13,6 +13,9 @@ export const ERROR_CODES = Object.freeze({
13
13
  CANDIDATE_UNSUPPORTED: "CANDIDATE_UNSUPPORTED", CANDIDATE_STALE_BASE: "CANDIDATE_STALE_BASE",
14
14
  CANDIDATE_CONFLICT: "CANDIDATE_CONFLICT", CANDIDATE_DETACHED_HEAD: "CANDIDATE_DETACHED_HEAD",
15
15
  CANDIDATE_REF_RACE: "CANDIDATE_REF_RACE", CANDIDATE_COMMIT_FAILED: "CANDIDATE_COMMIT_FAILED",
16
+ COMMIT_ALL_CONFIRMATION_REQUIRED: "COMMIT_ALL_CONFIRMATION_REQUIRED", COMMIT_ALL_NO_CHANGES: "COMMIT_ALL_NO_CHANGES",
17
+ COMMIT_ALL_UNSAFE_STATE: "COMMIT_ALL_UNSAFE_STATE", COMMIT_ALL_INCOHERENT_BOUNDARY: "COMMIT_ALL_INCOHERENT_BOUNDARY",
18
+ COMMIT_ALL_STALE_PLAN: "COMMIT_ALL_STALE_PLAN", COMMIT_ALL_VERIFICATION_FAILED: "COMMIT_ALL_VERIFICATION_FAILED",
16
19
  EXECUTION_REVISION_CONFLICT: "EXECUTION_REVISION_CONFLICT", EXECUTION_LIMIT_EXCEEDED: "EXECUTION_LIMIT_EXCEEDED",
17
20
  DELIVERY_INVALID_RANGE: "DELIVERY_INVALID_RANGE", DELIVERY_RANGE_TOO_LARGE: "DELIVERY_RANGE_TOO_LARGE",
18
21
  DELIVERY_INVALID_FINDINGS: "DELIVERY_INVALID_FINDINGS", DELIVERY_DIAGNOSTIC_TOO_LARGE: "DELIVERY_DIAGNOSTIC_TOO_LARGE",
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
+ import { createHash } from "node:crypto";
4
5
  import { spawnSync } from "node:child_process";
5
6
  import { ERROR_CODES, fail } from "./errors.js";
6
7
 
@@ -119,6 +120,104 @@ const patchFromIndex = (root, base, env) => {
119
120
  return result.stdout;
120
121
  };
121
122
 
123
+ const nulPaths = (value) => value.toString("utf8").split("\0").filter(Boolean);
124
+ const unsafeName = (relative) => {
125
+ const parts = relative.split("/");
126
+ const name = parts.at(-1).toLowerCase();
127
+ if (parts.some((part) => ["node_modules", "coverage", ".cache", ".next", ".nuxt", ".output", "vendor"].includes(part))
128
+ || ["dist", "build", "tmp"].includes(parts[0]) || /\.(?:log|tmp|swp)$/.test(name)) return "generated_or_local";
129
+ if (relative === ".work-context/local" || relative.startsWith(".work-context/local/")) return "local_only";
130
+ if (name === ".env" || name.startsWith(".env.") || /(?:^|[._-])(secret|secrets|credential|credentials|private)(?:[._-]|$)/.test(name)
131
+ || /\.(?:pem|key|p12|pfx)$/i.test(name) || ["id_rsa", "id_ed25519"].includes(name)) return "potential_secret";
132
+ return null;
133
+ };
134
+
135
+ const secretContent = (root, relative) => {
136
+ const absolute = path.join(root, relative);
137
+ let stat;
138
+ try { stat = fs.statSync(absolute); } catch (error) { if (error.code === "ENOENT") return false; throw error; }
139
+ if (!stat.isFile() || stat.size > 1024 * 1024) return false;
140
+ const content = fs.readFileSync(absolute);
141
+ if (content.includes(0)) return false;
142
+ const text = content.toString("utf8");
143
+ return /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(text)
144
+ || /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/.test(text)
145
+ || /\b(?:ghp|github_pat|glpat)-?[A-Za-z0-9_]{20,}\b/.test(text)
146
+ || /(?:api[_-]?key|access[_-]?token|client[_-]?secret|password)\s*[:=]\s*["']?(?!example|placeholder|changeme)[A-Za-z0-9_+/.=-]{12,}/i.test(text);
147
+ };
148
+
149
+ function nestedRepository(root, relative) {
150
+ let absolute = path.join(root, relative);
151
+ while (absolute !== root) {
152
+ if (fs.existsSync(absolute) && fs.statSync(absolute).isDirectory()) {
153
+ const result = git(absolute, ["rev-parse", "--show-toplevel"], { allowFailure: true });
154
+ if (result.status === 0 && fs.realpathSync(result.stdout.trim()) !== root) return true;
155
+ }
156
+ absolute = path.dirname(absolute);
157
+ }
158
+ return false;
159
+ }
160
+
161
+ const gitOperation = (root) => {
162
+ const result = git(root, ["rev-parse", "--git-dir"], { allowFailure: true });
163
+ if (result.status !== 0) return "unknown";
164
+ const directory = path.resolve(root, result.stdout.trim());
165
+ return ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "BISECT_LOG", "rebase-apply", "rebase-merge", "sequencer"]
166
+ .find((entry) => fs.existsSync(path.join(directory, entry))) || null;
167
+ };
168
+
169
+ const explicitExclusion = (relative, exclusions) => exclusions.some((item) => relative === item || relative.startsWith(`${item}/`));
170
+
171
+ export function inspectCommitAll(root, personalRoot, options = {}) {
172
+ const repository = repositoryState(root);
173
+ const readOnlyEnv = { GIT_OPTIONAL_LOCKS: "0" };
174
+ const operation = gitOperation(repository.root);
175
+ if (operation) fail(ERROR_CODES.COMMIT_ALL_UNSAFE_STATE, "Commit all is unavailable while another Git operation is in progress", { operation });
176
+ const unmerged = git(repository.root, ["ls-files", "--unmerged", "-z"], { encoding: null, env: readOnlyEnv }).stdout;
177
+ if (unmerged.length) fail(ERROR_CODES.COMMIT_ALL_UNSAFE_STATE, "Commit all is unavailable while the Git index contains unresolved conflicts");
178
+ const explicitExclusions = options.excludePaths?.length ? normalizeCandidatePaths(repository.root, personalRoot, options.excludePaths) : [];
179
+ const changed = nulPaths(git(repository.root, ["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--name-only", "-z", "HEAD", "--"], { encoding: null, env: readOnlyEnv }).stdout);
180
+ const untracked = nulPaths(git(repository.root, ["ls-files", "--others", "--exclude-standard", "-z"], { encoding: null, env: readOnlyEnv }).stdout);
181
+ const gitlinks = new Set(nulPaths(git(repository.root, ["ls-files", "--stage", "-z"], { encoding: null, env: readOnlyEnv }).stdout)
182
+ .filter((entry) => entry.startsWith("160000 ")).map((entry) => entry.slice(entry.indexOf("\t") + 1)));
183
+ const included = [];
184
+ const excluded = [];
185
+ for (const relative of [...new Set([...changed, ...untracked])].sort()) {
186
+ if ([".work-context/.locks", ".work-context/.transactions"].some((item) => relative === item || relative.startsWith(`${item}/`))) continue;
187
+ if (relative === ".work-context/local" || relative.startsWith(".work-context/local/")) {
188
+ excluded.push({ path: relative, reason: "local_only" });
189
+ continue;
190
+ }
191
+ const normalized = normalizeCandidatePaths(repository.root, personalRoot, [relative])[0];
192
+ const reason = explicitExclusion(normalized, explicitExclusions) ? "user_excluded"
193
+ : normalized === ".gitmodules" && gitlinks.size ? "submodule_metadata"
194
+ : gitlinks.has(normalized) || [...gitlinks].some((gitlink) => normalized.startsWith(`${gitlink}/`))
195
+ ? "submodule"
196
+ : nestedRepository(repository.root, normalized) ? "nested_repository" : unsafeName(normalized) || (secretContent(repository.root, normalized) ? "potential_secret" : null);
197
+ if (reason) excluded.push({ path: normalized, reason });
198
+ else included.push(normalized);
199
+ }
200
+ if (!included.length) return { repository_root: repository.root, base_head: repository.head, included_paths: [], excluded_paths: excluded, patch: "", patch_fingerprint: null, stat: "" };
201
+ let captured;
202
+ try { captured = capturePaths(repository.root, personalRoot, repository.head, included); }
203
+ catch (error) {
204
+ if (error.code === ERROR_CODES.CANDIDATE_UNSUPPORTED) fail(ERROR_CODES.COMMIT_ALL_INCOHERENT_BOUNDARY, "Commit-all changes cannot form one supported text patch", { cause: error.message });
205
+ throw error;
206
+ }
207
+ const preview = previewPatch(repository.root, repository.head, captured.patch);
208
+ if (preview.patch !== captured.patch) fail(ERROR_CODES.COMMIT_ALL_VERIFICATION_FAILED, "Commit-all preview did not reproduce the inspected patch");
209
+ return {
210
+ repository_root: repository.root,
211
+ base_head: repository.head,
212
+ included_paths: captured.paths,
213
+ excluded_paths: excluded,
214
+ patch: captured.patch,
215
+ patch_fingerprint: createHash("sha256").update(captured.patch).digest("hex"),
216
+ stat: preview.stat,
217
+ recent_subjects: git(repository.root, ["log", "-5", "--format=%s"], { env: readOnlyEnv }).stdout.trim().split("\n").filter(Boolean),
218
+ };
219
+ }
220
+
122
221
  export function normalizeCandidatePaths(root, personalRoot, values) {
123
222
  if (!Array.isArray(values) || !values.length) fail(ERROR_CODES.INVALID_ARGUMENT, "At least one path is required");
124
223
  const personal = fs.existsSync(personalRoot) ? fs.realpathSync(personalRoot) : path.resolve(personalRoot);
@@ -173,6 +272,7 @@ export function commitPatch(root, base, patchText, message, options = {}) {
173
272
  rejectUnsupportedPatch(patchText);
174
273
  if (typeof message !== "string" || !message.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Commit message is required");
175
274
  const repository = repositoryState(root);
275
+ if (options.expectedHead && repository.head !== options.expectedHead) fail(ERROR_CODES.COMMIT_ALL_STALE_PLAN, "Git HEAD no longer matches the confirmed commit-all plan", { expected_head: options.expectedHead, actual_head: repository.head });
176
276
  const branch = currentBranch(repository.root);
177
277
  const baseCheck = git(repository.root, ["cat-file", "-e", `${base}^{commit}`], { allowFailure: true });
178
278
  if (baseCheck.status !== 0) fail(ERROR_CODES.CANDIDATE_STALE_BASE, "Candidate base commit is unavailable", { base });
@@ -201,6 +301,18 @@ export function commitPatch(root, base, patchText, message, options = {}) {
201
301
  expectedHead: repository.head,
202
302
  stderr: updated.stderr.trim(),
203
303
  });
204
- return { branch, previous_head: repository.head, commit, stale: repository.head !== base };
304
+ const publication = { branch, previous_head: repository.head, commit, stale: repository.head !== base };
305
+ options.afterUpdateRef?.(publication);
306
+ return publication;
307
+ });
308
+ }
309
+
310
+ export function rollbackCommitRef(root, publication) {
311
+ const repository = repositoryState(root);
312
+ const updated = git(repository.root, ["update-ref", publication.branch, publication.previous_head, publication.commit], { allowFailure: true });
313
+ if (updated.status !== 0) fail(ERROR_CODES.CANDIDATE_REF_RACE, "Cannot roll back a candidate commit after a storage failure", {
314
+ branch: publication.branch,
315
+ expectedHead: publication.commit,
316
+ stderr: updated.stderr.trim(),
205
317
  });
206
318
  }
package/src/protocol.js CHANGED
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
3
3
  export const WORK_CONTEXT_PROTOCOL = Object.freeze({
4
4
  schema: 1,
5
5
  major: 1,
6
- minor: 1,
6
+ minor: 3,
7
7
  });
8
8
 
9
9
  export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR = Object.freeze({
@@ -13,7 +13,7 @@ export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR = Object.freeze({
13
13
  major: WORK_CONTEXT_PROTOCOL.major,
14
14
  minor: WORK_CONTEXT_PROTOCOL.minor,
15
15
  }),
16
- operations: Object.freeze(["delivery.doctor", "commit.acknowledge"]),
16
+ operations: Object.freeze(["delivery.doctor", "commit.acknowledge", "commit.inspect_all", "commit.all", "execution.complete_current"]),
17
17
  });
18
18
 
19
19
  export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR_BYTES = JSON.stringify(WORK_CONTEXT_PROTOCOL_DESCRIPTOR);