opencode-work-context 0.1.13 → 0.2.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/README.md CHANGED
@@ -54,11 +54,24 @@ Then create a task and its first stage in OpenCode:
54
54
  /wc resume 000001 02
55
55
  ```
56
56
 
57
- `stage add` only creates a `planned` stage. It never starts that stage or binds
58
- the current OpenCode session to it. Open a separate OpenCode session and use
59
- `/wc resume <workspace> <stage>` explicitly for every transition into an added
60
- stage. Multiple sessions may work on the same non-terminal stage through
61
- explicit resume and handoff operations.
57
+ `stage add` creates a stage and, when run from a new OpenCode session that is
58
+ not associated with a workspace, immediately enters the new stage in that
59
+ session. From an already associated session it only creates a `planned` stage;
60
+ use `/wc resume <workspace> <stage>` in a separate OpenCode session to enter it.
61
+ Multiple sessions may work on the same non-terminal stage through explicit
62
+ resume and handoff operations.
63
+
64
+ Stages remain in progress until the user explicitly requests `/wc stage finish`.
65
+ Do not infer that request from completed work. Automatic completion is allowed
66
+ only when the workspace Planning-stage prompt includes this standalone line:
67
+
68
+ ```text
69
+ AUTO_STAGE_FINISH: allowed
70
+ ```
71
+
72
+ To correct a completed stage without discarding its result or session history,
73
+ use `/wc stage reopen <workspace> <stage> "reason"`. Reopening leaves
74
+ downstream stages unchanged and requires a separate-session explicit resume.
62
75
 
63
76
  When you return later, continue from the active stage. A stage must have a
64
77
  non-empty prompt before implementation begins; if the prompt is missing or
package/commands/wc.md CHANGED
@@ -22,6 +22,7 @@ Use these exact tool mappings; do not invent shortened tool names:
22
22
  - `resume <workspace> <stage>` -> `work_context_start_session`
23
23
  - `stage force-close <workspace> <stage> <sessionId> "reason" FORCE_CLOSE` -> `work_context_force_close_session`
24
24
  - `stage add [<workspace>] ...` -> `work_context_add_stage` (optional `prompt`; a detailed local prompt is expected for stages created from planning, while shared context belongs in workspace knowledge)
25
+ - `stage reopen <workspace> <stage> "reason"` -> `work_context_reopen_stage`
25
26
  - `stage rename [<workspace>] [<stage>] "title"` -> `work_context_rename_stage`
26
27
  - `stage update [<workspace>] [<stage>] "description"` -> `work_context_update_stage`
27
28
  - `stage update-prompt [<workspace>] [<stage>] "prompt"` -> `work_context_update_stage_prompt`
@@ -42,6 +43,7 @@ Supported syntax:
42
43
  - `resume <workspace> <stage>`
43
44
  - `stage force-close <workspace> <stage> <sessionId> "reason" FORCE_CLOSE`
44
45
  - `stage add [<workspace>] "title" ["prompt"]`
46
+ - `stage reopen <workspace> <stage> "reason"`
45
47
  - `stage rename [<workspace>] [<stage>] "title"`
46
48
  - `stage update [<workspace>] [<stage>] "description"`
47
49
  - `stage update-prompt [<workspace>] [<stage>] "prompt"`
@@ -64,13 +66,16 @@ Supported syntax:
64
66
  - on every subsequent resume, report the context and wait for explicit user confirmation; do not automatically continue implementation
65
67
  - when `resume.next_action` is `await_confirmation`, do not inspect or modify application code until the user confirms
66
68
  - `create` enters the new workspace's Planning stage in the current OpenCode session only when that session is not yet in a workspace; otherwise it only creates the workspace and its planning session
67
- - `stage add` only creates a planned stage; it never starts, resumes, or binds the current OpenCode session to that stage, even when the session is not yet associated with a workspace
68
- - entering an added stage always requires a separate OpenCode session and an explicit `resume <workspace> <stage>` operation; do not invoke `resume` automatically after creation
69
+ - `stage add` creates a stage; when the current OpenCode session is not associated with a workspace, it also enters the new stage in that session
70
+ - when `stage add` is invoked from an associated session, it only creates a planned stage and leaves the current stage unchanged; enter it later with an explicit `resume <workspace> <stage>` in a separate OpenCode session
69
71
  - `resume` returns `resume.next_action` and `resume.instruction`; begin or continue implementation only when the stage prompt is non-empty and, after reviewing it, there are no unanswered questions
70
72
  - when `resume.next_action` is `ask_questions`, do not inspect or modify application code and ask the user focused questions needed to make the prompt actionable
71
73
  - before `stage finish`, review durable findings: add new knowledge, update changed knowledge, supersede obsolete knowledge, or explicitly use `knowledgeReview=none` when the stage produced no durable findings; use `knowledgeReview=added` after ledger changes
74
+ - invoke `stage finish` only when the user explicitly requests that lifecycle command; do not infer the request from completed work, tests, or a final report
75
+ - automatic completion is allowed only when the current workspace's Planning-stage prompt contains an exact standalone line `AUTO_STAGE_FINISH: allowed`; otherwise leave the stage in progress and report that the work is ready for the user's lifecycle decision
72
76
  - `stage finish` closes and completes only the current stage session; it never starts, resumes, or binds the same OpenCode session to a downstream stage
73
77
  - `stage finish` always validates the Knowledge Base and returns total and active entry counts plus downstream unfinished stages for informational prompt review; do not begin a downstream stage until the user explicitly resumes it in a separate OpenCode session
78
+ - `stage reopen <workspace> <stage> "reason"` applies only to a completed stage, preserves its result and completion history, records the reason, changes it to `in_progress`, and does not start a session or affect downstream stages; use an explicit separate-session `resume` to work on it again
74
79
  - `knowledge list|add|update|supersede <workspace> ...`
75
80
 
76
81
  Arguments: $ARGUMENTS
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-work-context",
3
3
  "type": "module",
4
- "version": "0.1.13",
4
+ "version": "0.2.0",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -39,6 +39,7 @@ export const WORK_CONTEXT_ACTIONS = [
39
39
  { value: "stage.update-prompt", title: "Update stage prompt", description: "Replace the detailed working prompt", category: "Stage" },
40
40
  { value: "stage.update-result", title: "Update stage result", description: "Replace an existing completion result", category: "Stage" },
41
41
  { value: "stage.archive", title: "Archive stage", description: "Archive a non-active stage", category: "Stage" },
42
+ { value: "stage.reopen", title: "Reopen stage", description: "Reopen a completed stage with a reason", category: "Stage" },
42
43
  { value: "stage.handoff", title: "Hand off stage", description: "Close this session and preserve continuation", category: "Stage" },
43
44
  { value: "stage.abandon", title: "Abandon stage session", description: "Close this session and keep the stage resumable", category: "Stage" },
44
45
  { value: "stage.finish", title: "Finish stage", description: "Complete a stage and review knowledge", category: "Stage" },
@@ -305,7 +306,7 @@ export const buildWorkContextActionCommand = (action, { workspace, stage, value,
305
306
  if (!normalizedStage) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Invalid stage ID" } };
306
307
  const commandName = action.replace(".", " ");
307
308
  if (["resume", "stage.archive", "stage.handoff", "stage.abandon", "stage.finish"].includes(action)) return { ok: true, command: `/wc ${commandName} ${normalizedWorkspace} ${normalizedStage}` };
308
- const inputCommands = { "stage.rename": "title", "stage.update": "description", "stage.update-prompt": "prompt", "stage.update-result": "result" };
309
+ const inputCommands = { "stage.rename": "title", "stage.update": "description", "stage.update-prompt": "prompt", "stage.update-result": "result", "stage.reopen": "reason" };
309
310
  if (Object.hasOwn(inputCommands, action)) return value?.trim()
310
311
  ? { ok: true, command: `/wc ${commandName} ${normalizedWorkspace} ${normalizedStage} ${quoteWorkContextArgument(value.trim())}` }
311
312
  : { ok: false, error: { code: "INVALID_ARGUMENT", message: `${inputCommands[action][0].toUpperCase()}${inputCommands[action].slice(1)} is required` } };
@@ -338,6 +339,7 @@ export const createWorkContextActionFlow = (api, { projectRoot, sessionId, read
338
339
  else if (action === "stage.update") requireValue("Update stage description", "Description", action, context);
339
340
  else if (action === "stage.update-prompt") requireValue("Update stage prompt", "Detailed prompt", action, context);
340
341
  else if (action === "stage.update-result") requireValue("Update stage result", "Completion result", action, context);
342
+ else if (action === "stage.reopen") requireValue("Reopen stage", "Reason for reopening", action, context);
341
343
  else void insert(buildWorkContextActionCommand(action, context));
342
344
  };
343
345
  const selectStage = (action, workspace, stages) => showSelect("Select stage", stages.map((stage) => ({
@@ -388,7 +390,7 @@ export const createWorkContextActionFlow = (api, { projectRoot, sessionId, read
388
390
  });
389
391
  const showStageActions = (workspace, stage, { backTitle = "Back to workspaces", onBack = () => void browseWorkspaces() } = {}) => showSelect(`${workspace.id}/${stage.id} ${stage.title}`, [
390
392
  { title: backTitle, value: "back", category: "Navigation" },
391
- ...WORK_CONTEXT_ACTIONS.filter((action) => ["resume", "stage.rename", "stage.update", "stage.update-prompt", "stage.update-result", "stage.archive", "stage.handoff", "stage.abandon", "stage.finish"].includes(action.value)),
393
+ ...WORK_CONTEXT_ACTIONS.filter((action) => ["resume", "stage.rename", "stage.update", "stage.update-prompt", "stage.update-result", "stage.archive", "stage.reopen", "stage.handoff", "stage.abandon", "stage.finish"].includes(action.value)),
392
394
  ], (option) => {
393
395
  if (option.value === "back") { onBack(); return; }
394
396
  runStageAction(option.value, workspace.id, stage.id);
@@ -64,7 +64,6 @@ export const createWorkspaceSwitcherFlow = (api, { read = readWorkContextSnapsho
64
64
  description: workspace.selectedSession
65
65
  ? `${workspace.status} · ${workspace.selectedSession.state || "unknown"} session`
66
66
  : `${workspace.status} · no OpenCode session available`,
67
- footer: workspace.selectedSession?.opencode_session_id,
68
67
  category: workspace.id === data.currentWorkspace ? "Current" : workspace.status,
69
68
  disabled: !workspace.selectedSession,
70
69
  value: workspace,
package/src/core.js CHANGED
@@ -14,10 +14,12 @@ const activeKnowledge = (records) => records
14
14
  .map(({ id: knowledgeId, title, kind, text, sources }) => ({ id: knowledgeId, title, kind, text, sources }));
15
15
  const body = (title, goal = "", prompt = "") => `# ${title}\n\n${goal ? `## Goal\n\n${goal}\n` : ""}${prompt ? `\n## Prompt\n\n${prompt}\n` : ""}`;
