opencode-work-context 0.1.13 → 0.2.1
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 +18 -5
- package/commands/wc.md +7 -2
- package/package.json +1 -1
- package/plugin/stage-switcher.js +2 -2
- package/plugin/work-context-modal.js +4 -2
- package/plugin/workspace-switcher.js +0 -1
- package/src/core.js +54 -10
- package/src/stage-status.js +3 -0
- package/src/storage.js +10 -2
- package/src/tool-definitions.js +18 -5
- package/tools/work_context_reopen_stage.js +3 -0
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`
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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`
|
|
68
|
-
-
|
|
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
package/plugin/stage-switcher.js
CHANGED
|
@@ -2,6 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { contextFor } from "../src/opencode-adapter.js";
|
|
4
4
|
import { atomicWrite } from "../src/storage.js";
|
|
5
|
+
import { isDependencySatisfied } from "../src/stage-status.js";
|
|
5
6
|
|
|
6
7
|
const TERMINAL_STATUSES = new Set(["completed", "cancelled", "archived"]);
|
|
7
8
|
const SESSION_STATE_RANK = { active: 0, handed_off: 1, abandoned: 2, closed: 3 };
|
|
@@ -69,7 +70,6 @@ export const readStageSwitcherSnapshot = ({ projectRoot: root, sessionId } = {})
|
|
|
69
70
|
const listed = context.listStages(current.workspace).data;
|
|
70
71
|
const workspace = context.listWorkspaces().data.find((item) => item.workspace === current.workspace);
|
|
71
72
|
if (!workspace) return errorResult("NOT_FOUND", "The current work-context workspace no longer exists");
|
|
72
|
-
const completed = new Set(listed.stages.filter((stage) => stage.status === "completed").map((stage) => stage.stage));
|
|
73
73
|
return {
|
|
74
74
|
ok: true,
|
|
75
75
|
data: {
|
|
@@ -77,7 +77,7 @@ export const readStageSwitcherSnapshot = ({ projectRoot: root, sessionId } = {})
|
|
|
77
77
|
currentStage: current.stage,
|
|
78
78
|
stages: listed.stages.map((stage) => {
|
|
79
79
|
const sessions = listed.sessions.filter((session) => session.stage === stage.stage);
|
|
80
|
-
const blockers = (stage.depends_on || []).filter((dependency) => !
|
|
80
|
+
const blockers = (stage.depends_on || []).filter((dependency) => !isDependencySatisfied(listed.stages.find((item) => item.stage === dependency)));
|
|
81
81
|
return {
|
|
82
82
|
id: stage.stage,
|
|
83
83
|
title: stage.title,
|
|
@@ -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
|
@@ -7,6 +7,7 @@ import { event, reduceSessions, activeSession, assertActive } from "./sessions.j
|
|
|
7
7
|
import { generateProjections, renderSessions } from "./projections.js";
|
|
8
8
|
import { nextKnowledgeId, parseKnowledge, renderKnowledge, validateKnowledgeInput, validateKnowledgeRecords } from "./knowledge.js";
|
|
9
9
|
import { normalizeStageId, normalizeWorkspaceId } from "./identifiers.js";
|
|
10
|
+
import { isDependencySatisfied } from "./stage-status.js";
|
|
10
11
|
|
|
11
12
|
const actor = (options) => options.actor || "OpenCode";
|
|
12
13
|
const activeKnowledge = (records) => records
|
|
@@ -14,10 +15,12 @@ const activeKnowledge = (records) => records
|
|
|
14
15
|
.map(({ id: knowledgeId, title, kind, text, sources }) => ({ id: knowledgeId, title, kind, text, sources }));
|
|
15
16
|
const body = (title, goal = "", prompt = "") => `# ${title}\n\n${goal ? `## Goal\n\n${goal}\n` : ""}${prompt ? `\n## Prompt\n\n${prompt}\n` : ""}`;
|
|
16
17
|
const stageBody = (record, title, goal, prompt = record.data.prompt || "") => {
|
|
17
|
-
const result = record.body.match(/\n## Result[\s\S]
|
|
18
|
-
|
|
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}`;
|
|
19
21
|
};
|
|
20
|
-
const stageResult = (record) => record.body.match(/\n## Result\s*\n([\s\S]
|
|
22
|
+
const stageResult = (record) => record.body.match(/\n## Result\s*\n([\s\S]*?)(?=\n## Reopen History|$)/)?.[1]?.trim() ?? null;
|
|
23
|
+
const automaticFinishAllowed = (storage, workspace) => /(?:^|\n)AUTO_STAGE_FINISH:\s*allowed\s*$/mi.test(storage.readStage(workspace, "01").data.prompt || "");
|
|
21
24
|
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
25
|
|
|
23
26
|
function parseIssue(url) {
|
|
@@ -150,7 +153,7 @@ export class WorkContext {
|
|
|
150
153
|
const stages = this.listStages(workspace).data.stages;
|
|
151
154
|
for (const dependency of stageRecord.data.depends_on) {
|
|
152
155
|
const record = stages.find((item) => item.stage === dependency);
|
|
153
|
-
if (!record
|
|
156
|
+
if (!isDependencySatisfied(record)) fail(ERROR_CODES.INVALID_STATE, `Stage dependency is not completed: ${dependency}`);
|
|
154
157
|
}
|
|
155
158
|
}
|
|
156
159
|
|
|
@@ -164,7 +167,7 @@ export class WorkContext {
|
|
|
164
167
|
fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
|
|
165
168
|
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
169
|
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.";
|
|
170
|
+
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
171
|
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
172
|
const sessionId = options.sessionId || randomUUID();
|
|
170
173
|
if (this.storage.readEvents().some((item) => item.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
|
|
@@ -187,9 +190,10 @@ export class WorkContext {
|
|
|
187
190
|
previous: "The previous session did not save a result; the stopping point needs to be clarified.",
|
|
188
191
|
now: planningPrompt,
|
|
189
192
|
workspace_knowledge: [],
|
|
193
|
+
lifecycle: { automatic_finish_allowed: false },
|
|
190
194
|
},
|
|
191
195
|
next_action: "start_work",
|
|
192
|
-
instruction: planningPrompt,
|
|
196
|
+
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
197
|
},
|
|
194
198
|
}, [workspace, "01"]);
|
|
195
199
|
});
|
|
@@ -246,6 +250,7 @@ export class WorkContext {
|
|
|
246
250
|
const firstResume = previous.length === 0;
|
|
247
251
|
const hasPrompt = Boolean(stageRecord.data.prompt?.trim());
|
|
248
252
|
const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
|
|
253
|
+
const automaticFinish = automaticFinishAllowed(this.storage, workspace);
|
|
249
254
|
return this.result({
|
|
250
255
|
workspace,
|
|
251
256
|
stage,
|
|
@@ -265,14 +270,15 @@ export class WorkContext {
|
|
|
265
270
|
previous: previousSession?.summary || "The previous session did not save a result; the stopping point needs to be clarified.",
|
|
266
271
|
now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
|
|
267
272
|
workspace_knowledge: workspaceKnowledge,
|
|
273
|
+
lifecycle: { automatic_finish_allowed: automaticFinish },
|
|
268
274
|
},
|
|
269
275
|
next_action: hasPrompt ? (firstResume ? "start_work" : "await_confirmation") : "ask_questions",
|
|
270
|
-
instruction: hasPrompt
|
|
276
|
+
instruction: `${hasPrompt
|
|
271
277
|
? firstResume
|
|
272
278
|
? stageRecord.data.prompt
|
|
273
279
|
|| `Review stage ${stage}: ${stageRecord.data.title} and begin work only after confirming there are no unanswered questions.`
|
|
274
280
|
: `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.`,
|
|
281
|
+
: `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
282
|
},
|
|
277
283
|
}, [workspace, stage]);
|
|
278
284
|
});
|
|
@@ -353,12 +359,14 @@ export class WorkContext {
|
|
|
353
359
|
if (!result?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Result is required");
|
|
354
360
|
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
355
361
|
const record = this.storage.readStage(workspace, stage);
|
|
362
|
+
if (record.data.status !== "completed") fail(ERROR_CODES.INVALID_STATE, "Cannot update the result of an unfinished stage");
|
|
356
363
|
const currentResult = stageResult(record);
|
|
357
364
|
if (currentResult === null) fail(ERROR_CODES.INVALID_STATE, "Stage has no result to update");
|
|
358
365
|
const nextResult = result.trim();
|
|
359
366
|
if (currentResult === nextResult) return this.result({ workspace, stage, result: nextResult }, []);
|
|
360
367
|
record.data.updated_at = new Date().toISOString();
|
|
361
|
-
const
|
|
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}`;
|
|
362
370
|
this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, nextBody);
|
|
363
371
|
generateProjections(this.storage);
|
|
364
372
|
return this.result({ workspace, stage, result: nextResult }, [workspace, stage]);
|
|
@@ -495,6 +503,37 @@ export class WorkContext {
|
|
|
495
503
|
return this.closeSession(workspace, stage, sessionId, reason, "abandoned");
|
|
496
504
|
}
|
|
497
505
|
|
|
506
|
+
reopenStage(workspace, stage, reason) {
|
|
507
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
508
|
+
stage = normalizeStageId(stage);
|
|
509
|
+
if (!reason?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Reopen reason is required");
|
|
510
|
+
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
511
|
+
const workspaceRecord = this.storage.readWorkspace(workspace);
|
|
512
|
+
if (workspaceRecord.data.status === "cancelled") fail(ERROR_CODES.INVALID_STATE, "Cannot reopen a stage in a cancelled workspace");
|
|
513
|
+
const record = this.storage.readStage(workspace, stage);
|
|
514
|
+
const active = activeSession(this.storage.readEvents(), workspace, stage);
|
|
515
|
+
if (active) fail(ERROR_CODES.ACTIVE_SESSION_EXISTS, "Cannot reopen a stage with an active session", { session_id: active.session_id });
|
|
516
|
+
if (record.data.status !== "completed") fail(ERROR_CODES.INVALID_STATE, "Only completed stages can be reopened", { status: record.data.status });
|
|
517
|
+
const reopenedAt = new Date().toISOString();
|
|
518
|
+
const previousResult = stageResult(record);
|
|
519
|
+
const entry = { at: reopenedAt, reason: reason.trim(), actor: actor(this.options), ...(previousResult ? { previous_result: previousResult } : {}) };
|
|
520
|
+
record.data.status = "in_progress";
|
|
521
|
+
record.data.reopen_history = [...(record.data.reopen_history || []), entry];
|
|
522
|
+
record.data.updated_at = reopenedAt;
|
|
523
|
+
const history = record.body.match(/\n## Reopen History[\s\S]*?(?=\n## Result|$)/)?.[0]
|
|
524
|
+
|| "\n\n## Reopen History\n";
|
|
525
|
+
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`);
|
|
527
|
+
if (workspaceRecord.data.status === "completed") {
|
|
528
|
+
workspaceRecord.data.status = "in_progress";
|
|
529
|
+
workspaceRecord.data.updated_at = reopenedAt;
|
|
530
|
+
this.storage.writeMarkdown(this.storage.workspaceFile(workspace), workspaceRecord.data, workspaceRecord.body);
|
|
531
|
+
}
|
|
532
|
+
generateProjections(this.storage);
|
|
533
|
+
return this.result({ workspace, stage, status: "in_progress", reopen: entry, session_started: false, resume_required: true }, [workspace, stage]);
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
|
|
498
537
|
finish(workspace, stage, sessionId, options = {}) {
|
|
499
538
|
workspace = normalizeWorkspaceId(workspace);
|
|
500
539
|
stage = normalizeStageId(stage);
|
|
@@ -533,7 +572,12 @@ export class WorkContext {
|
|
|
533
572
|
}
|
|
534
573
|
|
|
535
574
|
help(command = "") {
|
|
536
|
-
|
|
575
|
+
return this.result({
|
|
576
|
+
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.",
|
|
579
|
+
}, []);
|
|
580
|
+
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
581
|
}
|
|
538
582
|
|
|
539
583
|
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));
|
package/src/tool-definitions.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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
|
|
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 };
|