opencode-work-context 0.1.3 → 0.1.5

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
@@ -1,7 +1,67 @@
1
- # opencode-work-context
1
+ # OpenCode Work Context
2
2
 
3
- Filesystem work-context core and OpenCode adapter for standalone projects. The
4
- package is ESM and has no dependency on Mezzio or PHP.
3
+ Keep the context of a task between OpenCode sessions.
4
+
5
+ Create one workspace for one task, split it into stages, and return to the
6
+ exact stage where you stopped. The optional sidebar shows the current task and
7
+ its progress at a glance.
8
+
9
+ ![OpenCode Work Context stages sidebar](docs/assets/opencode-work-context.png)
10
+
11
+ > Example: one workspace for one task, linked to Jira issue `AN-142`, with
12
+ > three completed stages and the current work highlighted at stage 04.
13
+ >
14
+ > The sidebar is an optional read-only TUI panel. The core workflow works
15
+ > through `/wc` commands and OpenCode tools without it.
16
+
17
+ ## How It Works
18
+
19
+ ```text
20
+ Workspace: Add CSV export to analytics report
21
+ ├── ✓ 01. Planning
22
+ ├── ✓ 02. Update the export endpoint
23
+ ├── ✓ 03. Add the download action
24
+ ├── • 04. Handle export edge cases <- current stage
25
+ └── 05. Verify the export flow
26
+ ```
27
+
28
+ - **Workspace** is one concrete task, such as adding CSV export.
29
+ - **Stage** is one step in that task.
30
+ - **Planning** is normally the first stage.
31
+ - **Resume** starts a new session at a selected stage.
32
+ - **Handoff** preserves the context when moving work to another session.
33
+
34
+ ## Quick Start
35
+
36
+ Run this from the root of a standalone OpenCode project:
37
+
38
+ ```sh
39
+ npx opencode-work-context init
40
+ ```
41
+
42
+ Then create a task and its first stage in OpenCode:
43
+
44
+ ```text
45
+ /wc create "Add CSV export to analytics report"
46
+ /wc stage rename 000001 01 "Planning"
47
+ /wc stage add 000001 "Update the export endpoint"
48
+ /wc resume 000001 02
49
+ ```
50
+
51
+ When you return later, continue from the active stage:
52
+
53
+ ```text
54
+ /wc resume 000001 02
55
+ ```
56
+
57
+ Useful commands:
58
+
59
+ ```text
60
+ /wc list
61
+ /wc workspace list 000001
62
+ /wc stage handoff 000001 02
63
+ /wc stage finish 000001 02
64
+ ```
5
65
 
6
66
  ## Install
7
67
 
@@ -11,7 +71,7 @@ Run from the root of a standalone OpenCode project:
11
71
  npx opencode-work-context init
12
72
  ```
13
73
 
14
- `init` installs `opencode-work-context@0.1.1` as an exact devDependency using
74
+ `init` installs the current package version as an exact devDependency using
15
75
  standard `npm`, preserving normal lifecycle behavior for the host project. The
16
76
  dependency root is the project root when it has `package.json`, otherwise
17
77
  `.opencode` when `.opencode/package.json` exists, and finally the project root
@@ -19,10 +79,10 @@ with a new `package.json` when neither exists. Package files, lockfiles, and
19
79
  `node_modules` are changed only in that dependency root; integration files and
20
80
  `.gitignore` always belong to the project root.
21
81
 
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.
82
+ The installer ensures that the dependency-root package uses `"type": "module"`
83
+ and generates an ESM plugin loader. OpenCode loads local plugins as JavaScript
84
+ modules; keeping the generated `.js` integration path ESM avoids a CommonJS
85
+ interop failure before custom tools are registered.
26
86
  It does not create a workspace. Start one explicitly with `/wc create "Title"`.
27
87
 
28
88
  Use `--force` to replace a conflicting package-owned generated file or package
@@ -38,12 +98,43 @@ Generated files:
38
98
  - `<workspace>/KNOWLEDGE.md` is the canonical durable knowledge ledger and is
39
99
  created on the first explicit knowledge operation.
40
100
 
101
+ The optional read-only stages panel is a separate TUI plugin. Add a project-local
102
+ loader outside OpenCode's server-plugin autoscan at `.opencode/tui-plugins/work-context-stages.js`:
103
+
104
+ ```js
105
+ export { default } from "opencode-work-context/tui";
106
+ ```
107
+
108
+ Enable that loader explicitly in `.opencode/tui.json`:
109
+
110
+ ```json
111
+ { "$schema": "https://opencode.ai/tui.json", "plugin": ["./tui-plugins/work-context-stages.js"] }
112
+ ```
113
+
114
+ The package keeps the
115
+ existing `opencode-work-context/plugin` server export unchanged and exposes the
116
+ panel as `opencode-work-context/tui`. The panel only reads canonical storage via
117
+ `WorkContext.openExisting`; it does not create `.work-context`, call lifecycle
118
+ tools, or modify Markdown/JSONL projections. Hosts without the TUI plugin API
119
+ continue to load the server plugin and its tools normally.
120
+
41
121
  Tools are registered by the installed plugin and are not copied into the project.
122
+ Tracker links support GitLab issues (`/-/issues/<number>`), GitHub issues
123
+ (`/issues/<number>`), and Jira issues (`/browse/KEY-123`). They are URL-based
124
+ references only; the plugin does not call provider APIs or synchronize issue
125
+ metadata.
42
126
  Knowledge operations are explicit: list, add, update, and supersede. Finishing a
43
- stage requires declaring whether its knowledge review was `added` or `none`.
127
+ stage automatically validates the Knowledge Base by default (`knowledgeReview=auto`);
128
+ the legacy `added` and `none` modes remain accepted.
44
129
  Finish a workspace explicitly with `/wc workspace finish <workspace>`; it is
45
130
  accepted only after every stage is `completed`. Use `/wc workspace list <workspace>`
46
- to list stages with their descriptions.
131
+ to list stages with their descriptions. Workspace titles can be changed with
132
+ `/wc workspace rename <workspace> "title"`, and existing stage descriptions can
133
+ be changed with `/wc stage update <workspace> <stage> "description"`.
134
+
135
+ If the host `opencode.json` restricts `experimental.primary_tools`, add the
136
+ registered `work_context_*` tool names to that allowlist; the installer does not
137
+ rewrite project-specific agent policy.
47
138
 
48
139
  ## License
49
140
 
@@ -68,3 +159,8 @@ The package layout is intentionally small:
68
159
  - `test/` contains core contract tests.
69
160
 
70
161
  Run `npm test` when explicitly verifying a checkout.
162
+
163
+ Run `npm run test:integration` for the reusable plugin-boundary scenarios. These
164
+ tests create isolated fixture projects, use a small fake OpenCode host, and
165
+ exercise a new session resume through the server title hook and read-only TUI
166
+ snapshot without requiring an interactive OpenCode process.
@@ -18,9 +18,7 @@ const dependencyRoot = fs.existsSync(path.join(projectRoot, "package.json"))
18
18
  const dependencyManifestFile = path.join(dependencyRoot, "package.json");
19
19
  let dependencyManifest = {};
20
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`;
21
+ const pluginLoader = `export { default } from "${packageManifest.name}/plugin";\n`;
24
22
  const command = fs.readFileSync(path.join(packageRoot, "commands", "wc.md"), "utf8");