16
16
  const stageBody = (record, title, goal, prompt = record.data.prompt || "") => {
17
- const result = record.body.match(/\n## Result[\s\S]*$/)?.[0] || "";
18
- return `${body(title, goal, prompt).trimEnd()}${result}`;
17
+ const result = record.body.match(/\n## Result\s*\n[\s\S]*?(?=\n## Reopen History|$)/)?.[0] || "";
18
+ const history = record.body.match(/\n## Reopen History[\s\S]*?(?=\n## Result|$)/)?.[0] || "";
19
+ return `${body(title, goal, prompt).trimEnd()}${result}${history}`;
19
20
  };
20
- const stageResult = (record) => record.body.match(/\n## Result\s*\n([\s\S]*)$/)?.[1]?.trim() ?? null;
21
+ const stageResult = (record) => record.body.match(/\n## Result\s*\n([\s\S]*?)(?=\n## Reopen History|$)/)?.[1]?.trim() ?? null;
22
+ const automaticFinishAllowed = (storage, workspace) => /(?:^|\n)AUTO_STAGE_FINISH:\s*allowed\s*$/mi.test(storage.readStage(workspace, "01").data.prompt || "");
21
23
  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; } } };
22
24
 
23
25
  function parseIssue(url) {
@@ -164,7 +166,7 @@ export class WorkContext {
164
166
  fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
165
167
  this.storage.writeMarkdown(this.storage.workspaceFile(workspace), { schema: 1, workspace, title: title.trim(), status: "in_progress", created_at: now, updated_at: now, tracker_links: [] }, body(title));
166
168
  const planningGoal = "Clarify the work goal and constraints";
167
- const planningPrompt = "Diagnose and plan the task without functional changes. 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.";
169
+ const planningPrompt = "Diagnose and plan the task without functional changes. 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.";
168
170
  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));
169
171
  const sessionId = options.sessionId || randomUUID();
170
172
  if (this.storage.readEvents().some((item) => item.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
@@ -187,9 +189,10 @@ export class WorkContext {
187
189
  previous: "The previous session did not save a result; the stopping point needs to be clarified.",
188
190
  now: planningPrompt,
189
191
  workspace_knowledge: [],
192
+ lifecycle: { automatic_finish_allowed: false },
190
193
  },
191
194
  next_action: "start_work",
192
- instruction: planningPrompt,
195
+ instruction: `${planningPrompt}\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.`,
193
196
  },
194
197
  }, [workspace, "01"]);
195
198
  });
