opencode-work-context 0.1.5 → 0.1.7

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/commands/wc.md CHANGED
@@ -20,9 +20,11 @@ Use these exact tool mappings; do not invent shortened tool names:
20
20
  - `workspace rename <workspace> "title"` -> `work_context_rename_workspace`
21
21
  - `workspace finish <workspace>` -> `work_context_workspace_finish`
22
22
  - `resume <workspace> <stage>` -> `work_context_start_session`
23
- - `stage add [<workspace>] ...` -> `work_context_add_stage`
23
+ - `stage force-close <workspace> <stage> <sessionId> "reason" FORCE_CLOSE` -> `work_context_force_close_session`
24
+ - `stage add [<workspace>] ...` -> `work_context_add_stage` (optional `prompt`; detailed prompt is expected for stages created from planning)
24
25
  - `stage rename [<workspace>] <stage> "title"` -> `work_context_rename_stage`
25
26
  - `stage update [<workspace>] <stage> "description"` -> `work_context_update_stage`
27
+ - `stage update-prompt [<workspace>] <stage> "prompt"` -> `work_context_update_stage_prompt`
26
28
  - `stage archive [<workspace>] <stage>` -> `work_context_archive_stage`
27
29
  - `stage handoff <workspace> <stage>` -> `work_context_handoff_stage`
28
30
  - `stage abandon <workspace> <stage>` -> `work_context_abandon_stage`
@@ -37,9 +39,11 @@ Supported syntax:
37
39
  - `workspace rename <workspace> "title"`
38
40
  - `workspace finish <workspace>`
39
41
  - `resume <workspace> <stage>`
40
- - `stage add [<workspace>] "title"`
42
+ - `stage force-close <workspace> <stage> <sessionId> "reason" FORCE_CLOSE`
43
+ - `stage add [<workspace>] "title" ["prompt"]`
41
44
  - `stage rename [<workspace>] <stage> "title"`
42
45
  - `stage update [<workspace>] <stage> "description"`
46
+ - `stage update-prompt [<workspace>] <stage> "prompt"`
43
47
  - `stage archive [<workspace>] <stage>`
44
48
  - `stage finish <workspace> <stage>`
45
49
  - `<workspace> [<stage>] link-issue <URL>`
@@ -47,6 +51,8 @@ Supported syntax:
47
51
  - `stage handoff <workspace> <stage>`
48
52
  - `stage abandon <workspace> <stage>`
49
53
  - `stage finish <workspace> <stage>` automatically reviews the Knowledge Base (`auto` by default)
54
+ - `resume` returns an actionable `resume.next_action` and `resume.instruction`; begin or continue the work immediately from that structured context
55
+ - `stage finish` returns downstream unfinished stages whose prompts should be reviewed after new findings
50
56
  - `knowledge list|add|update|supersede <workspace> ...`
51
57
 
52
58
  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.5",