25
23
  const generated = new Map([
26
24
  [path.join(".work-context", "config.yaml"), defaultConfig()],
@@ -62,7 +60,15 @@ function ensurePackageJson() {
62
60
  if (fs.existsSync(file)) return;
63
61
  const name = path.basename(projectRoot).toLowerCase().replace(/[^a-z0-9._-]+/g, "-") || "opencode-project";
64
62
  fs.mkdirSync(path.dirname(file), { recursive: true });
65
- fs.writeFileSync(file, `${JSON.stringify({ name, version: "1.0.0", private: true }, null, 2)}\n`);
63
+ fs.writeFileSync(file, `${JSON.stringify({ name, version: "1.0.0", private: true, type: "module" }, null, 2)}\n`);
64
+ }
65
+
66
+ function ensureModuleScope() {
67
+ const file = path.join(dependencyRoot, "package.json");
68
+ const manifest = JSON.parse(fs.readFileSync(file, "utf8"));
69
+ if (manifest.type === "module") return;
70
+ manifest.type = "module";
71
+ writeAtomic(file, `${JSON.stringify(manifest, null, 2)}\n`);
66
72
  }
67
73
 
68
74
  function checkConflicts(force) {
@@ -250,6 +256,7 @@ if (options) {
250
256
  if (nodeModules.failed) process.exitCode = 1;
251
257
  try {
252
258
  if (!nodeModules.failed) ensurePackageJson();
259
+ if (!nodeModules.failed) ensureModuleScope();
253
260
  if (!nodeModules.failed) {
254
261
  if (installPackage(snapshot)) {
255
262
  markNodeModulesInstalled(nodeModules);
package/commands/wc.md CHANGED
@@ -17,10 +17,16 @@ Use these exact tool mappings; do not invent shortened tool names:
17
17
  - `create` -> `work_context_create_workspace`
18
18
  - `list` -> `work_context_list_workspaces`
19
19
  - `workspace list <workspace>` or `<workspace> list` -> `work_context_workspace_list`
20
+ - `workspace rename <workspace> "title"` -> `work_context_rename_workspace`
20
21
  - `workspace finish <workspace>` -> `work_context_workspace_finish`
21
22
  - `resume <workspace> <stage>` -> `work_context_start_session`
22
- - `add-stage <workspace> ...` -> `work_context_add_stage`
23
- - `finish <workspace> <stage>` -> `work_context_finish_stage`
23
+ - `stage add [<workspace>] ...` -> `work_context_add_stage`
24
+ - `stage rename [<workspace>] <stage> "title"` -> `work_context_rename_stage`
25
+ - `stage update [<workspace>] <stage> "description"` -> `work_context_update_stage`
26
+ - `stage archive [<workspace>] <stage>` -> `work_context_archive_stage`
27
+ - `stage handoff <workspace> <stage>` -> `work_context_handoff_stage`
28
+ - `stage abandon <workspace> <stage>` -> `work_context_abandon_stage`
29
+ - `stage finish <workspace> <stage>` -> `work_context_finish_stage`
24
30
 
25
31
  Supported syntax:
26
32
 
@@ -28,14 +34,19 @@ Supported syntax:
28
34
  - `create "title"`
29
35
  - `list` or `<workspace> list`
30
36
  - `workspace list <workspace>`
37
+ - `workspace rename <workspace> "title"`
31
38
  - `workspace finish <workspace>`
32
39
  - `resume <workspace> <stage>`
33
- - `add-stage <workspace> "title"`
40
+ - `stage add [<workspace>] "title"`
41
+ - `stage rename [<workspace>] <stage> "title"`
42
+ - `stage update [<workspace>] <stage> "description"`
43
+ - `stage archive [<workspace>] <stage>`
44
+ - `stage finish <workspace> <stage>`
34
45
  - `<workspace> [<stage>] link-issue <URL>`
35
46
  - `session rename "summary"`
36
- - `session close`
37
- - `handoff <workspace> <stage>`
38
- - `finish <workspace> <stage>` requires an explicit knowledge review: `added` or `none`
47
+ - `stage handoff <workspace> <stage>`
48
+ - `stage abandon <workspace> <stage>`
49
+ - `stage finish <workspace> <stage>` automatically reviews the Knowledge Base (`auto` by default)
39
50
  - `knowledge list|add|update|supersede <workspace> ...`
40
51
 
41
52
  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.3",
4
+ "version": "0.1.5",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -29,7 +29,9 @@
29
29
  "opencode-work-context": "bin/opencode-work-context.js"
30
30
  },
31
31
  "scripts": {
32
- "test": "node --test"
32
+ "test": "node --test",
33
+ "test:integration": "node --test test/integration/*.test.js",
34
+ "test:tui": "OPENCODE_TUI_SMOKE=1 bun --conditions=browser test test/stages-tui.test.js"
33
35
  },
34
36
  "files": [
35
37
  "bin",
@@ -41,12 +43,16 @@
41
43
  "LICENSE"
42
44
  ],
43
45
  "dependencies": {
44
- "@opencode-ai/plugin": "^1.14.50"
46
+ "@opencode-ai/plugin": "^1.14.50",
47
+ "@opentui/solid": "^0.4.5",
48
+ "solid-js": "1.9.12"
45
49
  },
46
50
  "exports": {
47
51
  ".": "./src/index.js",
48
52
  "./adapter": "./src/opencode-adapter.js",
49
53
  "./plugin": "./plugin/work-context.js",
54
+ "./server": "./plugin/server.js",
55
+ "./tui": "./plugin/stages-tui.js",
50
56
  "./tools/*": "./tools/*.js"
51
57
  }
52
58
  }
@@ -0,0 +1,3 @@
1
+ import server from "./work-context.js";
2
+
3
+ export default { id: "work-context", server };
@@ -0,0 +1,255 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { readStagesSnapshot } from "../src/stages-snapshot.js";
4
+ import { renderStagesPanel } from "../src/stages-renderer.js";
5
+ import { jsx } from "@opentui/solid/jsx-runtime";
6
+ import { createSignal } from "solid-js";
7
+
8
+ const DEBOUNCE_MS = 150;
9
+ const POLL_MS = 1000;
10
+ const PATH_TIMEOUT_MS = 5000;
11
+ const PATH_POLL_MS = 25;
12
+ const WORK_CONTEXT_PREFIX = "work" + "_" + "context_";
13
+ const statusMarker = (status) => ({
14
+ planned: "[ ]",
15
+ in_progress: "[•]",
16
+ completed: "[✓]",
17
+ cancelled: "[!]",
18
+ archived: "[-]",
19
+ }[status] || "[?]");
20
+
21
+ export { readStagesSnapshot, renderStagesPanel };
22
+
23
+ const defaultRuntime = { jsx };
24
+
25
+ const renderStagesContent = (result, theme, runtime = defaultRuntime) => !result?.ok || !result.data?.workspace
26
+ ? [
27
+ runtime.jsx("text", { children: runtime.jsx("b", { children: "Stages" }) }),
28
+ ...renderStagesPanel(result).split("\n").slice(1).map((line) => runtime.jsx("text", { children: line })),
29
+ ]
30
+ : [
31
+ runtime.jsx("box", {
32
+ flexDirection: "row",
33
+ children: [
34
+ runtime.jsx("text", { children: runtime.jsx("b", { children: "Stages" }) }),
35
+ runtime.jsx("text", { fg: theme?.current?.textMuted, children: ` · ${result.data.workspace.status}` }),
36
+ ],
37
+ }),
38
+ ...result.data.stages.map((stage) => runtime.jsx("box", {
39
+ flexDirection: "row",
40
+ children: [
41
+ runtime.jsx("text", { flexShrink: 0, marginRight: 1, fg: stage.current || stage.id === result.data.currentStage ? theme?.current?.warning : theme?.current?.textMuted, children: statusMarker(stage.status) }),
42
+ runtime.jsx("text", { flexGrow: 1, flexShrink: 1, wrapMode: "word", fg: stage.current || stage.id === result.data.currentStage ? theme?.current?.warning : theme?.current?.textMuted, children: `${stage.id}. ${stage.title}` }),
43
+ ],
44
+ })),
45
+ ];
46
+
47
+ export const renderStagesElement = (result, theme, runtime = defaultRuntime) => {
48
+ return runtime.jsx("box", {
49
+ flexDirection: "column",
50
+ children: () => renderStagesContent(typeof result === "function" ? result() : result, theme, runtime),
51
+ });
52
+ };
53
+
54
+ const sessionIdFromEvent = (event) => event?.properties?.info?.id
55
+ || event?.properties?.sessionID
56
+ || event?.sessionID
57
+ || event?.sessionId
58
+ || event?.data?.info?.id
59
+ || event?.data?.sessionID
60
+ || event?.properties?.part?.sessionID;
61
+ const isCompletedWorkContextTool = (event) => {
62
+ const part = event?.properties?.part;
63
+ return event?.type === "message.part.updated"
64
+ && part?.type === "tool"
65
+ && part.tool?.startsWith(WORK_CONTEXT_PREFIX)
66
+ && ["completed", "error"].includes(part.state?.status);
67
+ };
68
+ export const sessionIdForSlot = (api, initialSessionId, slotContext = {}, slotState = {}) => slotState.session_id
69
+ || slotState.sessionID
70
+ || slotState.sessionId
71
+ || slotState.session
72
+ || slotContext.session_id
73
+ || slotContext.sessionID
74
+ || slotContext.sessionId
75
+ || slotContext.session
76
+ || api.route?.current?.params?.sessionID
77
+ || api.route?.current?.params?.sessionId
78
+ || api.route?.current?.params?.session_id
79
+ || api.route?.current?.params?.session
80
+ || initialSessionId;
81
+ const disposeRegistration = (registration) => {
82
+ if (typeof registration === "function") registration();
83
+ else registration?.dispose?.();
84
+ };
85
+
86
+ export const createStagesTuiController = ({ projectRoot, read = readStagesSnapshot, debounceMs = DEBOUNCE_MS, pollMs = POLL_MS, createSignal: makeSignal = createSignal } = {}) => {
87
+ const snapshots = new Map();
88
+ const generations = new Map();
89
+ const timers = new Map();
90
+ const pollers = new Map();
91
+ const [version, setVersion] = makeSignal(0);
92
+ let disposed = false;
93
+
94
+ const readSnapshot = async (sessionId) => {
95
+ if (disposed || !sessionId) return;
96
+ const currentGeneration = (generations.get(sessionId) || 0) + 1;
97
+ generations.set(sessionId, currentGeneration);
98
+ const entry = snapshots.get(sessionId) || { result: null, successful: null };
99
+ snapshots.set(sessionId, entry);
100
+ setVersion((value) => value + 1);
101
+ try {
102
+ const result = await read({ projectRoot, sessionId });
103
+ if (disposed || currentGeneration !== generations.get(sessionId)) return;
104
+ if (result?.ok) {
105
+ entry.successful = result;
106
+ entry.result = result;
107
+ } else {
108
+ entry.result = entry.successful
109
+ ? { ...entry.successful, stale: true, error: result?.error || { code: "STORAGE_ERROR" } }
110
+ : result;
111
+ }
112
+ } catch (error) {
113
+ if (disposed || currentGeneration !== generations.get(sessionId)) return;
114
+ entry.result = entry.successful
115
+ ? { ...entry.successful, stale: true, error: { code: error.code || "STORAGE_ERROR", message: error.message } }
116
+ : { ok: false, error: { code: error.code || "STORAGE_ERROR", message: error.message } };
117
+ }
118
+ snapshots.set(sessionId, entry);
119
+ setVersion((value) => value + 1);
120
+ };
121
+
122
+ const scheduleRefresh = (sessionId) => {
123
+ if (disposed || !sessionId) return;
124
+ const previous = timers.get(sessionId);
125
+ if (previous) clearTimeout(previous);
126
+ timers.set(sessionId, setTimeout(() => {
127
+ timers.delete(sessionId);
128
+ void readSnapshot(sessionId);
129
+ }, debounceMs));
130
+ };
131
+
132
+ const watch = (sessionId) => {
133
+ if (disposed || !sessionId || pollers.has(sessionId) || !pollMs) return;
134
+ pollers.set(sessionId, setInterval(() => scheduleRefresh(sessionId), pollMs));
135
+ };
136
+
137
+ const resultFor = (sessionId) => {
138
+ version();
139
+ watch(sessionId);
140
+ const entry = snapshots.get(sessionId);
141
+ if (!entry) {
142
+ void readSnapshot(sessionId);
143
+ return { ok: true, data: { schema: 1, workspace: null, stages: [], currentStage: null }, loading: true };
144
+ }
145
+ return entry.result || { ok: true, data: { schema: 1, workspace: null, stages: [], currentStage: null }, loading: true };
146
+ };
147
+
148
+ return {
149
+ load: readSnapshot,
150
+ scheduleRefresh,
151
+ resultFor,
152
+ dispose: () => {
153
+ if (disposed) return;
154
+ disposed = true;
155
+ generations.clear();
156
+ for (const timer of timers.values()) clearTimeout(timer);
157
+ timers.clear();
158
+ for (const poller of pollers.values()) clearInterval(poller);
159
+ pollers.clear();
160
+ snapshots.clear();
161
+ },
162
+ };
163
+ };
164
+
165
+ const sleep = (milliseconds, signal) => new Promise((resolve) => {
166
+ const timer = setTimeout(resolve, milliseconds);
167
+ const onAbort = () => { clearTimeout(timer); resolve(); };
168
+ signal?.addEventListener("abort", onAbort, { once: true });
169
+ if (signal) setTimeout(() => signal.removeEventListener("abort", onAbort), milliseconds);
170
+ });
171
+
172
+ export const resolveProjectRoot = async (api, { timeoutMs = PATH_TIMEOUT_MS, pollMs = PATH_POLL_MS } = {}) => {
173
+ if (!api?.slots?.register) return null;
174
+ const signal = api.lifecycle?.signal;
175
+ const deadline = Date.now() + timeoutMs;
176
+ while (!signal?.aborted && Date.now() <= deadline) {
177
+ if (api.state?.path?.worktree) return api.state.path.worktree;
178
+ try {
179
+ const location = await api.client?.location?.get?.({});
180
+ const directory = location?.data?.directory || location?.data?.project?.directory;
181
+ if (directory) return directory;
182
+ } catch {}
183
+ await sleep(pollMs, signal);
184
+ }
185
+ return null;
186
+ };
187
+
188
+ const renderStagesSlot = (controller, theme, sessionId, runtime = defaultRuntime) => runtime.jsx("box", {
189
+ flexDirection: "column",
190
+ children: renderStagesElement(() => controller.resultFor(sessionId), theme, runtime),
191
+ });
192
+
193
+ const ACTIVE_WORKSPACE_SESSION = "__active_" + "work" + "_context_workspace__";
194
+
195
+ // Optional TUI entry point. It is deliberately not imported by the server plugin.
196
+ export const tui = async (api, options = {}) => {
197
+ const projectRoot = await resolveProjectRoot(api, options);
198
+ if (!projectRoot) return;
199
+
200
+ const initialSessionId = api.route?.current?.name === "session"
201
+ ? api.route.current.params?.sessionID
202
+ || api.route.current.params?.sessionId
203
+ || api.route.current.params?.session_id
204
+ : undefined;
205
+ const controller = createStagesTuiController({
206
+ projectRoot,
207
+ read: api.stagesSnapshotProvider || readStagesSnapshot,
208
+ debounceMs: options.debounceMs,
209
+ pollMs: options.pollMs,
210
+ createSignal: options.runtime?.createSignal,
211
+ });
212
+ await controller.load(initialSessionId);
213
+ let currentSessionId = initialSessionId;
214
+ let storageWatcher;
215
+ try {
216
+ storageWatcher = fs.watch(path.join(projectRoot, ".work-context"), { recursive: true }, () => {
217
+ controller.scheduleRefresh(currentSessionId);
218
+ });
219
+ } catch {
220
+ // Missing storage is valid; the provider will continue to expose an empty state.
221
+ }
222
+
223
+ let cleanup = () => {};
224
+ const unregisterSlot = api.slots.register({
225
+ dispose: () => cleanup(),
226
+ slots: {
227
+ sidebar_content: (slotContext = {}, slotState = {}) => {
228
+ const sessionId = sessionIdForSlot(api, initialSessionId, slotContext, slotState) || ACTIVE_WORKSPACE_SESSION;
229
+ currentSessionId = sessionId;
230
+ return renderStagesSlot(controller, api.theme, sessionId, options.runtime);
231
+ },
232
+ },
233
+ });
234
+ const unsubscribe = api.event?.on?.("session.updated", (event) => {
235
+ controller.scheduleRefresh(sessionIdFromEvent(event));
236
+ });
237
+ const unsubscribeTool = api.event?.on?.("message.part.updated", (event) => {
238
+ if (isCompletedWorkContextTool(event)) controller.scheduleRefresh(sessionIdFromEvent(event));
239
+ });
240
+
241
+ let cleaned = false;
242
+ cleanup = () => {
243
+ if (cleaned) return;
244
+ cleaned = true;
245
+ controller.dispose();
246
+ storageWatcher?.close();
247
+ disposeRegistration(unsubscribe);
248
+ disposeRegistration(unsubscribeTool);
249
+ disposeRegistration(unregisterSlot);
250
+ };
251
+ api.lifecycle?.onDispose?.(cleanup);
252
+
253
+ };
254
+
255
+ export default { id: "work-context-stages", tui };
@@ -3,19 +3,34 @@ import { contextFor, titleFor } from "../src/opencode-adapter.js";
3
3
 
4
4
  export default async ({ client, directory, worktree }) => ({
5
5
  tool: tools,
6
+ "tool.execute.after": async ({ tool, sessionID }) => {
7
+ if (!tool?.startsWith("work_context_") || !sessionID) return;
8
+ await updateSessionTitle(client, worktree || directory, directory, sessionID);
9
+ },
6
10
  event: async ({ event }) => {
7
11
  if (event.type !== "session.updated") return;
8
12
  const info = event.properties?.info;
9
13
  const sessionId = info?.id || event.properties?.sessionID;
10
14
  const eventDirectory = info?.directory || directory;
11
- const context = contextFor(worktree || eventDirectory, sessionId);
12
- const session = context.sessionById(sessionId);
13
- if (!session) return;
14
- const title = titleFor(context, session.workspace, session.stage, sessionId, session);
15
- if (title) {
16
- const current = await client.session.get({ path: { id: sessionId }, query: { directory: eventDirectory } });
17
- const session = current.data ?? current;
18
- if (session.title !== title) await client.session.update({ path: { id: sessionId }, query: { directory: eventDirectory }, body: { title } });
15
+ try {
16
+ await updateSessionTitle(client, worktree || eventDirectory, eventDirectory, sessionId);
17
+ } catch {
18
+ // A malformed or unavailable work-context must not break the server hook.
19
19
  }
20
20
  },
21
21
  });
22
+
23
+ async function updateSessionTitle(client, projectRoot, directory, sessionId) {
24
+ try {
25
+ const context = contextFor(projectRoot, sessionId);
26
+ const session = context.sessionById(sessionId) || context.sessionByOpenCodeId(sessionId);
27
+ if (!session) return;
28
+ const title = titleFor(context, session.workspace, session.stage, sessionId, session);
29
+ if (!title) return;
30
+ const current = await client.session.get({ path: { id: sessionId }, query: { directory } });
31
+ const currentSession = current.data ?? current;
32
+ if (currentSession.title !== title) await client.session.update({ path: { id: sessionId }, query: { directory }, body: { title } });
33
+ } catch {
34
+ // Storage/API failures must not break tool execution or the server hook.
35
+ }
36
+ }
package/src/core.js CHANGED
@@ -15,14 +15,23 @@ const id = (value, digits) => {
15
15
  const stageId = (value) => id(String(value).padStart(2, "0"), 2);
16
16
  const actor = (options) => options.actor || "OpenCode";
17
17
  const body = (title, goal = "") => `# ${title}\n\n${goal ? `## Goal\n\n${goal}\n` : ""}`;
18
+ const stageBody = (record, title, goal) => {
19
+ const result = record.body.match(/\n## Result[\s\S]*$/)?.[0] || "";
20
+ return `${body(title, goal).trimEnd()}${result}`;
21
+ };
18
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; } } };
19
23
 
20
24
  function parseIssue(url) {
21
25
  try {
22
26
  const parsed = new URL(url);
23
- const match = parsed.pathname.match(/\/([^/]+)\/-\/issues\/(\d+)\/?$/);
24
- if (!/^https?:$/.test(parsed.protocol) || !match) fail(ERROR_CODES.INVALID_ISSUE_URL, "Expected a GitLab issue URL");
25
- return { url: parsed.toString(), provider: "gitlab", project: parsed.pathname.split("/-/issues/")[0].replace(/^\//, ""), iid: Number(match[2]) };
27
+ if (!/^https?:$/.test(parsed.protocol)) fail(ERROR_CODES.INVALID_ISSUE_URL, "Expected a supported tracker issue URL");
28
+ let match = parsed.pathname.match(/^\/(.+)\/-\/issues\/(\d+)\/?$/);
29
+ if (match) return { url: parsed.toString(), provider: "gitlab", project: match[1], iid: Number(match[2]) };
30
+ match = parsed.pathname.match(/^\/([^/]+\/[^/]+)\/issues\/(\d+)\/?$/);
31
+ if (match) return { url: parsed.toString(), provider: "github", project: match[1], iid: Number(match[2]) };
32
+ match = parsed.pathname.match(/^\/browse\/([A-Za-z][A-Za-z0-9]+-\d+)\/?$/);
33
+ if (match) return { url: parsed.toString(), provider: "jira", project: match[1].split("-")[0], key: match[1] };
34
+ fail(ERROR_CODES.INVALID_ISSUE_URL, "Expected a supported tracker issue URL");
26
35
  } catch (error) {
27
36
  if (error.code === ERROR_CODES.INVALID_ISSUE_URL) throw error;
28
37
  fail(ERROR_CODES.INVALID_ISSUE_URL, "Invalid issue URL");
@@ -113,7 +122,7 @@ export class WorkContext {
113
122
  const record = this.storage.readWorkspace(workspace);
114
123
  const stages = this.listStages(workspace).data.stages;
115
124
  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");
125
+ const incompleteStages = stages.filter((stage) => stage.status !== "completed" && stage.status !== "archived");
117
126
  if (incompleteStages.length) fail(ERROR_CODES.INVALID_STATE, "All workspace stages must be completed before finishing", {
118
127
  workspace,
119
128
  incompleteStages: incompleteStages.map(({ stage, title, description, status }) => ({ stage, title, description, status })),
@@ -131,6 +140,13 @@ export class WorkContext {
131
140
  return reduceSessions(this.storage.readEvents()).find((session) => session.session_id === sessionId) || null;
132
141
  }
133
142
 
143
+ sessionByOpenCodeId(opencodeSessionId, workspace = null, stage = null) {
144
+ return reduceSessions(this.storage.readEvents()).filter((session) => session.opencode_session_id === opencodeSessionId
145
+ && (!workspace || session.workspace === workspace)
146
+ && (!stage || session.stage === stage)
147
+ && session.state === "active").at(-1) || null;
148
+ }
149
+
134
150
  assertDependenciesCompleted(workspace, stageRecord) {
135
151
  const stages = this.listStages(workspace).data.stages;
136
152
  for (const dependency of stageRecord.data.depends_on) {
@@ -149,15 +165,30 @@ export class WorkContext {
149
165
  if (fs.existsSync(this.storage.workspaceDir(workspace))) fail(ERROR_CODES.CONFLICT, "Workspace already exists");
150
166
  fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
151
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));
152
- this.storage.writeMarkdown(this.storage.stageFile(workspace, "01"), { schema: 1, workspace, stage: "01", title: `Планирование: ${title.trim()}`, status: "in_progress", goal: "Уточнить цель и ограничения работы", depends_on: [], owner: actor(this.options), created_at: now, updated_at: now, tracker_links: [] }, body(`Планирование: ${title.trim()}`, "Уточнить цель и ограничения работы"));
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("Планирование", "Уточнить цель и ограничения работы"));
153
169
  const sessionId = options.sessionId || randomUUID();
154
170
  if (this.storage.readEvents().some((item) => item.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
155
- this.writeEvents([event("session.started", workspace, "01", 1, sessionId, actor(this.options), { summary: `планирование ${title.trim()}` })]);
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 })]);
156
172
  generateProjections(this.storage);
157
173
  return this.result({ workspace, stage: "01", session_id: sessionId, ordinal: "01/01" }, [workspace, "01"]);
158
174
  });
159
175
  }
160
176
 
177
+ renameWorkspace(workspace, title) {
178
+ id(workspace, 6);
179
+ if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Title is required");
180
+ return this.transact(`workspace-${workspace}`, () => {
181
+ const record = this.storage.readWorkspace(workspace);
182
+ const nextTitle = title.trim();
183
+ if (record.data.title === nextTitle) return this.result({ workspace, title: nextTitle }, []);
184
+ record.data.title = nextTitle;
185
+ record.data.updated_at = new Date().toISOString();
186
+ this.storage.writeMarkdown(this.storage.workspaceFile(workspace), record.data, body(nextTitle));
187
+ generateProjections(this.storage);
188
+ return this.result({ workspace, title: nextTitle }, [workspace]);
189
+ });
190
+ }
191
+
161
192
  nextWorkspace() {
162
193
  const ids = this.listWorkspaces().data.map((workspace) => Number(workspace.workspace));
163
194
  return String(Math.max(0, ...ids) + 1).padStart(6, "0");
@@ -171,8 +202,15 @@ export class WorkContext {
171
202
  const stageRecord = this.storage.readStage(workspace, stage);
172
203
  this.assertDependenciesCompleted(workspace, stageRecord);
173
204
  const events = this.storage.readEvents();
174
- if (activeSession(events, workspace, stage)) fail(ERROR_CODES.ACTIVE_SESSION_EXISTS, "Stage already has an active session");
175
- if (["completed", "cancelled"].includes(stageRecord.data.status)) fail(ERROR_CODES.INVALID_STATE, "Cannot start a session for a terminal stage");
205
+ const current = activeSession(events, workspace, stage);
206
+ if (current) {
207
+ const canTakeOver = options.takeover
208
+ && current.session_id !== sessionId
209
+ && current.opencode_session_id !== options.opencodeSessionId;
210
+ if (!canTakeOver) fail(ERROR_CODES.ACTIVE_SESSION_EXISTS, "Stage already has an active session");
211
+ this.writeEvents([event("session.handed_off", workspace, stage, current.ordinal, current.session_id, actor(this.options), { reason: "resumed in a new OpenCode session" })]);
212
+ }
213
+ if (["completed", "cancelled", "archived"].includes(stageRecord.data.status)) fail(ERROR_CODES.INVALID_STATE, "Cannot start a session for a terminal stage");
176
214
  if (reduceSessions(events).some((session) => session.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
177
215
  const previous = reduceSessions(events).filter((session) => session.workspace === workspace && session.stage === stage);
178
216
  const ordinal = previous.length + 1;
@@ -183,7 +221,7 @@ export class WorkContext {
183
221
  }
184
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 })]);
185
223
  generateProjections(this.storage);
186
- return this.result({ workspace, stage, session_id: sessionId, ordinal: `01/${String(ordinal).padStart(2, "0")}` }, [workspace, stage]);
224
+ return this.result({ workspace, stage, session_id: sessionId, ordinal: `${stage}/${String(ordinal).padStart(2, "0")}` }, [workspace, stage]);
187
225
  });
188
226
  }
189
227
 
@@ -205,6 +243,53 @@ export class WorkContext {
205
243
  });
206
244
  }
207
245
 
246
+ renameStage(workspace, stage, title) {
247
+ id(workspace, 6);
248
+ stage = stageId(stage);
249
+ if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Title is required");
250
+ return this.transact(`stage-${workspace}-${stage}`, () => {
251
+ const record = this.storage.readStage(workspace, stage);
252
+ const nextTitle = title.trim();
253
+ if (record.data.title === nextTitle) return this.result({ workspace, stage, title: nextTitle }, []);
254
+ record.data.title = nextTitle;
255
+ record.data.updated_at = new Date().toISOString();
256
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, stageBody(record, nextTitle, record.data.goal));
257
+ generateProjections(this.storage);
258
+ return this.result({ workspace, stage, title: nextTitle }, [workspace, stage]);
259
+ });
260
+ }
261
+
262
+ updateStage(workspace, stage, description) {
263
+ id(workspace, 6);
264
+ stage = stageId(stage);
265
+ if (!description?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Description is required");
266
+ return this.transact(`stage-${workspace}-${stage}`, () => {
267
+ const record = this.storage.readStage(workspace, stage);
268
+ const nextDescription = description.trim();
269
+ if (record.data.goal === nextDescription) return this.result({ workspace, stage, description: nextDescription }, []);
270
+ record.data.goal = nextDescription;
271
+ record.data.updated_at = new Date().toISOString();
272
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, stageBody(record, record.data.title, nextDescription));
273
+ generateProjections(this.storage);
274
+ return this.result({ workspace, stage, description: nextDescription }, [workspace, stage]);
275
+ });
276
+ }
277
+
278
+ archiveStage(workspace, stage) {
279
+ id(workspace, 6);
280
+ stage = stageId(stage);
281
+ return this.transact(`stage-${workspace}-${stage}`, () => {
282
+ const record = this.storage.readStage(workspace, stage);
283
+ if (record.data.status === "archived") return this.result({ workspace, stage, status: "archived" }, []);
284
+ if (activeSession(this.storage.readEvents(), workspace, stage)) fail(ERROR_CODES.ACTIVE_SESSION_EXISTS, "Cannot archive a stage with an active session");
285
+ record.data.status = "archived";
286
+ record.data.updated_at = new Date().toISOString();
287
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, record.body);
288
+ generateProjections(this.storage);
289
+ return this.result({ workspace, stage, status: "archived" }, [workspace, stage]);
290
+ });
291
+ }
292
+
208
293
  listKnowledge(workspace) {
209
294
  id(workspace, 6);
210
295
  this.storage.assertNoSymlinks();
@@ -294,6 +379,10 @@ export class WorkContext {
294
379
  });
