opencode-work-context 0.2.1 → 0.3.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
@@ -73,6 +73,13 @@ To correct a completed stage without discarding its result or session history,
73
73
  use `/wc stage reopen <workspace> <stage> "reason"`. Reopening leaves
74
74
  downstream stages unchanged and requires a separate-session explicit resume.
75
75
 
76
+ To recover an archived stage, use `/wc stage restore <workspace> <stage>
77
+ "reason"`. It restores the status saved during archiving and preserves the
78
+ stage body, result, and recovery history. Archives written by older versions
79
+ did not save their source status and restore to `in_progress`. To reopen an
80
+ accidentally completed workspace, use `/wc workspace reopen <workspace>
81
+ "reason"`; it only accepts `completed` workspaces, never cancelled ones.
82
+
76
83
  When you return later, continue from the active stage. A stage must have a
77
84
  non-empty prompt before implementation begins; if the prompt is missing or
78
85
  ambiguous, `/wc resume` instructs the agent to ask focused questions first.
@@ -243,6 +250,8 @@ accepted only after every stage is `completed`. Use `/wc workspace list <workspa
243
250
  to list stages with their descriptions. Workspace titles can be changed with
244
251
  `/wc workspace rename <workspace> "title"`, and existing stage descriptions can
245
252
  be changed with `/wc stage update <workspace> <stage> "description"`.
253
+ `/wc workspace reopen <workspace> "reason"` records a recovery entry and returns
254
+ only a completed workspace to `in_progress`.
246
255
 
247
256
  If the host `opencode.json` restricts `experimental.primary_tools`, add the
248
257
  registered `work_context_*` tool names to that allowlist; the installer does not
package/commands/wc.md CHANGED
@@ -19,10 +19,12 @@ Use these exact tool mappings; do not invent shortened tool names:
19
19
  - `workspace list <workspace>` or `<workspace> list` -> `work_context_workspace_list`
20
20
  - `workspace rename <workspace> "title"` -> `work_context_rename_workspace`
21
21
  - `workspace finish <workspace>` -> `work_context_workspace_finish`
22
+ - `workspace reopen <workspace> "reason"` -> `work_context_reopen_workspace`
22
23
  - `resume <workspace> <stage>` -> `work_context_start_session`
23
24
  - `stage force-close <workspace> <stage> <sessionId> "reason" FORCE_CLOSE` -> `work_context_force_close_session`
24
25
  - `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
26
  - `stage reopen <workspace> <stage> "reason"` -> `work_context_reopen_stage`
27
+ - `stage restore <workspace> <stage> "reason"` -> `work_context_restore_stage`
26
28
  - `stage rename [<workspace>] [<stage>] "title"` -> `work_context_rename_stage`
27
29
  - `stage update [<workspace>] [<stage>] "description"` -> `work_context_update_stage`
28
30
  - `stage update-prompt [<workspace>] [<stage>] "prompt"` -> `work_context_update_stage_prompt`
@@ -40,10 +42,12 @@ Supported syntax:
40
42
  - `workspace list <workspace>`
41
43
  - `workspace rename <workspace> "title"`
42
44
  - `workspace finish <workspace>`
45
+ - `workspace reopen <workspace> "reason"`
43
46
  - `resume <workspace> <stage>`
44
47
  - `stage force-close <workspace> <stage> <sessionId> "reason" FORCE_CLOSE`
45
48
  - `stage add [<workspace>] "title" ["prompt"]`
46
49
  - `stage reopen <workspace> <stage> "reason"`
50
+ - `stage restore <workspace> <stage> "reason"`
47
51
  - `stage rename [<workspace>] [<stage>] "title"`
48
52
  - `stage update [<workspace>] [<stage>] "description"`
49
53
  - `stage update-prompt [<workspace>] [<stage>] "prompt"`
@@ -76,6 +80,8 @@ Supported syntax:
76
80
  - `stage finish` closes and completes only the current stage session; it never starts, resumes, or binds the same OpenCode session to a downstream stage
77
81
  - `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
82
  - `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