4
+ "version": "0.1.7",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -23,7 +23,7 @@ export default async ({ client, directory, worktree }) => ({
23
23
  async function updateSessionTitle(client, projectRoot, directory, sessionId) {
24
24
  try {
25
25
  const context = contextFor(projectRoot, sessionId);
26
- const session = context.sessionById(sessionId) || context.sessionByOpenCodeId(sessionId);
26
+ const session = context.sessionById(sessionId) || context.sessionByOpenCodeId(sessionId, null, null, null);
27
27
  if (!session) return;
28
28
  const title = titleFor(context, session.workspace, session.stage, sessionId, session);
29
29
  if (!title) return;
package/src/core.js CHANGED
@@ -14,10 +14,10 @@ const id = (value, digits) => {
14
14
  };
15
15
  const stageId = (value) => id(String(value).padStart(2, "0"), 2);
16
16
  const actor = (options) => options.actor || "OpenCode";
17
- const body = (title, goal = "") => `# ${title}\n\n${goal ? `## Goal\n\n${goal}\n` : ""}`;
18
- const stageBody = (record, title, goal) => {
17
+ const body = (title, goal = "", prompt = "") => `# ${title}\n\n${goal ? `## Goal\n\n${goal}\n` : ""}${prompt ? `\n## Prompt\n\n${prompt}\n` : ""}`;
18
+ const stageBody = (record, title, goal, prompt = record.data.prompt || "") => {
19
19
  const result = record.body.match(/\n## Result[\s\S]*$/)?.[0] || "";
20
- return `${body(title, goal).trimEnd()}${result}`;
20
+ return `${body(title, goal, prompt).trimEnd()}${result}`;
21
21
  };
22
22
  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; } } };
23
23
 
@@ -68,7 +68,7 @@ export class WorkContext {
68
68
  }
69
69
 
70
70
  transact(name, fn) {
71
- // Все mutating operations меняют общий sessions.jsonl, поэтому нужен единый lock.
71
+ // All mutating operations update the shared sessions.jsonl, so they need one lock.
72
72
  this.storage.assertSafeRoots();
73
73
  return withLock(this.storage.lockPath("write"), () => {
74
74
  this.storage.assertNoSymlinks();
@@ -140,11 +140,11 @@ export class WorkContext {
140
140
  return reduceSessions(this.storage.readEvents()).find((session) => session.session_id === sessionId) || null;
141
141
  }
142
142
 
143
- sessionByOpenCodeId(opencodeSessionId, workspace = null, stage = null) {
143
+ sessionByOpenCodeId(opencodeSessionId, workspace = null, stage = null, state = "active") {
144
144
  return reduceSessions(this.storage.readEvents()).filter((session) => session.opencode_session_id === opencodeSessionId
145
145
  && (!workspace || session.workspace === workspace)
146
146
  && (!stage || session.stage === stage)
147
- && session.state === "active").at(-1) || null;
147
+ && (!state || session.state === state)).at(-1) || null;
148
148
  }
149
149
 
150
150
  assertDependenciesCompleted(workspace, stageRecord) {
@@ -165,10 +165,12 @@ export class WorkContext {
165
165
  if (fs.existsSync(this.storage.workspaceDir(workspace))) fail(ERROR_CODES.CONFLICT, "Workspace already exists");
166
166
  fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
167
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));
168
- this.storage.writeMarkdown(this.storage.stageFile(workspace, "01"), { schema: 1, workspace, stage: "01", title: "Планирование", status: "in_progress", goal: "Уточнить цель и ограничения работы", depends_on: [], owner: actor(this.options), created_at: now, updated_at: now, tracker_links: [] }, body("Планирование", "Уточнить цель и ограничения работы"));
168
+ const planningGoal = "Clarify the work goal and constraints";
169
+ const planningPrompt = "Diagnose and plan the task without functional changes. Discuss possible solutions, record constraints, and decompose the work into the following stages. For each new implementation stage, write a separate detailed prompt with context, concrete actions, constraints, completion criteria, and the expected result. Ask clarifying questions only when genuinely blocked.";
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");
171
- this.writeEvents([event("session.started", workspace, "01", 1, sessionId, actor(this.options), { summary: `планирование ${title.trim()}`, opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
173
+ this.writeEvents([event("session.started", workspace, "01", 1, sessionId, actor(this.options), { summary: `planning ${title.trim()}`, opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
172
174
  generateProjections(this.storage);
173
175
  return this.result({ workspace, stage: "01", session_id: sessionId, ordinal: "01/01" }, [workspace, "01"]);
174
176
  });
@@ -219,9 +221,30 @@ export class WorkContext {
219
221
  stageRecord.data.updated_at = new Date().toISOString();
220
222
  this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), stageRecord.data, stageRecord.body);
221
223
  }
222
- this.writeEvents([event("session.started", workspace, stage, ordinal, sessionId, actor(this.options), { summary: options.summary || "продолжение работы", opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
224
+ this.writeEvents([event("session.started", workspace, stage, ordinal, sessionId, actor(this.options), { summary: options.summary || "continued work", opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
223
225
  generateProjections(this.storage);
224
- return this.result({ workspace, stage, session_id: sessionId, ordinal: `${stage}/${String(ordinal).padStart(2, "0")}` }, [workspace, stage]);
226
+ const previousSession = previous.at(-1) || null;
227
+ const firstResume = previous.length === 0;
228
+ return this.result({
229
+ workspace,
230
+ stage,
231
+ session_id: sessionId,
232
+ ordinal: `${stage}/${String(ordinal).padStart(2, "0")}`,
233
+ title: stageRecord.data.title,
234
+ description: stageRecord.data.goal,
235
+ prompt: stageRecord.data.prompt || null,
236
+ resume: {
237
+ first: firstResume,
238
+ summary: firstResume
239
+ ? `Starting work on stage ${stage}: ${stageRecord.data.title}.`
240
+ : `Continuing work on stage ${stage}: ${stageRecord.data.title}. Last recorded summary: ${previousSession?.summary || "no saved report"}.`,
241
+ last_session_summary: previousSession?.summary || null,
242
+ next_action: firstResume ? "start_work" : "continue_work",
243
+ instruction: stageRecord.data.prompt || (firstResume
244
+ ? `Review stage ${stage}: ${stageRecord.data.title} and begin work.`
245
+ : `Continue work on stage ${stage}: ${stageRecord.data.title}.`),
246
+ },
247
+ }, [workspace, stage]);
225
248
  });
226
249
  }
227
250
 
@@ -237,7 +260,9 @@ export class WorkContext {
237
260
  if (dependsOn.includes(stage)) fail(ERROR_CODES.INVALID_ARGUMENT, "A stage cannot depend on itself");
238
261
  if (dependsOn.some((dependency) => !stages.some((item) => item.stage === dependency))) fail(ERROR_CODES.INVALID_ARGUMENT, "dependsOn must reference existing stages");
239
262
  const now = new Date().toISOString();
240
- this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), { schema: 1, workspace, stage, title: title.trim(), status: "planned", goal: options.goal || title.trim(), depends_on: dependsOn, owner: options.owner || actor(this.options), created_at: now, updated_at: now, tracker_links: [] }, body(title, options.goal || title));
263
+ const prompt = options.prompt?.trim() || undefined;
264
+ const metadata = { schema: 1, workspace, stage, title: title.trim(), status: "planned", goal: options.goal || title.trim(), ...(prompt ? { prompt } : {}), depends_on: dependsOn, owner: options.owner || actor(this.options), created_at: now, updated_at: now, tracker_links: [] };
265
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), metadata, body(title, options.goal || title, prompt));
241
266
  generateProjections(this.storage);
242
267
  return this.result({ workspace, stage }, [stage]);
243
268
  });
@@ -275,6 +300,22 @@ export class WorkContext {
275
300
  });
276
301
  }
277
302
 
303
+ updateStagePrompt(workspace, stage, prompt) {
304
+ id(workspace, 6);
305
+ stage = stageId(stage);
306
+ if (!prompt?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Prompt is required");
307
+ return this.transact(`stage-${workspace}-${stage}`, () => {
308
+ const record = this.storage.readStage(workspace, stage);
309
+ const nextPrompt = prompt.trim();
310
+ if (record.data.prompt === nextPrompt) return this.result({ workspace, stage, prompt: nextPrompt }, []);
311
+ record.data.prompt = nextPrompt;
312
+ record.data.updated_at = new Date().toISOString();
313
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, stageBody(record, record.data.title, record.data.goal, nextPrompt));
314
+ generateProjections(this.storage);
315
+ return this.result({ workspace, stage, prompt: nextPrompt }, [workspace, stage]);
316
+ });
317
+ }
318
+
278
319
  archiveStage(workspace, stage) {
279
320
  id(workspace, 6);
280
321
  stage = stageId(stage);
@@ -369,6 +410,25 @@ export class WorkContext {
369
410
  });
370
411
  }
371
412
 
413
+ forceCloseSession(workspace, stage, sessionId, reason, confirmation) {
414
+ id(workspace, 6);
415
+ stage = stageId(stage);
416
+ if (!sessionId?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Session ID is required");
417
+ if (!reason?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Force-close reason is required");
418
+ if (confirmation !== "FORCE_CLOSE") fail(ERROR_CODES.CONFIRMATION_REQUIRED, "Force close requires confirmation FORCE_CLOSE", { expected: "FORCE_CLOSE" });
419
+ return this.transact(`stage-${workspace}-${stage}`, () => {
420
+ const session = this.storage.readEvents().length
421
+ ? this.sessionById(sessionId)
422
+ : null;
423
+ if (!session || session.workspace !== workspace || session.stage !== stage) fail(ERROR_CODES.NOT_FOUND, "Session not found", { session_id: sessionId, workspace, stage });
424
+ if (session.state === "closed") return this.result({ session_id: sessionId, state: "closed", idempotent: true }, []);
425
+ if (session.state !== "active") fail(ERROR_CODES.SESSION_NOT_ACTIVE, "Session is not active", { session_id: sessionId, state: session.state });
426
+ this.writeEvents([event("session.closed", workspace, stage, session.ordinal, sessionId, actor(this.options), { reason: reason.trim(), forced: true })]);
427
+ generateProjections(this.storage);
428
+ return this.result({ session_id: sessionId, state: "closed", forced: true, reason: reason.trim() }, []);
429
+ });
430
+ }
431
+
372
432
  handoff(workspace, stage, sessionId, options = {}) {
373
433
  stage = stageId(stage);
374
434
  return this.transact(`stage-${workspace}-${stage}`, () => {
@@ -404,15 +464,26 @@ export class WorkContext {
404
464
  current.data.updated_at = new Date().toISOString();
405
465
  this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), current.data, `${current.body}\n\n## Result\n\n${options.result || "Stage completed."}`);
406
466
  generateProjections(this.storage);
407
- return this.result({ session_id: sessionId, workspace, stage, state: "closed", status: "completed", knowledge_review: knowledgeReview, ...(knowledgeEntries ? { knowledge_entries: knowledgeEntries.length } : {}) }, [workspace, stage]);
467
+ const promptReview = this.listStages(workspace).data.stages
468
+ .filter((item) => Number(item.stage) > Number(stage) && !["completed", "archived"].includes(item.status))
469
+ .map(({ stage: id, title, description, prompt, status }) => ({ stage: id, title, description, prompt: prompt || null, status }));
470
+ const data = { session_id: sessionId, workspace, stage, state: "closed", status: "completed", knowledge_review: knowledgeReview, prompt_review: promptReview, ...(knowledgeEntries ? { knowledge_entries: knowledgeEntries.length } : {}) };
471
+ const incompleteStages = this.listStages(workspace).data.stages.filter((item) => !["completed", "archived"].includes(item.status));
472
+ const next = incompleteStages.length ? null : {
473
+ action: "workspace_finish",
474
+ workspace,
475
+ command: `/wc workspace finish ${workspace}`,
476
+ reason: "All workspace stages are completed",
477
+ };
478
+ return this.result(data, [workspace, stage], next);
408
479
  });
409
480
  }
410
481
 
411
482
  help(command = "") {
412
- return this.result({ command, syntax: "/wc [create|list|workspace list|workspace rename|workspace finish|resume|stage add|stage rename|stage update|stage archive|stage handoff|stage abandon|stage finish|link-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]", note: "workspace is optional for stage add/rename/update/archive when the current session identifies one workspace; 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; stage finish reviews Knowledge Base automatically by default (knowledgeReview=auto); mutating commands call structured tools; only explicit lifecycle operations change storage." }, []);
483
+ 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 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 is optional for stage add/rename/update/archive when the current session identifies one workspace; stage add accepts an optional prompt, which should contain the complete implementation context when the stage is created from stage 01 planning; resume returns resume.next_action and resume.instruction for immediate work; force-close requires a session ID, reason, and exact confirmation FORCE_CLOSE; stage finish returns downstream stages for prompt review; 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; stage finish reviews Knowledge Base automatically by default (knowledgeReview=auto); mutating commands call structured tools; only explicit lifecycle operations change storage." }, []);
413
484
  }
414
485
 
415
- result(data, changed) {
416
- return { ok: true, data, changed, next: null };
486
+ result(data, changed, next = null) {
487
+ return { ok: true, data, changed, next };
417
488
  }
418
489
  }
package/src/storage.js CHANGED
@@ -36,8 +36,8 @@ const validEvents = new Set(["session.started", "session.renamed", "session.hand
36
36
  const validateEvent = (item) => {
37
37
  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");
38
38
  const keys = Object.keys(item.data);
39
- const allowed = item.event === "session.started" ? ["summary", "opencode_session_id", "branch"] : item.event === "session.renamed" ? ["summary"] : ["reason"];
40
- if (keys.some((key) => !allowed.includes(key)) || (item.event === "session.started" && (typeof item.data.summary !== "string" || !item.data.summary.trim() || (item.data.opencode_session_id !== null && item.data.opencode_session_id !== undefined && typeof item.data.opencode_session_id !== "string") || (item.data.branch !== null && item.data.branch !== undefined && typeof item.data.branch !== "string"))) || (item.event === "session.renamed" && (typeof item.data.summary !== "string" || !item.data.summary.trim())) || (item.event !== "session.started" && (typeof item.data.reason !== "string" || !item.data.reason.trim()))) fail(ERROR_CODES.STORAGE_ERROR, "Invalid session event data");
39
+ const allowed = item.event === "session.started" ? ["summary", "opencode_session_id", "branch"] : item.event === "session.renamed" ? ["summary"] : ["reason", "forced"];
40
+ if (keys.some((key) => !allowed.includes(key)) || (item.event === "session.started" && (typeof item.data.summary !== "string" || !item.data.summary.trim() || (item.data.opencode_session_id !== null && item.data.opencode_session_id !== undefined && typeof item.data.opencode_session_id !== "string") || (item.data.branch !== null && item.data.branch !== undefined && typeof item.data.branch !== "string"))) || (item.event === "session.renamed" && (typeof item.data.summary !== "string" || !item.data.summary.trim())) || (item.event !== "session.started" && item.event !== "session.renamed" && (typeof item.data.reason !== "string" || !item.data.reason.trim()) || (item.data.forced !== undefined && typeof item.data.forced !== "boolean"))) fail(ERROR_CODES.STORAGE_ERROR, "Invalid session event data");
41
41
  };
42
42
  const validateEventStream = (events) => {
43
43
  const ids = new Set();
@@ -69,13 +69,13 @@ const validateEventStream = (events) => {
69
69
  }
70
70
  };
71
71
  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", "depends_on", "owner", "created_at", "updated_at", "tracker_links"];
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"];
73
73
  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
74
  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
75
  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
76
  const statuses = kind === "workspace" ? ["in_progress", "completed", "cancelled"] : ["planned", "in_progress", "completed", "cancelled", "archived"];
77
77
  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") || !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");
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");
79
79
  }
80
80
  export function atomicWrite(file, content) {
81
81
  ensure(path.dirname(file));
@@ -231,7 +231,18 @@ export class FileStorage {
231
231
  appendEvents(events) {
232
232
  ensure(path.dirname(this.sessionFile()));
233
233
  const current = fs.existsSync(this.sessionFile()) ? fs.readFileSync(this.sessionFile(), "utf8") : "";
234
- atomicWrite(this.sessionFile(), current + events.map((item) => JSON.stringify(item)).join("\n") + "\n");
234
+ let previousTimestamp = current.trim().split("\n").filter(Boolean).at(-1);
235
+ previousTimestamp = previousTimestamp ? JSON.parse(previousTimestamp).occurred_at : null;
236
+ const monotonic = events.map((item) => {
237
+ const currentTime = Date.parse(item.occurred_at);
238
+ const previousTime = previousTimestamp ? Date.parse(previousTimestamp) : null;
239
+ if (previousTime !== null && currentTime < previousTime) {
240
+ item.occurred_at = new Date(previousTime + 1).toISOString();
241
+ }
242
+ previousTimestamp = item.occurred_at;
243
+ return item;
244
+ });
245
+ atomicWrite(this.sessionFile(), current + monotonic.map((item) => JSON.stringify(item)).join("\n") + "\n");
235
246
  }
236
247
  readEvents() {
237
248
  this.assertNoSymlinks();
@@ -29,13 +29,15 @@ export const work_context_rename_workspace = tool({ description: "Rename a works
29
29
  export const work_context_workspace_finish = tool({ description: "Finish a workspace after all stages are completed.", args: { workspace: tool.schema.string().regex(/^\d{6}$/) }, execute: run((ctx, a) => ctx.finishWorkspace(a.workspace)) });
30
30
  export const work_context_create_workspace = tool({ description: "Create workspace, stage 01, and active session.", args: { title: tool.schema.string() }, execute: run((ctx, a, oc) => ctx.createWorkspace(a.title, { sessionId: randomUUID(), opencodeSessionId: oc.sessionID })) });
31
31
  export const work_context_start_session = tool({ description: "Start a new active session for a stage.", 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 })) });
32
- export const work_context_add_stage = tool({ description: "Add a planned stage to the current or specified workspace.", args: { workspace: tool.schema.string().regex(/^\d{6}$/).optional(), title: tool.schema.string(), goal: tool.schema.string().optional(), dependsOn: tool.schema.array(tool.schema.string()).optional() }, execute: run((ctx, a) => ctx.addStage(workspaceFromSession(ctx, a.workspace), a.title, { goal: a.goal, dependsOn: a.dependsOn })) });
32
+ export const work_context_add_stage = tool({ description: "Add a planned stage. Prompt is optional for manually created stages and should be detailed when the stage comes from planning.", args: { workspace: tool.schema.string().regex(/^\d{6}$/).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((ctx, a) => ctx.addStage(workspaceFromSession(ctx, a.workspace), a.title, { goal: a.goal, prompt: a.prompt, dependsOn: a.dependsOn })) });
33
33
  export const work_context_rename_stage = tool({ description: "Rename a stage while preserving its ID and history.", args: { workspace: tool.schema.string().regex(/^\d{6}$/).optional(), stage: tool.schema.string().regex(/^\d{1,2}$/), title: tool.schema.string() }, execute: run((ctx, a) => ctx.renameStage(workspaceFromSession(ctx, a.workspace), a.stage, a.title)) });
34
34
  export const work_context_update_stage = tool({ description: "Update an existing stage description.", args: { workspace: tool.schema.string().regex(/^\d{6}$/).optional(), stage: tool.schema.string().regex(/^\d{1,2}$/), description: tool.schema.string() }, execute: run((ctx, a) => ctx.updateStage(workspaceFromSession(ctx, a.workspace), a.stage, a.description)) });
35
+ export const work_context_update_stage_prompt = tool({ description: "Update the optional working prompt of an existing stage.", args: { workspace: tool.schema.string().regex(/^\d{6}$/).optional(), stage: tool.schema.string().regex(/^\d{1,2}$/), prompt: tool.schema.string() }, execute: run((ctx, a) => ctx.updateStagePrompt(workspaceFromSession(ctx, a.workspace), a.stage, a.prompt)) });
35
36
  export const work_context_archive_stage = tool({ description: "Archive a stage while preserving its ID and history.", args: { workspace: tool.schema.string().regex(/^\d{6}$/), stage: tool.schema.string().regex(/^\d{1,2}$/) }, execute: run((ctx, a) => ctx.archiveStage(a.workspace, a.stage)) });
36
37
  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)) });
37
38
  export const work_context_rename_session = tool({ description: "Rename the current active session summary.", args: { ...common, summary: tool.schema.string() }, execute: run((ctx, a, oc) => ctx.renameSession(a.workspace, a.stage, sessionFor(ctx, oc, a.workspace, a.stage), a.summary)) });
38
39
  export const work_context_close_session = tool({ description: "Close the current session without finishing its stage.", args: { ...common }, execute: run((ctx, a, oc) => ctx.closeSession(a.workspace, a.stage, sessionFor(ctx, oc, a.workspace, a.stage))) });
40
+ 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().regex(/^\d{6}$/), stage: tool.schema.string().regex(/^\d{1,2}$/), 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)) });
39
41
  export const work_context_handoff_stage = tool({ description: "Hand off the current stage by closing the current session.", args: { ...common }, execute: run((ctx, a, oc) => ctx.handoff(a.workspace, a.stage, sessionFor(ctx, oc, a.workspace, a.stage))) });
40
42
  export const work_context_abandon_stage = tool({ description: "Abandon the current stage session without completing the stage.", args: { ...common }, execute: run((ctx, a, oc) => ctx.abandon(a.workspace, a.stage, sessionFor(ctx, oc, a.workspace, a.stage))) });
41
43
  export const work_context_finish_stage = tool({ description: "Finish a stage and automatically validate the Knowledge Base by default.", args: { ...common, result: tool.schema.string().optional(), knowledgeReview: tool.schema.string().optional() }, execute: run((ctx, a, oc) => ctx.finish(a.workspace, a.stage, sessionFor(ctx, oc, a.workspace, a.stage), { result: a.result, knowledgeReview: a.knowledgeReview })) });
@@ -45,4 +47,4 @@ export const work_context_add_knowledge = tool({ description: "Add a durable kno
45
47
  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)) });
46
48
  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) ) });
47
49
 
48
- 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_archive_stage, work_context_link_issue, work_context_rename_session, work_context_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 };
50
+ 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_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 };