295
380
  }
296
381
 
382
+ abandon(workspace, stage, sessionId, reason = "abandoned") {
383
+ return this.closeSession(workspace, stage, sessionId, reason, "abandoned");
384
+ }
385
+
297
386
  finish(workspace, stage, sessionId, options = {}) {
298
387
  stage = stageId(stage);
299
388
  return this.transact(`stage-${workspace}-${stage}`, () => {
@@ -305,7 +394,9 @@ export class WorkContext {
305
394
  if (known?.state === "closed") return this.result({ session_id: sessionId, workspace, stage, state: "closed", status: "completed" }, []);
306
395
  fail(ERROR_CODES.SESSION_NOT_ACTIVE, "Session did not complete this stage");
307
396
  }
308
- if (!['added', 'none'].includes(options.knowledgeReview)) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge review must be 'added' or 'none'");
397
+ const knowledgeReview = options.knowledgeReview || "auto";
398
+ if (!['auto', 'added', 'none'].includes(knowledgeReview)) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge review must be 'auto', 'added' or 'none'");
399
+ const knowledgeEntries = knowledgeReview === "auto" ? this.listKnowledge(workspace).data : null;
309
400
  const active = activeSession(events, workspace, stage);
310
401
  if (!active || active.session_id !== sessionId) fail(active ? ERROR_CODES.ACTIVE_SESSION_EXISTS : ERROR_CODES.SESSION_NOT_ACTIVE, active ? "Another active session owns this stage" : "Session is not active");
311
402
  this.writeEvents([event("session.closed", workspace, stage, active.ordinal, sessionId, actor(this.options), { reason: "stage_completed" })]);
@@ -313,12 +404,12 @@ export class WorkContext {
313
404
  current.data.updated_at = new Date().toISOString();
314
405
  this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), current.data, `${current.body}\n\n## Result\n\n${options.result || "Stage completed."}`);
315
406
  generateProjections(this.storage);
316
- return this.result({ session_id: sessionId, workspace, stage, state: "closed", status: "completed" }, [workspace, stage]);
407
+ return this.result({ session_id: sessionId, workspace, stage, state: "closed", status: "completed", knowledge_review: knowledgeReview, ...(knowledgeEntries ? { knowledge_entries: knowledgeEntries.length } : {}) }, [workspace, stage]);
317
408
  });
