opencode-work-context 0.14.1 → 0.16.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.
package/src/core.js CHANGED
@@ -3,7 +3,7 @@ import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { FileStorage, atomicWrite, withLock, defaultConfig, loadConfig } from "./storage.js";
5
5
  import { ERROR_CODES, fail } from "./errors.js";
6
- import { event, reduceSessions, activeSession, assertActive } from "./sessions.js";
6
+ import { event, reduceSessions, activeSession, assertActive, nativeSessionId, openCodeSessionAffinity } from "./sessions.js";
7
7
  import { diagnoseSessionAssociations } from "./session-diagnostics.js";
8
8
  import { generateProjections, renderSessions } from "./projections.js";
9
9
  import { nextKnowledgeId, parseKnowledge, renderKnowledge, validateKnowledgeInput, validateKnowledgeRecords } from "./knowledge.js";
@@ -15,9 +15,62 @@ import { doctorDelivery as runDeliveryDoctor } from "./delivery-doctor.js";
15
15
  import { applyExecutionItemPatch, applyExecutionTextPatchItems, assertExecutionSize, EXECUTION_SECTIONS, executionInputUsesItems, executionItems, executionItemsFromState, executionPatchUsesItems, executionReadModel, executionSchemaFor, normalizeExecutionItemState, normalizeExecutionState } from "./stage-execution.js";
16
16
  import { CAPABILITY_CLASSIFICATIONS, CAPABILITY_DEPTHS, CAPABILITY_PROFILES, capabilityProfileMode, capabilityRecommendations, configureCapabilityMappings, readCapabilityMappings, resetCapabilityMappings, validateCapabilityMappings } from "./capability-profiles.js";
17
17
  import { acknowledgeGitCommit, initializeGitCheckpoint } from "./git-acknowledgement.js";
18
- import { rollbackCommitRef } from "./git-candidates.js";
18
+ import { isCommitAncestor, repositoryState, rollbackCommitRef } from "./git-candidates.js";
19
+ import { enqueueIntegrationNotice } from "./integration-notices.js";
20
+ import { DependencyHandoffStore } from "./dependency-handoffs.js";
19
21
 
20
22
  const actor = (options) => options.actor || "OpenCode";
23
+ const directDependents = (stages, sourceStage) => stages.filter((item) => item.depends_on.includes(sourceStage)).map((item) => item.stage).sort();
24
+ const dependencyEpochs = (stage, timestamp) => ({
25
+ ...Object.fromEntries((stage.depends_on || []).map((dependency) => [dependency, { generation: 1, added_at: stage.created_at || timestamp }])),
26
+ ...(stage.dependency_epochs || {}),
27
+ });
28
+ const targetGenerations = (stages, sourceStage, targets) => Object.fromEntries(targets.map((target) => {
29
+ const dependent = stages.find((stage) => stage.stage === target);
30
+ return [target, dependent.dependency_epochs?.[sourceStage]?.generation || 1];
31
+ }));
32
+ const assertProspectiveDependencyGraph = (stages) => {
33
+ const byId = new Map(stages.map((stage) => [stage.stage, stage]));
34
+ const visiting = new Set();
35
+ const visited = new Set();
36
+ const visit = (stage) => {
37
+ if (visiting.has(stage)) fail(ERROR_CODES.DEPENDENCY_CYCLE, "Stage dependency cycle detected", { stage });
38
+ if (visited.has(stage)) return;
39
+ visiting.add(stage);
40
+ for (const dependency of byId.get(stage).depends_on) {
41
+ if (!byId.has(dependency)) fail(ERROR_CODES.NOT_FOUND, `Stage dependency not found: ${dependency}`, { dependency });
42
+ visit(dependency);
43
+ }
44
+ visiting.delete(stage);
45
+ visited.add(stage);
46
+ };
47
+ for (const stage of byId.keys()) visit(stage);
48
+ };
49
+ const assertDependencyMutationStage = (stage, role) => {
50
+ if (!["planned", "in_progress"].includes(stage.status)) fail(ERROR_CODES.INVALID_STATE, `${role} stage must be planned or in progress`, { stage: stage.stage, status: stage.status });
51
+ };
52
+ const boundedList = (value, name) => {
53
+ if (value === undefined) return [];
54
+ if (!Array.isArray(value) || value.length > 20 || value.some((item) => typeof item !== "string" || !item.trim() || item.trim().length > 500)) fail(ERROR_CODES.INVALID_ARGUMENT, `${name} must contain at most 20 bounded non-empty strings`);
55
+ return value.map((item) => item.trim());
56
+ };
57
+ const enqueueCoverageNotices = (storage, publication) => {
58
+ const coverage = publication?.candidate_record?.coverage;
59
+ if (!coverage) return { queued: 0, skipped: 0 };
60
+ let queued = 0;
61
+ for (const entry of coverage.entries) {
62
+ if (enqueueIntegrationNotice(storage.projectRoot, {
63
+ workspace: publication.candidate_record.workspace,
64
+ stage: entry.stage,
65
+ candidate: publication.candidate_record.candidate,
66
+ commitHash: publication.commit,
67
+ currentItemId: entry.current_item_id,
68
+ selectedStages: coverage.entries.map((item) => item.stage),
69
+ personalRoot: storage.personalRoot,
70
+ })) queued += 1;
71
+ }
72
+ return { queued, skipped: coverage.entries.length - queued };
73
+ };
21
74
  const workspaceMode = (data) => data.mode || "standard";
22
75
  const COMMIT_MODES = ["manual", "per_item"];
23
76
  const workspaceCommitMode = (data) => data.commit_mode || "manual";