83
+ - `stage restore <workspace> <stage> "reason"` applies only to an archived stage and restores its saved pre-archive status. New archives preserve that status; legacy archives restore to `in_progress`. It records the reason, preserves stage content and results, does not start a session, and requires explicit separate-session `resume` when restored to `planned` or `in_progress`.
84
+ - `workspace reopen <workspace> "reason"` applies only to a completed workspace, changes it to `in_progress`, and records durable recovery history. Cancelled workspaces cannot be reopened.
79
85
  - `knowledge list|add|update|supersede <workspace> ...`
80
86
 
81
87
  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.2.1",
4
+ "version": "0.3.0",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -32,6 +32,7 @@ export const WORK_CONTEXT_ACTIONS = [
32
32
  { value: "workspace.list", title: "Inspect workspace", description: "List one workspace and its stages", category: "Workspace" },
33
33
  { value: "workspace.rename", title: "Rename workspace", description: "Change a workspace title", category: "Workspace" },
34
34
  { value: "workspace.finish", title: "Finish workspace", description: "Complete a workspace", category: "Workspace" },
35
+ { value: "workspace.reopen", title: "Reopen workspace", description: "Reopen a completed workspace with a reason", category: "Workspace" },
35
36
  { value: "stage.add", title: "Add stage", description: "Create a planned stage with an optional prompt", category: "Stage" },
36
37
  { value: "resume", title: "Resume stage", description: "Start or continue work on a stage", category: "Stage" },
37
38
  { value: "stage.rename", title: "Rename stage", description: "Change a stage title", category: "Stage" },
@@ -40,6 +41,7 @@ export const WORK_CONTEXT_ACTIONS = [
40
41
  { value: "stage.update-result", title: "Update stage result", description: "Replace an existing completion result", category: "Stage" },
41
42
  { value: "stage.archive", title: "Archive stage", description: "Archive a non-active stage", category: "Stage" },
42
43
  { value: "stage.reopen", title: "Reopen stage", description: "Reopen a completed stage with a reason", category: "Stage" },
44
+ { value: "stage.restore", title: "Restore stage", description: "Restore an archived stage with a reason", category: "Stage" },
43
45
  { value: "stage.handoff", title: "Hand off stage", description: "Close this session and preserve continuation", category: "Stage" },
44
46
  { value: "stage.abandon", title: "Abandon stage session", description: "Close this session and keep the stage resumable", category: "Stage" },
45
47
  { value: "stage.finish", title: "Finish stage", description: "Complete a stage and review knowledge", category: "Stage" },
@@ -295,6 +297,9 @@ export const buildWorkContextActionCommand = (action, { workspace, stage, value,
295
297
  if (!normalizedWorkspace) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Invalid workspace ID" } };
296
298
  if (action === "workspace.list") return { ok: true, command: `/wc workspace list ${normalizedWorkspace}` };
297
299
  if (action === "workspace.finish") return { ok: true, command: `/wc workspace finish ${normalizedWorkspace}` };
300
+ if (action === "workspace.reopen") return value?.trim()
301
+ ? { ok: true, command: `/wc workspace reopen ${normalizedWorkspace} ${quoteWorkContextArgument(value.trim())}` }
302
+ : { ok: false, error: { code: "INVALID_ARGUMENT", message: "Reason is required" } };
298
303
  if (action === "workspace.rename") return value?.trim()
299
304
  ? { ok: true, command: `/wc workspace rename ${normalizedWorkspace} ${quoteWorkContextArgument(value.trim())}` }
300
305
  : { ok: false, error: { code: "INVALID_ARGUMENT", message: "Title is required" } };
@@ -306,7 +311,7 @@ export const buildWorkContextActionCommand = (action, { workspace, stage, value,
306
311
  if (!normalizedStage) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Invalid stage ID" } };
307
312
  const commandName = action.replace(".", " ");
308
313
  if (["resume", "stage.archive", "stage.handoff", "stage.abandon", "stage.finish"].includes(action)) return { ok: true, command: `/wc ${commandName} ${normalizedWorkspace} ${normalizedStage}` };
309
- const inputCommands = { "stage.rename": "title", "stage.update": "description", "stage.update-prompt": "prompt", "stage.update-result": "result", "stage.reopen": "reason" };
314
+ const inputCommands = { "stage.rename": "title", "stage.update": "description", "stage.update-prompt": "prompt", "stage.update-result": "result", "stage.reopen": "reason", "stage.restore": "reason" };
310
315
  if (Object.hasOwn(inputCommands, action)) return value?.trim()
311
316
  ? { ok: true, command: `/wc ${commandName} ${normalizedWorkspace} ${normalizedStage} ${quoteWorkContextArgument(value.trim())}` }
312
317
  : { ok: false, error: { code: "INVALID_ARGUMENT", message: `${inputCommands[action][0].toUpperCase()}${inputCommands[action].slice(1)} is required` } };
@@ -339,7 +344,7 @@ export const createWorkContextActionFlow = (api, { projectRoot, sessionId, read
339
344
  else if (action === "stage.update") requireValue("Update stage description", "Description", action, context);
340
345
  else if (action === "stage.update-prompt") requireValue("Update stage prompt", "Detailed prompt", action, context);
341
346
  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);
347
+ else if (action === "stage.reopen" || action === "stage.restore") requireValue(action === "stage.restore" ? "Restore stage" : "Reopen stage", action === "stage.restore" ? "Reason for restoring" : "Reason for reopening", action, context);
343
348
  else void insert(buildWorkContextActionCommand(action, context));
344
349
  };
345
350
  const selectStage = (action, workspace, stages) => showSelect("Select stage", stages.map((stage) => ({
@@ -367,6 +372,7 @@ export const createWorkContextActionFlow = (api, { projectRoot, sessionId, read
367
372
  })), (option) => {
368
373
  const workspace = option.value;
369
374
  if (action === "workspace.list" || action === "workspace.finish") void insert(buildWorkContextActionCommand(action, { workspace: workspace.id }));
375
+ else if (action === "workspace.reopen") requireValue("Reopen workspace", "Reason for reopening", action, { workspace: workspace.id });
370
376
  else if (action === "workspace.rename") requireValue("Rename workspace", "New title", action, { workspace: workspace.id });
371
377
  else if (action === "stage.add") addStage(workspace.id);
372
378
  else if (!workspace.stages?.length) toast("No stages found");
@@ -381,16 +387,17 @@ export const createWorkContextActionFlow = (api, { projectRoot, sessionId, read
381
387
  };
382
388
  const showWorkspaceActions = (workspace) => showSelect(`${workspace.id} ${workspace.title}`, [
383
389
  { title: "Back to workspaces", value: "back", category: "Navigation" },
384
- ...WORK_CONTEXT_ACTIONS.filter((action) => ["workspace.list", "stage.add", "workspace.rename", "workspace.finish"].includes(action.value)),
390
+ ...WORK_CONTEXT_ACTIONS.filter((action) => ["workspace.list", "stage.add", "workspace.rename", "workspace.finish", "workspace.reopen"].includes(action.value)),
385
391
  ], (option) => {
386
392
  if (option.value === "back") { void browseWorkspaces(); return; }
387
393
  if (option.value === "workspace.list" || option.value === "workspace.finish") void insert(buildWorkContextActionCommand(option.value, { workspace: workspace.id }));
394
+ else if (option.value === "workspace.reopen") requireValue("Reopen workspace", "Reason for reopening", option.value, { workspace: workspace.id });
388
395
  else if (option.value === "workspace.rename") requireValue("Rename workspace", "New title", option.value, { workspace: workspace.id });
389
396
  else if (option.value === "stage.add") addStage(workspace.id);
390
397
  });
391
398
  const showStageActions = (workspace, stage, { backTitle = "Back to workspaces", onBack = () => void browseWorkspaces() } = {}) => showSelect(`${workspace.id}/${stage.id} ${stage.title}`, [
392
399
  { title: backTitle, value: "back", category: "Navigation" },
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)),
400
+ ...WORK_CONTEXT_ACTIONS.filter((action) => ["resume", "stage.rename", "stage.update", "stage.update-prompt", "stage.update-result", "stage.archive", "stage.reopen", "stage.restore", "stage.handoff", "stage.abandon", "stage.finish"].includes(action.value)),
394
401
  ], (option) => {
395
402
  if (option.value === "back") { onBack(); return; }
396
403
  runStageAction(option.value, workspace.id, stage.id);
package/src/core.js CHANGED
@@ -15,11 +15,13 @@ const activeKnowledge = (records) => records
15
15
  .map(({ id: knowledgeId, title, kind, text, sources }) => ({ id: knowledgeId, title, kind, text, sources }));
16
16
  const body = (title, goal = "", prompt = "") => `# ${title}\n\n${goal ? `## Goal\n\n${goal}\n` : ""}${prompt ? `\n## Prompt\n\n${prompt}\n` : ""}`;
17
17
  const stageBody = (record, title, goal, prompt = record.data.prompt || "") => {
18
- const result = record.body.match(/\n## Result\s*\n[\s\S]*?(?=\n## Reopen History|$)/)?.[0] || "";
19
- const history = record.body.match(/\n## Reopen History[\s\S]*?(?=\n## Result|$)/)?.[0] || "";
20
- return `${body(title, goal, prompt).trimEnd()}${result}${history}`;
18
+ const result = record.body.match(/\n## Result\s*\n[\s\S]*?(?=\n## (?:Reopen|Archive) History|$)/)?.[0] || "";
19
+ const reopenHistory = record.body.match(/\n## Reopen History[\s\S]*?(?=\n## (?:Result|Archive History)|$)/)?.[0] || "";
20
+ const archiveHistory = record.body.match(/\n## Archive History[\s\S]*?(?=\n## (?:Result|Reopen History)|$)/)?.[0] || "";
21
+ return `${body(title, goal, prompt).trimEnd()}${result}${reopenHistory}${archiveHistory}`;
21
22
  };
22
- const stageResult = (record) => record.body.match(/\n## Result\s*\n([\s\S]*?)(?=\n## Reopen History|$)/)?.[1]?.trim() ?? null;
23
+ const stageResult = (record) => record.body.match(/\n## Result\s*\n([\s\S]*?)(?=\n## (?:Reopen|Archive) History|$)/)?.[1]?.trim() ?? null;
24
+ const appendHistory = (bodyText, heading, entry) => `${bodyText.trimEnd()}${bodyText.includes(`\n## ${heading}\n`) ? "" : `\n\n## ${heading}\n`}\n- ${entry}\n`;
23
25
  const automaticFinishAllowed = (storage, workspace) => /(?:^|\n)AUTO_STAGE_FINISH:\s*allowed\s*$/mi.test(storage.readStage(workspace, "01").data.prompt || "");
24
26
  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; } } };
25
27
 
@@ -138,6 +140,23 @@ export class WorkContext {
138
140
  });
139
141
  }
140
142
 
143
+ reopenWorkspace(workspace, reason) {
144
+ workspace = normalizeWorkspaceId(workspace);
145
+ if (!reason?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Reopen reason is required");
146
+ return this.transact(`workspace-${workspace}`, () => {
147
+ const record = this.storage.readWorkspace(workspace);
148
+ if (record.data.status !== "completed") fail(ERROR_CODES.INVALID_STATE, "Only completed workspaces can be reopened", { status: record.data.status });
149
+ const reopenedAt = new Date().toISOString();
150
+ const entry = { at: reopenedAt, reason: reason.trim(), actor: actor(this.options) };
151
+ record.data.status = "in_progress";
152
+ record.data.reopen_history = [...(record.data.reopen_history || []), entry];
153
+ record.data.updated_at = reopenedAt;
154
+ this.storage.writeMarkdown(this.storage.workspaceFile(workspace), record.data, appendHistory(record.body, "Reopen History", `${reopenedAt}: ${reason.trim()}`));
155
+ generateProjections(this.storage);
156
+ return this.result({ workspace, status: "in_progress", reopen: entry }, [workspace]);
157
+ });
158
+ }
159
+
141
160
  sessionById(sessionId) {
142
161
  return reduceSessions(this.storage.readEvents()).find((session) => session.session_id === sessionId) || null;
143
162
  }
@@ -365,8 +384,9 @@ export class WorkContext {
365
384
  const nextResult = result.trim();
366
385
  if (currentResult === nextResult) return this.result({ workspace, stage, result: nextResult }, []);
367
386
  record.data.updated_at = new Date().toISOString();
368
- const history = record.body.match(/\n## Reopen History[\s\S]*?(?=\n## Result|$)/)?.[0] || "";
369
- const nextBody = `${body(record.data.title, record.data.goal, record.data.prompt).trimEnd()}\n\n## Result\n\n${nextResult}${history}`;
387
+ const history = record.body.match(/\n## Reopen History[\s\S]*?(?=\n## (?:Result|Archive History)|$)/)?.[0] || "";
388
+ const archiveHistory = record.body.match(/\n## Archive History[\s\S]*?(?=\n## (?:Result|Reopen History)|$)/)?.[0] || "";
389
+ const nextBody = `${body(record.data.title, record.data.goal, record.data.prompt).trimEnd()}\n\n## Result\n\n${nextResult}${history}${archiveHistory}`;
370
390
  this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, nextBody);
371
391
  generateProjections(this.storage);
372
392
  return this.result({ workspace, stage, result: nextResult }, [workspace, stage]);
@@ -380,14 +400,46 @@ export class WorkContext {
380
400
  const record = this.storage.readStage(workspace, stage);
381
401
  if (record.data.status === "archived") return this.result({ workspace, stage, status: "archived" }, []);
382
402
  if (activeSession(this.storage.readEvents(), workspace, stage)) fail(ERROR_CODES.ACTIVE_SESSION_EXISTS, "Cannot archive a stage with an active session");
403
+ const archivedAt = new Date().toISOString();
404
+ const entry = { action: "archived", at: archivedAt, actor: actor(this.options), previous_status: record.data.status };
383
405
  record.data.status = "archived";
384
- record.data.updated_at = new Date().toISOString();
385
- this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, record.body);
406
+ record.data.archive_history = [...(record.data.archive_history || []), entry];
407
+ record.data.updated_at = archivedAt;
408
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, appendHistory(record.body, "Archive History", `${archivedAt}: archived from ${entry.previous_status}`));
386
409
  generateProjections(this.storage);
387
410
  return this.result({ workspace, stage, status: "archived" }, [workspace, stage]);
388
411
  });
389
412
  }
390
413
 
414
+ restoreStage(workspace, stage, reason) {
415
+ workspace = normalizeWorkspaceId(workspace);
416
+ stage = normalizeStageId(stage);
417
+ if (!reason?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Restore reason is required");
418
+ return this.transact(`stage-${workspace}-${stage}`, () => {
419
+ const workspaceRecord = this.storage.readWorkspace(workspace);
420
+ if (workspaceRecord.data.status === "cancelled") fail(ERROR_CODES.INVALID_STATE, "Cannot restore a stage in a cancelled workspace");
421
+ const record = this.storage.readStage(workspace, stage);
422
+ const active = activeSession(this.storage.readEvents(), workspace, stage);
423
+ if (active) fail(ERROR_CODES.ACTIVE_SESSION_EXISTS, "Cannot restore a stage with an active session", { session_id: active.session_id });
424
+ if (record.data.status !== "archived") fail(ERROR_CODES.INVALID_STATE, "Only archived stages can be restored", { status: record.data.status });
425
+ const archived = [...(record.data.archive_history || [])].reverse().find((item) => item.action === "archived");
426
+ const restoredStatus = archived?.previous_status || "in_progress";
427
+ const restoredAt = new Date().toISOString();
428
+ const entry = { action: "restored", at: restoredAt, reason: reason.trim(), actor: actor(this.options), restored_status: restoredStatus };
429
+ record.data.status = restoredStatus;
430
+ record.data.archive_history = [...(record.data.archive_history || []), entry];
431
+ record.data.updated_at = restoredAt;
432
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, appendHistory(record.body, "Archive History", `${restoredAt}: restored to ${restoredStatus}; ${reason.trim()}`));
433
+ if (workspaceRecord.data.status === "completed" && ["planned", "in_progress"].includes(restoredStatus)) {
434
+ workspaceRecord.data.status = "in_progress";
435
+ workspaceRecord.data.updated_at = restoredAt;
436
+ this.storage.writeMarkdown(this.storage.workspaceFile(workspace), workspaceRecord.data, workspaceRecord.body);
437
+ }
438
+ generateProjections(this.storage);
439
+ return this.result({ workspace, stage, status: restoredStatus, restore: entry, session_started: false, resume_required: ["planned", "in_progress"].includes(restoredStatus) }, [workspace, stage]);
440
+ });
441
+ }
442
+
391
443
  listKnowledge(workspace) {
392
444
  workspace = normalizeWorkspaceId(workspace);
393
445
  this.storage.assertNoSymlinks();
@@ -520,10 +572,11 @@ export class WorkContext {
520
572
  record.data.status = "in_progress";
521
573
  record.data.reopen_history = [...(record.data.reopen_history || []), entry];
522
574
  record.data.updated_at = reopenedAt;
523
- const history = record.body.match(/\n## Reopen History[\s\S]*?(?=\n## Result|$)/)?.[0]
575
+ const history = record.body.match(/\n## Reopen History[\s\S]*?(?=\n## (?:Result|Archive History)|$)/)?.[0]
524
576
  || "\n\n## Reopen History\n";
525
577
  const priorResult = previousResult ? `\n Previous result: ${previousResult}` : "";
526
- 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`);
578
+ const archiveHistory = record.body.match(/\n## Archive History[\s\S]*?(?=\n## (?:Result|Reopen History)|$)/)?.[0] || "";
579
+ 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}`);
527
580
  if (workspaceRecord.data.status === "completed") {
528
581
  workspaceRecord.data.status = "in_progress";
529
582
  workspaceRecord.data.updated_at = reopenedAt;
@@ -574,8 +627,8 @@ export class WorkContext {
574
627
  help(command = "") {
575
628
  return this.result({
576
629
  command,
577
- 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]",
578
- 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.",
630
+ syntax: "/wc [create|list|workspace list|workspace rename|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|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
631
+ 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; 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.",
579
632
  }, []);
580
633
  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." }, []);
581
634
  }
package/src/storage.js CHANGED
@@ -40,6 +40,17 @@ const validReopenHistory = (history) => Array.isArray(history) && history.every(
40
40
  && requiredString(item, "reason")
41
41
  && requiredString(item, "actor")
42
42
  && (item.previous_result === undefined || requiredString(item, "previous_result")));
43
+ const validArchiveHistory = (history) => Array.isArray(history) && history.every((item) => item
44
+ && typeof item === "object"
45
+ && !Array.isArray(item)
46
+ && Object.keys(item).every((key) => ["action", "at", "reason", "actor", "previous_status", "restored_status"].includes(key))
47
+ && ["archived", "restored"].includes(item.action)
48
+ && validTimestamp(item.at)
49
+ && requiredString(item, "actor")
50
+ && (item.reason === undefined || requiredString(item, "reason"))
51
+ && (item.previous_status === undefined || ["planned", "in_progress", "completed", "cancelled"].includes(item.previous_status))
52
+ && (item.restored_status === undefined || ["planned", "in_progress", "completed", "cancelled"].includes(item.restored_status))
53
+ && (item.action === "archived" ? item.previous_status !== undefined && item.reason === undefined && item.restored_status === undefined : requiredString(item, "reason") && item.restored_status !== undefined && item.previous_status === undefined));
43
54
  const validEvents = new Set(["session.started", "session.renamed", "session.handed_off", "session.closed", "session.abandoned"]);
44
55
  const validateEvent = (item) => {
45
56
  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");
@@ -77,13 +88,22 @@ const validateEventStream = (events) => {
77
88
  }
78
89
  };
79
90
  function validateMetadata(data, kind, workspace, stage = null) {
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"];
91
+ const allowed = kind === "workspace" ? ["schema", "workspace", "title", "status", "created_at", "updated_at", "tracker_links", "reopen_history"] : ["schema", "workspace", "stage", "title", "status", "goal", "prompt", "depends_on", "owner", "created_at", "updated_at", "tracker_links", "reopen_history", "archive_history"];
81
92
  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`);
82
93
  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`);
83
94
  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`);
84
95
  const statuses = kind === "workspace" ? ["in_progress", "completed", "cancelled"] : ["planned", "in_progress", "completed", "cancelled", "archived"];
85
96
  if (!statuses.includes(data.status)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} status`);
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");
97
+ const invalidWorkspaceHistory = kind === "workspace" && data.reopen_history !== undefined && !validReopenHistory(data.reopen_history);
98
+ const invalidStageMetadata = kind === "stage" && (
99
+ data.stage !== stage || !/^\d{2}$/.test(data.stage) || !requiredString(data, "goal")
100
+ || (data.prompt !== undefined && !requiredString(data, "prompt")) || !requiredString(data, "owner")
101
+ || !Array.isArray(data.depends_on) || new Set(data.depends_on).size !== data.depends_on.length
102
+ || data.depends_on.includes(data.stage) || data.depends_on.some((item) => typeof item !== "string" || !/^\d{2}$/.test(item))
103
+ || (data.reopen_history !== undefined && !validReopenHistory(data.reopen_history))
104
+ || (data.archive_history !== undefined && !validArchiveHistory(data.archive_history))
105
+ );
106
+ if (invalidWorkspaceHistory || invalidStageMetadata) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} metadata`);
87
107
  }
88
108
  export function atomicWrite(file, content) {
89
109
  ensure(path.dirname(file));
@@ -53,6 +53,7 @@ export const work_context_list_workspaces = tool({ description: "List work-conte
53
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)) });
54
54
  export const work_context_rename_workspace = tool({ description: "Rename a workspace.", args: { workspace: tool.schema.string(), title: tool.schema.string() }, execute: run((ctx, a) => ctx.renameWorkspace(a.workspace, a.title)) });
55
55
  export const work_context_workspace_finish = tool({ description: "Finish a workspace after all stages are completed.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.finishWorkspace(a.workspace)) });
56
+ export const work_context_reopen_workspace = tool({ description: "Reopen a completed workspace with a required reason and durable history.", args: { workspace: tool.schema.string(), reason: tool.schema.string() }, execute: run((ctx, a) => ctx.reopenWorkspace(a.workspace, a.reason)) });
56
57
  export const work_context_create_workspace = tool({ description: "Create a workspace; enter its planning stage only when the current OpenCode session is not associated with a workspace.", args: { title: tool.schema.string() }, execute: run((ctx, a, oc) => {
57
58
  const currentSession = ctx.sessionByOpenCodeId(oc.sessionID);
58
59
  return ctx.createWorkspace(a.title, { sessionId: randomUUID(), ...(currentSession ? {} : { opencodeSessionId: oc.sessionID }) });
@@ -65,6 +66,7 @@ export const work_context_update_stage_prompt = tool({ description: "Update the
65
66
  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); }) });
66
67
  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
68
  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)) });
69
+ export const work_context_restore_stage = tool({ description: "Restore an archived stage to its saved pre-archive status with a required reason. Actionable stages require explicit resume in a separate OpenCode session.", args: { ...common, reason: tool.schema.string() }, execute: run((ctx, a) => ctx.restoreStage(a.workspace, a.stage, a.reason)) });
68
70
  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)) });
69
71
  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); }) });
70
72
  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)); }) });
@@ -78,4 +80,4 @@ export const work_context_add_knowledge = tool({ description: "Add a durable kno
78
80
  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)) });
79
81
  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) ) });
80
82
 
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 };
83
+ export default { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_workspace_finish, work_context_reopen_workspace, 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_restore_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_workspace } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_reopen_workspace;
@@ -0,0 +1,3 @@
1
+ import { work_context_restore_stage } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_restore_stage;