318
409
  }
319
410
 
320
411
  help(command = "") {
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." }, []);
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." }, []);
322
413
  }
323
414
 
324
415
  result(data, changed) {
package/src/index.js CHANGED
@@ -6,3 +6,5 @@ export * from "./projections.js";
6
6
  export * from "./title.js";
7
7
  export * from "./core.js";
8
8
  export * from "./knowledge.js";
9
+ export * from "./stages-snapshot.js";
10
+ export * from "./stages-renderer.js";
@@ -2,6 +2,7 @@ import path from "node:path";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { WorkContext } from "./core.js";
4
4
  import { renderTitle } from "./title.js";
5
+ export { readStagesSnapshot } from "./stages-snapshot.js";
5
6
 
6
7
  export function contextFor(directory, sessionId, actor = "OpenCode") {
7
8
  return WorkContext.openExisting(directory, { sessionId, actor });
@@ -11,6 +12,6 @@ export function titleFor(context, workspace, stage, sessionId, knownSession = nu
11
12
  if (!current) return null;
12
13
  const meta = context.storage.readWorkspace(workspace).data;
13
14
  const stageMeta = context.storage.readStage(workspace, stage).data;
14
- return renderTitle({ workspace, stage, ordinal: current.ordinal, summary: current.summary, state: current.state, trackerLinks: stageMeta.tracker_links?.length ? stageMeta.tracker_links : meta.tracker_links, issuePrefix: context.storage.config.title?.issue_prefix || "short" });
15
+ return renderTitle({ workspace, workspaceTitle: meta.title, stage, ordinal: current.ordinal, state: current.state, trackerLinks: stageMeta.tracker_links?.length ? stageMeta.tracker_links : meta.tracker_links, issuePrefix: context.storage.config.title?.issue_prefix || "short" });
15
16
  }
16
17
  export const packageRoot = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
@@ -0,0 +1,22 @@
1
+ const statusMarker = (status) => ({
2
+ planned: "[ ]",
3
+ in_progress: "[•]",
4
+ completed: "[✓]",
5
+ cancelled: "[!]",
6
+ archived: "[-]",
7
+ }[status] || "[?]");
8
+
9
+ export function renderStagesPanel(result) {
10
+ if (!result?.ok) return `work-context stages\n! unavailable: ${result?.error?.code || "STORAGE_ERROR"}`;
11
+ const snapshot = result.data;
12
+ if (!snapshot.workspace) return `work-context stages\n(no workspace for this session)${result.stale ? `\n! stale: ${result.error?.code || "STORAGE_ERROR"}` : ""}`;
13
+
14
+ const lines = [
15
+ `Stages · ${snapshot.workspace.status}`,
16
+ ];
17
+ for (const stage of snapshot.stages) {
18
+ lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}`);
19
+ }
20
+ if (result.stale) lines.push(`! stale: ${result.error?.code || "STORAGE_ERROR"}`);
21
+ return lines.join("\n");
22
+ }
@@ -0,0 +1,67 @@
1
+ import { WorkContext } from "./core.js";
2
+
3
+ const emptySnapshot = () => ({
4
+ schema: 1,
5
+ workspace: null,
6
+ stages: [],
7
+ currentStage: null,
8
+ generatedAt: new Date().toISOString(),
9
+ });
10
+
11
+ /**
12
+ * Build the TUI read model from canonical metadata and the event stream.
13
+ * openExisting is intentional: this boundary must never initialize storage.
14
+ */
15
+ export function readStagesSnapshot({ projectRoot, sessionId }) {
16
+ try {
17
+ const context = WorkContext.openExisting(projectRoot, { sessionId, actor: "OpenCode TUI" });
18
+ let session = sessionId ? context.sessionById(sessionId) : null;
19
+ if (!session && sessionId) {
20
+ for (const workspace of context.listWorkspaces().data) {
21
+ const candidate = context.listStages(workspace.workspace).data.sessions
22
+ .find((item) => item.opencode_session_id === sessionId);
23
+ if (candidate) { session = candidate; break; }
24
+ }
25
+ }
26
+ if (!session) {
27
+ const activeWorkspaces = context.listWorkspaces().data.filter((workspace) => workspace.status === "in_progress");
28
+ if (activeWorkspaces.length === 1) {
29
+ const workspaceStages = context.listStages(activeWorkspaces[0].workspace).data;
30
+ session = workspaceStages.sessions.find((item) => item.state === "active") || null;
31
+ if (!session) session = { workspace: activeWorkspaces[0].workspace, stage: null };
32
+ }
33
+ }
34
+ if (!session) return { ok: true, data: emptySnapshot() };
35
+
36
+ const workspace = context.storage.readWorkspace(session.workspace).data;
37
+ const stages = context.listStages(session.workspace).data.stages
38
+ .filter((stage) => stage.status !== "archived")
39
+ .sort((left, right) => Number(left.stage) - Number(right.stage))
40
+ .map((stage) => ({
41
+ id: stage.stage,
42
+ title: stage.title,
43
+ status: stage.status,
44
+ description: stage.description,
45
+ current: stage.stage === session.stage,
46
+ }));
47
+ const currentStage = stages.some((stage) => stage.current) ? session.stage : null;
48
+
49
+ return {
50
+ ok: true,
51
+ data: {
52
+ schema: 1,
53
+ workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status },
54
+ stages,
55
+ currentStage,
56
+ generatedAt: new Date().toISOString(),
57
+ },
58
+ };
59
+ } catch (error) {
60
+ if (error.code === "NOT_FOUND") return { ok: true, data: emptySnapshot() };
61
+ return {
62
+ ok: false,
63
+ error: { code: error.code || "STORAGE_ERROR", message: error.message, details: error.details || {} },
64
+ data: emptySnapshot(),
65
+ };
66
+ }
67
+ }
package/src/storage.js CHANGED
@@ -13,13 +13,23 @@ const validTimestamp = (value) => {
13
13
  };
14
14
  const requiredString = (data, key) => typeof data[key] === "string" && data[key].trim().length > 0;
15
15
  const validTrackerLinks = (links) => links.every((link) => {
16
- if (!link || typeof link !== "object" || Object.keys(link).some((key) => !["url", "provider", "project", "iid"].includes(key)) || typeof link.url !== "string" || typeof link.provider !== "string" || typeof link.project !== "string" || !Number.isInteger(link.iid)) return false;
16
+ if (!link || typeof link !== "object" || typeof link.url !== "string" || typeof link.provider !== "string" || typeof link.project !== "string") return false;
17
17
  try {
18
18
  const url = new URL(link.url);
19
- const marker = url.pathname.lastIndexOf("/-/issues/");
20
- const project = marker > 1 ? url.pathname.slice(1, marker) : "";
21
- const iid = marker > 1 ? Number(url.pathname.slice(marker + "/-/issues/".length).replace(/\/$/, "")) : NaN;
22
- return link.provider === "gitlab" && (url.protocol === "http:" || url.protocol === "https:") && project === link.project && iid === link.iid;
19
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
20
+ if (link.provider === "gitlab" || link.provider === "github") {
21
+ const allowed = ["url", "provider", "project", "iid"];
22
+ const match = url.pathname.match(link.provider === "gitlab" ? /^\/(.+)\/-\/issues\/(\d+)\/?$/ : /^\/([^/]+\/[^/]+)\/issues\/(\d+)\/?$/);
23
+ return Object.keys(link).every((key) => allowed.includes(key)) && Object.keys(link).length === allowed.length && match && match[1] === link.project && Number(match[2]) === link.iid && Number.isInteger(link.iid) && link.iid > 0;
24
+ }
25
+ if (link.provider === "jira") {
26
+ return Object.keys(link).every((key) => ["url", "provider", "project", "key"].includes(key))
27
+ && typeof link.key === "string"
28
+ && /^[A-Za-z][A-Za-z0-9]+-\d+$/.test(link.key)
29
+ && url.pathname === `/browse/${link.key}`
30
+ && link.project === link.key.substring(0, link.key.lastIndexOf("-"));
31
+ }
32
+ return false;
23
33
  } catch { return false; }
24
34
  });
25
35
  const validEvents = new Set(["session.started", "session.renamed", "session.handed_off", "session.closed", "session.abandoned"]);
@@ -62,8 +72,8 @@ function validateMetadata(data, kind, workspace, stage = null) {
62
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"];
63
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`);
64
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`);
65
- if (!validTrackerLinks(data.tracker_links) || data.tracker_links.some((link) => !link.provider.trim() || !link.project.trim() || !Number.isInteger(link.iid) || link.iid < 1)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} tracker links`);
66
- const statuses = kind === "workspace" ? ["in_progress", "completed", "cancelled"] : ["planned", "in_progress", "completed", "cancelled"];
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
+ const statuses = kind === "workspace" ? ["in_progress", "completed", "cancelled"] : ["planned", "in_progress", "completed", "cancelled", "archived"];
67
77
  if (!statuses.includes(data.status)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} status`);
68
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");
69
79
  }
package/src/title.js CHANGED
@@ -1,6 +1,10 @@
1
- export function renderTitle({ workspace, stage, ordinal, summary, state = "active", trackerLinks = [], issuePrefix = "short" }) {
1
+ export function renderTitle({ workspace, workspaceTitle, stage, ordinal, state = "active", trackerLinks = [], issuePrefix = "short" }) {
2
2
  const link = trackerLinks[0]; let prefix = "";
3
- if (link && issuePrefix !== "none") prefix = issuePrefix === "full" ? `${link.project}#${link.iid} | ` : `GL#${link.iid} | `;
3
+ if (link && issuePrefix !== "none") {
4
+ const identifier = link.key || link.iid;
5
+ const short = (link.provider || "gitlab") === "gitlab" ? `GL#${identifier}` : link.provider === "github" ? `GH#${identifier}` : `JIRA ${identifier}`;
6
+ prefix = issuePrefix === "full" ? `${link.project}#${identifier} | ` : `${short} | `;
7
+ }
4
8
  const suffix = state === "active" ? "" : ` (${state})`;
5
- return `${prefix}${workspace} ${stage}/${String(ordinal).padStart(2, "0")}${suffix}: ${(summary || "продолжение работы").replace(/[\r\n|]+/g, " ").trim().slice(0, 80)}`;
9
+ return `${prefix}${workspace} ${stage}/${String(ordinal).padStart(2, "0")}${suffix}\n${(workspaceTitle || workspace).replace(/[\r\n|]+/g, " ").trim().slice(0, 80)}`;
6
10
  }
