opencode-work-context 0.1.9 → 0.1.11
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 +74 -13
- package/bin/opencode-work-context.js +7 -2
- package/commands/wc.md +32 -18
- package/package.json +4 -2
- package/plugin/stages-tui.js +8 -1
- package/plugin/tui.js +13 -0
- package/plugin/work-context-modal.js +548 -0
- package/src/core.js +63 -9
- package/src/errors.js +1 -0
- package/src/index.js +1 -0
- package/src/stages-snapshot.js +1 -1
- package/src/tool-definitions.js +44 -14
- package/src/work-context-snapshot.js +81 -0
- package/tools/work_context_update_stage_prompt.js +2 -0
- package/tools/work_context_update_stage_result.js +2 -0
package/README.md
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
Keep the context of a task between OpenCode sessions.
|
|
4
4
|
|
|
5
5
|
Create one workspace for one task, split it into stages, and return to the
|
|
6
|
-
exact stage where you stopped. The optional sidebar
|
|
7
|
-
its progress at a glance.
|
|
6
|
+
exact stage where you stopped. The optional sidebar and modal show the current
|
|
7
|
+
task and its progress at a glance.
|
|
8
8
|
|
|
9
9
|

|
|
10
10
|
|
|
@@ -44,11 +44,16 @@ Then create a task and its first stage in OpenCode:
|
|
|
44
44
|
```text
|
|
45
45
|
/wc create "Add CSV export to analytics report"
|
|
46
46
|
/wc stage rename 000001 01 "Planning"
|
|
47
|
-
/wc stage add 000001 "Update the export endpoint"
|
|
47
|
+
/wc stage add 000001 "Update the export endpoint" "Inspect the current endpoint, implement CSV export, add regression tests, and verify the result."
|
|
48
48
|
/wc resume 000001 02
|
|
49
49
|
```
|
|
50
50
|
|
|
51
|
-
When you return later, continue from the active stage
|
|
51
|
+
When you return later, continue from the active stage. A stage must have a
|
|
52
|
+
non-empty prompt before implementation begins; if the prompt is missing or
|
|
53
|
+
ambiguous, `/wc resume` instructs the agent to ask focused questions first.
|
|
54
|
+
Before working, the agent reports the stage essence, the previous session's
|
|
55
|
+
result or stopping point, and what it will do now. On subsequent resumes, it
|
|
56
|
+
only reports that context and waits for explicit confirmation before continuing:
|
|
52
57
|
|
|
53
58
|
```text
|
|
54
59
|
/wc resume 000001 02
|
|
@@ -63,6 +68,16 @@ Useful commands:
|
|
|
63
68
|
/wc stage finish 000001 02
|
|
64
69
|
```
|
|
65
70
|
|
|
71
|
+
Workspace IDs are exactly six digits. Stage IDs are one or two digits and are
|
|
72
|
+
normalized to two digits by the command contract. Canonical examples are:
|
|
73
|
+
|
|
74
|
+
```text
|
|
75
|
+
/wc workspace list 000004
|
|
76
|
+
/wc resume 000004 02
|
|
77
|
+
/wc stage handoff 000004 02
|
|
78
|
+
/wc stage finish 000004 02
|
|
79
|
+
```
|
|
80
|
+
|
|
66
81
|
## Install
|
|
67
82
|
|
|
68
83
|
Run from the root of a standalone OpenCode project:
|
|
@@ -80,7 +95,7 @@ with a new `package.json` when neither exists. Package files, lockfiles, and
|
|
|
80
95
|
`.gitignore` always belong to the project root.
|
|
81
96
|
|
|
82
97
|
The installer ensures that the dependency-root package uses `"type": "module"`
|
|
83
|
-
and generates
|
|
98
|
+
and generates ESM server and TUI loaders. OpenCode loads local plugins as JavaScript
|
|
84
99
|
modules; keeping the generated `.js` integration path ESM avoids a CommonJS
|
|
85
100
|
interop failure before custom tools are registered.
|
|
86
101
|
It does not create a workspace. Start one explicitly with `/wc create "Title"`.
|
|
@@ -89,6 +104,30 @@ Use `--force` to replace a conflicting package-owned generated file or package
|
|
|
89
104
|
version. Without it, existing files are never silently overwritten. Re-running
|
|
90
105
|
with unchanged files is safe and idempotent.
|
|
91
106
|
|
|
107
|
+
## Update
|
|
108
|
+
|
|
109
|
+
Run the update from the root of the OpenCode project that has the plugin
|
|
110
|
+
installed:
|
|
111
|
+
|
|
112
|
+
```sh
|
|
113
|
+
npx --yes opencode-work-context@latest init --force
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
This installs the latest package version as an exact devDependency and refreshes
|
|
117
|
+
the package-owned server and TUI loaders. It preserves the project's
|
|
118
|
+
`.work-context` data. Check the installed version with:
|
|
119
|
+
|
|
120
|
+
```sh
|
|
121
|
+
npm ls opencode-work-context --depth=0
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Restart OpenCode after updating so it reloads the new server plugin, TUI loader,
|
|
125
|
+
keymap, and modal code. A restart is required after changing package code or
|
|
126
|
+
`.opencode/tui.json`; lifecycle data changes are picked up by the existing
|
|
127
|
+
refresh mechanisms.
|
|
128
|
+
Use a specific version instead of `latest` when you need a pinned upgrade, for
|
|
129
|
+
example `npx --yes opencode-work-context@0.1.10 init --force`.
|
|
130
|
+
|
|
92
131
|
Generated files:
|
|
93
132
|
|
|
94
133
|
- `.work-context/config.yaml` for filesystem configuration;
|
|
@@ -99,7 +138,7 @@ Generated files:
|
|
|
99
138
|
- `<workspace>/KNOWLEDGE.md` is the canonical durable knowledge ledger and is
|
|
100
139
|
created on the first explicit knowledge operation.
|
|
101
140
|
|
|
102
|
-
The optional read-only stages panel
|
|
141
|
+
The optional read-only stages panel and modal are a separate TUI plugin. `init` installs a
|
|
103
142
|
project-local loader outside OpenCode's server-plugin autoscan at
|
|
104
143
|
`.opencode/tui-plugins/work-context-stages.js` and enables it in `.opencode/tui.json`:
|
|
105
144
|
|
|
@@ -113,21 +152,43 @@ Enable that loader explicitly in `.opencode/tui.json`:
|
|
|
113
152
|
{ "$schema": "https://opencode.ai/tui.json", "plugin": ["./tui-plugins/work-context-stages.js"] }
|
|
114
153
|
```
|
|
115
154
|
|
|
116
|
-
The package keeps the
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
`
|
|
155
|
+
The package keeps the existing `opencode-work-context/plugin` server export and
|
|
156
|
+
also exposes the explicit server entry as `opencode-work-context/server`.
|
|
157
|
+
The combined read-only panel and modal are exposed only as
|
|
158
|
+
`opencode-work-context/tui`. Both TUI adapters read canonical storage via
|
|
159
|
+
`WorkContext.openExisting`; they do not create `.work-context`, call lifecycle
|
|
120
160
|
tools, or modify Markdown/JSONL projections. Hosts without the TUI plugin API
|
|
121
161
|
continue to load the server plugin and its tools normally.
|
|
122
162
|
|
|
123
|
-
|
|
163
|
+
The modal is opened with `Ctrl+Alt+W` when the host supports the public TUI
|
|
164
|
+
keymap and dialog APIs. Its `l`, `r`, `h`, and `f` actions only prepare visible
|
|
165
|
+
`/wc` commands. They never submit, invoke tools, dispatch commands, invoke an
|
|
166
|
+
LLM, or mutate storage. Prompt insertion is best effort: a host-provided public
|
|
167
|
+
append bridge may insert the command, otherwise the modal shows the exact
|
|
168
|
+
command and `PROMPT_INSERT_UNAVAILABLE` for manual submission. The installed
|
|
169
|
+
`@opencode-ai/plugin` 1.18.21 declarations expose `TuiPromptRef/set`, not a
|
|
170
|
+
confirmed `prompt.append` API, so runtime support must be verified rather than
|
|
171
|
+
assumed.
|
|
172
|
+
|
|
173
|
+
Tools are registered by the installed server export and are not copied into the
|
|
174
|
+
project. Core and storage remain in the installed package; projects should not
|
|
175
|
+
copy `src/` or `tools/`. `.work-context` Markdown, JSONL, `INDEX.md`, and
|
|
176
|
+
`SESSIONS.md` are generated projections and must never be edited manually.
|
|
124
177
|
Tracker links support GitLab issues (`/-/issues/<number>`), GitHub issues
|
|
125
178
|
(`/issues/<number>`), and Jira issues (`/browse/KEY-123`). They are URL-based
|
|
126
179
|
references only; the plugin does not call provider APIs or synchronize issue
|
|
127
180
|
metadata.
|
|
128
181
|
Knowledge operations are explicit: list, add, update, and supersede. Finishing a
|
|
129
|
-
stage
|
|
130
|
-
|
|
182
|
+
stage always validates the Knowledge Base and reports its total and active entry
|
|
183
|
+
counts. Before finishing, persist new durable findings, update changed entries,
|
|
184
|
+
supersede obsolete entries, or explicitly use `knowledgeReview=none` when no
|
|
185
|
+
durable findings were produced. The default `knowledgeReview=auto` remains
|
|
186
|
+
accepted, and `knowledgeReview=added` records that the ledger was changed.
|
|
187
|
+
Every stage start/resume includes all active entries in
|
|
188
|
+
`resume.context.workspace_knowledge`. Agents should treat this as established
|
|
189
|
+
workspace-wide context and avoid repeating earlier analysis unless an entry is
|
|
190
|
+
incomplete, contradicted, or requires verification. Superseded entries and full
|
|
191
|
+
stage results are not injected into later stages.
|
|
131
192
|
Finish a workspace explicitly with `/wc workspace finish <workspace>`; it is
|
|
132
193
|
accepted only after every stage is `completed`. Use `/wc workspace list <workspace>`
|
|
133
194
|
to list stages with their descriptions. Workspace titles can be changed with
|
|
@@ -18,8 +18,13 @@ 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 =
|
|
22
|
-
|
|
21
|
+
const pluginLoader = `// Server tools and lifecycle hooks stay in the installed package.
|
|
22
|
+
import serverPlugin from "${packageManifest.name}/server";
|
|
23
|
+
|
|
24
|
+
export default serverPlugin.server;
|
|
25
|
+
`;
|
|
26
|
+
const tuiLoader = `// TUI integration stays in the installed package; do not copy src/ or tools.
|
|
27
|
+
import { createSignal } from "solid-js";
|
|
23
28
|
import { jsx } from "@opentui/solid/jsx-runtime";
|
|
24
29
|
import plugin from "${packageManifest.name}/tui";
|
|
25
30
|
|
package/commands/wc.md
CHANGED
|
@@ -21,14 +21,15 @@ Use these exact tool mappings; do not invent shortened tool names:
|
|
|
21
21
|
- `workspace finish <workspace>` -> `work_context_workspace_finish`
|
|
22
22
|
- `resume <workspace> <stage>` -> `work_context_start_session`
|
|
23
23
|
- `stage force-close <workspace> <stage> <sessionId> "reason" FORCE_CLOSE` -> `work_context_force_close_session`
|
|
24
|
-
- `stage add [<workspace>] ...` -> `work_context_add_stage` (optional `prompt`; detailed prompt is expected for stages created from planning)
|
|
25
|
-
- `stage rename [<workspace>] <stage> "title"` -> `work_context_rename_stage`
|
|
26
|
-
- `stage update [<workspace>] <stage> "description"` -> `work_context_update_stage`
|
|
27
|
-
- `stage update-prompt [<workspace>] <stage> "prompt"` -> `work_context_update_stage_prompt`
|
|
28
|
-
- `stage
|
|
29
|
-
- `stage
|
|
30
|
-
- `stage
|
|
31
|
-
- `stage
|
|
24
|
+
- `stage add [<workspace>] ...` -> `work_context_add_stage` (optional `prompt`; a detailed local prompt is expected for stages created from planning, while shared context belongs in workspace knowledge)
|
|
25
|
+
- `stage rename [<workspace>] [<stage>] "title"` -> `work_context_rename_stage`
|
|
26
|
+
- `stage update [<workspace>] [<stage>] "description"` -> `work_context_update_stage`
|
|
27
|
+
- `stage update-prompt [<workspace>] [<stage>] "prompt"` -> `work_context_update_stage_prompt`
|
|
28
|
+
- `stage update-result [<workspace>] [<stage>] "result"` -> `work_context_update_stage_result`
|
|
29
|
+
- `stage archive [<workspace>] [<stage>]` -> `work_context_archive_stage`
|
|
30
|
+
- `stage handoff [<workspace>] [<stage>]` -> `work_context_handoff_stage`
|
|
31
|
+
- `stage abandon [<workspace>] [<stage>]` -> `work_context_abandon_stage`
|
|
32
|
+
- `stage finish [<workspace>] [<stage>]` -> `work_context_finish_stage`
|
|
32
33
|
|
|
33
34
|
Supported syntax:
|
|
34
35
|
|
|
@@ -41,18 +42,31 @@ Supported syntax:
|
|
|
41
42
|
- `resume <workspace> <stage>`
|
|
42
43
|
- `stage force-close <workspace> <stage> <sessionId> "reason" FORCE_CLOSE`
|
|
43
44
|
- `stage add [<workspace>] "title" ["prompt"]`
|
|
44
|
-
- `stage rename [<workspace>] <stage> "title"`
|
|
45
|
-
- `stage update [<workspace>] <stage> "description"`
|
|
46
|
-
- `stage update-prompt [<workspace>] <stage> "prompt"`
|
|
47
|
-
- `stage
|
|
48
|
-
- `stage
|
|
45
|
+
- `stage rename [<workspace>] [<stage>] "title"`
|
|
46
|
+
- `stage update [<workspace>] [<stage>] "description"`
|
|
47
|
+
- `stage update-prompt [<workspace>] [<stage>] "prompt"`
|
|
48
|
+
- `stage update-result [<workspace>] [<stage>] "result"`
|
|
49
|
+
- `stage archive [<workspace>] [<stage>]`
|
|
50
|
+
- `stage handoff [<workspace>] [<stage>]`
|
|
51
|
+
- `stage abandon [<workspace>] [<stage>]`
|
|
52
|
+
- `stage finish [<workspace>] [<stage>]`
|
|
49
53
|
- `<workspace> [<stage>] link-issue <URL>`
|
|
50
54
|
- `session rename "summary"`
|
|
51
|
-
- `stage handoff <workspace> <stage>`
|
|
52
|
-
- `stage abandon <workspace> <stage>`
|
|
53
|
-
- `stage finish <workspace> <stage>` automatically reviews the Knowledge Base (`auto` by default)
|
|
54
|
-
-
|
|
55
|
-
- `stage
|
|
55
|
+
- `stage handoff [<workspace>] <stage>`
|
|
56
|
+
- `stage abandon [<workspace>] <stage>`
|
|
57
|
+
- `stage finish [<workspace>] <stage>` automatically reviews the Knowledge Base (`auto` by default)
|
|
58
|
+
- stage lifecycle commands may omit stage, using the current OpenCode session; with one numeric identifier, six digits mean workspace and one or two digits mean stage
|
|
59
|
+
- `stage update-result` replaces an existing result and does not create a result for an unfinished stage
|
|
60
|
+
- `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
|
|
61
|
+
- `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
|
|
62
|
+
- on every subsequent resume, report the context and wait for explicit user confirmation; do not automatically continue implementation
|
|
63
|
+
- when `resume.next_action` is `await_confirmation`, do not inspect or modify application code until the user confirms
|
|
64
|
+
- `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
|
|
65
|
+
- `stage add` enters the newly created stage and returns its actionable `resume` context when the current OpenCode session is not yet in a workspace; otherwise it only creates the planned stage
|
|
66
|
+
- `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
|
|
67
|
+
- 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
|
|
68
|
+
- 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
|
|
69
|
+
- `stage finish` always validates the Knowledge Base and returns total and active entry counts plus downstream unfinished stages whose prompts should be reviewed after new findings
|
|
56
70
|
- `knowledge list|add|update|supersede <workspace> ...`
|
|
57
71
|
|
|
58
72
|
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.
|
|
4
|
+
"version": "0.1.11",
|
|
5
5
|
"description": "Filesystem work-context core and OpenCode adapter",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": {
|
|
@@ -29,6 +29,8 @@
|
|
|
29
29
|
"opencode-work-context": "bin/opencode-work-context.js"
|
|
30
30
|
},
|
|
31
31
|
"scripts": {
|
|
32
|
+
"check:language": "node scripts/check-repository-language.js",
|
|
33
|
+
"prepublishOnly": "npm run check:language",
|
|
32
34
|
"test": "node --test",
|
|
33
35
|
"test:integration": "node --test test/integration/*.test.js",
|
|
34
36
|
"test:tui": "OPENCODE_TUI_SMOKE=1 bun --conditions=browser test test/stages-tui.test.js"
|
|
@@ -52,7 +54,7 @@
|
|
|
52
54
|
"./adapter": "./src/opencode-adapter.js",
|
|
53
55
|
"./plugin": "./plugin/work-context.js",
|
|
54
56
|
"./server": "./plugin/server.js",
|
|
55
|
-
"./tui": "./plugin/
|
|
57
|
+
"./tui": "./plugin/tui.js",
|
|
56
58
|
"./tools/*": "./tools/*.js"
|
|
57
59
|
}
|
|
58
60
|
}
|
package/plugin/stages-tui.js
CHANGED
|
@@ -10,6 +10,8 @@ const POLL_MS = 1000;
|
|
|
10
10
|
const PATH_TIMEOUT_MS = 5000;
|
|
11
11
|
const PATH_POLL_MS = 25;
|
|
12
12
|
const WORK_CONTEXT_PREFIX = "work" + "_" + "context_";
|
|
13
|
+
const activeTuiInstances = new WeakMap();
|
|
14
|
+
const ACTIVE_TUI_KEY = Symbol.for("opencode-work-context.stages-tui");
|
|
13
15
|
const statusMarker = (status) => ({
|
|
14
16
|
planned: "[ ]",
|
|
15
17
|
in_progress: "[•]",
|
|
@@ -194,6 +196,7 @@ const ACTIVE_WORKSPACE_SESSION = "__active_" + "work" + "_context_workspace__";
|
|
|
194
196
|
|
|
195
197
|
// Optional TUI entry point. It is deliberately not imported by the server plugin.
|
|
196
198
|
export const tui = async (api, options = {}) => {
|
|
199
|
+
if (activeTuiInstances.has(api) || api?.[ACTIVE_TUI_KEY]) return activeTuiInstances.get(api) || api[ACTIVE_TUI_KEY];
|
|
197
200
|
const projectRoot = await resolveProjectRoot(api, options);
|
|
198
201
|
if (!projectRoot) return;
|
|
199
202
|
|
|
@@ -242,14 +245,18 @@ export const tui = async (api, options = {}) => {
|
|
|
242
245
|
cleanup = () => {
|
|
243
246
|
if (cleaned) return;
|
|
244
247
|
cleaned = true;
|
|
248
|
+
if (activeTuiInstances.get(api) === cleanup) activeTuiInstances.delete(api);
|
|
249
|
+
if (api?.[ACTIVE_TUI_KEY] === cleanup) delete api[ACTIVE_TUI_KEY];
|
|
245
250
|
controller.dispose();
|
|
246
251
|
storageWatcher?.close();
|
|
247
252
|
disposeRegistration(unsubscribe);
|
|
248
253
|
disposeRegistration(unsubscribeTool);
|
|
249
254
|
disposeRegistration(unregisterSlot);
|
|
250
255
|
};
|
|
256
|
+
api[ACTIVE_TUI_KEY] = cleanup;
|
|
257
|
+
activeTuiInstances.set(api, cleanup);
|
|
251
258
|
api.lifecycle?.onDispose?.(cleanup);
|
|
252
|
-
|
|
259
|
+
return cleanup;
|
|
253
260
|
};
|
|
254
261
|
|
|
255
262
|
export default { id: "work-context-stages", tui };
|
package/plugin/tui.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import stages from "./stages-tui.js";
|
|
2
|
+
import modal from "./work-context-modal.js";
|
|
3
|
+
|
|
4
|
+
// Keep the sidebar and modal adapters composed under one optional TUI entry.
|
|
5
|
+
// The server plugin remains a separate runtime contract.
|
|
6
|
+
export const tui = async (api, options = {}) => {
|
|
7
|
+
await stages.tui(api, options);
|
|
8
|
+
await modal.tui(api, options);
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
// Preserve the original package entrypoint identity so nested OpenCode configs
|
|
12
|
+
// deduplicate older stages-only loaders before either can register a second slot.
|
|
13
|
+
export default { id: stages.id, tui };
|
|
@@ -0,0 +1,548 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { readWorkContextSnapshot } from "../src/work-context-snapshot.js";
|
|
4
|
+
import { jsx } from "@opentui/solid/jsx-runtime";
|
|
5
|
+
import { createSignal } from "solid-js";
|
|
6
|
+
|
|
7
|
+
const COMMAND_NAME = "work_context.open";
|
|
8
|
+
const SHORTCUT = "ctrl+alt+w";
|
|
9
|
+
const DEBOUNCE_MS = 150;
|
|
10
|
+
const POLL_MS = 1000;
|
|
11
|
+
const MARKERS = { planned: "[ ]", in_progress: "[•]", completed: "[✓]", cancelled: "[!]" };
|
|
12
|
+
const COMMANDS = { list: "list", resume: "resume", handoff: "stage handoff", finish: "stage finish" };
|
|
13
|
+
const activeTuiInstances = new WeakMap();
|
|
14
|
+
|
|
15
|
+
export const WORK_CONTEXT_ACTIONS = [
|
|
16
|
+
{ value: "help", title: "Help", description: "Show work-context command help", category: "General" },
|
|
17
|
+
{ value: "list", title: "Browse workspaces", description: "Search workspaces and their stages", category: "General" },
|
|
18
|
+
{ value: "browse.stages", title: "Browse stages", description: "Search stages across every workspace", category: "General" },
|
|
19
|
+
{ value: "browse.sessions", title: "Browse sessions", description: "Search active and historical work sessions", category: "General" },
|
|
20
|
+
{ value: "create", title: "Create workspace", description: "Create a workspace from a title", category: "Workspace" },
|
|
21
|
+
{ value: "workspace.list", title: "Inspect workspace", description: "List one workspace and its stages", category: "Workspace" },
|
|
22
|
+
{ value: "workspace.rename", title: "Rename workspace", description: "Change a workspace title", category: "Workspace" },
|
|
23
|
+
{ value: "workspace.finish", title: "Finish workspace", description: "Complete a workspace", category: "Workspace" },
|
|
24
|
+
{ value: "stage.add", title: "Add stage", description: "Create a planned stage with an optional prompt", category: "Stage" },
|
|
25
|
+
{ value: "resume", title: "Resume stage", description: "Start or continue work on a stage", category: "Stage" },
|
|
26
|
+
{ value: "stage.rename", title: "Rename stage", description: "Change a stage title", category: "Stage" },
|
|
27
|
+
{ value: "stage.update", title: "Update stage description", description: "Replace a stage description", category: "Stage" },
|
|
28
|
+
{ value: "stage.update-prompt", title: "Update stage prompt", description: "Replace the detailed working prompt", category: "Stage" },
|
|
29
|
+
{ value: "stage.update-result", title: "Update stage result", description: "Replace an existing completion result", category: "Stage" },
|
|
30
|
+
{ value: "stage.archive", title: "Archive stage", description: "Archive a non-active stage", category: "Stage" },
|
|
31
|
+
{ value: "stage.handoff", title: "Hand off stage", description: "Close this session and preserve continuation", category: "Stage" },
|
|
32
|
+
{ value: "stage.abandon", title: "Abandon stage session", description: "Close this session and keep the stage resumable", category: "Stage" },
|
|
33
|
+
{ value: "stage.finish", title: "Finish stage", description: "Complete a stage and review knowledge", category: "Stage" },
|
|
34
|
+
{ value: "session.rename", title: "Rename work session", description: "Change the current work-context session summary", category: "Session" },
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
const disposeRegistration = (registration) => {
|
|
38
|
+
if (typeof registration === "function") registration();
|
|
39
|
+
else registration?.dispose?.();
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const closeDialog = (api) => api?.ui?.dialog?.clear?.();
|
|
43
|
+
const textOf = (value) => String(value || "").toLocaleLowerCase();
|
|
44
|
+
const matches = (value, query) => !query || textOf(value).includes(textOf(query));
|
|
45
|
+
|
|
46
|
+
const validWorkspace = (workspace) => typeof workspace === "string" && /^\d{6}$/.test(workspace);
|
|
47
|
+
const validStage = (stage) => typeof stage === "string" && /^\d{1,2}$/.test(stage) && Number(stage) > 0;
|
|
48
|
+
|
|
49
|
+
/** Prepare a canonical command without parsing or executing it. */
|
|
50
|
+
export const prepareWorkContextCommand = (action, workspace, stage) => {
|
|
51
|
+
if (!validWorkspace(workspace)) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Workspace must be six digits" } };
|
|
52
|
+
if (!Object.hasOwn(COMMANDS, action)) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Unsupported work-context command" } };
|
|
53
|
+
if (action === "list") return { ok: true, command: `/wc workspace list ${workspace}` };
|
|
54
|
+
if (!validStage(stage)) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Stage must be one or two digits" } };
|
|
55
|
+
const normalizedStage = stage.padStart(2, "0");
|
|
56
|
+
return { ok: true, command: `/wc ${COMMANDS[action]} ${workspace} ${normalizedStage}` };
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** Use only a host-provided prompt append bridge; never submit the prompt. */
|
|
60
|
+
export const insertPromptCommand = (api, command) => {
|
|
61
|
+
if (typeof command !== "string" || !command.startsWith("/wc ")) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Invalid prepared command" } };
|
|
62
|
+
const append = api?.ui?.prompt?.append || api?.prompt?.append;
|
|
63
|
+
if (typeof append !== "function") return { ok: false, command, error: { code: "PROMPT_INSERT_UNAVAILABLE", message: "Prompt insertion is unavailable; submit this command manually." } };
|
|
64
|
+
try { append(command); } catch (error) {
|
|
65
|
+
return { ok: false, command, error: { code: error.code || "PROMPT_INSERT_ERROR", message: error.message || "Prompt insertion failed; submit this command manually." } };
|
|
66
|
+
}
|
|
67
|
+
return { ok: true, command, submitted: false };
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/** Append through the public TUI endpoint; keep compatibility bridges as a fallback. */
|
|
71
|
+
export const appendPromptCommand = async (api, command) => {
|
|
72
|
+
if (typeof command !== "string" || !command.startsWith("/wc ")) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Invalid prepared command" } };
|
|
73
|
+
if (typeof api?.client?.tui?.appendPrompt === "function") {
|
|
74
|
+
try {
|
|
75
|
+
await api.client.tui.appendPrompt({ directory: api.state?.path?.directory || api.state?.path?.worktree, text: command }, { throwOnError: true });
|
|
76
|
+
return { ok: true, command, submitted: false };
|
|
77
|
+
} catch (error) {
|
|
78
|
+
return { ok: false, command, error: { code: error.code || "PROMPT_INSERT_ERROR", message: error.message || "Prompt insertion failed" } };
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return insertPromptCommand(api, command);
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
export const quoteWorkContextArgument = (value) => JSON.stringify(String(value));
|
|
85
|
+
|
|
86
|
+
export const filterWorkspaces = (workspaces = [], query = "") => workspaces
|
|
87
|
+
.map((workspace) => ({
|
|
88
|
+
...workspace,
|
|
89
|
+
stages: (workspace.stages || []).filter((stage) => matches(`${stage.id} ${stage.title} ${stage.description}`, query)),
|
|
90
|
+
}))
|
|
91
|
+
.filter((workspace) => matches(`${workspace.id} ${workspace.title} ${workspace.status}`, query) || workspace.stages.length);
|
|
92
|
+
|
|
93
|
+
export const createWorkContextModalController = ({
|
|
94
|
+
projectRoot,
|
|
95
|
+
sessionId,
|
|
96
|
+
read = readWorkContextSnapshot,
|
|
97
|
+
debounceMs = DEBOUNCE_MS,
|
|
98
|
+
pollMs = POLL_MS,
|
|
99
|
+
createSignal: makeSignal = createSignal,
|
|
100
|
+
onClose = () => {},
|
|
101
|
+
onCommand = () => {},
|
|
102
|
+
} = {}) => {
|
|
103
|
+
const [version, setVersion] = makeSignal(0);
|
|
104
|
+
const [query, setQuery] = makeSignal("");
|
|
105
|
+
const [workspaceIndex, setWorkspaceIndex] = makeSignal(0);
|
|
106
|
+
const [stageIndex, setStageIndex] = makeSignal(0);
|
|
107
|
+
const [details, setDetails] = makeSignal(false);
|
|
108
|
+
let result = null;
|
|
109
|
+
let successful = null;
|
|
110
|
+
let timer;
|
|
111
|
+
let poller;
|
|
112
|
+
let disposed = false;
|
|
113
|
+
let onSelectionChange = () => {};
|
|
114
|
+
|
|
115
|
+
const refresh = async () => {
|
|
116
|
+
if (disposed) return;
|
|
117
|
+
try {
|
|
118
|
+
const next = await read({ projectRoot, sessionId });
|
|
119
|
+
if (disposed) return;
|
|
120
|
+
if (next?.ok) { successful = next; result = next; }
|
|
121
|
+
else result = successful ? { ...successful, stale: true, error: next?.error || { code: "STORAGE_ERROR" } } : next;
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (disposed) return;
|
|
124
|
+
result = successful
|
|
125
|
+
? { ...successful, stale: true, error: { code: error.code || "STORAGE_ERROR", message: error.message } }
|
|
126
|
+
: { ok: false, error: { code: error.code || "STORAGE_ERROR", message: error.message } };
|
|
127
|
+
}
|
|
128
|
+
setVersion((value) => value + 1);
|
|
129
|
+
};
|
|
130
|
+
const scheduleRefresh = () => {
|
|
131
|
+
if (disposed) return;
|
|
132
|
+
clearTimeout(timer);
|
|
133
|
+
timer = setTimeout(() => { timer = undefined; void refresh(); }, debounceMs);
|
|
134
|
+
};
|
|
135
|
+
const snapshot = () => { version(); return result; };
|
|
136
|
+
const workspaces = () => filterWorkspaces(snapshot()?.data?.workspaces || [], query());
|
|
137
|
+
const selectedWorkspace = () => workspaces()[Math.min(workspaceIndex(), Math.max(0, workspaces().length - 1))] || null;
|
|
138
|
+
const selectedStage = () => selectedWorkspace()?.stages?.[Math.min(stageIndex(), Math.max(0, (selectedWorkspace()?.stages || []).length - 1))] || null;
|
|
139
|
+
const [preparedCommand, setPreparedCommand] = makeSignal(null);
|
|
140
|
+
const prepareCommand = (action) => {
|
|
141
|
+
const workspace = selectedWorkspace()?.id;
|
|
142
|
+
const stage = selectedStage()?.id;
|
|
143
|
+
const prepared = prepareWorkContextCommand(action, workspace, stage);
|
|
144
|
+
setPreparedCommand(prepared);
|
|
145
|
+
return prepared;
|
|
146
|
+
};
|
|
147
|
+
const insertCommand = (action) => {
|
|
148
|
+
const prepared = prepareCommand(action);
|
|
149
|
+
if (!prepared.ok) return prepared;
|
|
150
|
+
const inserted = onCommand(prepared.command);
|
|
151
|
+
const result = inserted && typeof inserted === "object" ? { ...prepared, ...inserted } : prepared;
|
|
152
|
+
setPreparedCommand(result);
|
|
153
|
+
return result;
|
|
154
|
+
};
|
|
155
|
+
const moveWorkspace = (delta) => {
|
|
156
|
+
const count = workspaces().length;
|
|
157
|
+
if (count) setWorkspaceIndex(Math.max(0, Math.min(count - 1, workspaceIndex() + delta)));
|
|
158
|
+
setStageIndex(0);
|
|
159
|
+
};
|
|
160
|
+
const moveStage = (delta) => {
|
|
161
|
+
const count = selectedWorkspace()?.stages?.length || 0;
|
|
162
|
+
if (count) setStageIndex(Math.max(0, Math.min(count - 1, stageIndex() + delta)));
|
|
163
|
+
};
|
|
164
|
+
const handleKey = (event) => {
|
|
165
|
+
const rawKey = typeof event === "string" ? event : event?.key || event?.name;
|
|
166
|
+
const key = ({ ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right", Escape: "escape" })[rawKey] || rawKey;
|
|
167
|
+
if (key === "up") moveWorkspace(-1);
|
|
168
|
+
else if (key === "down") moveWorkspace(1);
|
|
169
|
+
else if (key === "left") moveStage(-1);
|
|
170
|
+
else if (key === "right") moveStage(1);
|
|
171
|
+
else if (key === "Enter") setDetails((value) => !value);
|
|
172
|
+
else if (key === "d") setDetails((value) => !value);
|
|
173
|
+
else if (key === "l") insertCommand("list");
|
|
174
|
+
else if (key === "r") insertCommand("resume");
|
|
175
|
+
else if (key === "h") insertCommand("handoff");
|
|
176
|
+
else if (key === "f") insertCommand("finish");
|
|
177
|
+
else if (key === "Backspace") setQuery(query().slice(0, -1));
|
|
178
|
+
else if (key === "escape") { if (query()) setQuery(""); else onClose(); }
|
|
179
|
+
else if (key === "/") setQuery("");
|
|
180
|
+
else if (typeof key === "string" && key.length === 1 && !event?.ctrlKey && !event?.metaKey) setQuery(query() + key);
|
|
181
|
+
setVersion((value) => value + 1);
|
|
182
|
+
onSelectionChange();
|
|
183
|
+
};
|
|
184
|
+
void refresh();
|
|
185
|
+
if (pollMs) poller = setInterval(scheduleRefresh, pollMs);
|
|
186
|
+
return {
|
|
187
|
+
snapshot, query, setQuery, workspaces, selectedWorkspace, selectedStage, details, preparedCommand, prepareCommand, insertCommand, handleKey, scheduleRefresh,
|
|
188
|
+
onSelectionChange: (handler) => { onSelectionChange = typeof handler === "function" ? handler : () => {}; },
|
|
189
|
+
dispose: () => { disposed = true; clearTimeout(timer); clearInterval(poller); },
|
|
190
|
+
};
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
const line = (runtime, children, props = {}) => runtime.jsx("text", { ...props, children });
|
|
194
|
+
const marker = (status) => MARKERS[status] || "[?]";
|
|
195
|
+
|
|
196
|
+
export const renderWorkContextModal = (controller, theme, runtime = { jsx }, { maxListHeight = 24 } = {}) => {
|
|
197
|
+
let workspaceScroll;
|
|
198
|
+
let stageScroll;
|
|
199
|
+
controller.onSelectionChange?.(() => queueMicrotask(() => {
|
|
200
|
+
try { workspaceScroll?.scrollChildIntoView?.(`workspace-${controller.selectedWorkspace()?.id}`); } catch {}
|
|
201
|
+
try { stageScroll?.scrollChildIntoView?.(`stage-${controller.selectedStage()?.id}`); } catch {}
|
|
202
|
+
}));
|
|
203
|
+
return runtime.jsx("box", {
|
|
204
|
+
flexDirection: "column", gap: 1, paddingLeft: 1, paddingRight: 1, paddingBottom: 1, flexGrow: 1, focusable: true, onKeyDown: controller.handleKey,
|
|
205
|
+
children: () => {
|
|
206
|
+
const result = controller.snapshot();
|
|
207
|
+
const workspaces = controller.workspaces();
|
|
208
|
+
const selected = controller.selectedWorkspace();
|
|
209
|
+
const stage = controller.selectedStage();
|
|
210
|
+
const data = result?.data;
|
|
211
|
+
const status = result?.stale ? `STALE · ${result.error?.code || "STORAGE_ERROR"}` : result?.ok === false ? `ERROR · ${result.error?.code || "STORAGE_ERROR"}` : "LIVE";
|
|
212
|
+
const muted = theme?.current?.textMuted;
|
|
213
|
+
const selectedWorkspaceIndex = selected ? workspaces.indexOf(selected) : -1;
|
|
214
|
+
const selectedStageIndex = stage && selected ? (selected.stages || []).indexOf(stage) : -1;
|
|
215
|
+
const workspaceItems = workspaces.map((workspace, index) => runtime.jsx("box", {
|
|
216
|
+
id: `workspace-${workspace.id}`, flexDirection: "row", gap: 1, children: [
|
|
217
|
+
line(runtime, index === selectedWorkspaceIndex ? ">" : " ", { flexShrink: 0, marginRight: 1, fg: index === selectedWorkspaceIndex ? theme?.current?.text : muted }),
|
|
218
|
+
line(runtime, `${workspace.id} ${workspace.title}`, { flexGrow: 1, flexShrink: 1, wrapMode: "word", fg: workspace.id === data?.currentWorkspace ? theme?.current?.warning : theme?.current?.text }),
|
|
219
|
+
line(runtime, workspace.status, { flexShrink: 0, fg: muted }),
|
|
220
|
+
],
|
|
221
|
+
}));
|
|
222
|
+
const stageItems = selected ? (selected.stages || []).map((item, index) => runtime.jsx("box", {
|
|
223
|
+
id: `stage-${item.id}`, flexDirection: "row", children: [
|
|
224
|
+
line(runtime, index === selectedStageIndex ? ">" : " ", { flexShrink: 0, marginRight: 1, fg: index === selectedStageIndex ? theme?.current?.text : muted }),
|
|
225
|
+
line(runtime, `${marker(item.status)} ${item.id}. ${item.title}${item.current ? " · current" : ""}`, { flexGrow: 1, flexShrink: 1, wrapMode: "word", fg: item.current ? theme?.current?.warning : theme?.current?.text }),
|
|
226
|
+
],
|
|
227
|
+
})) : [];
|
|
228
|
+
const children = [runtime.jsx("box", {
|
|
229
|
+
flexDirection: "row", justifyContent: "space-between", paddingLeft: 2, paddingRight: 2,
|
|
230
|
+
children: [
|
|
231
|
+
line(runtime, runtime.jsx("b", { children: "Work Context" }), { fg: theme?.current?.text }),
|
|
232
|
+
line(runtime, "esc", { fg: muted }),
|
|
233
|
+
],
|
|
234
|
+
}), runtime.jsx("box", {
|
|
235
|
+
flexDirection: "column", gap: 0, paddingLeft: 2, paddingRight: 2,
|
|
236
|
+
children: [
|
|
237
|
+
line(runtime, `Filter ${controller.query() || "type to filter"}`, { fg: controller.query() ? theme?.current?.text : muted }),
|
|
238
|
+
line(runtime, `Status ${status}`, { fg: result?.stale || result?.ok === false ? theme?.current?.warning : muted }),
|
|
239
|
+
],
|
|
240
|
+
})];
|
|
241
|
+
if (result?.ok === false && !data) children.push(runtime.jsx("box", { paddingLeft: 2, children: line(runtime, result.error?.message || "Cannot read work-context storage", { fg: theme?.current?.error }) }));
|
|
242
|
+
if (!workspaces.length) children.push(line(runtime, controller.query() ? "No matching workspaces or stages." : "No workspaces found.", { paddingLeft: 2, fg: muted }));
|
|
243
|
+
else children.push(runtime.jsx("box", {
|
|
244
|
+
flexDirection: "row", gap: 2, flexGrow: 1, paddingLeft: 2, paddingRight: 2,
|
|
245
|
+
children: [
|
|
246
|
+
runtime.jsx("box", { flexDirection: "column", width: "40%", flexShrink: 0, children: [
|
|
247
|
+
line(runtime, "Workspaces", { fg: muted }),
|
|
248
|
+
runtime.jsx("scrollbox", { ref: (node) => { workspaceScroll = node; }, maxHeight: maxListHeight, scrollY: true, verticalScrollbarOptions: { visible: false }, children: workspaceItems }),
|
|
249
|
+
] }),
|
|
250
|
+
runtime.jsx("box", { flexDirection: "column", flexGrow: 1, flexShrink: 1, children: [
|
|
251
|
+
line(runtime, selected ? `Stages ${selected.title}` : "Stages", { wrapMode: "word", fg: muted }),
|
|
252
|
+
runtime.jsx("scrollbox", { ref: (node) => { stageScroll = node; }, maxHeight: maxListHeight, scrollY: true, verticalScrollbarOptions: { visible: false }, children: stageItems }),
|
|
253
|
+
...(controller.details() && stage ? [
|
|
254
|
+
line(runtime, "Details", { marginTop: 1, fg: muted }),
|
|
255
|
+
line(runtime, stage.description || "No description.", { wrapMode: "word", fg: theme?.current?.text }),
|
|
256
|
+
line(runtime, `Sessions ${(selected.sessions || []).length}`, { fg: muted }),
|
|
257
|
+
...(selected.sessions || []).map((session) => line(runtime, `${session.state || "unknown"} ${session.session_id || "unknown"} stage ${session.stage || "-"}`, { wrapMode: "word", fg: muted })),
|
|
258
|
+
] : []),
|
|
259
|
+
] }),
|
|
260
|
+
],
|
|
261
|
+
}));
|
|
262
|
+
const prepared = controller.preparedCommand();
|
|
263
|
+
if (prepared) children.push(runtime.jsx("box", { paddingLeft: 2, paddingRight: 2, children: line(runtime, prepared.command
|
|
264
|
+
? `Prepared (not submitted): ${prepared.command}${prepared.error ? ` · ${prepared.error.message || prepared.error.code}` : ""}`
|
|
265
|
+
: `Command unavailable: ${prepared.error?.message || prepared.error?.code || "INVALID_ARGUMENT"}`, { fg: prepared.error ? theme?.current?.warning : theme?.current?.text }) }));
|
|
266
|
+
children.push(runtime.jsx("box", { paddingLeft: 2, paddingRight: 2, children: line(runtime, "↑↓ workspace · ←→ stage · d/Enter details · l list · r resume · h handoff · f finish", { fg: muted }) }));
|
|
267
|
+
return children;
|
|
268
|
+
},
|
|
269
|
+
});
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
export const buildWorkContextActionCommand = (action, { workspace, stage, value, prompt } = {}) => {
|
|
273
|
+
if (action === "help" || action === "list") return { ok: true, command: `/wc ${action}` };
|
|
274
|
+
if (action === "create") return value?.trim()
|
|
275
|
+
? { ok: true, command: `/wc create ${quoteWorkContextArgument(value.trim())}` }
|
|
276
|
+
: { ok: false, error: { code: "INVALID_ARGUMENT", message: "Title is required" } };
|
|
277
|
+
if (action === "session.rename") return value?.trim()
|
|
278
|
+
? { ok: true, command: `/wc session rename ${quoteWorkContextArgument(value.trim())}` }
|
|
279
|
+
: { ok: false, error: { code: "INVALID_ARGUMENT", message: "Summary is required" } };
|
|
280
|
+
if (!validWorkspace(workspace)) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Workspace must be six digits" } };
|
|
281
|
+
if (action === "workspace.list") return { ok: true, command: `/wc workspace list ${workspace}` };
|
|
282
|
+
if (action === "workspace.finish") return { ok: true, command: `/wc workspace finish ${workspace}` };
|
|
283
|
+
if (action === "workspace.rename") return value?.trim()
|
|
284
|
+
? { ok: true, command: `/wc workspace rename ${workspace} ${quoteWorkContextArgument(value.trim())}` }
|
|
285
|
+
: { ok: false, error: { code: "INVALID_ARGUMENT", message: "Title is required" } };
|
|
286
|
+
if (action === "stage.add") {
|
|
287
|
+
if (!value?.trim()) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Title is required" } };
|
|
288
|
+
return { ok: true, command: `/wc stage add ${workspace} ${quoteWorkContextArgument(value.trim())}${prompt?.trim() ? ` ${quoteWorkContextArgument(prompt.trim())}` : ""}` };
|
|
289
|
+
}
|
|
290
|
+
if (!validStage(stage)) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Stage must be one or two digits" } };
|
|
291
|
+
const normalizedStage = stage.padStart(2, "0");
|
|
292
|
+
const commandName = action.replace(".", " ");
|
|
293
|
+
if (["resume", "stage.archive", "stage.handoff", "stage.abandon", "stage.finish"].includes(action)) return { ok: true, command: `/wc ${commandName} ${workspace} ${normalizedStage}` };
|
|
294
|
+
const inputCommands = { "stage.rename": "title", "stage.update": "description", "stage.update-prompt": "prompt", "stage.update-result": "result" };
|
|
295
|
+
if (Object.hasOwn(inputCommands, action)) return value?.trim()
|
|
296
|
+
? { ok: true, command: `/wc ${commandName} ${workspace} ${normalizedStage} ${quoteWorkContextArgument(value.trim())}` }
|
|
297
|
+
: { ok: false, error: { code: "INVALID_ARGUMENT", message: `${inputCommands[action][0].toUpperCase()}${inputCommands[action].slice(1)} is required` } };
|
|
298
|
+
return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Unsupported work-context action" } };
|
|
299
|
+
};
|
|
300
|
+
|
|
301
|
+
export const createWorkContextActionFlow = (api, { projectRoot, sessionId, read = readWorkContextSnapshot } = {}) => {
|
|
302
|
+
const stack = api?.ui?.dialog;
|
|
303
|
+
const toast = (message, variant = "warning") => api?.ui?.toast?.({ message, variant });
|
|
304
|
+
const showSelect = (title, options, onSelect) => stack.replace(() => api.ui.DialogSelect({ title, placeholder: "Search", options, onSelect }));
|
|
305
|
+
const showPrompt = (title, placeholder, onConfirm) => stack.replace(() => api.ui.DialogPrompt({ title, placeholder, onConfirm }));
|
|
306
|
+
const insert = async (prepared) => {
|
|
307
|
+
if (!prepared.ok) { toast(prepared.error.message); return; }
|
|
308
|
+
stack.clear();
|
|
309
|
+
const inserted = await appendPromptCommand(api, prepared.command);
|
|
310
|
+
toast(inserted.ok ? "Command added to prompt" : inserted.error?.message || "Prompt insertion failed", inserted.ok ? "success" : "error");
|
|
311
|
+
};
|
|
312
|
+
const requireValue = (title, placeholder, action, context = {}) => showPrompt(title, placeholder, (value) => {
|
|
313
|
+
const prepared = buildWorkContextActionCommand(action, { ...context, value });
|
|
314
|
+
if (!prepared.ok) { toast(prepared.error.message); requireValue(title, placeholder, action, context); return; }
|
|
315
|
+
void insert(prepared);
|
|
316
|
+
});
|
|
317
|
+
const addStage = (workspace) => showPrompt("Add stage", "Stage title", (title) => {
|
|
318
|
+
if (!title?.trim()) { toast("Title is required"); addStage(workspace); return; }
|
|
319
|
+
showPrompt("Add stage prompt", "Optional detailed prompt", (prompt) => void insert(buildWorkContextActionCommand("stage.add", { workspace, value: title, prompt })));
|
|
320
|
+
});
|
|
321
|
+
const runStageAction = (action, workspace, stage) => {
|
|
322
|
+
const context = { workspace, stage };
|
|
323
|
+
if (action === "stage.rename") requireValue("Rename stage", "New title", action, context);
|
|
324
|
+
else if (action === "stage.update") requireValue("Update stage description", "Description", action, context);
|
|
325
|
+
else if (action === "stage.update-prompt") requireValue("Update stage prompt", "Detailed prompt", action, context);
|
|
326
|
+
else if (action === "stage.update-result") requireValue("Update stage result", "Completion result", action, context);
|
|
327
|
+
else void insert(buildWorkContextActionCommand(action, context));
|
|
328
|
+
};
|
|
329
|
+
const selectStage = (action, workspace, stages) => showSelect("Select stage", stages.map((stage) => ({
|
|
330
|
+
title: `${marker(stage.status)} ${stage.id}. ${stage.title}`,
|
|
331
|
+
description: stage.description || stage.status,
|
|
332
|
+
value: stage,
|
|
333
|
+
})), (option) => runStageAction(action, workspace, option.value.id));
|
|
334
|
+
const loadWorkspaces = async () => {
|
|
335
|
+
let result;
|
|
336
|
+
try { result = await read({ projectRoot, sessionId }); }
|
|
337
|
+
catch (error) { toast(error.message || "Cannot read work-context storage", "error"); return null; }
|
|
338
|
+
if (!result?.ok) { toast(result?.error?.message || "Cannot read work-context storage", "error"); return null; }
|
|
339
|
+
const workspaces = result.data?.workspaces || [];
|
|
340
|
+
if (!workspaces.length) { toast("No workspaces found"); return null; }
|
|
341
|
+
return { workspaces, currentWorkspace: result.data?.currentWorkspace };
|
|
342
|
+
};
|
|
343
|
+
const selectWorkspace = async (action) => {
|
|
344
|
+
const loaded = await loadWorkspaces();
|
|
345
|
+
if (!loaded) return;
|
|
346
|
+
const { workspaces } = loaded;
|
|
347
|
+
showSelect("Select workspace", workspaces.map((workspace) => ({
|
|
348
|
+
title: `${workspace.id} ${workspace.title}`,
|
|
349
|
+
description: workspace.status,
|
|
350
|
+
value: workspace,
|
|
351
|
+
})), (option) => {
|
|
352
|
+
const workspace = option.value;
|
|
353
|
+
if (action === "workspace.list" || action === "workspace.finish") void insert(buildWorkContextActionCommand(action, { workspace: workspace.id }));
|
|
354
|
+
else if (action === "workspace.rename") requireValue("Rename workspace", "New title", action, { workspace: workspace.id });
|
|
355
|
+
else if (action === "stage.add") addStage(workspace.id);
|
|
356
|
+
else if (!workspace.stages?.length) toast("No stages found");
|
|
357
|
+
else selectStage(action, workspace.id, workspace.stages);
|
|
358
|
+
});
|
|
359
|
+
};
|
|
360
|
+
const progress = (workspace) => {
|
|
361
|
+
const counts = (workspace.stages || []).reduce((all, stage) => ({ ...all, [stage.status]: (all[stage.status] || 0) + 1 }), {});
|
|
362
|
+
return [["completed", "✓"], ["in_progress", "•"], ["planned", "□"], ["cancelled", "!"]]
|
|
363
|
+
.flatMap(([status, symbol]) => counts[status] ? [`${symbol}${counts[status]}`] : [])
|
|
364
|
+
.join(" ") || "No stages";
|
|
365
|
+
};
|
|
366
|
+
const showWorkspaceActions = (workspace) => showSelect(`${workspace.id} ${workspace.title}`, [
|
|
367
|
+
{ title: "Back to workspaces", value: "back", category: "Navigation" },
|
|
368
|
+
...WORK_CONTEXT_ACTIONS.filter((action) => ["workspace.list", "stage.add", "workspace.rename", "workspace.finish"].includes(action.value)),
|
|
369
|
+
], (option) => {
|
|
370
|
+
if (option.value === "back") { void browseWorkspaces(); return; }
|
|
371
|
+
if (option.value === "workspace.list" || option.value === "workspace.finish") void insert(buildWorkContextActionCommand(option.value, { workspace: workspace.id }));
|
|
372
|
+
else if (option.value === "workspace.rename") requireValue("Rename workspace", "New title", option.value, { workspace: workspace.id });
|
|
373
|
+
else if (option.value === "stage.add") addStage(workspace.id);
|
|
374
|
+
});
|
|
375
|
+
const showStageActions = (workspace, stage, { backTitle = "Back to workspaces", onBack = () => void browseWorkspaces() } = {}) => showSelect(`${workspace.id}/${stage.id} ${stage.title}`, [
|
|
376
|
+
{ title: backTitle, value: "back", category: "Navigation" },
|
|
377
|
+
...WORK_CONTEXT_ACTIONS.filter((action) => ["resume", "stage.rename", "stage.update", "stage.update-prompt", "stage.update-result", "stage.archive", "stage.handoff", "stage.abandon", "stage.finish"].includes(action.value)),
|
|
378
|
+
], (option) => {
|
|
379
|
+
if (option.value === "back") { onBack(); return; }
|
|
380
|
+
runStageAction(option.value, workspace.id, stage.id);
|
|
381
|
+
});
|
|
382
|
+
const browseWorkspaces = async () => {
|
|
383
|
+
const loaded = await loadWorkspaces();
|
|
384
|
+
if (!loaded) return;
|
|
385
|
+
const rank = { in_progress: 0, planned: 1, completed: 2, cancelled: 3 };
|
|
386
|
+
const workspaces = [...loaded.workspaces].sort((left, right) => {
|
|
387
|
+
if (left.id === loaded.currentWorkspace) return -1;
|
|
388
|
+
if (right.id === loaded.currentWorkspace) return 1;
|
|
389
|
+
return (rank[left.status] ?? 9) - (rank[right.status] ?? 9) || left.id.localeCompare(right.id);
|
|
390
|
+
});
|
|
391
|
+
const options = workspaces.flatMap((workspace) => {
|
|
392
|
+
const category = `${workspace.id} · ${workspace.title} · ${workspace.status}`;
|
|
393
|
+
return [
|
|
394
|
+
{ title: "Overview", description: workspace.status, footer: progress(workspace), category, value: { type: "workspace", workspace } },
|
|
395
|
+
...(workspace.stages || []).map((stage) => ({
|
|
396
|
+
title: `${marker(stage.status)} ${stage.id}. ${stage.title}${stage.current ? " · current" : ""}`,
|
|
397
|
+
description: stage.description || stage.status,
|
|
398
|
+
category,
|
|
399
|
+
value: { type: "stage", workspace, stage },
|
|
400
|
+
})),
|
|
401
|
+
];
|
|
402
|
+
});
|
|
403
|
+
showSelect("Workspaces", options, (option) => {
|
|
404
|
+
if (option.value.type === "workspace") showWorkspaceActions(option.value.workspace);
|
|
405
|
+
else showStageActions(option.value.workspace, option.value.stage);
|
|
406
|
+
});
|
|
407
|
+
};
|
|
408
|
+
const browseStages = async () => {
|
|
409
|
+
const loaded = await loadWorkspaces();
|
|
410
|
+
if (!loaded) return;
|
|
411
|
+
const rank = { in_progress: 0, planned: 1, completed: 2, cancelled: 3 };
|
|
412
|
+
const entries = loaded.workspaces.flatMap((workspace) => (workspace.stages || []).map((stage) => ({ workspace, stage })));
|
|
413
|
+
if (!entries.length) { toast("No stages found"); return; }
|
|
414
|
+
entries.sort((left, right) => {
|
|
415
|
+
if (left.stage.current) return -1;
|
|
416
|
+
if (right.stage.current) return 1;
|
|
417
|
+
return (rank[left.stage.status] ?? 9) - (rank[right.stage.status] ?? 9)
|
|
418
|
+
|| left.workspace.id.localeCompare(right.workspace.id)
|
|
419
|
+
|| Number(left.stage.id) - Number(right.stage.id);
|
|
420
|
+
});
|
|
421
|
+
const labels = { in_progress: "In progress", planned: "Planned", completed: "Completed", cancelled: "Cancelled" };
|
|
422
|
+
showSelect("Stages", entries.map(({ workspace, stage }) => ({
|
|
423
|
+
title: `${marker(stage.status)} ${workspace.id}/${stage.id} ${stage.title} · ${workspace.title}`,
|
|
424
|
+
description: stage.description || stage.status,
|
|
425
|
+
category: stage.current ? "Current" : labels[stage.status] || stage.status,
|
|
426
|
+
value: { workspace, stage },
|
|
427
|
+
})), (option) => showStageActions(option.value.workspace, option.value.stage, { backTitle: "Back to stages", onBack: () => void browseStages() }));
|
|
428
|
+
};
|
|
429
|
+
const sessionOrdinal = (session) => String(session.ordinal).includes("/")
|
|
430
|
+
? String(session.ordinal)
|
|
431
|
+
: `${session.stage}/${String(session.ordinal).padStart(2, "0")}`;
|
|
432
|
+
const showSessionDetails = (workspace, session) => {
|
|
433
|
+
const stage = (workspace.stages || []).find((item) => item.id === session.stage);
|
|
434
|
+
const options = [
|
|
435
|
+
{ title: "Back to sessions", value: "back", category: "Navigation" },
|
|
436
|
+
...(stage ? [{ title: "Open stage actions", value: "stage", category: "Navigation" }] : []),
|
|
437
|
+
{ title: `Workspace ${workspace.id} ${workspace.title}`, value: "workspace", category: "Details", disabled: true },
|
|
438
|
+
{ title: `Stage ${session.stage}${stage ? ` ${stage.title}` : ""}`, value: "stage-detail", category: "Details", disabled: true },
|
|
439
|
+
{ title: `State ${session.state || "unknown"}`, value: "state", category: "Details", disabled: true },
|
|
440
|
+
{ title: `Summary ${session.summary || "No summary"}`, value: "summary", category: "Details", disabled: true },
|
|
441
|
+
{ title: `Session ${session.session_id}`, value: "session", category: "Details", disabled: true },
|
|
442
|
+
...(session.opencode_session_id ? [{ title: `OpenCode ${session.opencode_session_id}`, value: "opencode", category: "Details", disabled: true }] : []),
|
|
443
|
+
...(session.branch ? [{ title: `Branch ${session.branch}`, value: "branch", category: "Details", disabled: true }] : []),
|
|
444
|
+
...(session.updated_at ? [{ title: `Updated ${session.updated_at}`, value: "updated", category: "Details", disabled: true }] : []),
|
|
445
|
+
];
|
|
446
|
+
showSelect(`${workspace.id} ${sessionOrdinal(session)}`, options, (option) => {
|
|
447
|
+
if (option.value === "back") { void browseSessions(); return; }
|
|
448
|
+
if (option.value === "stage" && stage) showStageActions(workspace, stage, { backTitle: "Back to session", onBack: () => showSessionDetails(workspace, session) });
|
|
449
|
+
});
|
|
450
|
+
};
|
|
451
|
+
const browseSessions = async () => {
|
|
452
|
+
const loaded = await loadWorkspaces();
|
|
453
|
+
if (!loaded) return;
|
|
454
|
+
const rank = { active: 0, handed_off: 1, abandoned: 2, closed: 3 };
|
|
455
|
+
const entries = loaded.workspaces.flatMap((workspace) => (workspace.sessions || []).map((session) => ({ workspace, session })));
|
|
456
|
+
if (!entries.length) { toast("No sessions found"); return; }
|
|
457
|
+
entries.sort((left, right) => {
|
|
458
|
+
const leftCurrent = left.session.opencode_session_id === sessionId || left.session.session_id === sessionId;
|
|
459
|
+
const rightCurrent = right.session.opencode_session_id === sessionId || right.session.session_id === sessionId;
|
|
460
|
+
if (leftCurrent) return -1;
|
|
461
|
+
if (rightCurrent) return 1;
|
|
462
|
+
return (rank[left.session.state] ?? 9) - (rank[right.session.state] ?? 9)
|
|
463
|
+
|| String(right.session.updated_at || "").localeCompare(String(left.session.updated_at || ""));
|
|
464
|
+
});
|
|
465
|
+
const labels = { active: "Active", handed_off: "Handed off", abandoned: "Abandoned", closed: "Closed" };
|
|
466
|
+
showSelect("Sessions", entries.map(({ workspace, session }) => {
|
|
467
|
+
const current = session.opencode_session_id === sessionId || session.session_id === sessionId;
|
|
468
|
+
return {
|
|
469
|
+
title: `${workspace.id} ${sessionOrdinal(session)} ${session.summary || "Work session"} · ${workspace.title}`,
|
|
470
|
+
description: `${session.state || "unknown"} · ${session.session_id}`,
|
|
471
|
+
footer: session.updated_at || session.started_at,
|
|
472
|
+
category: current ? "Current" : labels[session.state] || session.state || "Unknown",
|
|
473
|
+
value: { workspace, session },
|
|
474
|
+
};
|
|
475
|
+
}), (option) => showSessionDetails(option.value.workspace, option.value.session));
|
|
476
|
+
};
|
|
477
|
+
const selectAction = (action) => {
|
|
478
|
+
if (action === "help") void insert(buildWorkContextActionCommand(action));
|
|
479
|
+
else if (action === "list") void browseWorkspaces();
|
|
480
|
+
else if (action === "browse.stages") void browseStages();
|
|
481
|
+
else if (action === "browse.sessions") void browseSessions();
|
|
482
|
+
else if (action === "create") requireValue("Create workspace", "Workspace title", action);
|
|
483
|
+
else if (action === "session.rename") requireValue("Rename work session", "Session summary", action);
|
|
484
|
+
else void selectWorkspace(action);
|
|
485
|
+
};
|
|
486
|
+
const open = () => {
|
|
487
|
+
stack.setSize?.("medium");
|
|
488
|
+
showSelect("Work Context", WORK_CONTEXT_ACTIONS, (option) => selectAction(option.value));
|
|
489
|
+
};
|
|
490
|
+
return { open, selectAction };
|
|
491
|
+
};
|
|
492
|
+
|
|
493
|
+
export const openWorkContextActionDialog = (api, runtime = {}, options = {}) => {
|
|
494
|
+
if (typeof api?.ui?.DialogSelect !== "function" || typeof api?.ui?.DialogPrompt !== "function" || typeof api?.ui?.dialog?.replace !== "function") return openCompatibilityDialog(api, runtime, options);
|
|
495
|
+
const flow = createWorkContextActionFlow(api, {
|
|
496
|
+
projectRoot: options.projectRoot || api.state?.path?.worktree,
|
|
497
|
+
sessionId: api.route?.current?.params?.sessionID || api.route?.current?.params?.sessionId,
|
|
498
|
+
read: options.read || readWorkContextSnapshot,
|
|
499
|
+
});
|
|
500
|
+
flow.open();
|
|
501
|
+
return true;
|
|
502
|
+
};
|
|
503
|
+
|
|
504
|
+
export const openCompatibilityDialog = (api, runtime = {}, options = {}) => {
|
|
505
|
+
const stack = api?.ui?.dialog;
|
|
506
|
+
if (!stack || typeof runtime.jsx !== "function" || typeof stack.replace !== "function") return false;
|
|
507
|
+
const projectRoot = options.projectRoot || api.state?.path?.worktree;
|
|
508
|
+
const sessionId = api.route?.current?.params?.sessionID || api.route?.current?.params?.sessionId;
|
|
509
|
+
let watcher;
|
|
510
|
+
let closed = false;
|
|
511
|
+
const close = () => {
|
|
512
|
+
if (closed) return;
|
|
513
|
+
closed = true;
|
|
514
|
+
controller.dispose();
|
|
515
|
+
watcher?.close();
|
|
516
|
+
closeDialog(api);
|
|
517
|
+
};
|
|
518
|
+
const controller = createWorkContextModalController({ projectRoot, sessionId, read: options.read || readWorkContextSnapshot, createSignal: runtime.createSignal, onClose: close, onCommand: (command) => insertPromptCommand(api, command) });
|
|
519
|
+
try { watcher = projectRoot && fs.watch(path.join(projectRoot, ".work-context"), { recursive: true }, () => controller.scheduleRefresh?.()); } catch {}
|
|
520
|
+
const maxListHeight = Math.max(8, Math.floor((api.renderer?.height || 60) / 2) - 6);
|
|
521
|
+
const render = () => renderWorkContextModal(controller, api.theme, runtime, { maxListHeight });
|
|
522
|
+
stack.replace(render, close);
|
|
523
|
+
return true;
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
export const registerWorkContextModal = (api, runtime = {}) => {
|
|
527
|
+
if (typeof api?.keymap?.registerLayer !== "function") return { supported: false, dispose: () => {} };
|
|
528
|
+
const command = { name: COMMAND_NAME, title: "Open Work Context", desc: "Prepare a work-context command", category: "Work Context", namespace: "palette", run: () => openWorkContextActionDialog(api, runtime) };
|
|
529
|
+
const registration = api.keymap.registerLayer({ commands: [command], bindings: [{ key: SHORTCUT, cmd: COMMAND_NAME, desc: command.title }] });
|
|
530
|
+
return { supported: true, dispose: () => disposeRegistration(registration) };
|
|
531
|
+
};
|
|
532
|
+
|
|
533
|
+
export const tui = async (api, options = {}) => {
|
|
534
|
+
activeTuiInstances.get(api)?.();
|
|
535
|
+
const registration = registerWorkContextModal(api, options.runtime || options);
|
|
536
|
+
if (!registration.supported) return;
|
|
537
|
+
let disposed = false;
|
|
538
|
+
const cleanup = () => {
|
|
539
|
+
if (disposed) return;
|
|
540
|
+
disposed = true;
|
|
541
|
+
registration.dispose();
|
|
542
|
+
};
|
|
543
|
+
activeTuiInstances.set(api, cleanup);
|
|
544
|
+
api.lifecycle?.onDispose?.(cleanup);
|
|
545
|
+
return cleanup;
|
|
546
|
+
};
|
|
547
|
+
|
|
548
|
+
export default { id: "work-context-modal", tui };
|
package/src/core.js
CHANGED
|
@@ -14,11 +14,15 @@ const id = (value, digits) => {
|
|
|
14
14
|
};
|
|
15
15
|
const stageId = (value) => id(String(value).padStart(2, "0"), 2);
|
|
16
16
|
const actor = (options) => options.actor || "OpenCode";
|
|
17
|
+
const activeKnowledge = (records) => records
|
|
18
|
+
.filter((record) => record.status === "active")
|
|
19
|
+
.map(({ id: knowledgeId, title, kind, text, sources }) => ({ id: knowledgeId, title, kind, text, sources }));
|
|
17
20
|
const body = (title, goal = "", prompt = "") => `# ${title}\n\n${goal ? `## Goal\n\n${goal}\n` : ""}${prompt ? `\n## Prompt\n\n${prompt}\n` : ""}`;
|
|
18
21
|
const stageBody = (record, title, goal, prompt = record.data.prompt || "") => {
|
|
19
22
|
const result = record.body.match(/\n## Result[\s\S]*$/)?.[0] || "";
|
|
20
23
|
return `${body(title, goal, prompt).trimEnd()}${result}`;
|
|
21
24
|
};
|
|
25
|
+
const stageResult = (record) => record.body.match(/\n## Result\s*\n([\s\S]*)$/)?.[1]?.trim() ?? null;
|
|
22
26
|
const assertNoSymlinkPath = (file) => { let current = path.parse(file).root; for (const part of file.slice(current.length).split(path.sep).filter(Boolean)) { current = path.join(current, part); try { if (fs.lstatSync(current).isSymbolicLink()) fail(ERROR_CODES.STORAGE_ERROR, `Symlink path component is not supported: ${current}`); } catch (error) { if (error.code !== "ENOENT") throw error; break; } } };
|
|
23
27
|
|
|
24
28
|
function parseIssue(url) {
|
|
@@ -166,13 +170,34 @@ export class WorkContext {
|
|
|
166
170
|
fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
|
|
167
171
|
this.storage.writeMarkdown(this.storage.workspaceFile(workspace), { schema: 1, workspace, title: title.trim(), status: "in_progress", created_at: now, updated_at: now, tracker_links: [] }, body(title));
|
|
168
172
|
const planningGoal = "Clarify the work goal and constraints";
|
|
169
|
-
const planningPrompt = "Diagnose and plan the task without functional changes. Discuss possible solutions, record constraints, and decompose the work into the following stages. For each new implementation stage, write a separate detailed prompt with context, concrete actions, constraints, completion criteria, and the expected result. Ask clarifying questions only when genuinely blocked.";
|
|
173
|
+
const planningPrompt = "Diagnose and plan the task without functional changes. Discuss possible solutions, record durable workspace-wide facts, decisions, constraints, important files, and risks through explicit knowledge operations, and decompose the work into the following stages. For each new implementation stage, write a separate detailed prompt with local context, concrete actions, constraints, completion criteria, and the expected result; do not duplicate shared knowledge that every stage receives in resume.context.workspace_knowledge. Ask clarifying questions only when genuinely blocked.";
|
|
170
174
|
this.storage.writeMarkdown(this.storage.stageFile(workspace, "01"), { schema: 1, workspace, stage: "01", title: "Planning", status: "in_progress", goal: planningGoal, prompt: planningPrompt, depends_on: [], owner: actor(this.options), created_at: now, updated_at: now, tracker_links: [] }, body("Planning", planningGoal, planningPrompt));
|
|
171
175
|
const sessionId = options.sessionId || randomUUID();
|
|
172
176
|
if (this.storage.readEvents().some((item) => item.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
|
|
173
177
|
this.writeEvents([event("session.started", workspace, "01", 1, sessionId, actor(this.options), { summary: `planning ${title.trim()}`, opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
|
|
174
178
|
generateProjections(this.storage);
|
|
175
|
-
return this.result({
|
|
179
|
+
return this.result({
|
|
180
|
+
workspace,
|
|
181
|
+
stage: "01",
|
|
182
|
+
session_id: sessionId,
|
|
183
|
+
ordinal: "01/01",
|
|
184
|
+
title: "Planning",
|
|
185
|
+
description: planningGoal,
|
|
186
|
+
prompt: planningPrompt,
|
|
187
|
+
resume: {
|
|
188
|
+
first: true,
|
|
189
|
+
summary: "Starting work on stage 01: Planning.",
|
|
190
|
+
last_session_summary: null,
|
|
191
|
+
context: {
|
|
192
|
+
essence: planningGoal,
|
|
193
|
+
previous: "The previous session did not save a result; the stopping point needs to be clarified.",
|
|
194
|
+
now: planningPrompt,
|
|
195
|
+
workspace_knowledge: [],
|
|
196
|
+
},
|
|
197
|
+
next_action: "start_work",
|
|
198
|
+
instruction: planningPrompt,
|
|
199
|
+
},
|
|
200
|
+
}, [workspace, "01"]);
|
|
176
201
|
});
|
|
177
202
|
}
|
|
178
203
|
|
|
@@ -225,6 +250,8 @@ export class WorkContext {
|
|
|
225
250
|
generateProjections(this.storage);
|
|
226
251
|
const previousSession = previous.at(-1) || null;
|
|
227
252
|
const firstResume = previous.length === 0;
|
|
253
|
+
const hasPrompt = Boolean(stageRecord.data.prompt?.trim());
|
|
254
|
+
const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
|
|
228
255
|
return this.result({
|
|
229
256
|
workspace,
|
|
230
257
|
stage,
|
|
@@ -239,10 +266,19 @@ export class WorkContext {
|
|
|
239
266
|
? `Starting work on stage ${stage}: ${stageRecord.data.title}.`
|
|
240
267
|
: `Continuing work on stage ${stage}: ${stageRecord.data.title}. Last recorded summary: ${previousSession?.summary || "no saved report"}.`,
|
|
241
268
|
last_session_summary: previousSession?.summary || null,
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
269
|
+
context: {
|
|
270
|
+
essence: stageRecord.data.goal || stageRecord.data.title,
|
|
271
|
+
previous: previousSession?.summary || "The previous session did not save a result; the stopping point needs to be clarified.",
|
|
272
|
+
now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
|
|
273
|
+
workspace_knowledge: workspaceKnowledge,
|
|
274
|
+
},
|
|
275
|
+
next_action: hasPrompt ? (firstResume ? "start_work" : "await_confirmation") : "ask_questions",
|
|
276
|
+
instruction: hasPrompt
|
|
277
|
+
? firstResume
|
|
278
|
+
? stageRecord.data.prompt
|
|
279
|
+
|| `Review stage ${stage}: ${stageRecord.data.title} and begin work only after confirming there are no unanswered questions.`
|
|
280
|
+
: `Stage ${stage}: ${stageRecord.data.title} was resumed before. Report the context and wait for the user's confirmation before continuing work.`
|
|
281
|
+
: `Stage ${stage}: ${stageRecord.data.title} has no non-empty prompt. Do not start implementation; ask the user the questions needed to define the work.`,
|
|
246
282
|
},
|
|
247
283
|
}, [workspace, stage]);
|
|
248
284
|
});
|
|
@@ -316,6 +352,24 @@ export class WorkContext {
|
|
|
316
352
|
});
|
|
317
353
|
}
|
|
318
354
|
|
|
355
|
+
updateStageResult(workspace, stage, result) {
|
|
356
|
+
id(workspace, 6);
|
|
357
|
+
stage = stageId(stage);
|
|
358
|
+
if (!result?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Result is required");
|
|
359
|
+
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
360
|
+
const record = this.storage.readStage(workspace, stage);
|
|
361
|
+
const currentResult = stageResult(record);
|
|
362
|
+
if (currentResult === null) fail(ERROR_CODES.INVALID_STATE, "Stage has no result to update");
|
|
363
|
+
const nextResult = result.trim();
|
|
364
|
+
if (currentResult === nextResult) return this.result({ workspace, stage, result: nextResult }, []);
|
|
365
|
+
record.data.updated_at = new Date().toISOString();
|
|
366
|
+
const nextBody = `${body(record.data.title, record.data.goal, record.data.prompt).trimEnd()}\n\n## Result\n\n${nextResult}`;
|
|
367
|
+
this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, nextBody);
|
|
368
|
+
generateProjections(this.storage);
|
|
369
|
+
return this.result({ workspace, stage, result: nextResult }, [workspace, stage]);
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
|
|
319
373
|
archiveStage(workspace, stage) {
|
|
320
374
|
id(workspace, 6);
|
|
321
375
|
stage = stageId(stage);
|
|
@@ -456,7 +510,7 @@ export class WorkContext {
|
|
|
456
510
|
}
|
|
457
511
|
const knowledgeReview = options.knowledgeReview || "auto";
|
|
458
512
|
if (!['auto', 'added', 'none'].includes(knowledgeReview)) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge review must be 'auto', 'added' or 'none'");
|
|
459
|
-
const knowledgeEntries =
|
|
513
|
+
const knowledgeEntries = this.listKnowledge(workspace).data;
|
|
460
514
|
const active = activeSession(events, workspace, stage);
|
|
461
515
|
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");
|
|
462
516
|
this.writeEvents([event("session.closed", workspace, stage, active.ordinal, sessionId, actor(this.options), { reason: "stage_completed" })]);
|
|
@@ -467,7 +521,7 @@ export class WorkContext {
|
|
|
467
521
|
const promptReview = this.listStages(workspace).data.stages
|
|
468
522
|
.filter((item) => Number(item.stage) > Number(stage) && !["completed", "archived"].includes(item.status))
|
|
469
523
|
.map(({ stage: id, title, description, prompt, status }) => ({ stage: id, title, description, prompt: prompt || null, status }));
|
|
470
|
-
const data = { session_id: sessionId, workspace, stage, state: "closed", status: "completed", knowledge_review: knowledgeReview,
|
|
524
|
+
const data = { session_id: sessionId, workspace, stage, state: "closed", status: "completed", knowledge_review: knowledgeReview, knowledge_entries: knowledgeEntries.length, active_knowledge_entries: activeKnowledge(knowledgeEntries).length, prompt_review: promptReview };
|
|
471
525
|
const incompleteStages = this.listStages(workspace).data.stages.filter((item) => !["completed", "archived"].includes(item.status));
|
|
472
526
|
const next = incompleteStages.length ? null : {
|
|
473
527
|
action: "workspace_finish",
|
|
@@ -480,7 +534,7 @@ export class WorkContext {
|
|
|
480
534
|
}
|
|
481
535
|
|
|
482
536
|
help(command = "") {
|
|
483
|
-
return this.result({ command, syntax: "/wc [create|list|workspace list|workspace rename|workspace finish|resume|stage add|stage rename|stage update|stage update-prompt|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]", note: "workspace
|
|
537
|
+
return this.result({ command, syntax: "/wc [create|list|workspace list|workspace rename|workspace finish|resume|stage add|stage rename|stage update|stage update-prompt|stage update-result|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]", note: "workspace and stage are optional for stage rename/update/update-prompt/update-result/archive/handoff/abandon/finish and session rename/close when the current session identifies them; stage update-result requires an existing stage result; finish <stage> is a shortcut for stage finish <stage>; when only one numeric identifier is supplied, six digits mean workspace and one or two digits mean stage; stage add accepts an optional prompt, which should contain local implementation context when the stage is created from stage 01 planning; resume returns resume.next_action, resume.instruction, and active shared entries in resume.context.workspace_knowledge; implementation may begin only with a non-empty prompt and no unanswered questions; ask focused questions and do not modify application code when next_action is ask_questions; force-close requires a session ID, reason, and exact confirmation FORCE_CLOSE; before stage finish, add, update, or supersede durable findings, or explicitly declare none; stage finish always validates Knowledge Base and returns downstream stages for prompt review; workspace finish requires all non-archived stages to be completed; archived stages retain their IDs and history and are hidden from the TUI by default; mutating commands call structured tools; only explicit lifecycle operations change storage." }, []);
|
|
484
538
|
}
|
|
485
539
|
|
|
486
540
|
result(data, changed, next = null) {
|
package/src/errors.js
CHANGED
|
@@ -3,6 +3,7 @@ export const ERROR_CODES = Object.freeze({
|
|
|
3
3
|
ACTIVE_SESSION_EXISTS: "ACTIVE_SESSION_EXISTS", SESSION_NOT_ACTIVE: "SESSION_NOT_ACTIVE",
|
|
4
4
|
LOCKED: "LOCKED", STALE_LOCK: "STALE_LOCK", CONFLICT: "CONFLICT", INVALID_ISSUE_URL: "INVALID_ISSUE_URL",
|
|
5
5
|
ADAPTER_UNAVAILABLE: "ADAPTER_UNAVAILABLE", STORAGE_ERROR: "STORAGE_ERROR", CONFIRMATION_REQUIRED: "CONFIRMATION_REQUIRED",
|
|
6
|
+
STAGE_CONTEXT_REQUIRED: "STAGE_CONTEXT_REQUIRED",
|
|
6
7
|
});
|
|
7
8
|
|
|
8
9
|
export class WorkContextError extends Error {
|
package/src/index.js
CHANGED
package/src/stages-snapshot.js
CHANGED
|
@@ -19,7 +19,7 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
|
|
|
19
19
|
if (!session && sessionId) {
|
|
20
20
|
for (const workspace of context.listWorkspaces().data) {
|
|
21
21
|
const candidate = context.listStages(workspace.workspace).data.sessions
|
|
22
|
-
.
|
|
22
|
+
.filter((item) => item.opencode_session_id === sessionId).at(-1);
|
|
23
23
|
if (candidate) { session = candidate; break; }
|
|
24
24
|
}
|
|
25
25
|
}
|
package/src/tool-definitions.js
CHANGED
|
@@ -13,38 +13,68 @@ const run = (fn) => async (args, context) => {
|
|
|
13
13
|
}
|
|
14
14
|
};
|
|
15
15
|
const common = { workspace: tool.schema.string().regex(/^\d{6}$/), stage: tool.schema.string().regex(/^\d{1,2}$/) };
|
|
16
|
+
const contextualStage = { workspace: tool.schema.string().regex(/^\d{6}$/).optional(), stage: tool.schema.string().regex(/^\d{1,2}$/).optional() };
|
|
17
|
+
const sessionFromContext = (ctx, workspace) => ctx.sessionByOpenCodeId(ctx.options.sessionId, workspace || null, null, null)
|
|
18
|
+
|| (!workspace ? ctx.sessionById(ctx.options.sessionId) : null);
|
|
16
19
|
const workspaceFromSession = (ctx, workspace) => {
|
|
17
20
|
if (workspace) return workspace;
|
|
18
|
-
const session =
|
|
21
|
+
const session = sessionFromContext(ctx);
|
|
19
22
|
if (!session) fail(ERROR_CODES.INVALID_ARGUMENT, "Workspace is required when the current session is not associated with a workspace");
|
|
20
23
|
return session.workspace;
|
|
21
24
|
};
|
|
25
|
+
const stageFromSession = (ctx, workspace, stage) => {
|
|
26
|
+
if (stage) return stage;
|
|
27
|
+
const session = sessionFromContext(ctx, workspace);
|
|
28
|
+
if (!session) fail(ERROR_CODES.STAGE_CONTEXT_REQUIRED, "Stage is required when the current session is not associated with a stage");
|
|
29
|
+
return session.stage;
|
|
30
|
+
};
|
|
22
31
|
const sessionFor = (ctx, oc, workspace, stage) => ctx.sessionById(oc.sessionID)?.workspace === workspace
|
|
23
32
|
&& ctx.sessionById(oc.sessionID)?.stage === stage
|
|
24
33
|
? oc.sessionID
|
|
25
34
|
: ctx.sessionByOpenCodeId(oc.sessionID, workspace, stage)?.session_id || oc.sessionID;
|
|
35
|
+
const addStageFromTool = (ctx, args, oc) => {
|
|
36
|
+
const workspace = workspaceFromSession(ctx, args.workspace);
|
|
37
|
+
const created = ctx.addStage(workspace, args.title, { goal: args.goal, prompt: args.prompt, dependsOn: args.dependsOn });
|
|
38
|
+
const currentSession = ctx.sessionByOpenCodeId(oc.sessionID) || ctx.sessionById(oc.sessionID);
|
|
39
|
+
if (currentSession) return created;
|
|
40
|
+
const session = ctx.startSession(workspace, created.data.stage, {
|
|
41
|
+
sessionId: randomUUID(),
|
|
42
|
+
opencodeSessionId: oc.sessionID,
|
|
43
|
+
summary: `started ${created.data.title}`,
|
|
44
|
+
takeover: true,
|
|
45
|
+
});
|
|
46
|
+
return {
|
|
47
|
+
...session,
|
|
48
|
+
data: { ...session.data, created: created.data },
|
|
49
|
+
changed: [...new Set([...created.changed, ...session.changed])],
|
|
50
|
+
};
|
|
51
|
+
};
|
|
26
52
|
export const work_context_list_workspaces = tool({ description: "List work-context workspaces.", args: {}, execute: run((ctx) => ctx.listWorkspaces()) });
|
|
27
53
|
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
54
|
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)) });
|
|
29
55
|
export const work_context_workspace_finish = tool({ description: "Finish a workspace after all stages are completed.", args: { workspace: tool.schema.string().regex(/^\d{6}$/) }, execute: run((ctx, a) => ctx.finishWorkspace(a.workspace)) });
|
|
30
|
-
export const work_context_create_workspace = tool({ description: "Create workspace
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
export const
|
|
35
|
-
export const
|
|
36
|
-
export const
|
|
56
|
+
export const work_context_create_workspace = tool({ description: "Create a workspace; enter its planning stage only when the current OpenCode session is not associated with a workspace.", args: { title: tool.schema.string() }, execute: run((ctx, a, oc) => {
|
|
57
|
+
const currentSession = ctx.sessionByOpenCodeId(oc.sessionID);
|
|
58
|
+
return ctx.createWorkspace(a.title, { sessionId: randomUUID(), ...(currentSession ? {} : { opencodeSessionId: oc.sessionID }) });
|
|
59
|
+
}) });
|
|
60
|
+
export const work_context_start_session = tool({ description: "Start a new active session for a stage and return its prompt plus active workspace knowledge.", args: { ...common, summary: tool.schema.string().optional() }, execute: run((ctx, a, oc) => ctx.startSession(a.workspace, a.stage, { sessionId: randomUUID(), opencodeSessionId: oc.sessionID, summary: a.summary, takeover: true })) });
|
|
61
|
+
export const work_context_add_stage = tool({ description: "Add a stage; when workspace is omitted, enter the new stage in the current OpenCode session and return resume context.", args: { workspace: tool.schema.string().regex(/^\d{6}$/).optional(), title: tool.schema.string(), goal: tool.schema.string().optional(), prompt: tool.schema.string().optional(), dependsOn: tool.schema.array(tool.schema.string()).optional() }, execute: run(addStageFromTool) });
|
|
62
|
+
export const work_context_rename_stage = tool({ description: "Rename a stage while preserving its ID and history; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, title: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.renameStage(workspace, stageFromSession(ctx, workspace, a.stage), a.title); }) });
|
|
63
|
+
export const work_context_update_stage = tool({ description: "Update an existing stage description; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, description: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.updateStage(workspace, stageFromSession(ctx, workspace, a.stage), a.description); }) });
|
|
64
|
+
export const work_context_update_stage_prompt = tool({ description: "Update the optional working prompt of an existing stage; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, prompt: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.updateStagePrompt(workspace, stageFromSession(ctx, workspace, a.stage), a.prompt); }) });
|
|
65
|
+
export const work_context_update_stage_result = tool({ description: "Update an existing stage result; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, result: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.updateStageResult(workspace, stageFromSession(ctx, workspace, a.stage), a.result); }) });
|
|
66
|
+
export const work_context_archive_stage = tool({ description: "Archive a stage while preserving its ID and history; workspace and stage can be omitted in the current OpenCode session.", args: contextualStage, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.archiveStage(workspace, stageFromSession(ctx, workspace, a.stage)); }) });
|
|
37
67
|
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)) });
|
|
38
|
-
export const work_context_rename_session = tool({ description: "Rename the current active session summary.", args: { ...
|
|
39
|
-
export const work_context_close_session = tool({ description: "Close the current session without finishing its stage.", args: { ...
|
|
68
|
+
export const work_context_rename_session = tool({ description: "Rename the current active session summary; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, summary: tool.schema.string() }, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.renameSession(workspace, stage, sessionFor(ctx, oc, workspace, stage), a.summary); }) });
|
|
69
|
+
export const work_context_close_session = tool({ description: "Close the current session without finishing its stage; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage }, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.closeSession(workspace, stage, sessionFor(ctx, oc, workspace, stage)); }) });
|
|
40
70
|
export const work_context_force_close_session = tool({ description: "Force close a stale active session with an explicit reason and confirmation.", args: { workspace: tool.schema.string().regex(/^\d{6}$/), stage: tool.schema.string().regex(/^\d{1,2}$/), sessionId: tool.schema.string(), reason: tool.schema.string(), confirmation: tool.schema.string() }, execute: run((ctx, a) => ctx.forceCloseSession(a.workspace, a.stage, a.sessionId, a.reason, a.confirmation)) });
|
|
41
|
-
export const work_context_handoff_stage = tool({ description: "Hand off the current stage by closing the current session.", args:
|
|
42
|
-
export const work_context_abandon_stage = tool({ description: "Abandon the current stage session without completing the stage.", args:
|
|
43
|
-
export const work_context_finish_stage = tool({ description: "Finish a stage
|
|
71
|
+
export const work_context_handoff_stage = tool({ description: "Hand off the current stage by closing the current session; workspace and stage can be omitted in the current OpenCode session.", args: contextualStage, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.handoff(workspace, stage, sessionFor(ctx, oc, workspace, stage)); }) });
|
|
72
|
+
export const work_context_abandon_stage = tool({ description: "Abandon the current stage session without completing the stage; workspace and stage can be omitted in the current OpenCode session.", args: contextualStage, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.abandon(workspace, stage, sessionFor(ctx, oc, workspace, stage)); }) });
|
|
73
|
+
export const work_context_finish_stage = tool({ description: "Finish a stage after reviewing durable workspace knowledge; use knowledgeReview=added after changes or none when no durable findings exist. The ledger is always validated.", args: { ...contextualStage, result: tool.schema.string().optional(), knowledgeReview: tool.schema.string().optional() }, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.finish(workspace, stage, sessionFor(ctx, oc, workspace, stage), { result: a.result, knowledgeReview: a.knowledgeReview }); }) });
|
|
44
74
|
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)) });
|
|
45
75
|
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)) });
|
|
46
76
|
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)) });
|
|
47
77
|
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)) });
|
|
48
78
|
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) ) });
|
|
49
79
|
|
|
50
|
-
export default { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_workspace_finish, work_context_create_workspace, work_context_start_session, work_context_add_stage, work_context_rename_stage, work_context_update_stage, work_context_update_stage_prompt, work_context_archive_stage, work_context_link_issue, work_context_rename_session, work_context_close_session, work_context_force_close_session, work_context_handoff_stage, work_context_abandon_stage, work_context_finish_stage, work_context_help, work_context_list_knowledge, work_context_add_knowledge, work_context_update_knowledge, work_context_supersede_knowledge };
|
|
80
|
+
export default { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_workspace_finish, work_context_create_workspace, work_context_start_session, work_context_add_stage, work_context_rename_stage, work_context_update_stage, work_context_update_stage_prompt, work_context_update_stage_result, work_context_archive_stage, work_context_link_issue, work_context_rename_session, work_context_close_session, work_context_force_close_session, work_context_handoff_stage, work_context_abandon_stage, work_context_finish_stage, work_context_help, work_context_list_knowledge, work_context_add_knowledge, work_context_update_knowledge, work_context_supersede_knowledge };
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { WorkContext } from "./core.js";
|
|
2
|
+
|
|
3
|
+
const emptySnapshot = () => ({
|
|
4
|
+
schema: 1,
|
|
5
|
+
workspaces: [],
|
|
6
|
+
currentWorkspace: null,
|
|
7
|
+
currentStage: null,
|
|
8
|
+
generatedAt: new Date().toISOString(),
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
const errorResult = (error) => ({
|
|
12
|
+
ok: false,
|
|
13
|
+
error: {
|
|
14
|
+
code: error?.code || "STORAGE_ERROR",
|
|
15
|
+
message: error?.message || "Cannot read work-context storage",
|
|
16
|
+
details: error?.details || {},
|
|
17
|
+
},
|
|
18
|
+
data: emptySnapshot(),
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const sessionFor = (context, sessionId) => {
|
|
22
|
+
if (!sessionId) return null;
|
|
23
|
+
return context.sessionById(sessionId)
|
|
24
|
+
|| context.sessionByOpenCodeId(sessionId, null, null, null);
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const readWorkspace = (context, record, currentSession) => {
|
|
28
|
+
const listed = context.listStages(record.workspace).data;
|
|
29
|
+
const sessions = listed.sessions;
|
|
30
|
+
const matchingSession = currentSession?.workspace === record.workspace
|
|
31
|
+
? currentSession
|
|
32
|
+
: sessions.find((session) => session.session_id === currentSession?.session_id);
|
|
33
|
+
const currentStage = matchingSession?.stage || null;
|
|
34
|
+
return {
|
|
35
|
+
id: record.workspace,
|
|
36
|
+
title: record.title,
|
|
37
|
+
status: record.status,
|
|
38
|
+
stages: listed.stages
|
|
39
|
+
.filter((stage) => stage.status !== "archived")
|
|
40
|
+
.sort((left, right) => Number(left.stage) - Number(right.stage))
|
|
41
|
+
.map((stage) => ({
|
|
42
|
+
id: stage.stage,
|
|
43
|
+
title: stage.title,
|
|
44
|
+
status: stage.status,
|
|
45
|
+
description: stage.description,
|
|
46
|
+
current: stage.stage === currentStage,
|
|
47
|
+
})),
|
|
48
|
+
currentStage,
|
|
49
|
+
sessions,
|
|
50
|
+
activeSession: sessions.find((session) => session.state === "active") || null,
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/** Read all canonical metadata without initializing or projecting storage. */
|
|
55
|
+
export function readWorkContextSnapshot({ projectRoot, sessionId } = {}) {
|
|
56
|
+
try {
|
|
57
|
+
const context = WorkContext.openExisting(projectRoot, { sessionId, actor: "OpenCode TUI" });
|
|
58
|
+
const currentSession = sessionFor(context, sessionId);
|
|
59
|
+
const workspaces = context.listWorkspaces().data
|
|
60
|
+
.sort((left, right) => left.workspace.localeCompare(right.workspace))
|
|
61
|
+
.map((record) => readWorkspace(context, record, currentSession));
|
|
62
|
+
const currentWorkspace = currentSession?.workspace
|
|
63
|
+
&& workspaces.some((workspace) => workspace.id === currentSession.workspace)
|
|
64
|
+
? currentSession.workspace
|
|
65
|
+
: null;
|
|
66
|
+
return {
|
|
67
|
+
ok: true,
|
|
68
|
+
data: {
|
|
69
|
+
schema: 1,
|
|
70
|
+
workspaces,
|
|
71
|
+
currentWorkspace,
|
|
72
|
+
currentStage: currentWorkspace
|
|
73
|
+
? workspaces.find((workspace) => workspace.id === currentWorkspace)?.currentStage || null
|
|
74
|
+
: null,
|
|
75
|
+
generatedAt: new Date().toISOString(),
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
} catch (error) {
|
|
79
|
+
return errorResult(error);
|
|
80
|
+
}
|
|
81
|
+
}
|