@@ -246,6 +249,7 @@ export class WorkContext {
246
249
  const firstResume = previous.length === 0;
247
250
  const hasPrompt = Boolean(stageRecord.data.prompt?.trim());
248
251
  const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
252
+ const automaticFinish = automaticFinishAllowed(this.storage, workspace);
249
253
  return this.result({
250
254
  workspace,
251
255
  stage,
@@ -265,14 +269,15 @@ export class WorkContext {
265
269
  previous: previousSession?.summary || "The previous session did not save a result; the stopping point needs to be clarified.",
266
270
  now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
267
271
  workspace_knowledge: workspaceKnowledge,
272
+ lifecycle: { automatic_finish_allowed: automaticFinish },
268
273
  },
269
274
  next_action: hasPrompt ? (firstResume ? "start_work" : "await_confirmation") : "ask_questions",
270
- instruction: hasPrompt
275
+ instruction: `${hasPrompt
271
276
  ? firstResume
272
277
  ? stageRecord.data.prompt
273
278
  || `Review stage ${stage}: ${stageRecord.data.title} and begin work only after confirming there are no unanswered questions.`
274
279
  : `Stage ${stage}: ${stageRecord.data.title} was resumed before. Report the context and wait for the user's confirmation before continuing work.`
275
- : `Stage ${stage}: ${stageRecord.data.title} has no non-empty prompt. Do not start implementation; ask the user the questions needed to define the work.`,
280
+ : `Stage ${stage}: ${stageRecord.data.title} has no non-empty prompt. Do not start implementation; ask the user the questions needed to define the work.`}\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.`,
276
281
  },
277
282
  }, [workspace, stage]);
278
283
  });
@@ -353,12 +358,14 @@ export class WorkContext {
353
358
  if (!result?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Result is required");
354
359
  return this.transact(`stage-${workspace}-${stage}`, () => {
355
360
  const record = this.storage.readStage(workspace, stage);
361
+ if (record.data.status !== "completed") fail(ERROR_CODES.INVALID_STATE, "Cannot update the result of an unfinished stage");
356
362
  const currentResult = stageResult(record);
357
363
  if (currentResult === null) fail(ERROR_CODES.INVALID_STATE, "Stage has no result to update");
358
364
  const nextResult = result.trim();
359
365
  if (currentResult === nextResult) return this.result({ workspace, stage, result: nextResult }, []);
360
366
  record.data.updated_at = new Date().toISOString();
361
- const nextBody = `${body(record.data.title, record.data.goal, record.data.prompt).trimEnd()}\n\n## Result\n\n${nextResult}`;
367
+ const history = record.body.match(/\n## Reopen History[\s\S]*?(?=\n## Result|$)/)?.[0] || "";
368
+ const nextBody = `${body(record.data.title, record.data.goal, record.data.prompt).trimEnd()}\n\n## Result\n\n${nextResult}${history}`;
362
369
  this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, nextBody);
363
370
  generateProjections(this.storage);
364
371
  return this.result({ workspace, stage, result: nextResult }, [workspace, stage]);
@@ -495,6 +502,37 @@ export class WorkContext {
495
502
  return this.closeSession(workspace, stage, sessionId, reason, "abandoned");
496
503
  }
497
504
 
505
+ reopenStage(workspace, stage, reason) {
506
+ workspace = normalizeWorkspaceId(workspace);
507
+ stage = normalizeStageId(stage);
508
+ if (!reason?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Reopen reason is required");
509
+ return this.transact(`stage-${workspace}-${stage}`, () => {
510
+ const workspaceRecord = this.storage.readWorkspace(workspace);
511
+ if (workspaceRecord.data.status === "cancelled") fail(ERROR_CODES.INVALID_STATE, "Cannot reopen a stage in a cancelled workspace");
512
+ const record = this.storage.readStage(workspace, stage);
513
+ const active = activeSession(this.storage.readEvents(), workspace, stage);
514
+ if (active) fail(ERROR_CODES.ACTIVE_SESSION_EXISTS, "Cannot reopen a stage with an active session", { session_id: active.session_id });
515
+ if (record.data.status !== "completed") fail(ERROR_CODES.INVALID_STATE, "Only completed stages can be reopened", { status: record.data.status });
516
+ const reopenedAt = new Date().toISOString();
517
+ const previousResult = stageResult(record);
518
+ const entry = { at: reopenedAt, reason: reason.trim(), actor: actor(this.options), ...(previousResult ? { previous_result: previousResult } : {}) };
519
+ record.data.status = "in_progress";
520
+ record.data.reopen_history = [...(record.data.reopen_history || []), entry];
521
+ record.data.updated_at = reopenedAt;
522
+ const history = record.body.match(/\n## Reopen History[\s\S]*?(?=\n## Result|$)/)?.[0]
523
+ || "\n\n## Reopen History\n";
524
+ const priorResult = previousResult ? `\n Previous result: ${previousResult}` : "";
525
+ 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`);
526
+ if (workspaceRecord.data.status === "completed") {
527
+ workspaceRecord.data.status = "in_progress";
528
+ workspaceRecord.data.updated_at = reopenedAt;
529
+ this.storage.writeMarkdown(this.storage.workspaceFile(workspace), workspaceRecord.data, workspaceRecord.body);
530
+ }
531
+ generateProjections(this.storage);
532
+ return this.result({ workspace, stage, status: "in_progress", reopen: entry, session_started: false, resume_required: true }, [workspace, stage]);
533
+ });
534
+ }
535
+
498
536
  finish(workspace, stage, sessionId, options = {}) {
499
537
  workspace = normalizeWorkspaceId(workspace);
500
538
  stage = normalizeStageId(stage);
@@ -533,7 +571,12 @@ export class WorkContext {
533
571
  }
534
572
 
535
573
  help(command = "") {
536
- return this.result({ command, syntax: "/wc [create|list|workspace list|workspace rename|workspace finish|resume|stage add|stage rename|stage update|stage update-prompt|stage update-result|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]", note: "workspace and stage are optional for stage rename/update/update-prompt/update-result/archive/handoff/abandon/finish and session rename/close when the current session identifies them; explicit workspace and stage positions accept padded or unpadded positive integer IDs and structured results remain canonical; zero, signs, decimals, whitespace, and overlong identifiers are invalid; stage update-result requires an existing stage result; finish <stage> is a shortcut for stage finish <stage>; when only one numeric identifier is supplied, six digits mean workspace and one or two digits mean stage; stage add accepts an optional local prompt and only creates a planned stage; entering any added stage requires an explicit resume in a new OpenCode session; resume returns resume.next_action, resume.instruction, and active shared entries in resume.context.workspace_knowledge; implementation may begin only with a non-empty prompt and no unanswered questions; ask focused questions and do not modify application code when next_action is ask_questions; force-close requires a session ID, reason, and exact confirmation FORCE_CLOSE; before stage finish, add, update, or supersede durable findings, or explicitly declare none; stage finish closes only the current stage session and returns downstream stages for informational prompt review without starting one; workspace finish requires all non-archived stages to be completed; archived stages retain their IDs and history and are hidden from the TUI by default; mutating commands call structured tools; only explicit lifecycle operations change storage." }, []);
574
+ return this.result({
575
+ command,
576
+ syntax: "/wc [create|list|workspace list|workspace rename|workspace finish|resume|stage add|stage reopen|stage rename|stage update|stage update-prompt|stage update-result|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
577
+ note: "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, preserves completion history, does not affect downstream stages, and requires explicit separate-session resume.",
578
+ }, []);
579
+ return this.result({ command, syntax: "/wc [create|list|workspace list|workspace rename|workspace finish|resume|stage add|stage rename|stage update|stage update-prompt|stage update-result|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]", note: "workspace and stage are optional for stage rename/update/update-prompt/update-result/archive/handoff/abandon/finish and session rename/close when the current session identifies them; explicit workspace and stage positions accept padded or unpadded positive integer IDs and structured results remain canonical; zero, signs, decimals, whitespace, and overlong identifiers are invalid; stage update-result requires an existing stage result; finish <stage> is a shortcut for stage finish <stage>; when only one numeric identifier is supplied, six digits mean workspace and one or two digits mean stage; stage add accepts an optional local prompt; from an unassociated OpenCode session it also enters the new stage immediately, while an associated session remains on its current stage; resume returns resume.next_action, resume.instruction, and active shared entries in resume.context.workspace_knowledge; implementation may begin only with a non-empty prompt and no unanswered questions; ask focused questions and do not modify application code when next_action is ask_questions; force-close requires a session ID, reason, and exact confirmation FORCE_CLOSE; before stage finish, add, update, or supersede durable findings, or explicitly declare none; stage finish closes only the current stage session and returns downstream stages for informational prompt review without starting one; workspace finish requires all non-archived stages to be completed; archived stages retain their IDs and history and are hidden from the TUI by default; mutating commands call structured tools; only explicit lifecycle operations change storage." }, []);
537
580
  }
538
581
 
539
582
  result(data, changed, next = null) {
package/src/storage.js CHANGED
@@ -32,6 +32,14 @@ const validTrackerLinks = (links) => links.every((link) => {
32
32
  return false;
33
33
  } catch { return false; }
34
34
  });
35
+ const validReopenHistory = (history) => Array.isArray(history) && history.every((item) => item
36
+ && typeof item === "object"
37
+ && !Array.isArray(item)
38
+ && Object.keys(item).every((key) => ["at", "reason", "actor", "previous_result"].includes(key))
39
+ && validTimestamp(item.at)
40
+ && requiredString(item, "reason")
41
+ && requiredString(item, "actor")
42
+ && (item.previous_result === undefined || requiredString(item, "previous_result")));
35
43
  const validEvents = new Set(["session.started", "session.renamed", "session.handed_off", "session.closed", "session.abandoned"]);
36
44
  const validateEvent = (item) => {
37
45
  if (!item || item.schema !== 1 || Object.keys(item).some((key) => !["schema", "event_id", "event", "occurred_at", "session_id", "workspace", "stage", "ordinal", "actor", "data"].includes(key)) || !validEvents.has(item.event) || typeof item.event_id !== "string" || !item.event_id.trim() || !validTimestamp(item.occurred_at) || typeof item.session_id !== "string" || !item.session_id.trim() || !/^\d{6}$/.test(item.workspace) || !/^\d{2}$/.test(item.stage) || !Number.isInteger(item.ordinal) || item.ordinal < 1 || typeof item.actor !== "string" || !item.actor.trim() || !item.data || typeof item.data !== "object" || Array.isArray(item.data)) fail(ERROR_CODES.STORAGE_ERROR, "Invalid session event");
@@ -69,13 +77,13 @@ const validateEventStream = (events) => {
69
77
  }
70
78
  };
71
79
  function validateMetadata(data, kind, workspace, stage = null) {
72
- const allowed = kind === "workspace" ? ["schema", "workspace", "title", "status", "created_at", "updated_at", "tracker_links"] : ["schema", "workspace", "stage", "title", "status", "goal", "prompt", "depends_on", "owner", "created_at", "updated_at", "tracker_links"];
80
+ const allowed = kind === "workspace" ? ["schema", "workspace", "title", "status", "created_at", "updated_at", "tracker_links"] : ["schema", "workspace", "stage", "title", "status", "goal", "prompt", "depends_on", "owner", "created_at", "updated_at", "tracker_links", "reopen_history"];
73
81
  if (Object.keys(data).some((key) => !allowed.includes(key)) || data.schema !== 1 || !requiredString(data, "workspace") || !/^\d{6}$/.test(data.workspace) || data.workspace !== workspace) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} metadata`);
74
82
  if (!requiredString(data, "title") || !validTimestamp(data.created_at) || !validTimestamp(data.updated_at) || Date.parse(data.updated_at) < Date.parse(data.created_at) || !Array.isArray(data.tracker_links)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} metadata`);
75
83
  if (!validTrackerLinks(data.tracker_links) || data.tracker_links.some((link) => !link.provider.trim() || !link.project.trim() || ((link.provider === "gitlab" || link.provider === "github") ? (!Number.isInteger(link.iid) || link.iid < 1) : !link.key?.trim()))) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} tracker links`);
76
84
  const statuses = kind === "workspace" ? ["in_progress", "completed", "cancelled"] : ["planned", "in_progress", "completed", "cancelled", "archived"];
77
85
  if (!statuses.includes(data.status)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} status`);
78
- if (kind === "stage" && (data.stage !== stage || !/^\d{2}$/.test(data.stage) || !requiredString(data, "goal") || (data.prompt !== undefined && !requiredString(data, "prompt")) || !requiredString(data, "owner") || !Array.isArray(data.depends_on) || new Set(data.depends_on).size !== data.depends_on.length || data.depends_on.includes(data.stage) || data.depends_on.some((item) => typeof item !== "string" || !/^\d{2}$/.test(item)))) fail(ERROR_CODES.STORAGE_ERROR, "Invalid stage metadata");
86
+ if (kind === "stage" && (data.stage !== stage || !/^\d{2}$/.test(data.stage) || !requiredString(data, "goal") || (data.prompt !== undefined && !requiredString(data, "prompt")) || !requiredString(data, "owner") || !Array.isArray(data.depends_on) || new Set(data.depends_on).size !== data.depends_on.length || data.depends_on.includes(data.stage) || data.depends_on.some((item) => typeof item !== "string" || !/^\d{2}$/.test(item)) || (data.reopen_history !== undefined && !validReopenHistory(data.reopen_history)))) fail(ERROR_CODES.STORAGE_ERROR, "Invalid stage metadata");
79
87
  }
80
88
  export function atomicWrite(file, content) {
81
89
  ensure(path.dirname(file));
@@ -33,9 +33,21 @@ const sessionFor = (ctx, oc, workspace, stage) => ctx.sessionById(oc.sessionID)?
33
33
  && ctx.sessionById(oc.sessionID)?.stage === stage
34
34
  ? oc.sessionID
35
35
  : ctx.sessionByOpenCodeId(oc.sessionID, workspace, stage)?.session_id || oc.sessionID;
36
- const addStageFromTool = (ctx, args) => {
36
+ const addStageFromTool = (ctx, args, oc) => {
37
+ const currentSession = sessionFromContext(ctx);
37
38
  const workspace = workspaceFromSession(ctx, args.workspace);
38
- return ctx.addStage(workspace, args.title, { goal: args.goal, prompt: args.prompt, dependsOn: args.dependsOn });
39
+ const created = ctx.addStage(workspace, args.title, { goal: args.goal, prompt: args.prompt, dependsOn: args.dependsOn });
40
+ if (currentSession) return created;
41
+
42
+ const started = ctx.startSession(workspace, created.data.stage, {
43
+ sessionId: randomUUID(),
44
+ opencodeSessionId: oc.sessionID,
45
+ summary: `started ${args.title.trim()}`,
46
+ });
47
+ return {
48
+ ...started,
49
+ data: { ...started.data, status: "in_progress", session_started: true, resume_required: false },
50
+ };
39
51
  };
40
52
  export const work_context_list_workspaces = tool({ description: "List work-context workspaces.", args: {}, execute: run((ctx) => ctx.listWorkspaces()) });
41
53
  export const work_context_workspace_list = tool({ description: "List a workspace with stage descriptions and sessions.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.listStages(a.workspace)) });
@@ -46,23 +58,24 @@ export const work_context_create_workspace = tool({ description: "Create a works
46
58
  return ctx.createWorkspace(a.title, { sessionId: randomUUID(), ...(currentSession ? {} : { opencodeSessionId: oc.sessionID }) });
47
59
  }) });
48
60
  export const work_context_start_session = tool({ description: "Start a new active session for a stage and return its prompt plus active workspace knowledge.", args: { ...common, summary: tool.schema.string().optional() }, execute: run((ctx, a, oc) => ctx.startSession(a.workspace, a.stage, { sessionId: randomUUID(), opencodeSessionId: oc.sessionID, summary: a.summary, takeover: true })) });
49
- export const work_context_add_stage = tool({ description: "Add a planned stage without starting it; use resume explicitly in a new OpenCode session to enter the stage.", args: { workspace: tool.schema.string().optional(), title: tool.schema.string(), goal: tool.schema.string().optional(), prompt: tool.schema.string().optional(), dependsOn: tool.schema.array(tool.schema.string()).optional() }, execute: run(addStageFromTool) });
61
+ export const work_context_add_stage = tool({ description: "Add a stage; when the current OpenCode session is not associated with a workspace, enter the new stage in that session immediately.", args: { workspace: tool.schema.string().optional(), title: tool.schema.string(), goal: tool.schema.string().optional(), prompt: tool.schema.string().optional(), dependsOn: tool.schema.array(tool.schema.string()).optional() }, execute: run(addStageFromTool) });
50
62
  export const work_context_rename_stage = tool({ description: "Rename a stage while preserving its ID and history; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, title: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.renameStage(workspace, stageFromSession(ctx, workspace, a.stage), a.title); }) });
51
63
  export const work_context_update_stage = tool({ description: "Update an existing stage description; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, description: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.updateStage(workspace, stageFromSession(ctx, workspace, a.stage), a.description); }) });
52
64
  export const work_context_update_stage_prompt = tool({ description: "Update the optional working prompt of an existing stage; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, prompt: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.updateStagePrompt(workspace, stageFromSession(ctx, workspace, a.stage), a.prompt); }) });
53
65
  export const work_context_update_stage_result = tool({ description: "Update an existing stage result; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, result: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.updateStageResult(workspace, stageFromSession(ctx, workspace, a.stage), a.result); }) });
54
66
  export const work_context_archive_stage = tool({ description: "Archive a stage while preserving its ID and history; workspace and stage can be omitted in the current OpenCode session.", args: contextualStage, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.archiveStage(workspace, stageFromSession(ctx, workspace, a.stage)); }) });
67
+ export const work_context_reopen_stage = tool({ description: "Reopen a completed stage with a reason. This preserves completion history and requires explicit resume in a separate OpenCode session.", args: { ...common, reason: tool.schema.string() }, execute: run((ctx, a) => ctx.reopenStage(a.workspace, a.stage, a.reason)) });
55
68
  export const work_context_link_issue = tool({ description: "Link a GitLab issue URL to workspace or stage.", args: { workspace: tool.schema.string(), url: tool.schema.string(), stage: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.linkIssue(a.workspace, a.url, a.stage)) });
56
69
  export const work_context_rename_session = tool({ description: "Rename the current active session summary; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, summary: tool.schema.string() }, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.renameSession(workspace, stage, sessionFor(ctx, oc, workspace, stage), a.summary); }) });
57
70
  export const work_context_close_session = tool({ description: "Close the current session without finishing its stage; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage }, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.closeSession(workspace, stage, sessionFor(ctx, oc, workspace, stage)); }) });
58
71
  export const work_context_force_close_session = tool({ description: "Force close a stale active session with an explicit reason and confirmation.", args: { workspace: tool.schema.string(), stage: tool.schema.string(), sessionId: tool.schema.string(), reason: tool.schema.string(), confirmation: tool.schema.string() }, execute: run((ctx, a) => ctx.forceCloseSession(a.workspace, a.stage, a.sessionId, a.reason, a.confirmation)) });
59
72
  export const work_context_handoff_stage = tool({ description: "Hand off the current stage by closing the current session; workspace and stage can be omitted in the current OpenCode session.", args: contextualStage, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.handoff(workspace, stage, sessionFor(ctx, oc, workspace, stage)); }) });
60
73
  export const work_context_abandon_stage = tool({ description: "Abandon the current stage session without completing the stage; workspace and stage can be omitted in the current OpenCode session.", args: contextualStage, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.abandon(workspace, stage, sessionFor(ctx, oc, workspace, stage)); }) });
61
- export const work_context_finish_stage = tool({ description: "Finish a stage after reviewing durable workspace knowledge; use knowledgeReview=added after changes or none when no durable findings exist. The ledger is always validated.", args: { ...contextualStage, result: tool.schema.string().optional(), knowledgeReview: tool.schema.string().optional() }, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.finish(workspace, stage, sessionFor(ctx, oc, workspace, stage), { result: a.result, knowledgeReview: a.knowledgeReview }); }) });
74
+ export const work_context_finish_stage = tool({ description: "Finish a stage only for an explicit user lifecycle request, unless the Planning-stage prompt explicitly permits automatic completion. Review durable workspace knowledge; use knowledgeReview=added after changes or none when no durable findings exist.", args: { ...contextualStage, result: tool.schema.string().optional(), knowledgeReview: tool.schema.string().optional() }, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.finish(workspace, stage, sessionFor(ctx, oc, workspace, stage), { result: a.result, knowledgeReview: a.knowledgeReview }); }) });
62
75
  export const work_context_help = tool({ description: "Show work-context command help.", args: { command: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.help(a.command)) });
63
76
  export const work_context_list_knowledge = tool({ description: "List durable knowledge entries for a workspace.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.listKnowledge(a.workspace)) });
64
77
  export const work_context_add_knowledge = tool({ description: "Add a durable knowledge entry.", args: { workspace: tool.schema.string(), title: tool.schema.string(), kind: tool.schema.string().optional(), text: tool.schema.string(), sources: tool.schema.array(tool.schema.string()).optional() }, execute: run((ctx, a) => ctx.addKnowledge(a.workspace, a)) });
65
78
  export const work_context_update_knowledge = tool({ description: "Update a durable knowledge entry.", args: { workspace: tool.schema.string(), knowledgeId: tool.schema.string(), title: tool.schema.string().optional(), kind: tool.schema.string().optional(), status: tool.schema.string().optional(), text: tool.schema.string().optional(), sources: tool.schema.array(tool.schema.string()).optional(), replacement: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.updateKnowledge(a.workspace, a.knowledgeId, a)) });
66
79
  export const work_context_supersede_knowledge = tool({ description: "Supersede a durable knowledge entry.", args: { workspace: tool.schema.string(), knowledgeId: tool.schema.string(), replacement: tool.schema.string() }, execute: run((ctx, a) => ctx.supersedeKnowledge(a.workspace, a.knowledgeId, a.replacement) ) });
67
80
 
68
- export default { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_workspace_finish, work_context_create_workspace, work_context_start_session, work_context_add_stage, work_context_rename_stage, work_context_update_stage, work_context_update_stage_prompt, work_context_update_stage_result, work_context_archive_stage, work_context_link_issue, work_context_rename_session, work_context_close_session, work_context_force_close_session, work_context_handoff_stage, work_context_abandon_stage, work_context_finish_stage, work_context_help, work_context_list_knowledge, work_context_add_knowledge, work_context_update_knowledge, work_context_supersede_knowledge };
81
+ export default { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_workspace_finish, work_context_create_workspace, work_context_start_session, work_context_add_stage, work_context_rename_stage, work_context_update_stage, work_context_update_stage_prompt, work_context_update_stage_result, work_context_archive_stage, work_context_reopen_stage, work_context_link_issue, work_context_rename_session, work_context_close_session, work_context_force_close_session, work_context_handoff_stage, work_context_abandon_stage, work_context_finish_stage, work_context_help, work_context_list_knowledge, work_context_add_knowledge, work_context_update_knowledge, work_context_supersede_knowledge };
@@ -0,0 +1,3 @@
1
+ import { work_context_reopen_stage } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_reopen_stage;