@@ -1,5 +1,7 @@
1
1
  import { tool } from "@opencode-ai/plugin";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { contextFor, titleFor } from "../src/opencode-adapter.js";
4
+ import { fail, ERROR_CODES } from "../src/errors.js";
3
5
 
4
6
  const run = (fn) => async (args, context) => {
5
7
  try {
@@ -11,22 +13,36 @@ const run = (fn) => async (args, context) => {
11
13
  }
12
14
  };
13
15
  const common = { workspace: tool.schema.string().regex(/^\d{6}$/), stage: tool.schema.string().regex(/^\d{1,2}$/) };
16
+ const workspaceFromSession = (ctx, workspace) => {
17
+ if (workspace) return workspace;
18
+ const session = ctx.sessionByOpenCodeId(ctx.options.sessionId) || ctx.sessionById(ctx.options.sessionId);
19
+ if (!session) fail(ERROR_CODES.INVALID_ARGUMENT, "Workspace is required when the current session is not associated with a workspace");
20
+ return session.workspace;
21
+ };
22
+ const sessionFor = (ctx, oc, workspace, stage) => ctx.sessionById(oc.sessionID)?.workspace === workspace
23
+ && ctx.sessionById(oc.sessionID)?.stage === stage
24
+ ? oc.sessionID
25
+ : ctx.sessionByOpenCodeId(oc.sessionID, workspace, stage)?.session_id || oc.sessionID;
14
26
  export const work_context_list_workspaces = tool({ description: "List work-context workspaces.", args: {}, execute: run((ctx) => ctx.listWorkspaces()) });
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
27
  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)) });
