opencode-work-context 0.4.7 → 0.4.8

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
@@ -84,13 +84,30 @@ When you return later, continue from the active stage. A stage must have a
84
84
  non-empty prompt before implementation begins; if the prompt is missing or
85
85
  ambiguous, `/wc resume` instructs the agent to ask focused questions first.
86
86
  Before working, the agent reports the stage essence, the previous session's
87
- result or stopping point, and what it will do now. On subsequent resumes, it
88
- only reports that context and waits for explicit confirmation before continuing:
87
+ result or stopping point, and what it will do now. The summary uses a
88
+ plain-language goal and, for a larger stage with explicit scope, a short
89
+ `In this stage we will` list of expected outcomes. Raw IDs and operation metadata
90
+ are omitted. The agent then continues immediately instead of asking for generic
91
+ confirmation. A stage can explicitly require confirmation with this standalone
92
+ prompt line:
93
+
94
+ ```text
95
+ RESUME_CONFIRMATION: required
96
+ ```
97
+
98
+ Resume a stage with:
89
99
 
90
100
  ```text
91
101
  /wc resume 000001 02
92
102
  ```
93
103
 
104
+ After updating the npm package, refresh the generated slash-command contract
105
+ without touching project configuration or loaders:
106
+
107
+ ```bash
108
+ npx opencode-work-context sync-command --force
109
+ ```
110
+
94
111
  Useful commands:
95
112
 
96
113
  ```text
@@ -74,12 +74,33 @@ const hasSymlinkParent = (file) => {
74
74
  };
75
75
 
76
76
  function parseArgs(args) {
77
- if (args[0] !== "init") return fail("usage: opencode-work-context init [--force]");
77
+ if (args[0] === "sync-command") {
78
+ const unknown = args.slice(1).filter((arg) => arg !== "--force");
79
+ if (unknown.length) return fail(`unknown option: ${unknown[0]}`);
80
+ return { syncCommand: true, force: args.includes("--force") };
81
+ }
82
+ if (args[0] !== "init") return fail("usage: opencode-work-context init [--force] | sync-command");
78
83
  const unknown = args.slice(1).filter((arg) => arg !== "--force");
79
84
  if (unknown.length) return fail(`unknown option: ${unknown[0]}`);
80
85
  return { force: args.includes("--force") };
81
86
  }
82
87
 
88
+ function syncCommandProjection(force) {
89
+ const relative = ".opencode/commands/wc.md";
90
+ const file = path.join(projectRoot, relative);
91
+ if (hasSymlinkParent(file) || (exists(file) && (!fs.lstatSync(file).isFile() || fs.lstatSync(file).isSymbolicLink()))) {
92
+ fail(`refusing to overwrite non-regular file: ${relative}`);
93
+ return false;
94
+ }
95
+ if (exists(file) && fs.readFileSync(file, "utf8") !== command && !force) {
96
+ fail(`refusing to overwrite existing file: ${relative}; rerun with --force`);
97
+ return false;
98
+ }
99
+ writeAtomic(file, command);
100
+ console.log(`Updated ${relative} from opencode-work-context ${packageManifest.version}.`);
101
+ return true;
102
+ }
103
+
83
104
  function ensurePackageJson() {
84
105
  const file = path.join(dependencyRoot, "package.json");
85
106
  if (fs.existsSync(file)) return;
@@ -272,7 +293,15 @@ function writeGenerated() {
272
293
  }
273
294
 
274
295
  const options = parseArgs(process.argv.slice(2));
275
- if (options) {
296
+ if (options?.syncCommand) {
297
+ const initLock = acquireInitLock();
298
+ if (initLock.failed) process.exitCode = 1;
299
+ else {
300
+ try { syncCommandProjection(options.force); }
301
+ catch (error) { fail(`command sync failed: ${error.message}`); }
302
+ finally { releaseInitLock(initLock); }
303
+ }
304
+ } else if (options) {
276
305
  const initLock = acquireInitLock();
277
306
  if (initLock.failed) process.exitCode = 1;
278
307
  else if (checkConflicts(options.force) && checkPackageConflict(options.force)) {
package/commands/wc.md CHANGED
@@ -5,8 +5,9 @@ subtask: false
5
5
 
6
6
  Interpret `/wc $ARGUMENTS` as an explicit work-context operation. Use the matching
7
7
  `work_context_*` custom tool registered by the installed package plugin with structured arguments. Never edit work-context
8
- Markdown, JSONL, INDEX, or SESSIONS projections directly. For mutating operations,
9
- report the structured result and stable error code. Use `work_context_help` when
8
+ Markdown, JSONL, INDEX, or SESSIONS projections directly. For mutating operations
9
+ other than `resume`, report the structured result and stable error code. For
10
+ `resume`, follow its human-oriented presentation rules instead. Use `work_context_help` when
10
11
  the syntax is missing or ambiguous.
11
12
 
12
13
  For `workspace list <workspace>` (or `<workspace> list`), report the workspace
@@ -65,14 +66,16 @@ Supported syntax:
65
66
  - explicit workspace and stage positions accept canonical padded IDs or unpadded positive integers (`1..999999` and `1..99`); results and generated commands remain padded
66
67
  - zero, signs, decimals, whitespace, overlong values, and other non-digit identifier forms are invalid; a lone unpadded workspace ID is not reinterpreted under the one-identifier rule
67
68
  - `stage update-result` replaces an existing result and does not create a result for an unfinished stage
68
- - `resume` returns `resume.context` with the stage essence, the previous session's result/stopping point, and the current plan; report this concise context to the user before doing any work
69
+ - `resume` returns `resume.presentation` and `resume.context`; before doing any work, report a concise human-oriented summary in the user's language with the stage title, a plain-language Goal, previous progress when useful, and the immediate next action
70
+ - when the saved prompt contains several clear deliverables, add `In this stage we will` with 2-5 short outcome-oriented bullets derived only from the prompt, previous result, and workspace knowledge; do not invent scope, and omit this block for a small stage
71
+ - do not expose raw workspace/stage/session identifiers, ordinals, `ok` flags, or absent error codes in the user-facing resume summary
69
72
  - `resume.context.workspace_knowledge` contains every active durable knowledge entry for the workspace; treat it as established shared context, and do not repeat earlier analysis unless an entry is incomplete, contradicted, or needs verification
70
- - on every subsequent resume, report the context and wait for explicit user confirmation; do not automatically continue implementation
71
- - when `resume.next_action` is `await_confirmation`, do not inspect or modify application code until the user confirms
73
+ - after presenting the summary, continue work immediately when `resume.next_action` is `start_work`; do not ask for generic confirmation
74
+ - a stage may require confirmation only with an exact standalone `RESUME_CONFIRMATION: required` line in its saved prompt; when `resume.next_action` is `await_confirmation`, present the summary and wait before inspecting or modifying application code
72
75
  - `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
