opencode-work-context 0.1.2 → 0.1.4
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 +23 -5
- package/bin/opencode-work-context.js +11 -4
- package/commands/wc.md +10 -0
- package/package.json +4 -2
- package/plugin/stages-tui.js +155 -0
- package/plugin/work-context.js +23 -8
- package/src/core.js +1 -1
- package/src/index.js +2 -0
- package/src/opencode-adapter.js +1 -0
- package/src/stages-renderer.js +21 -0
- package/src/stages-snapshot.js +66 -0
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ Run from the root of a standalone OpenCode project:
|
|
|
11
11
|
npx opencode-work-context init
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
`init` installs `opencode-work-context@0.1.
|
|
14
|
+
`init` installs `opencode-work-context@0.1.3` as an exact devDependency using
|
|
15
15
|
standard `npm`, preserving normal lifecycle behavior for the host project. The
|
|
16
16
|
dependency root is the project root when it has `package.json`, otherwise
|
|
17
17
|
`.opencode` when `.opencode/package.json` exists, and finally the project root
|
|
@@ -19,10 +19,10 @@ with a new `package.json` when neither exists. Package files, lockfiles, and
|
|
|
19
19
|
`node_modules` are changed only in that dependency root; integration files and
|
|
20
20
|
`.gitignore` always belong to the project root.
|
|
21
21
|
|
|
22
|
-
The
|
|
23
|
-
ESM
|
|
24
|
-
|
|
25
|
-
|
|
22
|
+
The installer ensures that the dependency-root package uses `"type": "module"`
|
|
23
|
+
and generates an ESM plugin loader. OpenCode loads local plugins as JavaScript
|
|
24
|
+
modules; keeping the generated `.js` integration path ESM avoids a CommonJS
|
|
25
|
+
interop failure before custom tools are registered.
|
|
26
26
|
It does not create a workspace. Start one explicitly with `/wc create "Title"`.
|
|
27
27
|
|
|
28
28
|
Use `--force` to replace a conflicting package-owned generated file or package
|
|
@@ -38,6 +38,20 @@ Generated files:
|
|
|
38
38
|
- `<workspace>/KNOWLEDGE.md` is the canonical durable knowledge ledger and is
|
|
39
39
|
created on the first explicit knowledge operation.
|
|
40
40
|
|
|
41
|
+
The optional read-only stages panel is a separate TUI plugin. Add a project-local
|
|
42
|
+
loader at `.opencode/plugins/work-context-stages.js`:
|
|
43
|
+
|
|
44
|
+
```js
|
|
45
|
+
export { default } from "opencode-work-context/tui";
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Enable that loader in the host's TUI plugin configuration. The package keeps the
|
|
49
|
+
existing `opencode-work-context/plugin` server export unchanged and exposes the
|
|
50
|
+
panel as `opencode-work-context/tui`. The panel only reads canonical storage via
|
|
51
|
+
`WorkContext.openExisting`; it does not create `.work-context`, call lifecycle
|
|
52
|
+
tools, or modify Markdown/JSONL projections. Hosts without the TUI plugin API
|
|
53
|
+
continue to load the server plugin and its tools normally.
|
|
54
|
+
|
|
41
55
|
Tools are registered by the installed plugin and are not copied into the project.
|
|
42
56
|
Knowledge operations are explicit: list, add, update, and supersede. Finishing a
|
|
43
57
|
stage requires declaring whether its knowledge review was `added` or `none`.
|
|
@@ -45,6 +59,10 @@ Finish a workspace explicitly with `/wc workspace finish <workspace>`; it is
|
|
|
45
59
|
accepted only after every stage is `completed`. Use `/wc workspace list <workspace>`
|
|
46
60
|
to list stages with their descriptions.
|
|
47
61
|
|
|
62
|
+
If the host `opencode.json` restricts `experimental.primary_tools`, add the
|
|
63
|
+
registered `work_context_*` tool names to that allowlist; the installer does not
|
|
64
|
+
rewrite project-specific agent policy.
|
|
65
|
+
|
|
48
66
|
## License
|
|
49
67
|
|
|
50
68
|
MIT. Copyright (c) 2026 Nikita Mosiyash.
|
|
@@ -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 =
|
|
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
|
@@ -12,6 +12,16 @@ the syntax is missing or ambiguous.
|
|
|
12
12
|
For `workspace list <workspace>` (or `<workspace> list`), report the workspace
|
|
13
13
|
status and every stage as `stage - status - title - description`.
|
|
14
14
|
|
|
15
|
+
Use these exact tool mappings; do not invent shortened tool names:
|
|
16
|
+
|
|
17
|
+
- `create` -> `work_context_create_workspace`
|
|
18
|
+
- `list` -> `work_context_list_workspaces`
|
|
19
|
+
- `workspace list <workspace>` or `<workspace> list` -> `work_context_workspace_list`
|
|
20
|
+
- `workspace finish <workspace>` -> `work_context_workspace_finish`
|
|
21
|
+
- `resume <workspace> <stage>` -> `work_context_start_session`
|
|
22
|
+
- `add-stage <workspace> ...` -> `work_context_add_stage`
|
|
23
|
+
- `finish <workspace> <stage>` -> `work_context_finish_stage`
|
|
24
|
+
|
|
15
25
|
Supported syntax:
|
|
16
26
|
|
|
17
27
|
- `help [command]`
|
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.4",
|
|
5
5
|
"description": "Filesystem work-context core and OpenCode adapter",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": {
|
|
@@ -41,12 +41,14 @@
|
|
|
41
41
|
"LICENSE"
|
|
42
42
|
],
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@opencode-ai/plugin": "^1.14.50"
|
|
44
|
+
"@opencode-ai/plugin": "^1.14.50",
|
|
45
|
+
"@opentui/solid": "^0.4.5"
|
|
45
46
|
},
|
|
46
47
|
"exports": {
|
|
47
48
|
".": "./src/index.js",
|
|
48
49
|
"./adapter": "./src/opencode-adapter.js",
|
|
49
50
|
"./plugin": "./plugin/work-context.js",
|
|
51
|
+
"./tui": "./plugin/stages-tui.js",
|
|
50
52
|
"./tools/*": "./tools/*.js"
|
|
51
53
|
}
|
|
52
54
|
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { readStagesSnapshot } from "../src/stages-snapshot.js";
|
|
2
|
+
import { renderStagesPanel } from "../src/stages-renderer.js";
|
|
3
|
+
import { jsx } from "@opentui/solid/jsx-runtime";
|
|
4
|
+
|
|
5
|
+
const DEBOUNCE_MS = 150;
|
|
6
|
+
const statusMarker = (status) => ({
|
|
7
|
+
planned: "[ ]",
|
|
8
|
+
in_progress: "[•]",
|
|
9
|
+
completed: "[✓]",
|
|
10
|
+
cancelled: "[!]",
|
|
11
|
+
}[status] || "[?]");
|
|
12
|
+
|
|
13
|
+
export { readStagesSnapshot, renderStagesPanel };
|
|
14
|
+
|
|
15
|
+
export const renderStagesElement = (result, theme) => jsx("box", {
|
|
16
|
+
flexDirection: "column",
|
|
17
|
+
children: !result?.ok || !result.data?.workspace
|
|
18
|
+
? [
|
|
19
|
+
jsx("text", { children: jsx("b", { children: "Stages" }) }),
|
|
20
|
+
...renderStagesPanel(result).split("\n").slice(1).map((line) => jsx("text", { children: line })),
|
|
21
|
+
]
|
|
22
|
+
: [
|
|
23
|
+
jsx("box", {
|
|
24
|
+
flexDirection: "row",
|
|
25
|
+
children: [
|
|
26
|
+
jsx("text", { children: jsx("b", { children: "Stages" }) }),
|
|
27
|
+
jsx("text", { fg: theme?.current?.textMuted, children: ` · ${result.data.workspace.status}` }),
|
|
28
|
+
],
|
|
29
|
+
}),
|
|
30
|
+
...result.data.stages.map((stage) => jsx("box", {
|
|
31
|
+
flexDirection: "row",
|
|
32
|
+
children: [
|
|
33
|
+
jsx("text", { flexShrink: 0, marginRight: 1, fg: stage.current || stage.id === result.data.currentStage ? theme?.current?.warning : theme?.current?.textMuted, children: statusMarker(stage.status) }),
|
|
34
|
+
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}` }),
|
|
35
|
+
],
|
|
36
|
+
})),
|
|
37
|
+
],
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const sessionIdFromEvent = (event) => event?.properties?.info?.id
|
|
41
|
+
|| event?.properties?.sessionID
|
|
42
|
+
|| event?.sessionID
|
|
43
|
+
|| event?.sessionId
|
|
44
|
+
|| event?.data?.info?.id
|
|
45
|
+
|| event?.data?.sessionID;
|
|
46
|
+
const disposeRegistration = (registration) => {
|
|
47
|
+
if (typeof registration === "function") registration();
|
|
48
|
+
else registration?.dispose?.();
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export const createStagesTuiController = ({ projectRoot, read = readStagesSnapshot, debounceMs = DEBOUNCE_MS } = {}) => {
|
|
52
|
+
const snapshots = new Map();
|
|
53
|
+
const generations = new Map();
|
|
54
|
+
const timers = new Map();
|
|
55
|
+
let disposed = false;
|
|
56
|
+
|
|
57
|
+
const readSnapshot = async (sessionId) => {
|
|
58
|
+
if (disposed || !sessionId) return;
|
|
59
|
+
const currentGeneration = (generations.get(sessionId) || 0) + 1;
|
|
60
|
+
generations.set(sessionId, currentGeneration);
|
|
61
|
+
const entry = snapshots.get(sessionId) || { result: null, successful: null };
|
|
62
|
+
snapshots.set(sessionId, entry);
|
|
63
|
+
try {
|
|
64
|
+
const result = await read({ projectRoot, sessionId });
|
|
65
|
+
if (disposed || currentGeneration !== generations.get(sessionId)) return;
|
|
66
|
+
if (result?.ok) {
|
|
67
|
+
entry.successful = result;
|
|
68
|
+
entry.result = result;
|
|
69
|
+
} else {
|
|
70
|
+
entry.result = entry.successful
|
|
71
|
+
? { ...entry.successful, stale: true, error: result?.error || { code: "STORAGE_ERROR" } }
|
|
72
|
+
: result;
|
|
73
|
+
}
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if (disposed || currentGeneration !== generations.get(sessionId)) return;
|
|
76
|
+
entry.result = entry.successful
|
|
77
|
+
? { ...entry.successful, stale: true, error: { code: error.code || "STORAGE_ERROR", message: error.message } }
|
|
78
|
+
: { ok: false, error: { code: error.code || "STORAGE_ERROR", message: error.message } };
|
|
79
|
+
}
|
|
80
|
+
snapshots.set(sessionId, entry);
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const scheduleRefresh = (sessionId) => {
|
|
84
|
+
if (disposed || !sessionId) return;
|
|
85
|
+
const previous = timers.get(sessionId);
|
|
86
|
+
if (previous) clearTimeout(previous);
|
|
87
|
+
timers.set(sessionId, setTimeout(() => {
|
|
88
|
+
timers.delete(sessionId);
|
|
89
|
+
void readSnapshot(sessionId);
|
|
90
|
+
}, debounceMs));
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const resultFor = (sessionId) => {
|
|
94
|
+
const entry = snapshots.get(sessionId);
|
|
95
|
+
if (!entry) {
|
|
96
|
+
void readSnapshot(sessionId);
|
|
97
|
+
return { ok: true, data: { schema: 1, workspace: null, stages: [], currentStage: null }, loading: true };
|
|
98
|
+
}
|
|
99
|
+
return entry.result || { ok: true, data: { schema: 1, workspace: null, stages: [], currentStage: null }, loading: true };
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
load: readSnapshot,
|
|
104
|
+
scheduleRefresh,
|
|
105
|
+
resultFor,
|
|
106
|
+
dispose: () => {
|
|
107
|
+
if (disposed) return;
|
|
108
|
+
disposed = true;
|
|
109
|
+
generations.clear();
|
|
110
|
+
for (const timer of timers.values()) clearTimeout(timer);
|
|
111
|
+
timers.clear();
|
|
112
|
+
snapshots.clear();
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
// Optional TUI entry point. It is deliberately not imported by the server plugin.
|
|
118
|
+
export const tui = async (api) => {
|
|
119
|
+
// The same module can be loaded by the server plugin loader, where TUI APIs
|
|
120
|
+
// are unavailable. Return an empty hook set instead of undefined.
|
|
121
|
+
if (!api?.slots?.register || !api?.state?.path?.worktree) return {};
|
|
122
|
+
|
|
123
|
+
const projectRoot = api.state.path.worktree;
|
|
124
|
+
const initialSessionId = api.route?.current?.name === "session"
|
|
125
|
+
? api.route.current.params?.sessionID
|
|
126
|
+
: undefined;
|
|
127
|
+
const controller = createStagesTuiController({ projectRoot, read: api.stagesSnapshotProvider || readStagesSnapshot });
|
|
128
|
+
await controller.load(initialSessionId);
|
|
129
|
+
|
|
130
|
+
const unregisterSlot = api.slots.register({
|
|
131
|
+
slots: {
|
|
132
|
+
sidebar_content: (_context, { session_id: sessionId } = {}) => {
|
|
133
|
+
return renderStagesElement(controller.resultFor(sessionId), api.theme);
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
});
|
|
137
|
+
const unsubscribe = api.event?.on?.("session.updated", (event) => {
|
|
138
|
+
controller.scheduleRefresh(sessionIdFromEvent(event));
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
let cleaned = false;
|
|
142
|
+
const cleanup = () => {
|
|
143
|
+
if (cleaned) return;
|
|
144
|
+
cleaned = true;
|
|
145
|
+
controller.dispose();
|
|
146
|
+
disposeRegistration(unsubscribe);
|
|
147
|
+
disposeRegistration(unregisterSlot);
|
|
148
|
+
};
|
|
149
|
+
api.lifecycle?.onDispose?.(cleanup);
|
|
150
|
+
|
|
151
|
+
// Hosts without a lifecycle API can still explicitly release the adapter.
|
|
152
|
+
return { dispose: cleanup };
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
export default { id: "work-context-stages", tui };
|
package/plugin/work-context.js
CHANGED
|
@@ -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
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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);
|
|
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
|
@@ -183,7 +183,7 @@ export class WorkContext {
|
|
|
183
183
|
}
|
|
184
184
|
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
185
|
generateProjections(this.storage);
|
|
186
|
-
return this.result({ workspace, stage, session_id: sessionId, ordinal:
|
|
186
|
+
return this.result({ workspace, stage, session_id: sessionId, ordinal: `${stage}/${String(ordinal).padStart(2, "0")}` }, [workspace, stage]);
|
|
187
187
|
});
|
|
188
188
|
}
|
|
189
189
|
|
package/src/index.js
CHANGED
package/src/opencode-adapter.js
CHANGED
|
@@ -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 });
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const statusMarker = (status) => ({
|
|
2
|
+
planned: "[ ]",
|
|
3
|
+
in_progress: "[•]",
|
|
4
|
+
completed: "[✓]",
|
|
5
|
+
cancelled: "[!]",
|
|
6
|
+
}[status] || "[?]");
|
|
7
|
+
|
|
8
|
+
export function renderStagesPanel(result) {
|
|
9
|
+
if (!result?.ok) return `work-context stages\n! unavailable: ${result?.error?.code || "STORAGE_ERROR"}`;
|
|
10
|
+
const snapshot = result.data;
|
|
11
|
+
if (!snapshot.workspace) return `work-context stages\n(no workspace for this session)${result.stale ? `\n! stale: ${result.error?.code || "STORAGE_ERROR"}` : ""}`;
|
|
12
|
+
|
|
13
|
+
const lines = [
|
|
14
|
+
`Stages · ${snapshot.workspace.status}`,
|
|
15
|
+
];
|
|
16
|
+
for (const stage of snapshot.stages) {
|
|
17
|
+
lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}`);
|
|
18
|
+
}
|
|
19
|
+
if (result.stale) lines.push(`! stale: ${result.error?.code || "STORAGE_ERROR"}`);
|
|
20
|
+
return lines.join("\n");
|
|
21
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
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
|
+
.sort((left, right) => Number(left.stage) - Number(right.stage))
|
|
39
|
+
.map((stage) => ({
|
|
40
|
+
id: stage.stage,
|
|
41
|
+
title: stage.title,
|
|
42
|
+
status: stage.status,
|
|
43
|
+
description: stage.description,
|
|
44
|
+
current: stage.stage === session.stage,
|
|
45
|
+
}));
|
|
46
|
+
const currentStage = stages.some((stage) => stage.current) ? session.stage : null;
|
|
47
|
+
|
|
48
|
+
return {
|
|
49
|
+
ok: true,
|
|
50
|
+
data: {
|
|
51
|
+
schema: 1,
|
|
52
|
+
workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status },
|
|
53
|
+
stages,
|
|
54
|
+
currentStage,
|
|
55
|
+
generatedAt: new Date().toISOString(),
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (error.code === "NOT_FOUND") return { ok: true, data: emptySnapshot() };
|
|
60
|
+
return {
|
|
61
|
+
ok: false,
|
|
62
|
+
error: { code: error.code || "STORAGE_ERROR", message: error.message, details: error.details || {} },
|
|
63
|
+
data: emptySnapshot(),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
}
|