28
+ export const work_context_rename_workspace = tool({ description: "Rename a workspace.", args: { workspace: tool.schema.string().regex(/^\d{6}$/), title: tool.schema.string() }, execute: run((ctx, a) => ctx.renameWorkspace(a.workspace, a.title)) });
17
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)) });
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 })) });
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 })) });
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 })) });
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
+ 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 })) });
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
+ 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_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)) });
21
36
  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)) });
22
- 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, oc.sessionID, a.summary)) });
23
- 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, oc.sessionID)) });
24
- 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, oc.sessionID)) });
25
- export const work_context_finish_stage = tool({ description: "Finish a stage and close the current active session.", args: { ...common, result: tool.schema.string().optional(), knowledgeReview: tool.schema.string() }, execute: run((ctx, a, oc) => ctx.finish(a.workspace, a.stage, oc.sessionID, { result: a.result, knowledgeReview: a.knowledgeReview })) });
37
+ 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
+ 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))) });
39
+ 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
+ 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
+ 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 })) });
26
42
  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)) });
27
43
  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)) });
28
44
  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)) });
29
45
  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)) });
30
46
  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) ) });
31
47
 
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 };
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 };
@@ -0,0 +1,3 @@
1
+ import { work_context_abandon_stage } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_abandon_stage;
@@ -0,0 +1,2 @@
1
+ import { work_context_archive_stage } from "../src/tool-definitions.js";
2
+ export default work_context_archive_stage;
@@ -0,0 +1,2 @@
1
+ import { work_context_rename_stage } from "../src/tool-definitions.js";
2
+ export default work_context_rename_stage;
@@ -0,0 +1,2 @@
1
+ import { work_context_rename_workspace } from "../src/tool-definitions.js";
2
+ export default work_context_rename_workspace;
@@ -0,0 +1,2 @@
1
+ import { work_context_update_stage } from "../src/tool-definitions.js";
2
+ export default work_context_update_stage;
@@ -1,2 +0,0 @@
1
- import { work_context_list_stages } from "../src/tool-definitions.js";
2
- export default work_context_list_stages;