73
76
  - `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
74
77
  - 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
75
- - `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
78
+ - `resume` returns `resume.next_action` and `resume.instruction`; begin or continue implementation when the stage prompt is non-empty unless it explicitly requires confirmation or contains an unresolved decision that genuinely blocks progress
76
79
  - 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
77
80
  - 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
78
81
  - 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
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-work-context",
3
3
  "type": "module",
4
- "version": "0.4.7",
4
+ "version": "0.4.8",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
package/src/core.js CHANGED
@@ -21,8 +21,20 @@ const stageBody = (record, title, goal, prompt = record.data.prompt || "") => {
21
21
  return `${body(title, goal, prompt).trimEnd()}${result}${reopenHistory}${archiveHistory}`;
22
22
  };
23
23
  const stageResult = (record) => record.body.match(/\n## Result\s*\n([\s\S]*?)(?=\n## (?:Reopen|Archive) History|$)/)?.[1]?.trim() ?? null;
24
+ const preservedStageResult = (record) => stageResult(record)
25
+ || [...(record.data.reopen_history || [])].reverse().find((entry) => entry.previous_result)?.previous_result
26
+ || null;
24
27
  const appendHistory = (bodyText, heading, entry) => `${bodyText.trimEnd()}${bodyText.includes(`\n## ${heading}\n`) ? "" : `\n\n## ${heading}\n`}\n- ${entry}\n`;
25
28
  const automaticFinishAllowed = (storage, workspace) => /(?:^|\n)AUTO_STAGE_FINISH:\s*allowed\s*$/mi.test(storage.readStage(workspace, "01").data.prompt || "");
29
+ const resumeConfirmationRequired = (prompt) => /(?:^|\r?\n)RESUME_CONFIRMATION: required(?=\r?\n|$)/.test(prompt || "");
30
+ const resumePresentationInstruction = ({ confirmationRequired }) => `Before doing any work, give the user a concise context summary:
31
+ - Use the user's language.
32
+ - Name the stage without reporting workspace IDs, stage IDs, session UUIDs, ordinals, ok flags, or absent error codes.
33
+ - Add a short "Goal" section that restates presentation.goal in plain, non-technical language.
34
+ - When presentation.scope contains several clear deliverables, add "In this stage we will" with 2-5 short outcome-oriented bullets. Derive them only from the saved prompt, previous result, and workspace knowledge; do not invent scope. Omit this block for a small stage.
35
+ - Mention previous progress only when presentation.previous_result or presentation.previous_session_summary contains useful information.
36
+ - State the immediate next action in one sentence.
37
+ ${confirmationRequired ? "- Ask for the explicitly required confirmation and wait before inspecting or changing application code." : "- Then continue with the work immediately. Do not ask for generic confirmation; ask a focused question only when an unresolved decision genuinely blocks progress."}`;
26
38
  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; } } };
