opencode-work-context 0.7.0 → 0.9.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
@@ -9,6 +9,8 @@ import { nextKnowledgeId, parseKnowledge, renderKnowledge, validateKnowledgeInpu
9
9
  import { normalizeStageId, normalizeWorkspaceId } from "./identifiers.js";
10
10
  import { isDependencySatisfied } from "./stage-status.js";
11
11
  import { CandidateStore } from "./candidates.js";
12
+ import { DeliveryStore } from "./delivery.js";
13
+ import { applyExecutionPatch, assertExecutionSize, executionState, normalizeExecutionState } from "./stage-execution.js";
12
14
 
13
15
  const actor = (options) => options.actor || "OpenCode";
14
16
  const workspaceMode = (data) => data.mode || "standard";
@@ -34,6 +36,8 @@ const startupWorkflowPolicy = () => ({
34
36
  guidance: [
35
37
  "A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
36
38
  "Capture ready work promptly as an explicit commit candidate while unrelated work remains in progress.",
39
+ "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.",
40
+ "On resume, inspect related pending candidates before creating a duplicate or starting another commit boundary.",
37
41
  "Choose an exact candidate when separable, a shared foundation candidate when several stages use one change, or an integration candidate when intertwined changes form one coherent reviewable result.",
38
42
  "Mixed-stage provenance or complete files containing unrelated stage work are not reasons to stop, require prior commits, or reconstruct ownership after the fact.",
39
43
  "Stop only for a concrete patch conflict, an incoherent candidate boundary, or failed required verification, and report it explicitly.",
@@ -48,6 +52,8 @@ const resumePresentationInstruction = ({ confirmationRequired }) => `Before doin
48
52
  - Mention previous progress only when presentation.previous_result or presentation.previous_session_summary contains useful information.
49
53
  - State the immediate next action in one sentence.
50
54
  ${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."}`;
55
+ 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.` : "";
56
+ 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.`;
51
57
  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; } } };
52
58
 
53
59
  function parseIssue(url) {
@@ -246,7 +252,7 @@ export class WorkContext {
246
252
  lifecycle: { automatic_finish_allowed: false },
247
253
  },
248
254
  next_action: "start_work",
249
- instruction: `${planningPrompt}${startupWorkflowInstruction(workflowPolicy)}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
255
+ instruction: `${planningPrompt}${startupWorkflowInstruction(workflowPolicy)}${deliveryPlanningInstruction}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
250
256
  },
251
257
  }, [workspace, "01"]);
252
258
  });
@@ -282,6 +288,7 @@ export class WorkContext {
282
288
  }
283
289
 
284
290
  candidates() { return new CandidateStore(this); }
291
+ deliveries() { return new DeliveryStore(this); }
285
292
 
286
293
  createCandidate(workspace, title, message = null, options = {}) {
287
294
  return this.transact("candidate-create", () => this.result(this.candidates().create(workspace, title, message, options), ["local:candidates"]));
@@ -317,6 +324,15 @@ export class WorkContext {
317
324
  ), { session: this.options.sessionId, owner: actor(this.options) });
318
325
  }
319
326
 