@@ -59,13 +112,17 @@ const startupWorkflowPolicy = (commitMode = { mode: "manual" }) => ({
59
112
  mode: "startup",
60
113
  guidance: commitMode.mode === "per_item" ? [
61
114
  "A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
115
+ "When changes appear mixed or overlapping, report only a bounded, explicitly uncertain list of likely affected stages supported by deterministic local evidence; never infer file or hunk ownership.",
62
116
  "Before each direct commit or candidate fallback, read the effective commit mode again. Proceed only while per_item remains effective; this is an agent policy preflight, not atomic Git enforcement.",
63
117
  "Inspect pending candidates related to this stage, then assess direct publication of the explicit Current-item patch first.",
64
- "Only a ready exact candidate explicitly related to this stage may substitute when direct publication is unsafe but the patch is separable. Shared foundation and integration candidates do not satisfy Current completion.",
118
+ "Only a ready exact candidate explicitly related to this stage may ordinarily substitute when direct publication is unsafe but the patch is separable. Shared foundation and unconfirmed integration candidates do not satisfy Current completion.",
119
+ "A committed integration candidate satisfies publication only when explicit coverage still names this exact Current item. Do not republish or reconstruct provenance; perform remaining verification and complete Current separately.",
120
+ "Never convert an exact candidate into a multi-stage boundary automatically. Explicit user direction and the dedicated coverage confirmation are required.",
65
121
  "After a direct commit, reconcile any stale related candidate intent before completing Current.",
66
122
  "A true patch or merge conflict, failed required verification, or incoherent boundary is a blocker; record it and do not complete Current.",
67
123
  ] : [
68
124
  "A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
125
+ "When changes appear mixed or overlapping, report only a bounded, explicitly uncertain list of likely affected stages supported by deterministic local evidence; never infer file or hunk ownership.",
69
126
  "Capture ready work promptly as an explicit commit candidate while unrelated work remains in progress.",
70
127
  "Once a coherent commit intent exists, create or refresh its draft candidate before switching stages or handing off so pending publication remains visible in related stage context.",
71
128
  "On resume, inspect related pending candidates before creating a duplicate or starting another commit boundary.",
@@ -94,25 +151,23 @@ const executionInstruction = (record) => {
94
151
  };
95
152
  const commitModeInstruction = (commitMode) => {
96
153
  if (commitMode.mode !== "per_item") return "";
97
- return `\n\nChecklist commit policy: per_item (${commitMode.source}). This is persistent authorization to publish an explicit, coherent Current-item patch; it never authorizes unrelated changes. Immediately before each direct commit or candidate fallback, call work_context_read_effective_commit_mode and proceed only if it still returns per_item. This is an agent policy preflight, not atomic Git enforcement. Before completing Current, define its explicit patch boundary and run relevant verification. When a direct commit is safe, create it before complete-current. Candidate publication remains separate. A true patch or merge conflict, failed verification, or incoherent boundary is a blocker: record it and do not complete Current.`;
154
+ return `\n\nChecklist commit policy: per_item (${commitMode.source}). This is persistent authorization to publish an explicit, coherent Current-item patch; it never authorizes unrelated changes. Immediately before each direct commit or candidate fallback, call work_context_read_effective_commit_mode and proceed only if it still returns per_item. This is an agent policy preflight, not atomic Git enforcement. Before completing Current, define its explicit patch boundary and run relevant verification. When a direct commit is safe, create it before complete-current. Candidate publication remains separate. A committed integration candidate is a narrow substitute only when explicit durable coverage still names this exact Current item; do not publish it again, and complete Current only after remaining verification. Ordinary integration relations are traceability-only. A true patch or merge conflict, failed verification, or incoherent boundary is a blocker: record it and do not complete Current.`;
98
155
  };
99
156
  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.`;
100
157
  const assertOpenCodeSessionAvailable = (events, opencodeSessionId, workspace, stage) => {
101
158
  if (!opencodeSessionId) return;
102
- const conflicting = reduceSessions(events).find((session) => session.opencode_session_id === opencodeSessionId
103
- && session.state === "active"
104
- && (session.workspace !== workspace || session.stage !== stage));
105
- if (!conflicting) return;
159
+ const affinity = openCodeSessionAffinity(events, opencodeSessionId);
160
+ if (!affinity || (affinity.workspace === workspace && affinity.stage === stage)) return;
106
161
  fail(
107
162
  ERROR_CODES.CURRENT_OPENCODE_SESSION_ALREADY_ASSOCIATED,
108
- "The current OpenCode session is already associated with another active work-context stage",
163
+ "The current OpenCode session has immutable affinity to another work-context stage",
109
164
  {
110
- current_workspace: conflicting.workspace,
111
- current_stage: conflicting.stage,
112
- current_stage_session_id: conflicting.session_id,
165
+ current_workspace: affinity.workspace,
166
+ current_stage: affinity.stage,
167
+ current_stage_session_id: affinity.session_id,
113
168
  requested_workspace: workspace,
114
169
  requested_stage: stage,
115
- next_action: "Open a separate OpenCode session for the requested stage, or explicitly hand off or close the current stage before resuming it here.",
170
+ next_action: "Open a separate OpenCode session for the requested stage. Handoff, close, finish, abandon, and archive do not transfer this session's stage affinity.",
116
171
  },
117
172
  );
118
173
  };
@@ -204,6 +259,7 @@ export class WorkContext {
204
259
  return { ...stage, description: stage.goal };
205
260
  });
206
261
  const ids = new Set(stages.map((item) => item.stage));
262
+ for (const stage of stages) if (stage.delegation && !ids.has(stage.delegation.dependent_stage)) fail(ERROR_CODES.STORAGE_ERROR, `Missing delegation dependent stage: ${stage.delegation.dependent_stage}`);
207
263
  const visiting = new Set();
208
264
  const visited = new Set();
209
265
  const visit = (stage) => {
@@ -263,12 +319,16 @@ export class WorkContext {
263
319
  }
264
320
 
265
321
  sessionByOpenCodeId(opencodeSessionId, workspace = null, stage = null, state = "active") {
266
- return reduceSessions(this.storage.readEvents()).filter((session) => session.opencode_session_id === opencodeSessionId
322
+ return reduceSessions(this.storage.readEvents()).filter((session) => nativeSessionId(session) === opencodeSessionId
267
323
  && (!workspace || session.workspace === workspace)
268
324
  && (!stage || session.stage === stage)
269
325
  && (!state || session.state === state)).at(-1) || null;
270
326
  }
271
327
 
328
+ sessionAffinityByOpenCodeId(opencodeSessionId) {
329
+ return openCodeSessionAffinity(this.storage.readEvents(), opencodeSessionId);
330
+ }
331
+
272
332
  diagnoseSessionAssociations(opencodeSessionId = null) {
273
333
  this.storage.assertNoSymlinks();
274
334
  return { ok: true, data: diagnoseSessionAssociations(this.storage.readEvents(), opencodeSessionId) };
@@ -287,6 +347,7 @@ export class WorkContext {
287
347
  const mode = options.mode === undefined ? "standard" : options.mode;
288
348
  if (!["standard", "startup"].includes(mode)) fail(ERROR_CODES.INVALID_ARGUMENT, "Workspace mode must be 'standard' or 'startup'");
289
349
  const requestedWorkspace = options.workspace;
350
+ const startSession = options.startSession !== false;
290
351
  return this.transact("workspace-create", () => {
291
352
  const workspace = requestedWorkspace === undefined ? this.nextWorkspace() : normalizeWorkspaceId(requestedWorkspace);
292
353
  const now = new Date().toISOString();
@@ -297,12 +358,25 @@ export class WorkContext {
297
358
  const planningGoal = "Clarify the work goal and constraints";
298
359
  const planningPrompt = "Diagnose and plan the task without functional changes. Planning stage 01 is a continuously available coordination surface, never a prerequisite gate: do not make implementation, research, review, or other working stages depend on it. Discuss possible solutions, record durable workspace-wide facts, decisions, constraints, important files, and risks through explicit knowledge operations, and decompose the work into the following stages. For each new implementation stage, write a separate detailed prompt with local context, concrete actions, constraints, completion criteria, and the expected result; do not duplicate shared knowledge that every stage receives in resume.context.workspace_knowledge. Ask clarifying questions only when genuinely blocked. Stages must remain in progress until the user explicitly requests stage finish. If the user explicitly agrees to automatic completion for this workspace, add the exact standalone line AUTO_STAGE_FINISH: allowed to this Planning-stage prompt.";
299
360
  this.storage.writeMarkdown(this.storage.stageFile(workspace, "01"), { schema: 1, workspace, stage: "01", title: "Planning", status: "in_progress", goal: planningGoal, prompt: planningPrompt, depends_on: [], owner: actor(this.options), created_at: now, updated_at: now, tracker_links: [] }, body("Planning", planningGoal, planningPrompt));
300
- const sessionId = options.sessionId || randomUUID();
361
+ const sessionId = startSession ? options.sessionId || randomUUID() : null;
301
362
  const workflowPolicy = mode === "startup" && options.opencodeSessionId ? startupWorkflowPolicy() : null;
302
- if (this.storage.readEvents().some((item) => item.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
303
- this.writeEvents([event("session.started", workspace, "01", 1, sessionId, actor(this.options), { summary: `planning ${title.trim()}`, opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
304
- initializeGitCheckpoint(this.storage, { workspace, stage: "01", sessionId });
305
- generateProjections(this.storage);
363
+ if (startSession) {
364
+ if (this.storage.readEvents().some((item) => item.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
365
+ this.writeEvents([event("session.started", workspace, "01", 1, sessionId, actor(this.options), { summary: `planning ${title.trim()}`, opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
366
+ initializeGitCheckpoint(this.storage, { workspace, stage: "01", sessionId });
367
+ }
368
+ generateProjections(this.storage);
369
+ if (!startSession) return this.result({
370
+ workspace,
371
+ mode,
372
+ commit_mode: "manual",
373
+ stage: "01",
374
+ title: "Planning",
375
+ description: planningGoal,
376
+ session_id: null,
377
+ started: false,
378
+ next_action: "start_new_opencode_session_and_resume",
379
+ }, [workspace, "01"]);
306
380
  return this.result({
307
381
  workspace,
308
382
  mode,
@@ -387,6 +461,7 @@ export class WorkContext {
387
461
 
388
462
  candidates() { return new CandidateStore(this); }
389
463
  deliveries() { return new DeliveryStore(this); }
464
+ handoffs() { return new DependencyHandoffStore(this.storage); }
390
465
 
391
466
  createCandidate(workspace, title, message = null, options = {}) {
392
467
  return this.transact("candidate-create", () => this.result(this.candidates().create(workspace, title, message, options), ["local:candidates"]));
@@ -410,6 +485,13 @@ export class WorkContext {
410
485
  return this.transact("candidate-ready", () => this.result(this.candidates().setStatus(workspace, candidate, "ready"), ["local:candidates"]));
411
486
  }
412
487
 
488
+ confirmCandidateCoverage(workspace, candidate, selectedStages, confirmation) {
489
+ return this.transact("candidate-confirm-coverage", () => this.result(
490
+ this.candidates().confirmCoverage(workspace, candidate, selectedStages, confirmation),
491
+ ["local:candidates"],
492
+ ));
493
+ }
494
+
413
495
  discardCandidate(workspace, candidate) {
414
496
  return this.transact("candidate-discard", () => this.result(this.candidates().setStatus(workspace, candidate, "discarded"), ["local:candidates"]));
415
497
  }
@@ -417,9 +499,36 @@ export class WorkContext {
417
499
  commitCandidate(workspace, candidate, message = undefined, options = {}) {
418
500
  this.storage.assertSafeRoots();
419
501
  // Operations needing both locks always acquire candidate-git before write.
420
- return withLock(this.storage.lockPath("candidate-git"), () => this.transact("candidate-commit", () =>
421
- this.result(this.candidates().commit(workspace, candidate, message, options), ["local:candidates"])
422
- ), { session: this.options.sessionId, owner: actor(this.options) });
502
+ return withLock(this.storage.lockPath("candidate-git"), () => {
503
+ let publication;
504
+ try {
505
+ const result = this.transact("candidate-commit", () => this.result(this.candidates().commit(workspace, candidate, message, {
506
+ ...options,
507
+ afterUpdateRef: (published) => {
508
+ publication = published;
509
+ options.afterUpdateRef?.(published);
510
+ },
511
+ }), ["local:candidates"]));
512
+ const noticeDelivery = enqueueCoverageNotices(this.storage, publication);
513
+ return publication?.candidate_record?.coverage ? { ...result, data: { ...result.data, notice_delivery: noticeDelivery } } : result;
514
+ } catch (error) {
515
+ if (publication) {
516
+ try { rollbackCommitRef(this.storage.projectRoot, publication); }
517
+ catch (rollbackError) {
518
+ const head = repositoryState(this.storage.projectRoot).head;
519
+ if (isCommitAncestor(this.storage.projectRoot, publication.commit, head)) {
520
+ this.transact("candidate-commit-recovery", () => {
521
+ this.candidates().write(publication.candidate_record, publication.patch);
522
+ return this.result(publication.candidate_record, ["local:candidates"]);
523
+ });
524
+ enqueueCoverageNotices(this.storage, publication);
525
+ }
526
+ throw rollbackError;
527
+ }
528
+ }
529
+ throw error;
530
+ }
531
+ }, { session: this.options.sessionId, owner: actor(this.options) });
423
532
  }
424
533
 
425
534
  inspectCommitAll(workspace, options = {}) { return { ok: true, data: this.candidates().inspectAll(workspace, options) }; }
@@ -437,7 +546,13 @@ export class WorkContext {
437
546
  if (publication) {
438
547
  try { rollbackCommitRef(this.storage.projectRoot, publication); }
439
548
  catch (rollbackError) {
440
- this.candidates().write(publication.candidate_record, publication.patch);
549
+ const head = repositoryState(this.storage.projectRoot).head;
550
+ if (isCommitAncestor(this.storage.projectRoot, publication.commit, head)) {
551
+ this.transact("commit-all-recovery", () => {
552
+ this.candidates().write(publication.candidate_record, publication.patch);
553
+ return this.result(publication.candidate_record, ["local:candidates"]);
554
+ });
555
+ }
441
556
  throw rollbackError;
442
557
  }
443
558
  }
@@ -481,7 +596,7 @@ export class WorkContext {
481
596
  if (current) {
482
597
  const canTakeOver = options.takeover
483
598
  && current.session_id !== sessionId
484
- && current.opencode_session_id !== options.opencodeSessionId;
599
+ && nativeSessionId(current) !== options.opencodeSessionId;
485
600
  if (!canTakeOver) fail(ERROR_CODES.ACTIVE_SESSION_EXISTS, "Stage already has an active session");
486
601
  this.writeEvents([event("session.handed_off", workspace, stage, current.ordinal, current.session_id, actor(this.options), { reason: "resumed in a new OpenCode session" })]);
487
602
  }
@@ -510,10 +625,12 @@ export class WorkContext {
510
625
  const commitMode = effectiveCommitMode(workspaceRecord, stageRecord.data);
511
626
  const workflowPolicy = workspaceMode(workspaceRecord) === "startup" && options.opencodeSessionId ? startupWorkflowPolicy(commitMode) : null;
512
627
  const pendingCandidates = workflowPolicy ? this.candidates().activeProjection(workspace).by_stage[stage] || null : null;
628
+ const committedCoverage = workflowPolicy ? this.candidates().committedCoverageProjection(workspace).by_stage[stage] || null : null;
513
629
  const deliveryContext = stage === "01" ? this.deliveries().projection(workspace) : null;
514
630
  const hasDeliveryContext = deliveryContext && (deliveryContext.committed.count || deliveryContext.environments.length || deliveryContext.unavailable);
515
- const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
516
- const execution = this.storage.readStageExecution(workspace, stage);
631
+ const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
632
+ const execution = this.storage.readStageExecution(workspace, stage);
633
+ const dependencyContext = stageRecord.data.depends_on.length ? this.handoffs().context(workspace, stage, this.listStages(workspace).data.stages) : null;
517
634
  const automaticFinish = automaticFinishAllowed(this.storage, workspace);
518
635
  const recommendations = capabilityRecommendations(this.storage, stageRecord.data, readCapabilityMappings(this.storage, { homeDir: this.options.capabilityProfilesHome }));
519
636
  return this.result({
@@ -549,7 +666,10 @@ export class WorkContext {
549
666
  commit_mode: commitMode,
550
667
  ...(execution ? { execution_state: executionReadModel(execution) } : {}),
551
668
  ...(recommendations ? { capability_profiles: recommendations } : {}),
552
- ...(pendingCandidates ? { pending_candidates: pendingCandidates } : {}),
669
+ ...(pendingCandidates ? { pending_candidates: pendingCandidates } : {}),
670
+ ...(committedCoverage ? { committed_integration_coverage: committedCoverage } : {}),
671
+ ...(stageRecord.data.delegation ? { delegation_contract: stageRecord.data.delegation } : {}),
672
+ ...(dependencyContext ? { dependency_context: dependencyContext } : {}),
553
673
  ...(hasDeliveryContext ? { delivery_context: deliveryContext } : {}),
554
674
  ...(workflowPolicy ? { workflow_policy: workflowPolicy } : {}),
555
675
  lifecycle: { automatic_finish_allowed: automaticFinish },
@@ -603,6 +723,139 @@ export class WorkContext {
603
723
  });
604
724
  }
605
725
 
726
+ delegateStage(workspace, delegatorStage, sessionId, title, requestedOutcome, options = {}) {
727
+ workspace = normalizeWorkspaceId(workspace);
728
+ delegatorStage = normalizeStageId(delegatorStage);
729
+ if (delegatorStage === "01") fail(ERROR_CODES.PLANNING_DEPENDENCY_FORBIDDEN, "Planning stage 01 cannot depend on delegated working stages");
730
+ if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Title is required");
731
+ if (!requestedOutcome?.trim() || requestedOutcome.trim().length > 4000) fail(ERROR_CODES.INVALID_ARGUMENT, "requestedOutcome must be a bounded non-empty string");
732
+ const dependsOn = (options.dependsOn || []).map(normalizeStageId);
733
+ if (!Array.isArray(options.dependsOn || []) || new Set(dependsOn).size !== dependsOn.length) fail(ERROR_CODES.INVALID_ARGUMENT, "dependsOn must contain unique stage IDs");
734
+ if (dependsOn.includes("01")) fail(ERROR_CODES.PLANNING_DEPENDENCY_FORBIDDEN, "Working stages cannot depend on Planning stage 01");
735
+ assertCapabilityProfile(options.executionProfile, "executionProfile");
736
+ assertCapabilityDepth(options.executionDepth, "executionDepth");
737
+ assertCapabilityClassification(options.classification);
738
+ assertCapabilityProfile(options.reviewProfile, "reviewProfile");
739
+ if (Boolean(options.executionProfile) !== Boolean(options.executionDepth)) fail(ERROR_CODES.INVALID_ARGUMENT, "executionProfile and executionDepth must be provided together");
740
+ return this.transact(`workspace-${workspace}`, () => {
741
+ const stages = this.listStages(workspace).data.stages;
742
+ const delegator = stages.find((item) => item.stage === delegatorStage);
743
+ if (!delegator) fail(ERROR_CODES.NOT_FOUND, "Delegating stage not found");
744
+ assertDependencyMutationStage(delegator, "Delegating");
745
+ assertActive(this.storage.readEvents(), workspace, delegatorStage, sessionId);
746
+ if (stages.length >= 99) fail(ERROR_CODES.INVALID_STATE, "A workspace cannot contain more than 99 stages");
747
+ const stage = String(Math.max(0, ...stages.map((item) => Number(item.stage))) + 1).padStart(2, "0");
748
+ if (dependsOn.includes(stage)) fail(ERROR_CODES.INVALID_ARGUMENT, "A stage cannot depend on itself");
749
+ if (dependsOn.some((dependency) => !stages.some((item) => item.stage === dependency))) fail(ERROR_CODES.NOT_FOUND, "dependsOn must reference existing stages");
750
+ if (dependsOn.some((dependency) => stages.find((item) => item.stage === dependency).status === "cancelled")) fail(ERROR_CODES.INVALID_STATE, "A delegated stage cannot depend on a cancelled stage");
751
+ const now = new Date().toISOString();
752
+ const prompt = options.prompt?.trim() || undefined;
753
+ const metadata = { schema: 1, workspace, stage, title: title.trim(), status: "planned", goal: options.goal || title.trim(), ...(prompt ? { prompt } : {}), depends_on: dependsOn, delegation: { schema: 1, dependent_stage: delegatorStage, requested_outcome: requestedOutcome.trim(), created_at: now }, owner: options.owner || actor(this.options), ...(options.executionProfile ? { execution_profile: options.executionProfile, execution_depth: options.executionDepth, execution_classification: options.classification || "explicit" } : {}), ...(options.reviewProfile ? { review_profile: options.reviewProfile } : {}), created_at: now, updated_at: now, tracker_links: [] };
754
+ const delegatorRecord = this.storage.readStage(workspace, delegatorStage);
755
+ delegatorRecord.data.depends_on = [...delegatorRecord.data.depends_on, stage].sort();
756
+ delegatorRecord.data.dependency_epochs = { ...dependencyEpochs(delegatorRecord.data, now), [stage]: { generation: 1, added_at: now } };
757
+ delegatorRecord.data.updated_at = now;
758
+ assertProspectiveDependencyGraph([...stages.filter((item) => item.stage !== delegatorStage), { ...delegator, depends_on: delegatorRecord.data.depends_on }, metadata]);
759
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), metadata, body(title, options.goal || title, prompt));
760
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, delegatorStage), delegatorRecord.data, delegatorRecord.body);
761
+ generateProjections(this.storage);
762
+ return this.result({ workspace, delegator_stage: delegatorStage, stage, status: "planned", dependency_added: true, delegation_contract: metadata.delegation, session_started: false, resume_required: true }, [workspace, delegatorStage, stage]);
763
+ });
764
+ }
765
+
766
+ addStageDependency(workspace, stage, dependency) {
767
+ workspace = normalizeWorkspaceId(workspace);
768
+ stage = normalizeStageId(stage);
769
+ dependency = normalizeStageId(dependency);
770
+ if (stage === "01") fail(ERROR_CODES.PLANNING_DEPENDENCY_FORBIDDEN, "Planning stage 01 cannot depend on working stages");
771
+ if (dependency === "01") fail(ERROR_CODES.PLANNING_DEPENDENCY_FORBIDDEN, "Working stages cannot depend on Planning stage 01");
772
+ if (stage === dependency) fail(ERROR_CODES.INVALID_ARGUMENT, "A stage cannot depend on itself");
773
+ return this.transact(`workspace-${workspace}`, () => {
774
+ const stages = this.listStages(workspace).data.stages;
775
+ const dependent = stages.find((item) => item.stage === stage);
776
+ const source = stages.find((item) => item.stage === dependency);
777
+ if (!dependent || !source) fail(ERROR_CODES.NOT_FOUND, "Both dependency stages must exist");
778
+ assertDependencyMutationStage(dependent, "Dependent");
779
+ if (source.status === "cancelled") fail(ERROR_CODES.INVALID_STATE, "A cancelled stage cannot become a dependency", { stage: dependency, status: source.status });
780
+ if (dependent.depends_on.includes(dependency)) fail(ERROR_CODES.DEPENDENCY_EDGE_EXISTS, "Stage dependency already exists", { stage, dependency });
781
+ const nextDependencies = [...dependent.depends_on, dependency].sort();
782
+ assertProspectiveDependencyGraph(stages.map((item) => item.stage === stage ? { ...item, depends_on: nextDependencies } : item));
783
+ const record = this.storage.readStage(workspace, stage);
784
+ const epochs = dependencyEpochs(record.data, new Date().toISOString());
785
+ const previous = epochs[dependency];
786
+ const addedAt = new Date().toISOString();
787
+ record.data.depends_on = nextDependencies;
788
+ record.data.dependency_epochs = { ...epochs, [dependency]: { generation: (previous?.generation || 0) + 1, added_at: addedAt } };
789
+ record.data.updated_at = addedAt;
790
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, record.body);
791
+ generateProjections(this.storage);
792
+ return this.result({ workspace, stage, dependency, depends_on: nextDependencies, blocked: !isDependencySatisfied(source) }, [workspace, stage]);
793
+ });
794
+ }
795
+
796
+ removeStageDependency(workspace, stage, dependency) {
797
+ workspace = normalizeWorkspaceId(workspace);
798
+ stage = normalizeStageId(stage);
799
+ dependency = normalizeStageId(dependency);
800
+ return this.transact(`workspace-${workspace}`, () => {
801
+ const stages = this.listStages(workspace).data.stages;
802
+ const dependent = stages.find((item) => item.stage === stage);
803
+ if (!dependent) fail(ERROR_CODES.NOT_FOUND, "Dependent stage not found");
804
+ assertDependencyMutationStage(dependent, "Dependent");
805
+ if (!dependent.depends_on.includes(dependency)) fail(ERROR_CODES.DEPENDENCY_EDGE_NOT_FOUND, "Stage dependency does not exist", { stage, dependency });
806
+ const nextDependencies = dependent.depends_on.filter((item) => item !== dependency);
807
+ const record = this.storage.readStage(workspace, stage);
808
+ const removedAt = new Date().toISOString();
809
+ const epochs = dependencyEpochs(record.data, removedAt);
810
+ record.data.depends_on = nextDependencies;
811
+ record.data.dependency_epochs = { ...epochs, [dependency]: { ...epochs[dependency], removed_at: removedAt } };
812
+ record.data.updated_at = removedAt;
813
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, record.body);
814
+ generateProjections(this.storage);
815
+ return this.result({ workspace, stage, dependency, depends_on: nextDependencies, historical_handoffs_retained: true }, [workspace, stage]);
816
+ });
817
+ }
818
+
819
+ handoffEvidence(workspace, input = {}) {
820
+ const candidateIds = input.candidateIds || [];
821
+ const commits = input.commits || [];
822
+ if (!Array.isArray(candidateIds) || candidateIds.length > 20 || candidateIds.some((item) => typeof item !== "string" || !/^CC-\d{6}$/.test(item)) || new Set(candidateIds).size !== candidateIds.length) fail(ERROR_CODES.INVALID_ARGUMENT, "candidateIds must contain unique candidate IDs");
823
+ if (!Array.isArray(commits) || commits.length > 20 || commits.some((item) => typeof item !== "string" || !/^[0-9a-f]{40,64}$/.test(item)) || new Set(commits).size !== commits.length) fail(ERROR_CODES.INVALID_ARGUMENT, "commits must contain unique full lowercase commit hashes");
824
+ const committed = this.candidates().projectionRecords(workspace).filter((candidate) => candidateIds.includes(candidate.candidate));
825
+ if (committed.length !== candidateIds.length || committed.some((candidate) => candidate.status !== "committed")) fail(ERROR_CODES.INVALID_STATE, "Handoff candidate evidence must reference committed candidates");
826
+ if (commits.length || committed.length) {
827
+ const repository = repositoryState(this.storage.projectRoot);
828
+ const evidenceCommits = [...commits, ...committed.map((candidate) => candidate.commit_hash)];
829
+ if (evidenceCommits.some((commit) => !isCommitAncestor(repository.root, commit, repository.head))) fail(ERROR_CODES.INVALID_STATE, "Handoff evidence must reference committed ancestors of HEAD");
830
+ }
831
+ return { candidates: committed.map((candidate) => ({ candidate: candidate.candidate, commit_hash: candidate.commit_hash })), commits };
832
+ }
833
+
834
+ publishDependencyHandoff(workspace, stage, sessionId, input = {}) {
835
+ workspace = normalizeWorkspaceId(workspace);
836
+ stage = normalizeStageId(stage);
837
+ if (!input.outcome?.trim() || input.outcome.trim().length > 4000) fail(ERROR_CODES.INVALID_ARGUMENT, "outcome must be a bounded non-empty string");
838
+ return this.transact(`workspace-${workspace}`, () => {
839
+ const stages = this.listStages(workspace).data.stages;
840
+ const source = stages.find((item) => item.stage === stage);
841
+ if (!source) fail(ERROR_CODES.NOT_FOUND, "Source stage not found");
842
+ assertDependencyMutationStage(source, "Source");
843
+ assertActive(this.storage.readEvents(), workspace, stage, sessionId);
844
+ const targets = directDependents(stages, stage);
845
+ if (!targets.length) fail(ERROR_CODES.DEPENDENCY_TARGET_REQUIRED, "The source stage has no formal direct dependents");
846
+ const record = this.handoffs().append(workspace, { type: "handoff", kind: "intermediate", sourceStage: stage, targetStages: targets, targetGenerations: targetGenerations(stages, stage, targets), outcome: input.outcome, evidence: this.handoffEvidence(workspace, input), verification: boundedList(input.verification, "verification"), blockers: boundedList(input.blockers, "blockers"), actor: actor(this.options), sourceSessionId: sessionId });
847
+ generateProjections(this.storage);
848
+ return this.result({ workspace, stage, handoff: record }, [workspace, this.storage.dependencyHandoffsFile(workspace)]);
849
+ });
850
+ }
851
+
852
+ readDependencyContext(workspace, stage) {
853
+ workspace = normalizeWorkspaceId(workspace);
854
+ stage = normalizeStageId(stage);
855
+ const stages = this.listStages(workspace).data.stages;
856
+ return { ok: true, data: { workspace, stage, ...this.handoffs().context(workspace, stage, stages) } };
857
+ }
858
+
606
859
  setStageProfiles(workspace, stage, profiles = {}) {
607
860
  workspace = normalizeWorkspaceId(workspace);
608
861
  stage = normalizeStageId(stage);
@@ -893,14 +1146,18 @@ export class WorkContext {
893
1146
  const record = this.storage.readStage(workspace, stage);
894
1147
  if (record.data.status === "archived") return this.result({ workspace, stage, status: "archived" }, []);
895
1148
  if (activeSession(this.storage.readEvents(), workspace, stage)) fail(ERROR_CODES.ACTIVE_SESSION_EXISTS, "Cannot archive a stage with an active session");
1149
+ const stages = this.listStages(workspace).data.stages;
1150
+ const wasSatisfied = isDependencySatisfied(record.data);
1151
+ const targets = directDependents(stages, stage);
896
1152
  const archivedAt = new Date().toISOString();
897
1153
  const entry = { action: "archived", at: archivedAt, actor: actor(this.options), previous_status: record.data.status };
898
1154
  record.data.status = "archived";
899
1155
  record.data.archive_history = [...(record.data.archive_history || []), entry];
900
1156
  record.data.updated_at = archivedAt;
901
1157
  this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, appendHistory(record.body, "Archive History", `${archivedAt}: archived from ${entry.previous_status}`));
1158
+ const dependencyStatus = !wasSatisfied && targets.length ? this.handoffs().append(workspace, { type: "status", sourceStage: stage, targetStages: targets, targetGenerations: targetGenerations(stages, stage, targets), satisfied: true, reason: "archived", createdAt: archivedAt, actor: actor(this.options) }) : null;
902
1159
  generateProjections(this.storage);
903
- return this.result({ workspace, stage, status: "archived" }, [workspace, stage]);
1160
+ return this.result({ workspace, stage, status: "archived", ...(dependencyStatus ? { dependency_status: dependencyStatus } : {}) }, [workspace, stage, ...(dependencyStatus ? [this.storage.dependencyHandoffsFile(workspace)] : [])]);
904
1161
  });
905
1162
  }
906
1163
 
@@ -923,13 +1180,16 @@ export class WorkContext {
923
1180
  record.data.archive_history = [...(record.data.archive_history || []), entry];
924
1181
  record.data.updated_at = restoredAt;
925
1182
  this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, appendHistory(record.body, "Archive History", `${restoredAt}: restored to ${restoredStatus}; ${reason.trim()}`));
1183
+ const stages = this.listStages(workspace).data.stages;
1184
+ const targets = directDependents(stages, stage);
1185
+ const dependencyStatus = !isDependencySatisfied(record.data) && targets.length ? this.handoffs().append(workspace, { type: "status", sourceStage: stage, targetStages: targets, targetGenerations: targetGenerations(stages, stage, targets), satisfied: false, reason: "restored", createdAt: restoredAt, actor: actor(this.options) }) : null;
926
1186
  if (workspaceRecord.data.status === "completed" && ["planned", "in_progress"].includes(restoredStatus)) {
927
1187
  workspaceRecord.data.status = "in_progress";
928
1188
  workspaceRecord.data.updated_at = restoredAt;
929
1189
  this.storage.writeMarkdown(this.storage.workspaceFile(workspace), workspaceRecord.data, workspaceRecord.body);
930
1190
  }
931
1191
  generateProjections(this.storage);
932
- return this.result({ workspace, stage, status: restoredStatus, restore: entry, session_started: false, resume_required: ["planned", "in_progress"].includes(restoredStatus) }, [workspace, stage]);
1192
+ return this.result({ workspace, stage, status: restoredStatus, restore: entry, session_started: false, resume_required: ["planned", "in_progress"].includes(restoredStatus), ...(dependencyStatus ? { dependency_status: dependencyStatus } : {}) }, [workspace, stage, ...(dependencyStatus ? [this.storage.dependencyHandoffsFile(workspace)] : [])]);
933
1193
  });
934
1194
  }
935
1195
 
@@ -1079,6 +1339,8 @@ export class WorkContext {
1079
1339
  if (record.data.status !== "completed") fail(ERROR_CODES.INVALID_STATE, "Only completed stages can be reopened", { status: record.data.status });
1080
1340
  const reopenedAt = new Date().toISOString();
1081
1341
  const previousResult = stageResult(record);
1342
+ const stages = this.listStages(workspace).data.stages;
1343
+ const targets = directDependents(stages, stage);
1082
1344
  const entry = { at: reopenedAt, reason: reason.trim(), actor: actor(this.options), ...(previousResult ? { previous_result: previousResult } : {}) };
1083
1345
  record.data.status = "in_progress";
1084
1346
  record.data.reopen_history = [...(record.data.reopen_history || []), entry];
@@ -1088,13 +1350,14 @@ export class WorkContext {
1088
1350
  const priorResult = previousResult ? `\n Previous result: ${previousResult}` : "";
1089
1351
  const archiveHistory = record.body.match(/\n## Archive History[\s\S]*?(?=\n## (?:Result|Reopen History)|$)/)?.[0] || "";
1090
1352
  this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, `${body(record.data.title, record.data.goal, record.data.prompt).trimEnd()}${history}\n- ${reopenedAt}: ${reason.trim()}${priorResult}\n${archiveHistory}`);
1353
+ const dependencyStatus = targets.length ? this.handoffs().append(workspace, { type: "status", sourceStage: stage, targetStages: targets, targetGenerations: targetGenerations(stages, stage, targets), satisfied: false, reason: "reopened", createdAt: reopenedAt, actor: actor(this.options) }) : null;
1091
1354
  if (workspaceRecord.data.status === "completed") {
1092
1355
  workspaceRecord.data.status = "in_progress";
1093
1356
  workspaceRecord.data.updated_at = reopenedAt;
1094
1357
  this.storage.writeMarkdown(this.storage.workspaceFile(workspace), workspaceRecord.data, workspaceRecord.body);
1095
1358
  }
1096
1359
  generateProjections(this.storage);
1097
- return this.result({ workspace, stage, status: "in_progress", reopen: entry, session_started: false, resume_required: true }, [workspace, stage]);
1360
+ return this.result({ workspace, stage, status: "in_progress", reopen: entry, session_started: false, resume_required: true, ...(dependencyStatus ? { dependency_status: dependencyStatus } : {}) }, [workspace, stage, ...(dependencyStatus ? [this.storage.dependencyHandoffsFile(workspace)] : [])]);
1098
1361
  });
1099
1362
  }
1100
1363
 
@@ -1122,15 +1385,24 @@ export class WorkContext {
1122
1385
  ] : [];
1123
1386
  const active = activeSession(events, workspace, stage);
1124
1387
  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");
1388
+ const stages = this.listStages(workspace).data.stages;
1389
+ const targets = directDependents(stages, stage);
1390
+ const result = options.result?.trim() || "Stage completed.";
1391
+ const handoffOutcome = options.handoffOutcome?.trim() || result;
1392
+ if (targets.length && (!handoffOutcome || handoffOutcome.length > 4000)) fail(ERROR_CODES.INVALID_ARGUMENT, "handoffOutcome must be a bounded non-empty summary when the final result exceeds the handoff limit");
1393
+ const evidence = this.handoffEvidence(workspace, options);
1394
+ const verification = boundedList(options.verification, "verification");
1395
+ const blockers = boundedList(options.blockers, "blockers");
1125
1396
  this.writeEvents([event("session.closed", workspace, stage, active.ordinal, sessionId, actor(this.options), { reason: "stage_completed" })]);
1126
1397
  current.data.status = "completed";
1127
1398
  current.data.updated_at = new Date().toISOString();
1128
- this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), current.data, `${current.body}\n\n## Result\n\n${options.result || "Stage completed."}`);
1399
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), current.data, `${current.body}\n\n## Result\n\n${result}`);
1400
+ const finalHandoff = targets.length ? this.handoffs().append(workspace, { type: "handoff", kind: "final", sourceStage: stage, targetStages: targets, targetGenerations: targetGenerations(stages, stage, targets), outcome: handoffOutcome, evidence, verification, blockers, createdAt: current.data.updated_at, actor: actor(this.options), sourceSessionId: sessionId }) : null;
1129
1401
  generateProjections(this.storage);
1130
1402
  const promptReview = this.listStages(workspace).data.stages
1131
1403
  .filter((item) => Number(item.stage) > Number(stage) && !["completed", "archived"].includes(item.status))
1132
1404
  .map(({ stage: id, title, description, prompt, status }) => ({ stage: id, title, description, prompt: prompt || null, status }));
1133
- 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 } : {}) };
1405
+ 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, ...(finalHandoff ? { final_handoff: finalHandoff } : {}), ...(executionData ? { execution_state: executionData, execution_warnings: executionWarnings } : {}) };
1134
1406
  const incompleteStages = this.listStages(workspace).data.stages.filter((item) => !["completed", "archived"].includes(item.status));