27
39
 
28
40
  function parseIssue(url) {
@@ -266,8 +278,14 @@ export class WorkContext {
266
278
  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 })]);
267
279
  generateProjections(this.storage);
268
280
  const previousSession = previous.at(-1) || null;
281
+ const previousSessionSummary = previousSession?.summary && previousSession.summary !== "continued work"
282
+ ? previousSession.summary
283
+ : null;
269
284
  const firstResume = previous.length === 0;
270
285
  const hasPrompt = Boolean(stageRecord.data.prompt?.trim());
286
+ const confirmationRequired = hasPrompt && resumeConfirmationRequired(stageRecord.data.prompt);
287
+ const previousResult = preservedStageResult(stageRecord);
288
+ const workspaceTitle = this.storage.readWorkspace(workspace).data.title;
271
289
  const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
272
290
  const automaticFinish = automaticFinishAllowed(this.storage, workspace);
273
291
  return this.result({
@@ -282,22 +300,27 @@ export class WorkContext {
282
300
  first: firstResume,
283
301
  summary: firstResume
284
302
  ? `Starting work on stage ${stage}: ${stageRecord.data.title}.`
285
- : `Continuing work on stage ${stage}: ${stageRecord.data.title}. Last recorded summary: ${previousSession?.summary || "no saved report"}.`,
303
+ : `Continuing work on stage ${stage}: ${stageRecord.data.title}. Last recorded summary: ${previousSessionSummary || previousResult || "no saved report"}.`,
286
304
  last_session_summary: previousSession?.summary || null,
305
+ presentation: {
306
+ workspace_title: workspaceTitle,
307
+ stage_title: stageRecord.data.title,
308
+ goal: stageRecord.data.goal || stageRecord.data.title,
309
+ scope: stageRecord.data.prompt || null,
310
+ previous_result: previousResult,
311
+ previous_session_summary: previousSessionSummary,
312
+ },
287
313
  context: {
288
314
  essence: stageRecord.data.goal || stageRecord.data.title,
289
- previous: previousSession?.summary || "The previous session did not save a result; the stopping point needs to be clarified.",
315
+ previous: previousSessionSummary || previousResult || "No previous progress was recorded.",
290
316
  now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
291
317
  workspace_knowledge: workspaceKnowledge,
292
318
  lifecycle: { automatic_finish_allowed: automaticFinish },
293
319
  },
294
- next_action: hasPrompt ? (firstResume ? "start_work" : "await_confirmation") : "ask_questions",
320
+ next_action: hasPrompt ? confirmationRequired ? "await_confirmation" : "start_work" : "ask_questions",
295
321
  instruction: `${hasPrompt
296
- ? firstResume
297
- ? stageRecord.data.prompt
298
- || `Review stage ${stage}: ${stageRecord.data.title} and begin work only after confirming there are no unanswered questions.`
299
- : `Stage ${stage}: ${stageRecord.data.title} was resumed before. Report the context and wait for the user's confirmation before continuing work.`
300
- : `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.`,
322
+ ? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}`
323
+ : `This stage has no non-empty prompt. Give the user a concise plain-language summary of the stage title and goal, then ask focused questions needed to define the intended outcome and scope. Do not inspect or modify application code yet. Do not report raw operation metadata or identifiers.`}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
301
324
  },
302
325
  }, [workspace, stage]);
303
326
  });
@@ -61,7 +61,7 @@ export const work_context_create_workspace = tool({ description: "Create a works
61
61
  const currentSession = ctx.sessionByOpenCodeId(oc.sessionID);
62
62
  return ctx.createWorkspace(a.title, { sessionId: randomUUID(), ...(currentSession ? {} : { opencodeSessionId: oc.sessionID }) });
63
63
  }) });
64
- 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 })) });
64
+ export const work_context_start_session = tool({ description: "Start a new active session for a stage and return its human-oriented presentation, prompt, and 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 })) });
65
65
  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) });
66
66
  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); }) });
67
67
  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); }) });