opencode-work-context 0.1.0 → 0.1.2

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
@@ -11,14 +11,23 @@ Run from the root of a standalone OpenCode project:
11
11
  npx opencode-work-context init
12
12
  ```
13
13
 
14
- `init` installs `opencode-work-context@0.1.0` as an exact devDependency using
15
- standard `npm`, preserving normal lifecycle behavior for the host project. It
16
- creates `package.json` when absent and writes the integration files below.
14
+ `init` installs `opencode-work-context@0.1.1` as an exact devDependency using
15
+ standard `npm`, preserving normal lifecycle behavior for the host project. The
16
+ dependency root is the project root when it has `package.json`, otherwise
17
+ `.opencode` when `.opencode/package.json` exists, and finally the project root
18
+ with a new `package.json` when neither exists. Package files, lockfiles, and
19
+ `node_modules` are changed only in that dependency root; integration files and
20
+ `.gitignore` always belong to the project root.
21
+
22
+ The generated plugin loader follows the dependency root package scope: it uses
23
+ ESM export syntax for `"type": "module"` and a CommonJS-compatible dynamic
24
+ import otherwise. This keeps the required `.js` integration path loadable in
25
+ projects such as OpenCode projects with a package but no module type.
17
26
  It does not create a workspace. Start one explicitly with `/wc create "Title"`.
18
27
 
19
- Use `--force` to replace a conflicting package-owned generated file. Without it,
20
- existing files are never silently overwritten. Re-running with unchanged files is
21
- safe and idempotent.
28
+ Use `--force` to replace a conflicting package-owned generated file or package
29
+ version. Without it, existing files are never silently overwritten. Re-running
30
+ with unchanged files is safe and idempotent.
22
31
 
23
32
  Generated files:
24
33
 
@@ -32,6 +41,9 @@ Generated files:
32
41
  Tools are registered by the installed plugin and are not copied into the project.
33
42
  Knowledge operations are explicit: list, add, update, and supersede. Finishing a
34
43
  stage requires declaring whether its knowledge review was `added` or `none`.
44
+ Finish a workspace explicitly with `/wc workspace finish <workspace>`; it is
45
+ accepted only after every stage is `completed`. Use `/wc workspace list <workspace>`
46
+ to list stages with their descriptions.
35
47
 
36
48
  ## License
37
49
 
@@ -10,42 +10,23 @@ import { defaultConfig } from "../src/storage.js";
10
10
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
11
11
  const packageManifest = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"));
12
12
  const projectRoot = process.cwd();
13
- const command = [
14
- "---",
15
- "description: Explicit work-context lifecycle commands backed by installed package tools",
16
- "agent: build",
17
- "subtask: false",
18
- "---",
19
- "",
20
- "Interpret `/wc $ARGUMENTS` as an explicit work-context operation. Use the matching",
21
- "`work_context_*` custom tool registered by `.opencode/plugins/work-context.js`.",
22
- "Never edit work-context Markdown, JSONL, INDEX, or SESSIONS projections directly.",
23
- "For mutating operations, report the structured result and stable error code. Use",
24
- "`work_context_help` when the syntax is missing or ambiguous.",
25
- "",
26
- "Supported syntax:",
27
- "",
28
- "- `help [command]`",
29
- "- `create \"title\"`",
30
- "- `list` or `<workspace> list`",
31
- "- `resume <workspace> <stage>`",
32
- "- `add-stage <workspace> \"title\"`",
33
- "- `<workspace> [<stage>] link-issue <URL>`",
34
- "- `session rename \"summary\"`",
35
- "- `session close`",
36
- "- `handoff <workspace> <stage>`",
37
- "- `finish <workspace> <stage>` (requires explicit knowledge review: `added` or `none`)",
38
- "- `knowledge list|add|update|supersede <workspace> ...`",
39
- "",
40
- "Arguments: $ARGUMENTS",
41
- "",
42
- ].join("\n");
13
+ const dependencyRoot = fs.existsSync(path.join(projectRoot, "package.json"))
14
+ ? projectRoot
15
+ : fs.existsSync(path.join(projectRoot, ".opencode", "package.json"))
16
+ ? path.join(projectRoot, ".opencode")
17
+ : projectRoot;
18
+ const dependencyManifestFile = path.join(dependencyRoot, "package.json");
19
+ let dependencyManifest = {};
20
+ try { dependencyManifest = JSON.parse(fs.readFileSync(dependencyManifestFile, "utf8")); } catch {}
21
+ const pluginLoader = dependencyManifest.type === "module"
22
+ ? `export { default } from "${packageManifest.name}/plugin";\n`
23
+ : `module.exports = async (...args) => (await import("${packageManifest.name}/plugin")).default(...args);\n`;
24
+ const command = fs.readFileSync(path.join(packageRoot, "commands", "wc.md"), "utf8");
43
25
  const generated = new Map([
44
26
  [path.join(".work-context", "config.yaml"), defaultConfig()],
45
27
  [path.join(".opencode", "commands", "wc.md"), command],
46
28
  [path.join(".opencode", "plugins", "work-context.js"), `// Thin project integration; tools remain in the installed npm package.
47
- export { default } from "${packageManifest.name}/plugin";
48
- `],
29
+ ${pluginLoader}`],
49
30
  ]);
50
31
 
51
32
  const fail = (message) => {
@@ -77,19 +58,20 @@ function parseArgs(args) {
77
58
  }
78
59
 
79
60
  function ensurePackageJson() {
80
- const file = path.join(projectRoot, "package.json");
61
+ const file = path.join(dependencyRoot, "package.json");
81
62
  if (fs.existsSync(file)) return;
82
63
  const name = path.basename(projectRoot).toLowerCase().replace(/[^a-z0-9._-]+/g, "-") || "opencode-project";
64
+ fs.mkdirSync(path.dirname(file), { recursive: true });
83
65
  fs.writeFileSync(file, `${JSON.stringify({ name, version: "1.0.0", private: true }, null, 2)}\n`);
84
66
  }
85
67
 
86
68
  function checkConflicts(force) {
87
69
  const conflicts = ["package.json", "package-lock.json", "npm-shrinkwrap.json"].flatMap((relative) => {
88
- const file = path.join(projectRoot, relative);
70
+ const file = path.join(dependencyRoot, relative);
89
71
  if (!exists(file)) return [];
90
- if (hasSymlinkParent(file)) return [relative];
72
+ if (hasSymlinkParent(file)) return [path.relative(projectRoot, file)];
91
73
  const stat = fs.lstatSync(file);
92
- return stat.isFile() && !stat.isSymbolicLink() ? [] : [relative];
74
+ return stat.isFile() && !stat.isSymbolicLink() ? [] : [path.relative(projectRoot, file)];
93
75
  });
94
76
  conflicts.push(...[...generated].flatMap(([relative, content]) => {
95
77
  const file = path.join(projectRoot, relative);
@@ -106,7 +88,7 @@ function checkConflicts(force) {
106
88
  }
107
89
 
108
90
  function checkPackageConflict(force) {
109
- const file = path.join(projectRoot, "package.json");
91
+ const file = path.join(dependencyRoot, "package.json");
110
92
  if (!exists(file)) return true;
111
93
  let manifest;
112
94
  try { manifest = JSON.parse(fs.readFileSync(file, "utf8")); }
@@ -120,8 +102,11 @@ function checkPackageConflict(force) {
120
102
  }
121
103
 
122
104
  function snapshotFiles() {
123
- return ["package.json", "package-lock.json", "npm-shrinkwrap.json", ...generated.keys(), ".gitignore"].map((relative) => {
124
- const file = path.join(projectRoot, relative);
105
+ return [
106
+ ...["package.json", "package-lock.json", "npm-shrinkwrap.json"].map((relative) => path.join(dependencyRoot, relative)),
107
+ ...[...generated.keys()].map((relative) => path.join(projectRoot, relative)),
108
+ path.join(projectRoot, ".gitignore"),
109
+ ].map((file) => {
125
110
  return { file, exists: exists(file), content: exists(file) ? fs.readFileSync(file) : null };
126
111
  });
127
112
  }
@@ -166,9 +151,9 @@ function acquireInitLock() {
166
151
  }
167
152
 
168
153
  function prepareNodeModules(initLock) {
169
- const target = path.join(projectRoot, "node_modules");
170
- const backup = path.join(projectRoot, ".opencode-work-context-node_modules.backup");
171
- const journal = path.join(projectRoot, ".opencode-work-context-node_modules.recovery.json");
154
+ const target = path.join(dependencyRoot, "node_modules");
155
+ const backup = path.join(dependencyRoot, ".opencode-work-context-node_modules.backup");
156
+ const journal = path.join(dependencyRoot, ".opencode-work-context-node_modules.recovery.json");
172
157
  const result = { target, backup, journal, lock: initLock.lock, token: initLock.token, hadNodeModules: false };
173
158
  if (recoverNodeModules(result) === false) return { ...result, failed: true };
174
159
  if (exists(backup)) { fail("previous node_modules recovery is incomplete"); return { ...result, failed: true }; }
@@ -187,18 +172,29 @@ function recoverNodeModules({ target, backup, journal }) {
187
172
  try { state = JSON.parse(fs.readFileSync(journal, "utf8")); } catch { fail("cannot read node_modules recovery journal"); return false; }
188
173
  if (!state || typeof state !== "object" || Object.keys(state).some((key) => !["target", "backup", "hadNodeModules", "phase"].includes(key)) || typeof state.target !== "string" || typeof state.backup !== "string" || !["prepared", "installed", "committed"].includes(state.phase) || state.target !== target || state.backup !== backup || typeof state.hadNodeModules !== "boolean") { fail("invalid node_modules recovery journal"); return false; }
189
174
  if (exists(backup) && fs.lstatSync(backup).isSymbolicLink()) { fail("invalid node_modules recovery backup"); return false; }
190
- if (state.phase === "committed") {
191
- if (!exists(target) && exists(backup)) fs.renameSync(backup, target);
192
- else if (exists(backup)) fs.rmSync(backup, { recursive: true, force: true });
193
- } else if (exists(backup)) {
194
- if (exists(target)) fs.rmSync(target, { recursive: true, force: true });
195
- fs.renameSync(backup, target);
196
- } else if (!state.hadNodeModules && exists(target)) fs.rmSync(target, { recursive: true, force: true });
197
- fs.rmSync(journal, { force: true });
175
+ if (state.phase !== "committed" && state.hadNodeModules && !exists(backup)) {
176
+ fail("node_modules recovery backup is missing; refusing to continue");
177
+ return false;
178
+ }
179
+ try {
180
+ if (state.phase === "committed") {
181
+ if (!exists(target) && exists(backup)) fs.renameSync(backup, target);
182
+ else if (!exists(target)) { fail("committed node_modules recovery has no target or backup"); return false; }
183
+ else if (exists(backup)) fs.rmSync(backup, { recursive: true, force: true });
184
+ } else if (exists(backup)) {
185
+ if (exists(target)) fs.rmSync(target, { recursive: true, force: true });
186
+ fs.renameSync(backup, target);
187
+ } else if (!state.hadNodeModules && exists(target)) fs.rmSync(target, { recursive: true, force: true });
188
+ fs.rmSync(journal, { force: true });
189
+ } catch (error) {
190
+ fail(`node_modules recovery failed: ${error.message}`);
191
+ return false;
192
+ }
198
193
  return true;
199
194
  }
200
195
 
201
196
  function restoreNodeModules(snapshot) {
197
+ if (snapshot.committed) { releaseInitLock(snapshot); return; }
202
198
  if (snapshot.failed) { releaseInitLock(snapshot); return; }
203
199
  fs.rmSync(snapshot.target, { recursive: true, force: true });
204
200
  if (snapshot.backup && exists(snapshot.backup)) fs.renameSync(snapshot.backup, snapshot.target);
@@ -208,8 +204,11 @@ function restoreNodeModules(snapshot) {
208
204
 
209
205
  function commitNodeModules(snapshot) {
210
206
  if (snapshot.journal) writeAtomic(snapshot.journal, JSON.stringify({ target: snapshot.target, backup: snapshot.backup, hadNodeModules: snapshot.hadNodeModules, phase: "committed" }) + "\n");
211
- if (snapshot.backup) fs.rmSync(snapshot.backup, { recursive: true, force: true });
212
- if (snapshot.journal) fs.rmSync(snapshot.journal, { force: true });
207
+ snapshot.committed = true;
208
+ try { if (snapshot.backup) fs.rmSync(snapshot.backup, { recursive: true, force: true }); }
209
+ catch (error) { console.error(`opencode-work-context: committed; backup cleanup deferred: ${error.message}`); }
210
+ try { if (snapshot.journal) fs.rmSync(snapshot.journal, { force: true }); }
211
+ catch (error) { console.error(`opencode-work-context: committed; recovery journal cleanup deferred: ${error.message}`); }
213
212
  releaseInitLock(snapshot);
214
213
  }
215
214
 
@@ -224,7 +223,7 @@ function markNodeModulesInstalled(snapshot) {
224
223
 
225
224
  function installPackage(snapshot) {
226
225
  const spec = `${packageManifest.name}@${packageManifest.version}`;
227
- const result = spawnSync("npm", ["install", "--save-dev", "--save-exact", spec], { cwd: projectRoot, stdio: "inherit" });
226
+ const result = spawnSync("npm", ["install", "--save-dev", "--save-exact", spec], { cwd: dependencyRoot, stdio: "inherit" });
228
227
  if (result.error) { restoreFiles(snapshot); fail(`npm install failed: ${result.error.message}`); }
229
228
  else if (result.status !== 0) { restoreFiles(snapshot); fail(`npm install exited with status ${result.status}`); }
230
229
  return result.status === 0;
package/commands/wc.md CHANGED
@@ -1,6 +1,5 @@
1
1
  ---
2
2
  description: Explicit work-context lifecycle commands backed by structured tools
3
- agent: build
4
3
  subtask: false
5
4
  ---
6
5
 
@@ -10,11 +9,16 @@ Markdown, JSONL, INDEX, or SESSIONS projections directly. For mutating operation
10
9
  report the structured result and stable error code. Use `work_context_help` when
11
10
  the syntax is missing or ambiguous.
12
11
 
12
+ For `workspace list <workspace>` (or `<workspace> list`), report the workspace
13
+ status and every stage as `stage - status - title - description`.
14
+
13
15
  Supported syntax:
14
16
 
15
17
  - `help [command]`
16
18
  - `create "title"`
17
19
  - `list` or `<workspace> list`
20
+ - `workspace list <workspace>`
21
+ - `workspace finish <workspace>`
18
22
  - `resume <workspace> <stage>`
19
23
  - `add-stage <workspace> "title"`
20
24
  - `<workspace> [<stage>] link-issue <URL>`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-work-context",
3
3
  "type": "module",
4
- "version": "0.1.0",
4
+ "version": "0.1.2",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
package/src/core.js CHANGED
@@ -86,7 +86,10 @@ export class WorkContext {
86
86
  id(workspace, 6);
87
87
  const dir = path.join(this.storage.workspaceDir(workspace), "stages");
88
88
  if (!fs.existsSync(dir)) fail(ERROR_CODES.NOT_FOUND, "Workspace not found");
89
- const stages = fs.readdirSync(dir).filter((file) => /^\d{2}\.md$/.test(file)).map((file) => this.storage.readStage(workspace, file.slice(0, 2)).data);
89
+ const stages = fs.readdirSync(dir).filter((file) => /^\d{2}\.md$/.test(file)).map((file) => {
90
+ const stage = this.storage.readStage(workspace, file.slice(0, 2)).data;
91
+ return { ...stage, description: stage.goal };
92
+ });
90
93
  const ids = new Set(stages.map((item) => item.stage));
91
94
  const visiting = new Set();
92
95
  const visited = new Set();
@@ -104,6 +107,26 @@ export class WorkContext {
104
107
  return { ok: true, data: { workspace, stages, sessions: reduceSessions(this.storage.readEvents()).filter((session) => session.workspace === workspace) } };
105
108
  }
106
109
 
110
+ finishWorkspace(workspace) {
111
+ id(workspace, 6);
112
+ return this.transact(`workspace-${workspace}`, () => {
113
+ const record = this.storage.readWorkspace(workspace);
114
+ const stages = this.listStages(workspace).data.stages;
115
+ if (record.data.status === "cancelled") fail(ERROR_CODES.INVALID_STATE, "Cancelled workspace cannot be finished", { workspace, status: record.data.status });
116
+ const incompleteStages = stages.filter((stage) => stage.status !== "completed");
117
+ if (incompleteStages.length) fail(ERROR_CODES.INVALID_STATE, "All workspace stages must be completed before finishing", {
118
+ workspace,
119
+ incompleteStages: incompleteStages.map(({ stage, title, description, status }) => ({ stage, title, description, status })),
120
+ });
121
+ if (record.data.status === "completed") return this.result({ workspace, status: "completed", stages }, []);
122
+ record.data.status = "completed";
123
+ record.data.updated_at = new Date().toISOString();
124
+ this.storage.writeMarkdown(this.storage.workspaceFile(workspace), record.data, record.body);
125
+ generateProjections(this.storage);
126
+ return this.result({ workspace, status: "completed", stages }, [workspace]);
127
+ });
128
+ }
129
+
107
130
  sessionById(sessionId) {
108
131
  return reduceSessions(this.storage.readEvents()).find((session) => session.session_id === sessionId) || null;
109
132
  }
@@ -295,7 +318,7 @@ export class WorkContext {
295
318
  }
296
319
 
297
320
  help(command = "") {
298
- return this.result({ command, syntax: "/wc [create|list|resume|add-stage|link-issue|session rename|session close|handoff|finish|knowledge list|knowledge add|knowledge update|knowledge supersede|help]", note: "finish requires knowledgeReview=added|none; mutating commands call structured tools; only explicit lifecycle operations change storage." }, []);
321
+ return this.result({ command, syntax: "/wc [create|list|workspace list|workspace finish|resume|add-stage|link-issue|session rename|session close|handoff|finish|knowledge list|knowledge add|knowledge update|knowledge supersede|help]", note: "workspace finish requires all stages to be completed; stage finish requires knowledgeReview=added|none; mutating commands call structured tools; only explicit lifecycle operations change storage." }, []);
299
322
  }
300
323
 
301
324
  result(data, changed) {
@@ -13,6 +13,8 @@ const run = (fn) => async (args, context) => {
13
13
  const common = { workspace: tool.schema.string().regex(/^\d{6}$/), stage: tool.schema.string().regex(/^\d{1,2}$/) };
14
14
  export const work_context_list_workspaces = tool({ description: "List work-context workspaces.", args: {}, execute: run((ctx) => ctx.listWorkspaces()) });
15
15
  export const work_context_list_stages = tool({ description: "List stages and sessions for a workspace.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.listStages(a.workspace)) });
16
+ export const work_context_workspace_list = tool({ description: "List a workspace with stage descriptions and sessions.", args: { workspace: tool.schema.string().regex(/^\d{6}$/) }, execute: run((ctx, a) => ctx.listStages(a.workspace)) });
17
+ 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)) });
16
18
  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: oc.sessionID })) });
17
19
  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: oc.sessionID, summary: a.summary })) });
18
20
  export const work_context_add_stage = tool({ description: "Add a planned stage.", args: { workspace: tool.schema.string(), title: tool.schema.string(), goal: tool.schema.string().optional(), dependsOn: tool.schema.array(tool.schema.string()).optional() }, execute: run((ctx, a) => ctx.addStage(a.workspace, a.title, { goal: a.goal, dependsOn: a.dependsOn })) });
@@ -27,4 +29,4 @@ export const work_context_add_knowledge = tool({ description: "Add a durable kno
27
29
  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)) });
28
30
  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) ) });
29
31
 
30
- export default { work_context_list_workspaces, work_context_list_stages, work_context_create_workspace, work_context_start_session, work_context_add_stage, work_context_link_issue, work_context_rename_session, work_context_close_session, work_context_handoff_stage, work_context_finish_stage, work_context_help, work_context_list_knowledge, work_context_add_knowledge, work_context_update_knowledge, work_context_supersede_knowledge };
32
+ export default { work_context_list_workspaces, work_context_list_stages, work_context_workspace_list, work_context_workspace_finish, work_context_create_workspace, work_context_start_session, work_context_add_stage, work_context_link_issue, work_context_rename_session, work_context_close_session, work_context_handoff_stage, work_context_finish_stage, work_context_help, work_context_list_knowledge, work_context_add_knowledge, work_context_update_knowledge, work_context_supersede_knowledge };