327
+ readDelivery(workspace, options = {}) { return { ok: true, data: this.deliveries().readContext(workspace, options) }; }
328
+
329
+ markDelivery(workspace, environment, commit, confirmation) {
330
+ this.storage.assertSafeRoots();
331
+ return withLock(this.storage.lockPath("candidate-git"), () => this.transact("delivery-mark", () =>
332
+ this.result(this.deliveries().mark(workspace, environment, commit, confirmation), ["local:delivery"])
333
+ ), { session: this.options.sessionId, owner: actor(this.options) });
334
+ }
335
+
320
336
  nextWorkspace() {
321
337
  const ids = this.listWorkspaces().data.map((workspace) => Number(workspace.workspace));
322
338
  return String(Math.max(0, ...ids) + 1).padStart(6, "0");
@@ -360,7 +376,11 @@ export class WorkContext {
360
376
  const workspaceRecord = this.storage.readWorkspace(workspace).data;
361
377
  const workspaceTitle = workspaceRecord.title;
362
378
  const workflowPolicy = workspaceMode(workspaceRecord) === "startup" && options.opencodeSessionId ? startupWorkflowPolicy() : null;
379
+ const pendingCandidates = workflowPolicy ? this.candidates().activeProjection(workspace).by_stage[stage] || null : null;
380
+ const deliveryContext = stage === "01" ? this.deliveries().projection(workspace) : null;
381
+ const hasDeliveryContext = deliveryContext && (deliveryContext.committed.count || deliveryContext.environments.length || deliveryContext.unavailable);
363
382
  const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
383
+ const execution = this.storage.readStageExecution(workspace, stage);
364
384
  const automaticFinish = automaticFinishAllowed(this.storage, workspace);
365
385
  return this.result({
366
386
  workspace,
@@ -383,18 +403,22 @@ export class WorkContext {
383
403
  scope: stageRecord.data.prompt || null,
384
404
  previous_result: previousResult,
385
405
  previous_session_summary: previousSessionSummary,
406
+ ...(execution ? { execution_state: execution } : {}),
386
407
  },
387
408
  context: {
388
409
  essence: stageRecord.data.goal || stageRecord.data.title,
389
410
  previous: previousSessionSummary || previousResult || "No previous progress was recorded.",
390
411
  now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
391
- workspace_knowledge: workspaceKnowledge,
412
+ workspace_knowledge: workspaceKnowledge,
413
+ ...(execution ? { execution_state: execution } : {}),
414
+ ...(pendingCandidates ? { pending_candidates: pendingCandidates } : {}),
415
+ ...(hasDeliveryContext ? { delivery_context: deliveryContext } : {}),
392
416
  ...(workflowPolicy ? { workflow_policy: workflowPolicy } : {}),
393
417
  lifecycle: { automatic_finish_allowed: automaticFinish },
394
418
  },
395
419
  next_action: hasPrompt ? confirmationRequired ? "await_confirmation" : "start_work" : "ask_questions",
396
420
  instruction: `${hasPrompt
397
- ? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${startupWorkflowInstruction(workflowPolicy)}`
421
+ ? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${executionInstruction(execution)}${startupWorkflowInstruction(workflowPolicy)}${stage === "01" ? deliveryPlanningInstruction : ""}`
398
422
  : `This stage has no non-empty prompt. Give the user a concise plain-language summary of the stage title and goal, then ask focused questions needed to define the intended outcome and scope. Do not inspect or modify application code yet. Do not report raw operation metadata or identifiers.`}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
399
423
  },
400
424
  }, [workspace, stage]);
@@ -491,6 +515,57 @@ export class WorkContext {
491
515
  });
492
516
  }
493
517
 
518
+ readStageExecution(workspace, stage) {
519
+ workspace = normalizeWorkspaceId(workspace);
520
+ stage = normalizeStageId(stage);
521
+ this.storage.assertNoSymlinks();
522
+ this.storage.readStage(workspace, stage);
523
+ const record = this.storage.readStageExecution(workspace, stage);
524
+ return { ok: true, data: record || { schema: 1, workspace, stage, revision: 0, exists: false, ...normalizeExecutionState({}) } };
525
+ }
526
+
527
+ replaceStageExecution(workspace, stage, sessionId, expectedRevision, input) {
528
+ workspace = normalizeWorkspaceId(workspace);
529
+ stage = normalizeStageId(stage);
530
+ if (!Number.isInteger(expectedRevision) || expectedRevision < 0) fail(ERROR_CODES.INVALID_ARGUMENT, "expectedRevision must be a non-negative integer");
531
+ const state = normalizeExecutionState(input);
532
+ return this.transact(`stage-execution-${workspace}-${stage}`, () => {
533
+ const stageRecord = this.storage.readStage(workspace, stage);
534
+ 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 });
535
+ assertActive(this.storage.readEvents(), workspace, stage, sessionId);
536
+ const current = this.storage.readStageExecution(workspace, stage);
537
+ const revision = current?.revision || 0;
538
+ if (revision !== expectedRevision) fail(ERROR_CODES.EXECUTION_REVISION_CONFLICT, "Stage execution state changed since it was read", { expectedRevision, actualRevision: revision });
539
+ if (current && JSON.stringify(executionState(current)) === JSON.stringify(state)) return this.result(current, []);
540
+ const timestamp = new Date().toISOString();
541
+ const record = { schema: 1, workspace, stage, revision: revision + 1, created_at: current?.created_at || timestamp, updated_at: timestamp, updated_by: actor(this.options), ...state };
542
+ assertExecutionSize(record);
543
+ this.storage.writeStageExecution(workspace, stage, record);
544
+ return this.result(record, [this.storage.stageExecutionFile(workspace, stage)]);
545
+ });
546
+ }
547
+
548
+ updateStageExecution(workspace, stage, sessionId, expectedRevision, patch) {
549
+ workspace = normalizeWorkspaceId(workspace);
550
+ stage = normalizeStageId(stage);
551
+ if (!Number.isInteger(expectedRevision) || expectedRevision < 0) fail(ERROR_CODES.INVALID_ARGUMENT, "expectedRevision must be a non-negative integer");
552
+ return this.transact(`stage-execution-${workspace}-${stage}`, () => {
553
+ const stageRecord = this.storage.readStage(workspace, stage);
554
+ 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 });
555
+ assertActive(this.storage.readEvents(), workspace, stage, sessionId);
556
+ const current = this.storage.readStageExecution(workspace, stage);
557
+ const revision = current?.revision || 0;
558
+ if (revision !== expectedRevision) fail(ERROR_CODES.EXECUTION_REVISION_CONFLICT, "Stage execution state changed since it was read", { expectedRevision, actualRevision: revision });
559
+ const state = applyExecutionPatch(current ? executionState(current) : normalizeExecutionState({}), patch);
560
+ if (current && JSON.stringify(executionState(current)) === JSON.stringify(state)) return this.result(current, []);
561
+ const timestamp = new Date().toISOString();
562
+ const record = { schema: 1, workspace, stage, revision: revision + 1, created_at: current?.created_at || timestamp, updated_at: timestamp, updated_by: actor(this.options), ...state };
563
+ assertExecutionSize(record);
564
+ this.storage.writeStageExecution(workspace, stage, record);
565
+ return this.result(record, [this.storage.stageExecutionFile(workspace, stage)]);
566
+ });
567
+ }
568
+
494
569
  archiveStage(workspace, stage) {
495
570
  workspace = normalizeWorkspaceId(workspace);
496
571
  stage = normalizeStageId(stage);
@@ -718,6 +793,12 @@ export class WorkContext {
718
793
  const knowledgeReview = options.knowledgeReview || "auto";
719
794
  if (!['auto', 'added', 'none'].includes(knowledgeReview)) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge review must be 'auto', 'added' or 'none'");
720
795
  const knowledgeEntries = this.listKnowledge(workspace).data;
796
+ const execution = this.storage.readStageExecution(workspace, stage);
797
+ const executionWarnings = execution ? [
798
+ ...(execution.remaining.length ? [`${execution.remaining.length} remaining item(s)`] : []),
799
+ ...(execution.blockers.length ? [`${execution.blockers.length} blocker(s) or open question(s)`] : []),
800
+ ...(execution.verification.length ? [`${execution.verification.length} pending verification item(s)`] : []),
801
+ ] : [];
721
802
  const active = activeSession(events, workspace, stage);
722
803
  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");
723
804
  this.writeEvents([event("session.closed", workspace, stage, active.ordinal, sessionId, actor(this.options), { reason: "stage_completed" })]);
@@ -728,7 +809,7 @@ export class WorkContext {
728
809
  const promptReview = this.listStages(workspace).data.stages
729
810
  .filter((item) => Number(item.stage) > Number(stage) && !["completed", "archived"].includes(item.status))
730
811
  .map(({ stage: id, title, description, prompt, status }) => ({ stage: id, title, description, prompt: prompt || null, status }));
731
- 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 };
812
+ 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 } : {}) };
732
813
  const incompleteStages = this.listStages(workspace).data.stages.filter((item) => !["completed", "archived"].includes(item.status));
733
814
  const next = incompleteStages.length ? null : {
734
815
  action: "workspace_finish",
@@ -743,8 +824,8 @@ export class WorkContext {
743
824
  help(command = "") {
744
825
  return this.result({
745
826
  command,
746
- 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|workspace finish|workspace reopen|resume|stage add|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|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]",
747
- note: "associated OpenCode sessions in startup-mode workspaces receive the shared-worktree and commit-candidate policy on resume; standard mode remains conservative; candidate strategies are exact, shared_foundation, and integration, with optional related stage references for traceability only; commit candidates are local-only and require startup workflow mode; capture and commit use isolated Git indexes and never alter the ordinary index; candidate commit uses the stored message unless an explicit non-empty override is provided, and bypasses Git hooks and signing; stage finish requires an explicit user lifecycle request unless the Planning-stage prompt contains the exact line AUTO_STAGE_FINISH: allowed; stage reopen requires a completed stage and a reason; stage restore requires an archived stage and a reason, returns its saved pre-archive status (or in_progress for legacy archives), and requires explicit separate-session resume when actionable; workspace reopen requires a completed workspace and a reason.",
827
+ 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 mark|workspace finish|workspace reopen|resume|stage add|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]",
828
+ note: "delivery context is workspace-level local operational state; exact Git range inspection requires explicit immutable from and to hashes, while marking an environment requires DELIVERY_CONFIRMED after successful delivery and never executes deployment commands or stores secrets; stage execution state is a bounded stage-local operational checkpoint; replace and update require the current revision and active stage session, while read is available without mutation; checklist state never completes a stage, and explicit stage finish reports remaining execution work while preserving the final ledger; associated OpenCode sessions in startup-mode workspaces receive the shared-worktree and commit-candidate policy on resume; standard mode remains conservative; candidate strategies are exact, shared_foundation, and integration, with optional related stage references for traceability only; active candidates related to the resumed stage appear in resume.context.pending_candidates; commit candidates are local-only and require startup workflow mode; capture and commit use isolated Git indexes and never alter the ordinary index; candidate commit uses the stored message unless an explicit non-empty override is provided, and bypasses Git hooks and signing; stage finish requires an explicit user lifecycle request unless the Planning-stage prompt contains the exact line AUTO_STAGE_FINISH: allowed; stage reopen requires a completed stage and a reason; stage restore requires an archived stage and a reason, returns its saved pre-archive status (or in_progress for legacy archives), and requires explicit separate-session resume when actionable; workspace reopen requires a completed workspace and a reason.",
748
829
  }, []);
749
830
  }
750
831
 
@@ -0,0 +1,135 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { atomicWrite } from "./storage.js";
5
+ import { ERROR_CODES, fail } from "./errors.js";
6
+ import { normalizeWorkspaceId } from "./identifiers.js";
7
+ import { inspectCommitRange, isCommitAncestor, repositoryState } from "./git-candidates.js";
8
+
9
+ const environmentPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
10
+ const hashPattern = /^[0-9a-f]{40,64}$/;
11
+ const candidatePattern = /^CC-\d{6}$/;
12
+ const timestamp = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
13
+ const maxEnvironments = 20;
14
+ const maxCandidates = 10000;
15
+ const checkpointIntegrity = (checkpoint) => createHash("sha256").update(JSON.stringify({
16
+ deployed_head: checkpoint.deployed_head,
17
+ deployed_at: checkpoint.deployed_at,
18
+ deployed_candidates: checkpoint.deployed_candidates,
19
+ })).digest("hex");
20
+
21
+ const normalizeEnvironment = (value) => {
22
+ if (typeof value !== "string" || !environmentPattern.test(value)) fail(ERROR_CODES.INVALID_ARGUMENT, "Environment must use 1-64 letters, digits, dots, underscores or hyphens");
23
+ return value;
24
+ };
25
+
26
+ export function validateDeliveryRecord(data, workspace) {
27
+ const valid = data && typeof data === "object" && !Array.isArray(data)
28
+ && Object.keys(data).every((key) => ["schema", "workspace", "updated_at", "environments"].includes(key))
29
+ && data.schema === 1 && data.workspace === workspace && /^\d{6}$/.test(data.workspace)
30
+ && timestamp(data.updated_at) && data.environments && typeof data.environments === "object" && !Array.isArray(data.environments)
31
+ && Object.keys(data.environments).length <= maxEnvironments
32
+ && Object.entries(data.environments).every(([name, item]) => environmentPattern.test(name)
33
+ && item && typeof item === "object" && !Array.isArray(item)
34
+ && Object.keys(item).every((key) => ["deployed_head", "deployed_at", "deployed_candidates", "integrity"].includes(key))
35
+ && hashPattern.test(item.deployed_head) && timestamp(item.deployed_at)
36
+ && Array.isArray(item.deployed_candidates) && item.deployed_candidates.length <= maxCandidates
37
+ && item.deployed_candidates.every((candidate) => candidate && typeof candidate === "object" && !Array.isArray(candidate)
38
+ && Object.keys(candidate).length === 2 && candidatePattern.test(candidate.candidate) && hashPattern.test(candidate.commit_hash))
39
+ && new Set(item.deployed_candidates.map((candidate) => candidate.candidate)).size === item.deployed_candidates.length
40
+ && item.deployed_candidates.every((candidate, index) => index === 0 || item.deployed_candidates[index - 1].candidate < candidate.candidate)
41
+ && typeof item.integrity === "string" && /^[0-9a-f]{64}$/.test(item.integrity)
42
+ && item.integrity === checkpointIntegrity(item));
43
+ if (!valid) fail(ERROR_CODES.STORAGE_ERROR, "Invalid delivery checkpoint metadata");
44
+ return data;
45
+ }
46
+
47
+ export class DeliveryStore {
48
+ constructor(context) {
49
+ this.context = context;
50
+ this.directory = path.join(context.storage.personalRoot, "delivery");
51
+ }
52
+
53
+ file(workspace) { return path.join(this.directory, `${workspace}.json`); }
54
+
55
+ assertWorkspace(workspace) {
56
+ workspace = normalizeWorkspaceId(workspace);
57
+ this.context.storage.readWorkspace(workspace);
58
+ return workspace;
59
+ }
60
+
61
+ read(workspace) {
62
+ workspace = this.assertWorkspace(workspace);
63
+ try { return validateDeliveryRecord(JSON.parse(fs.readFileSync(this.file(workspace), "utf8")), workspace); }
64
+ catch (error) {
65
+ if (error.code === "ENOENT") return null;
66
+ if (error.code === ERROR_CODES.STORAGE_ERROR) throw error;
67
+ fail(ERROR_CODES.STORAGE_ERROR, "Invalid delivery checkpoint metadata", { cause: error.message });
68
+ }
69
+ }
70
+
71
+ projection(workspace) {
72
+ workspace = this.assertWorkspace(workspace);
73
+ let record;
74
+ try { record = this.read(workspace); } catch {
75
+ return { committed: this.context.candidates().committedProjection(workspace), plan_needed: false, environments: [], unavailable: true };
76
+ }
77
+ const candidateStore = this.context.candidates();
78
+ const committedRecords = candidateStore.projectionRecords(workspace).filter((candidate) => candidate.status === "committed");
79
+ const committed = candidateStore.committedProjection(workspace);
80
+ const committedById = new Map(committedRecords.map((candidate) => [candidate.candidate, candidate]));
81
+ const invalidCheckpoint = Object.values(record?.environments || {}).some((checkpoint) => checkpoint.deployed_candidates.some((candidate) => {
82
+ const metadata = committedById.get(candidate.candidate);
83
+ return !metadata || metadata.commit_hash !== candidate.commit_hash;
84
+ }));
85
+ if (invalidCheckpoint) return { committed, plan_needed: false, environments: [], unavailable: true };
86
+ const environments = Object.entries(record?.environments || {}).sort(([left], [right]) => left.localeCompare(right)).map(([environment, checkpoint]) => {
87
+ const delivered = new Set(checkpoint.deployed_candidates.map((candidate) => candidate.candidate));
88
+ return {
89
+ environment,
90
+ deployed_at: checkpoint.deployed_at,
91
+ pending: committedRecords.filter((candidate) => !delivered.has(candidate.candidate)).length,
92
+ };
93
+ });
94
+ return {
95
+ committed,
96
+ plan_needed: committed.count > 0 && environments.length === 0,
97
+ environments,
98
+ };
99
+ }
100
+
101
+ readContext(workspace, options = {}) {
102
+ workspace = this.assertWorkspace(workspace);
103
+ const projection = this.projection(workspace);
104
+ const record = this.read(workspace);
105
+ const environment = options.environment === undefined ? null : normalizeEnvironment(options.environment);
106
+ const checkpoint = environment ? record?.environments?.[environment] || null : null;
107
+ const hasFrom = options.from !== undefined;
108
+ const hasTo = options.to !== undefined;
109
+ if (hasFrom !== hasTo) fail(ERROR_CODES.INVALID_ARGUMENT, "Delivery range requires both from and to commit hashes");
110
+ const range = hasFrom ? inspectCommitRange(this.context.storage.projectRoot, options.from, options.to) : null;
111
+ return { workspace, environment, checkpoint, ...projection, ...(range ? { range } : {}) };
112
+ }
113
+
114
+ mark(workspace, environment, commit, confirmation) {
115
+ workspace = this.assertWorkspace(workspace);
116
+ environment = normalizeEnvironment(environment);
117
+ if (confirmation !== "DELIVERY_CONFIRMED") fail(ERROR_CODES.CONFIRMATION_REQUIRED, "Marking delivery requires DELIVERY_CONFIRMED confirmation");
118
+ if (typeof commit !== "string" || !hashPattern.test(commit)) fail(ERROR_CODES.INVALID_ARGUMENT, "Delivery commit must be a full commit hash");
119
+ const repository = repositoryState(this.context.storage.projectRoot);
120
+ if (!isCommitAncestor(repository.root, commit, repository.head)) fail(ERROR_CODES.DELIVERY_INVALID_RANGE, "Delivery commit must be available and reachable from current HEAD", { commit, currentHead: repository.head });
121
+ const committed = this.context.candidates().projectionRecords(workspace).filter((candidate) => candidate.status === "committed");
122
+ const deployedCandidates = committed.filter((candidate) => isCommitAncestor(repository.root, candidate.commit_hash, commit))
123
+ .map((candidate) => ({ candidate: candidate.candidate, commit_hash: candidate.commit_hash }))
124
+ .sort((left, right) => left.candidate.localeCompare(right.candidate));
125
+ const now = new Date().toISOString();
126
+ const record = this.read(workspace) || { schema: 1, workspace, updated_at: now, environments: {} };
127
+ record.updated_at = now;
128
+ const checkpoint = { deployed_head: commit, deployed_at: now, deployed_candidates: deployedCandidates };
129
+ checkpoint.integrity = checkpointIntegrity(checkpoint);
130
+ record.environments[environment] = checkpoint;
131
+ validateDeliveryRecord(record, workspace);
132
+ atomicWrite(this.file(workspace), `${JSON.stringify(record, null, 2)}\n`);
133
+ return { workspace, environment, checkpoint: record.environments[environment] };
134
+ }
135
+ }
package/src/errors.js CHANGED
@@ -9,6 +9,8 @@ export const ERROR_CODES = Object.freeze({
9
9
  CANDIDATE_UNSUPPORTED: "CANDIDATE_UNSUPPORTED", CANDIDATE_STALE_BASE: "CANDIDATE_STALE_BASE",
10
10
  CANDIDATE_CONFLICT: "CANDIDATE_CONFLICT", CANDIDATE_DETACHED_HEAD: "CANDIDATE_DETACHED_HEAD",
11
11
  CANDIDATE_REF_RACE: "CANDIDATE_REF_RACE", CANDIDATE_COMMIT_FAILED: "CANDIDATE_COMMIT_FAILED",
12
+ EXECUTION_REVISION_CONFLICT: "EXECUTION_REVISION_CONFLICT", EXECUTION_LIMIT_EXCEEDED: "EXECUTION_LIMIT_EXCEEDED",
13
+ DELIVERY_INVALID_RANGE: "DELIVERY_INVALID_RANGE", DELIVERY_RANGE_TOO_LARGE: "DELIVERY_RANGE_TOO_LARGE",
12
14
  });
13
15
 
14
16
  export class WorkContextError extends Error {
@@ -10,9 +10,10 @@ const git = (root, args, options = {}) => {
10
10
  encoding: options.encoding === null ? null : "utf8",
11
11
  env: { ...process.env, ...options.env },
12
12
  input: options.input,
13
- maxBuffer: 64 * 1024 * 1024,
13
+ maxBuffer: options.maxBuffer ?? 64 * 1024 * 1024,
14
14
  });
15
15
  if (result.error?.code === "ENOENT") fail(ERROR_CODES.GIT_UNAVAILABLE, "Git executable is unavailable");
16
+ if (result.error?.code === "ENOBUFS") fail(options.code || ERROR_CODES.GIT_UNAVAILABLE, options.message || "Git output exceeded the supported limit", { maxBuffer: options.maxBuffer });
16
17
  if (result.error) fail(ERROR_CODES.GIT_UNAVAILABLE, "Cannot execute Git", { cause: result.error.message });
17
18
  if (result.status !== 0 && !options.allowFailure) {
18
19
  fail(options.code || ERROR_CODES.CANDIDATE_INVALID_PATCH, options.message || "Git operation failed", {
@@ -36,6 +37,48 @@ export function repositoryState(projectRoot) {
36
37
  return { root, head: head.stdout.trim() };
37
38
  }
38
39
 
40
+ const assertCommitHash = (value, label) => {
41
+ if (typeof value !== "string" || !/^[0-9a-f]{40,64}$/.test(value)) fail(ERROR_CODES.INVALID_ARGUMENT, `${label} must be a full commit hash`);
42
+ return value;
43
+ };
44
+
45
+ const commitExists = (root, commit) => git(root, ["cat-file", "-e", `${commit}^{commit}`], { allowFailure: true }).status === 0;
46
+
47
+ export function isCommitAncestor(projectRoot, ancestor, descendant) {
48
+ const repository = repositoryState(projectRoot);
49
+ ancestor = assertCommitHash(ancestor, "Ancestor");
50
+ descendant = assertCommitHash(descendant, "Descendant");
51
+ if (!commitExists(repository.root, ancestor) || !commitExists(repository.root, descendant)) return false;
52
+ return git(repository.root, ["merge-base", "--is-ancestor", ancestor, descendant], { allowFailure: true }).status === 0;
53
+ }
54
+
55
+ export function inspectCommitRange(projectRoot, from, to) {
56
+ const repository = repositoryState(projectRoot);
57
+ from = assertCommitHash(from, "Range start");
58
+ to = assertCommitHash(to, "Range end");
59
+ if (!commitExists(repository.root, from) || !commitExists(repository.root, to) || !isCommitAncestor(repository.root, from, to)) {
60
+ fail(ERROR_CODES.DELIVERY_INVALID_RANGE, "Delivery range must contain available commits in ancestor order", { from, to });
61
+ }
62
+ const commitCount = Number(git(repository.root, ["rev-list", "--count", `${from}..${to}`]).stdout.trim());
63
+ const commits = git(repository.root, ["rev-list", "--reverse", `--skip=${Math.max(0, commitCount - 500)}`, "--max-count=500", `${from}..${to}`]).stdout.trim().split("\n").filter(Boolean);
64
+ const names = git(repository.root, ["diff", "--name-only", "-z", from, to, "--"], {
65
+ encoding: null,
66
+ maxBuffer: 4 * 1024 * 1024,
67
+ code: ERROR_CODES.DELIVERY_RANGE_TOO_LARGE,
68
+ message: "Delivery changed-path output exceeds the supported 4 MiB limit",
69
+ }).stdout.toString("utf8").split("\0").filter(Boolean);
70
+ return {
71
+ from,
72
+ to,
73
+ commit_count: commitCount,
74
+ commits,
75
+ commits_truncated: commitCount > commits.length,
76
+ changed_path_count: names.length,
77
+ changed_paths: names.slice(0, 500),
78
+ paths_truncated: names.length > 500,
79
+ };
80
+ }
81
+
39
82
  function withTemporaryIndex(root, base, fn) {
40
83
  const directory = fs.mkdtempSync(path.join(os.tmpdir(), "work-context-candidate-"));
41
84
  const index = path.join(directory, "index");
package/src/index.js CHANGED
@@ -7,8 +7,10 @@ export * from "./projections.js";
7
7
  export * from "./title.js";
8
8
  export * from "./core.js";
9
9
  export * from "./knowledge.js";
10
+ export * from "./stage-execution.js";
10
11
  export * from "./stages-snapshot.js";
11
12
  export * from "./stages-renderer.js";
12
13
  export * from "./work-context-snapshot.js";
13
14
  export * from "./git-candidates.js";
14
15
  export * from "./candidates.js";
16
+ export * from "./delivery.js";
@@ -0,0 +1,88 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { ERROR_CODES, fail } from "./errors.js";
3
+
4
+ export const EXECUTION_SECTIONS = Object.freeze([
5
+ "scope",
6
+ "completed",
7
+ "remaining",
8
+ "decisions",
9
+ "blockers",
10
+ "verification",
11
+ ]);
12
+
13
+ export const EXECUTION_LIMITS = Object.freeze({
14
+ itemsPerSection: 50,
15
+ totalItems: 200,
16
+ itemLength: 500,
17
+ bytes: 32768,
18
+ });
19
+
20
+ const exactKeys = (value, allowed) => Object.keys(value).every((key) => allowed.includes(key));
21
+ const validTimestamp = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
22
+
23
+ const normalizeItems = (items, section) => {
24
+ if (!Array.isArray(items)) fail(ERROR_CODES.INVALID_ARGUMENT, `${section} must be an array of strings`);
25
+ if (items.length > EXECUTION_LIMITS.itemsPerSection) fail(ERROR_CODES.EXECUTION_LIMIT_EXCEEDED, `${section} cannot contain more than ${EXECUTION_LIMITS.itemsPerSection} items`);
26
+ const normalized = [];
27
+ for (const item of items) {
28
+ if (typeof item !== "string" || !item.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, `${section} must contain non-empty strings`);
29
+ const value = item.trim();
30
+ if (value.length > EXECUTION_LIMITS.itemLength) fail(ERROR_CODES.EXECUTION_LIMIT_EXCEEDED, `Execution items cannot exceed ${EXECUTION_LIMITS.itemLength} characters`);
31
+ if (!normalized.includes(value)) normalized.push(value);
32
+ }
33
+ return normalized;
34
+ };
35
+
36
+ export function normalizeExecutionState(input) {
37
+ if (!input || typeof input !== "object" || Array.isArray(input) || !exactKeys(input, EXECUTION_SECTIONS)) fail(ERROR_CODES.INVALID_ARGUMENT, "Execution state contains unsupported fields");
38
+ const state = Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, normalizeItems(input[section] ?? [], section)]));
39
+ const total = EXECUTION_SECTIONS.reduce((count, section) => count + state[section].length, 0);
40
+ if (total > EXECUTION_LIMITS.totalItems) fail(ERROR_CODES.EXECUTION_LIMIT_EXCEEDED, `Execution state cannot contain more than ${EXECUTION_LIMITS.totalItems} items`);
41
+ const remaining = new Set(state.remaining);
42
+ const overlap = state.completed.find((item) => remaining.has(item));
43
+ if (overlap) fail(ERROR_CODES.INVALID_ARGUMENT, "An item cannot be both completed and remaining", { item: overlap });
44
+ return state;
45
+ }
46
+
47
+ export function applyExecutionPatch(current, patch) {
48
+ if (!patch || typeof patch !== "object" || Array.isArray(patch) || !exactKeys(patch, ["add", "remove"]) || (!patch.add && !patch.remove)) fail(ERROR_CODES.INVALID_ARGUMENT, "Execution update requires add or remove changes");
49
+ const validateChanges = (changes, operation) => {
50
+ if (changes === undefined) return {};
51
+ if (!changes || typeof changes !== "object" || Array.isArray(changes) || !exactKeys(changes, EXECUTION_SECTIONS)) fail(ERROR_CODES.INVALID_ARGUMENT, `Execution ${operation} changes contain unsupported fields`);
52
+ return Object.fromEntries(Object.entries(changes).map(([section, items]) => [section, normalizeItems(items, section)]));
53
+ };
54
+ const add = validateChanges(patch.add, "add");
55
+ const remove = validateChanges(patch.remove, "remove");
56
+ const next = {};
57
+ for (const section of EXECUTION_SECTIONS) {
58
+ const removed = new Set(remove[section] || []);
59
+ next[section] = [...current[section].filter((item) => !removed.has(item)), ...(add[section] || [])];
60
+ }
61
+ return normalizeExecutionState(next);
62
+ }
63
+
64
+ export function validateExecutionRecord(record, workspace, stage) {
65
+ const allowed = ["schema", "workspace", "stage", "revision", "created_at", "updated_at", "updated_by", ...EXECUTION_SECTIONS];
66
+ if (!record || typeof record !== "object" || Array.isArray(record) || !exactKeys(record, allowed)
67
+ || record.schema !== 1 || record.workspace !== workspace || record.stage !== stage
68
+ || !Number.isInteger(record.revision) || record.revision < 1
69
+ || !validTimestamp(record.created_at) || !validTimestamp(record.updated_at)
70
+ || Date.parse(record.updated_at) < Date.parse(record.created_at)
71
+ || typeof record.updated_by !== "string" || !record.updated_by.trim()) {
72
+ fail(ERROR_CODES.STORAGE_ERROR, "Invalid stage execution state");
73
+ }
74
+ let state;
75
+ try { state = normalizeExecutionState(Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, record[section]]))); }
76
+ catch (error) { fail(ERROR_CODES.STORAGE_ERROR, "Invalid stage execution state", { cause: error.message }); }
77
+ if (EXECUTION_SECTIONS.some((section) => JSON.stringify(state[section]) !== JSON.stringify(record[section]))) fail(ERROR_CODES.STORAGE_ERROR, "Stage execution state is not normalized");
78
+ if (Buffer.byteLength(JSON.stringify(record), "utf8") > EXECUTION_LIMITS.bytes) fail(ERROR_CODES.STORAGE_ERROR, "Stage execution state exceeds its storage limit");
79
+ return record;
80
+ }
81
+
82
+ export function executionState(record) {
83
+ return Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, record[section]]));
84
+ }
85
+
86
+ export function assertExecutionSize(record) {
87
+ if (Buffer.byteLength(JSON.stringify(record), "utf8") > EXECUTION_LIMITS.bytes) fail(ERROR_CODES.EXECUTION_LIMIT_EXCEEDED, `Execution state cannot exceed ${EXECUTION_LIMITS.bytes} bytes`);
88
+ }
@@ -7,6 +7,25 @@ const statusMarker = (status) => ({
7
7
  }[status] || "[?]");
8
8
 
9
9
  const compareStageIds = (left, right) => Number(left.id) - Number(right.id);
10
+ const candidateSummary = (stage) => {
11
+ const projection = stage.candidates;
12
+ if (!projection || !(projection.draft || projection.ready)) return null;
13
+ if (projection.draft + projection.ready > 1) return `Pending: ${projection.draft} draft · ${projection.ready} ready`;
14
+ const [candidate] = projection.items;
15
+ const others = candidate.related_stages.filter((related) => related !== stage.id);
16
+ return `Pending: ${candidate.status} · ${candidate.strategy}${others.length ? ` · also ${others.join(", ")}` : ""}`;
17
+ };
18
+ const deliverySummary = (delivery) => {
19
+ if (!delivery) return null;
20
+ if (delivery.unavailable) return "Delivery · unavailable";
21
+ if (delivery.plan_needed) return `Delivery · ${delivery.committed} commits · plan needed`;
22
+ if (delivery.environments.length === 1) {
23
+ const [environment] = delivery.environments;
24
+ return `Delivery · ${environment.environment} · ${environment.pending} tracked pending`;
25
+ }
26
+ const pending = delivery.environments.reduce((total, environment) => total + environment.pending, 0);
27
+ return `Delivery · ${delivery.environments.length} environments · ${pending} tracked pending`;
28
+ };
10
29
 
11
30
  /**
12
31
  * Render normalized stages as a dependency-to-dependent forest. A stage may
@@ -59,10 +78,13 @@ export function renderStagesPanel(result) {
59
78
  `Workflow · ${snapshot.workspace.mode || "standard"}`,
60
79
  ];
61
80
  const candidates = snapshot.workspace.candidates;
62
- if (candidates && (candidates.pending || candidates.ready)) lines.push(`Candidates · pending ${candidates.pending} · ready ${candidates.ready}`);
81
+ if (candidates && (candidates.pending || candidates.ready)) lines.push(`Candidates · ${candidates.pending} draft · ${candidates.ready} ready`);
82
+ const delivery = deliverySummary(snapshot.workspace.delivery);
83
+ if (delivery) lines.push(delivery);
63
84
  lines.push("", `Stages · ${snapshot.workspace.status}`);
64
85
  for (const stage of snapshot.stages) {
65
- lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}${stage.depends_on?.length ? `\nDeps: ${stage.depends_on.join(", ")}` : ""}`);
86
+ const pending = candidateSummary(stage);
87
+ lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}${stage.depends_on?.length ? `\nDeps: ${stage.depends_on.join(", ")}` : ""}${pending ? `\n${pending}` : ""}`);
66
88
  }
67
89
  if (result.stale) lines.push(`! stale: ${result.error?.code || "STORAGE_ERROR"}`);
68
90
  return lines.join("\n");
@@ -35,17 +35,24 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
35
35
 
36
36
  const workspace = context.storage.readWorkspace(session.workspace).data;
37
37
  const mode = workspace.mode || "standard";
38
- const candidates = mode === "startup" ? context.candidates().summary(session.workspace) : null;
39
- const stages = context.listStages(session.workspace).data.stages
38
+ const candidateProjection = mode === "startup" ? context.candidates().activeProjection(session.workspace) : null;
39
+ const deliveryProjection = context.deliveries().projection(session.workspace);
40
+ const delivery = deliveryProjection.committed.count || deliveryProjection.environments.length || deliveryProjection.unavailable
41
+ ? { committed: deliveryProjection.committed.count, plan_needed: deliveryProjection.plan_needed, environments: deliveryProjection.environments, ...(deliveryProjection.unavailable ? { unavailable: true } : {}) }
42
+ : null;
43
+ const visibleStages = context.listStages(session.workspace).data.stages
40
44
  .filter((stage) => stage.status !== "archived")
41
- .sort((left, right) => Number(left.stage) - Number(right.stage))
45
+ .sort((left, right) => Number(left.stage) - Number(right.stage));
46
+ const visibleStageIds = new Set(visibleStages.map((stage) => stage.stage));
47
+ const stages = visibleStages
42
48
  .map((stage) => ({
43
49
  id: stage.stage,
44
50
  title: stage.title,
45
51
  status: stage.status,
46
52
  description: stage.description,
47
- depends_on: stage.depends_on,
53
+ depends_on: stage.depends_on.filter((dependency) => visibleStageIds.has(dependency)),
48
54
  tracker_links: stage.tracker_links || [],
55
+ ...(candidateProjection?.by_stage[stage.stage] ? { candidates: candidateProjection.by_stage[stage.stage] } : {}),
49
56
  current: stage.stage === session.stage,
50
57
  }));
51
58
  const currentStage = stages.some((stage) => stage.current) ? session.stage : null;
@@ -54,7 +61,7 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
54
61
  ok: true,
55
62
  data: {
56
63
  schema: 1,
57
- workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status, mode, ...(candidates ? { candidates } : {}) },
64
+ workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status, mode, ...(candidateProjection ? { candidates: candidateProjection.summary } : {}), ...(delivery ? { delivery } : {}) },
58
65
  stages,
59
66
  currentStage,
60
67
  generatedAt: new Date().toISOString(),
package/src/storage.js CHANGED
@@ -3,6 +3,7 @@ import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { WorkContextError, ERROR_CODES, fail } from "./errors.js";
5
5
  import { parseFrontmatter, renderMarkdown } from "./markdown.js";
6
+ import { validateExecutionRecord } from "./stage-execution.js";
6
7
 
7
8
  const now = () => new Date().toISOString();
8
9
  const ensure = (dir) => fs.mkdirSync(dir, { recursive: true });
@@ -148,10 +149,23 @@ export class FileStorage {
148
149
  workspaceFile(id) { return path.join(this.workspaceDir(id), "workspace.md"); }
149
150
  knowledgeFile(id) { return path.join(this.workspaceDir(id), "KNOWLEDGE.md"); }
150
151
  stageFile(id, stage) { return path.join(this.workspaceDir(id), "stages", `${stage}.md`); }
152
+ stageExecutionFile(id, stage) { return path.join(this.workspaceDir(id), "stages", `${stage}.execution.json`); }
151
153
  sessionFile() { return path.join(this.personalRoot, "sessions.jsonl"); }
152
154
  lockPath(name = "write") { return path.join(this.root, ".locks", `${name}.lock`); }
153
155
  readWorkspace(id) { const record = this.readCanonical(this.workspaceFile(id)); validateMetadata(record.data, "workspace", id); return record; }
154
156
  readStage(id, stage) { const record = this.readCanonical(this.stageFile(id, stage)); validateMetadata(record.data, "stage", id, stage); return record; }
157
+ readStageExecution(id, stage) {
158
+ try { return validateExecutionRecord(JSON.parse(fs.readFileSync(this.stageExecutionFile(id, stage), "utf8")), id, stage); }
159
+ catch (error) {
160
+ if (error.code === "ENOENT") return null;
161
+ if (error.code === ERROR_CODES.STORAGE_ERROR) throw error;
162
+ fail(ERROR_CODES.STORAGE_ERROR, "Invalid stage execution state", { cause: error.message });
163
+ }
164
+ }
165
+ writeStageExecution(id, stage, record) {
166
+ validateExecutionRecord(record, id, stage);
167
+ atomicWrite(this.stageExecutionFile(id, stage), `${JSON.stringify(record, null, 2)}\n`);
168
+ }
155
169
  readKnowledge(id) { try { return fs.readFileSync(this.knowledgeFile(id), "utf8"); } catch (error) { if (error.code === "ENOENT") return null; throw error; } }
156
170
  transactionFile() { return path.join(this.root, ".locks", "transaction.json"); }
157
171
  writeTransaction(snapshot) { atomicWrite(this.transactionFile(), JSON.stringify({ schema: 1, files: snapshot.files.map((item) => ({ file: item.file, content: item.content.toString("base64") })), externalRoots: snapshot.externalRoots }) + "\n"); }