1135
1407
  const next = incompleteStages.length ? null : {
1136
1408
  action: "workspace_finish",
@@ -1138,15 +1410,15 @@ export class WorkContext {
1138
1410
  command: `/wc workspace finish ${workspace}`,
1139
1411
  reason: "All workspace stages are completed",
1140
1412
  };
1141
- return this.result(data, [workspace, stage], next);
1413
+ return this.result(data, [workspace, stage, ...(finalHandoff ? [this.storage.dependencyHandoffsFile(workspace)] : [])], next);
1142
1414
  });
1143
1415
  }
1144
1416
 
1145
1417
  help(command = "") {
1146
1418
  return this.result({
1147
1419
  command,
1148
- syntax: "/wc [create|list|workspace list|workspace rename|workspace mode|workspace commit-mode|stage commit-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]",
1149
- note: "Workspace commit mode is manual or per_item; stages may override or clear to inherit it. Read the effective mode immediately before each direct commit or candidate fallback because this agent-policy preflight is not atomic Git enforcement. Per-item mode authorizes commits only for explicit coherent Current-item boundaries and does not make complete-current perform Git work. 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.",
1420
+ syntax: "/wc [create|list|workspace list|workspace rename|workspace mode|workspace commit-mode|stage commit-mode|candidate create|candidate capture|candidate preview|candidate show|candidate list|candidate ready|candidate confirm-coverage|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 delegate|stage dependency add|stage dependency remove|stage dependency publish|stage dependency read|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]",
1421
+ note: "Workspace commit mode is manual or per_item; stages may override or clear to inherit it. Read the effective mode immediately before each direct commit or candidate fallback because this agent-policy preflight is not atomic Git enforcement. Per-item mode authorizes commits only for explicit coherent Current-item boundaries and does not make complete-current perform Git work. A committed integration candidate is a narrow substitute only after explicit revision-safe multi-stage coverage confirmation; relations alone remain traceability. Dependency delegation atomically creates a source stage and edge; explicit intermediate and final handoffs are bounded context only, while lifecycle states remain authoritative for satisfaction and no notice advances execution or lifecycle. 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.",
1150
1422
  }, []);
1151
1423
  }
1152
1424