opencode-work-context 0.1.11 → 0.1.13
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 +86 -19
- package/commands/wc.md +6 -2
- package/package.json +1 -1
- package/plugin/session-switcher.js +99 -0
- package/plugin/stage-switcher.js +217 -0
- package/plugin/stages-tui.js +4 -0
- package/plugin/work-context-modal.js +50 -21
- package/plugin/workspace-switcher.js +87 -0
- package/src/core.js +43 -44
- package/src/identifiers.js +12 -0
- package/src/index.js +1 -0
- package/src/opencode-adapter.js +1 -1
- package/src/stages-renderer.js +2 -0
- package/src/title.js +3 -2
- package/src/tool-definitions.js +12 -24
package/README.md
CHANGED
|
@@ -14,6 +14,12 @@ task and its progress at a glance.
|
|
|
14
14
|
> The sidebar is an optional read-only TUI panel. The core workflow works
|
|
15
15
|
> through `/wc` commands and OpenCode tools without it.
|
|
16
16
|
|
|
17
|
+
Work-context session titles put the stage title first so OpenCode's session
|
|
18
|
+
picker remains easy to scan. The second line carries the workspace and stage
|
|
19
|
+
IDs, session ordinal, optional issue reference, and inactive state. In the
|
|
20
|
+
optional sidebar, the workspace title is shown separately above the stages
|
|
21
|
+
panel.
|
|
22
|
+
|
|
17
23
|
## How It Works
|
|
18
24
|
|
|
19
25
|
```text
|
|
@@ -48,6 +54,12 @@ Then create a task and its first stage in OpenCode:
|
|
|
48
54
|
/wc resume 000001 02
|
|
49
55
|
```
|
|
50
56
|
|
|
57
|
+
`stage add` only creates a `planned` stage. It never starts that stage or binds
|
|
58
|
+
the current OpenCode session to it. Open a separate OpenCode session and use
|
|
59
|
+
`/wc resume <workspace> <stage>` explicitly for every transition into an added
|
|
60
|
+
stage. Multiple sessions may work on the same non-terminal stage through
|
|
61
|
+
explicit resume and handoff operations.
|
|
62
|
+
|
|
51
63
|
When you return later, continue from the active stage. A stage must have a
|
|
52
64
|
non-empty prompt before implementation begins; if the prompt is missing or
|
|
53
65
|
ambiguous, `/wc resume` instructs the agent to ask focused questions first.
|
|
@@ -68,16 +80,25 @@ Useful commands:
|
|
|
68
80
|
/wc stage finish 000001 02
|
|
69
81
|
```
|
|
70
82
|
|
|
71
|
-
Workspace
|
|
72
|
-
|
|
83
|
+
Workspace and stage IDs accept their canonical padded form or an unpadded
|
|
84
|
+
positive integer. Workspace IDs use `1..999999`; stage IDs use `1..99`.
|
|
85
|
+
Results, storage, logs, UI, and generated commands always use six-digit
|
|
86
|
+
workspace IDs and two-digit stage IDs, so these pairs are equivalent:
|
|
73
87
|
|
|
74
88
|
```text
|
|
75
89
|
/wc workspace list 000004
|
|
90
|
+
/wc workspace list 4
|
|
76
91
|
/wc resume 000004 02
|
|
92
|
+
/wc resume 4 2
|
|
77
93
|
/wc stage handoff 000004 02
|
|
78
|
-
/wc stage finish
|
|
94
|
+
/wc stage finish 4 2
|
|
79
95
|
```
|
|
80
96
|
|
|
97
|
+
Zero, signs, decimals, surrounding whitespace, overlong values, and other
|
|
98
|
+
non-digit forms are invalid. A single identifier keeps the command grammar's
|
|
99
|
+
existing disambiguation rule: six digits mean workspace; one or two digits mean
|
|
100
|
+
stage. Use explicit workspace and stage positions for unpadded workspace IDs.
|
|
101
|
+
|
|
81
102
|
## Install
|
|
82
103
|
|
|
83
104
|
Run from the root of a standalone OpenCode project:
|
|
@@ -138,7 +159,7 @@ Generated files:
|
|
|
138
159
|
- `<workspace>/KNOWLEDGE.md` is the canonical durable knowledge ledger and is
|
|
139
160
|
created on the first explicit knowledge operation.
|
|
140
161
|
|
|
141
|
-
The optional
|
|
162
|
+
The optional stages panel, action modal, and stage switcher are a separate TUI plugin. `init` installs a
|
|
142
163
|
project-local loader outside OpenCode's server-plugin autoscan at
|
|
143
164
|
`.opencode/tui-plugins/work-context-stages.js` and enables it in `.opencode/tui.json`:
|
|
144
165
|
|
|
@@ -154,21 +175,32 @@ Enable that loader explicitly in `.opencode/tui.json`:
|
|
|
154
175
|
|
|
155
176
|
The package keeps the existing `opencode-work-context/plugin` server export and
|
|
156
177
|
also exposes the explicit server entry as `opencode-work-context/server`.
|
|
157
|
-
The combined
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
178
|
+
The combined TUI adapters are exposed only as `opencode-work-context/tui`. They
|
|
179
|
+
read canonical storage through the package core and never edit Markdown or
|
|
180
|
+
JSONL projections directly. Hosts without the TUI plugin API continue to load
|
|
181
|
+
the server plugin and its tools normally.
|
|
182
|
+
|
|
183
|
+
The native `Ctrl+X` leader prefix followed by `W` runs `work_context.open` and opens a searchable stage switcher for
|
|
184
|
+
the current workspace. Selecting a stage opens its active OpenCode-backed
|
|
185
|
+
session, or otherwise its most recently updated OpenCode-backed session. If the
|
|
186
|
+
stage has no available session, the switcher creates a separate OpenCode
|
|
187
|
+
session, opens it, and executes the public `wc resume <workspace> <stage>`
|
|
188
|
+
command in that destination session. The command invokes the canonical
|
|
189
|
+
`work_context_start_session` flow and gives the destination agent its resume
|
|
190
|
+
context. It never rebinds, closes, or submits work in the session being left.
|
|
191
|
+
Completed, cancelled, archived, or dependency-blocked stages can open an
|
|
192
|
+
existing session but cannot create a new one. Cancelling the selector changes
|
|
193
|
+
nothing. A failed canonical start removes the newly created OpenCode session
|
|
194
|
+
when the host supports deletion; a navigation failure leaves the new linked
|
|
195
|
+
session available for a later switch.
|
|
196
|
+
|
|
197
|
+
The command palette still exposes `work_context.actions` for the broader action
|
|
198
|
+
modal. Its command actions only prepare visible `/wc` commands and never submit
|
|
199
|
+
or invoke an LLM. The switcher uses OpenCode's public structured session-command
|
|
200
|
+
endpoint rather than inserting `/wc resume` text into either prompt.
|
|
201
|
+
The shortcut is registered with the public keymap layer. If another plugin or
|
|
202
|
+
terminal reserves `Ctrl+X`, remove or change the conflicting binding, or
|
|
203
|
+
disable this TUI loader; the package does not use an internal keymap fallback.
|
|
172
204
|
|
|
173
205
|
Tools are registered by the installed server export and are not copied into the
|
|
174
206
|
project. Core and storage remain in the installed package; projects should not
|
|
@@ -189,6 +221,10 @@ Every stage start/resume includes all active entries in
|
|
|
189
221
|
workspace-wide context and avoid repeating earlier analysis unless an entry is
|
|
190
222
|
incomplete, contradicted, or requires verification. Superseded entries and full
|
|
191
223
|
stage results are not injected into later stages.
|
|
224
|
+
Finishing a stage closes its current session and may report downstream stages
|
|
225
|
+
whose prompts need review, but it never starts or resumes one of them. Any
|
|
226
|
+
downstream work begins only in a separate OpenCode session through an explicit
|
|
227
|
+
`/wc resume <workspace> <stage>` operation.
|
|
192
228
|
Finish a workspace explicitly with `/wc workspace finish <workspace>`; it is
|
|
193
229
|
accepted only after every stage is `completed`. Use `/wc workspace list <workspace>`
|
|
194
230
|
to list stages with their descriptions. Workspace titles can be changed with
|
|
@@ -199,6 +235,37 @@ If the host `opencode.json` restricts `experimental.primary_tools`, add the
|
|
|
199
235
|
registered `work_context_*` tool names to that allowlist; the installer does not
|
|
200
236
|
rewrite project-specific agent policy.
|
|
201
237
|
|
|
238
|
+
## Release
|
|
239
|
+
|
|
240
|
+
Maintainers publish this package only through
|
|
241
|
+
`.github/workflows/release.yml` and npm Trusted Publishing with GitHub Actions
|
|
242
|
+
OIDC. Do not create npm publish tokens or run `npm publish` locally.
|
|
243
|
+
|
|
244
|
+
From a clean checkout, run the release checks:
|
|
245
|
+
|
|
246
|
+
```sh
|
|
247
|
+
npm test
|
|
248
|
+
npm run test:tui
|
|
249
|
+
npm run check:language
|
|
250
|
+
npm pack --dry-run
|
|
251
|
+
git diff --check
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
Then create and push the release commit and matching tag:
|
|
255
|
+
|
|
256
|
+
```sh
|
|
257
|
+
npm version patch
|
|
258
|
+
git push origin main
|
|
259
|
+
git push origin v<version>
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
Use `minor` or `major` instead of `patch` when required. The tag must exactly
|
|
263
|
+
match the version in `package.json`. Pushing the tag runs the complete release
|
|
264
|
+
workflow and publishes through short-lived OIDC credentials with automatic
|
|
265
|
+
provenance. Monitor the GitHub Actions run and verify the version and `latest`
|
|
266
|
+
dist-tag in the npm registry. Never reuse or move a tag that has already been
|
|
267
|
+
pushed or published.
|
|
268
|
+
|
|
202
269
|
## License
|
|
203
270
|
|
|
204
271
|
MIT. Copyright (c) 2026 Nikita Mosiyash.
|
package/commands/wc.md
CHANGED
|
@@ -56,17 +56,21 @@ Supported syntax:
|
|
|
56
56
|
- `stage abandon [<workspace>] <stage>`
|
|
57
57
|
- `stage finish [<workspace>] <stage>` automatically reviews the Knowledge Base (`auto` by default)
|
|
58
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
|
+
- explicit workspace and stage positions accept canonical padded IDs or unpadded positive integers (`1..999999` and `1..99`); results and generated commands remain padded
|
|
60
|
+
- zero, signs, decimals, whitespace, overlong values, and other non-digit identifier forms are invalid; a lone unpadded workspace ID is not reinterpreted under the one-identifier rule
|
|
59
61
|
- `stage update-result` replaces an existing result and does not create a result for an unfinished stage
|
|
60
62
|
- `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
63
|
- `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
64
|
- on every subsequent resume, report the context and wait for explicit user confirmation; do not automatically continue implementation
|
|
63
65
|
- when `resume.next_action` is `await_confirmation`, do not inspect or modify application code until the user confirms
|
|
64
66
|
- `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`
|
|
67
|
+
- `stage add` only creates a planned stage; it never starts, resumes, or binds the current OpenCode session to that stage, even when the session is not yet associated with a workspace
|
|
68
|
+
- entering an added stage always requires a separate OpenCode session and an explicit `resume <workspace> <stage>` operation; do not invoke `resume` automatically after creation
|
|
66
69
|
- `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
70
|
- 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
71
|
- 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`
|
|
72
|
+
- `stage finish` closes and completes only the current stage session; it never starts, resumes, or binds the same OpenCode session to a downstream stage
|
|
73
|
+
- `stage finish` always validates the Knowledge Base and returns total and active entry counts plus downstream unfinished stages for informational prompt review; do not begin a downstream stage until the user explicitly resumes it in a separate OpenCode session
|
|
70
74
|
- `knowledge list|add|update|supersede <workspace> ...`
|
|
71
75
|
|
|
72
76
|
Arguments: $ARGUMENTS
|
package/package.json
CHANGED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { readWorkContextSnapshot } from "../src/work-context-snapshot.js";
|
|
2
|
+
|
|
3
|
+
const SESSION_STATE_RANK = { active: 0, handed_off: 1, abandoned: 2, closed: 3 };
|
|
4
|
+
|
|
5
|
+
const errorResult = (code, message, details = {}) => ({ ok: false, error: { code, message, details } });
|
|
6
|
+
const currentSessionId = (api) => api?.route?.current?.params?.sessionID || api?.route?.current?.params?.sessionId;
|
|
7
|
+
const projectRoot = (api) => api?.state?.path?.worktree || api?.state?.path?.directory;
|
|
8
|
+
const sessionTime = (session) => String(session.updated_at || session.started_at || "");
|
|
9
|
+
|
|
10
|
+
const compareSessions = (left, right, currentId) => {
|
|
11
|
+
const leftCurrent = left.opencode_session_id === currentId;
|
|
12
|
+
const rightCurrent = right.opencode_session_id === currentId;
|
|
13
|
+
if (leftCurrent !== rightCurrent) return leftCurrent ? -1 : 1;
|
|
14
|
+
return (SESSION_STATE_RANK[left.state] ?? 9) - (SESSION_STATE_RANK[right.state] ?? 9)
|
|
15
|
+
|| sessionTime(right).localeCompare(sessionTime(left))
|
|
16
|
+
|| Number(right.ordinal || 0) - Number(left.ordinal || 0)
|
|
17
|
+
|| String(left.workspace || "").localeCompare(String(right.workspace || ""))
|
|
18
|
+
|| String(left.stage || "").localeCompare(String(right.stage || ""));
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** Return one deterministic work-context record for each native OpenCode session. */
|
|
22
|
+
export const sortSessionSwitcherEntries = (entries = [], currentId = null) => {
|
|
23
|
+
const selected = new Map();
|
|
24
|
+
for (const entry of entries) {
|
|
25
|
+
const id = entry.session?.opencode_session_id;
|
|
26
|
+
if (!id || selected.has(id) && compareSessions(selected.get(id).session, entry.session, currentId) <= 0) continue;
|
|
27
|
+
selected.set(id, entry);
|
|
28
|
+
}
|
|
29
|
+
return [...selected.values()].sort((left, right) => compareSessions(left.session, right.session, currentId));
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export const selectSession = (entries = [], currentId = null) => sortSessionSwitcherEntries(entries, currentId)[0]?.session || null;
|
|
33
|
+
|
|
34
|
+
export const switchToSession = (api, session) => {
|
|
35
|
+
const sessionID = session?.opencode_session_id;
|
|
36
|
+
if (!sessionID) return errorResult("SESSION_OPENCODE_ID_MISSING", "This work-context session has no OpenCode session ID", { session_id: session?.session_id });
|
|
37
|
+
if (typeof api?.route?.navigate !== "function") return errorResult("SESSION_SWITCH_UNAVAILABLE", "This OpenCode host cannot switch sessions from a TUI plugin");
|
|
38
|
+
try {
|
|
39
|
+
api.ui?.dialog?.clear?.();
|
|
40
|
+
api.route.navigate("session", { sessionID });
|
|
41
|
+
return { ok: true, data: { opencode_session_id: sessionID, created: false, navigated: true } };
|
|
42
|
+
} catch (error) {
|
|
43
|
+
return errorResult(error.code || "SESSION_SWITCH_ERROR", error.message || "OpenCode could not open the selected session", { opencode_session_id: sessionID });
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export const createSessionSwitcherFlow = (api, { read = readWorkContextSnapshot } = {}) => {
|
|
48
|
+
const toast = (message, variant = "warning") => api?.ui?.toast?.({ message, variant });
|
|
49
|
+
const open = async () => {
|
|
50
|
+
let result;
|
|
51
|
+
try { result = await read({ projectRoot: projectRoot(api), sessionId: currentSessionId(api) }); }
|
|
52
|
+
catch (error) { result = errorResult(error.code || "STORAGE_ERROR", error.message || "Cannot read work-context storage"); }
|
|
53
|
+
if (!result?.ok) {
|
|
54
|
+
toast(`${result?.error?.code || "STORAGE_ERROR"}: ${result?.error?.message || "Cannot read work-context storage"}`, "error");
|
|
55
|
+
return result;
|
|
56
|
+
}
|
|
57
|
+
const data = result.data || {};
|
|
58
|
+
const entries = (data.workspaces || []).flatMap((workspace) => (workspace.sessions || []).map((session) => ({ workspace, session })));
|
|
59
|
+
if (!entries.length) { toast("No sessions found"); return result; }
|
|
60
|
+
const currentId = currentSessionId(api);
|
|
61
|
+
const available = sortSessionSwitcherEntries(entries, currentId);
|
|
62
|
+
const unavailable = entries.filter(({ session }) => !session.opencode_session_id);
|
|
63
|
+
const labels = { active: "Active", handed_off: "Handed off", abandoned: "Abandoned", closed: "Closed" };
|
|
64
|
+
api.ui.dialog.setSize?.("medium");
|
|
65
|
+
api.ui.dialog.replace(() => api.ui.DialogSelect({
|
|
66
|
+
title: "Switch session",
|
|
67
|
+
placeholder: "Search sessions",
|
|
68
|
+
options: [
|
|
69
|
+
...available.map(({ workspace, session }) => ({
|
|
70
|
+
title: `${workspace.id} ${session.stage || "-"}/${String(session.ordinal || 0).padStart(2, "0")} ${session.summary || "Work session"} · ${workspace.title}`,
|
|
71
|
+
description: `${session.state || "unknown"} · ${session.session_id || "unknown"}`,
|
|
72
|
+
footer: session.opencode_session_id,
|
|
73
|
+
category: session.opencode_session_id === currentId ? "Current" : labels[session.state] || session.state || "Unknown",
|
|
74
|
+
value: session,
|
|
75
|
+
})),
|
|
76
|
+
...unavailable.map(({ workspace, session }) => ({
|
|
77
|
+
title: `${workspace.id} ${session.stage || "-"}/${String(session.ordinal || 0).padStart(2, "0")} ${session.summary || "Work session"} · ${workspace.title}`,
|
|
78
|
+
description: `${session.state || "unknown"} · no OpenCode session available`,
|
|
79
|
+
category: "Unavailable",
|
|
80
|
+
disabled: true,
|
|
81
|
+
value: session,
|
|
82
|
+
})),
|
|
83
|
+
],
|
|
84
|
+
onSelect: (option) => {
|
|
85
|
+
const switched = switchToSession(api, option.value);
|
|
86
|
+
if (!switched.ok) toast(`${switched.error.code}: ${switched.error.message}`, "error");
|
|
87
|
+
else toast("Session opened", "success");
|
|
88
|
+
},
|
|
89
|
+
}));
|
|
90
|
+
return result;
|
|
91
|
+
};
|
|
92
|
+
return { open };
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
export const openSessionSwitcher = (api, options = {}) => {
|
|
96
|
+
if (typeof api?.ui?.DialogSelect !== "function" || typeof api?.ui?.dialog?.replace !== "function") return false;
|
|
97
|
+
void createSessionSwitcherFlow(api, options).open();
|
|
98
|
+
return true;
|
|
99
|
+
};
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { contextFor } from "../src/opencode-adapter.js";
|
|
4
|
+
import { atomicWrite } from "../src/storage.js";
|
|
5
|
+
|
|
6
|
+
const TERMINAL_STATUSES = new Set(["completed", "cancelled", "archived"]);
|
|
7
|
+
const SESSION_STATE_RANK = { active: 0, handed_off: 1, abandoned: 2, closed: 3 };
|
|
8
|
+
const RECENT_STAGE_LIMIT = 5;
|
|
9
|
+
const RECENT_STATE_FILE = path.join(".work-context", "local", "tui-state.json");
|
|
10
|
+
const recentStagesByApi = new WeakMap();
|
|
11
|
+
|
|
12
|
+
const errorResult = (code, message, details = {}) => ({ ok: false, error: { code, message, details } });
|
|
13
|
+
const currentSessionId = (api) => api?.route?.current?.params?.sessionID || api?.route?.current?.params?.sessionId;
|
|
14
|
+
const projectRoot = (api) => api?.state?.path?.worktree || api?.state?.path?.directory;
|
|
15
|
+
|
|
16
|
+
const readRecentState = (root) => {
|
|
17
|
+
if (!root) return {};
|
|
18
|
+
try {
|
|
19
|
+
const file = path.join(root, RECENT_STATE_FILE);
|
|
20
|
+
if (!fs.lstatSync(file).isFile()) return {};
|
|
21
|
+
const state = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
22
|
+
if (!state || state.schema !== 1 || !state.recent_stages || typeof state.recent_stages !== "object") return {};
|
|
23
|
+
return Object.fromEntries(Object.entries(state.recent_stages).map(([workspace, stages]) => [
|
|
24
|
+
workspace,
|
|
25
|
+
Array.isArray(stages) ? stages.filter((stage) => /^\d{2}$/.test(stage)).slice(0, RECENT_STAGE_LIMIT) : [],
|
|
26
|
+
]));
|
|
27
|
+
} catch { return {}; }
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const persistRecentState = (root, store) => {
|
|
31
|
+
if (!root) return;
|
|
32
|
+
try {
|
|
33
|
+
atomicWrite(path.join(root, RECENT_STATE_FILE), `${JSON.stringify({ schema: 1, recent_stages: Object.fromEntries(store) }, null, 2)}\n`);
|
|
34
|
+
} catch {}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const recentStageStore = (api) => {
|
|
38
|
+
let store = recentStagesByApi.get(api);
|
|
39
|
+
if (!store) {
|
|
40
|
+
store = new Map(Object.entries(readRecentState(projectRoot(api))));
|
|
41
|
+
recentStagesByApi.set(api, store);
|
|
42
|
+
}
|
|
43
|
+
return store;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** Keep navigation history in the plugin session; work-context storage stays unchanged. */
|
|
47
|
+
export const rememberRecentStage = (api, workspace, stage) => {
|
|
48
|
+
if (!api || !workspace || !stage) return;
|
|
49
|
+
const store = recentStageStore(api);
|
|
50
|
+
const recent = store.get(workspace) || [];
|
|
51
|
+
store.set(workspace, [stage, ...recent.filter((id) => id !== stage)].slice(0, RECENT_STAGE_LIMIT));
|
|
52
|
+
persistRecentState(projectRoot(api), store);
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export const recentStageIds = (api, workspace) => [...(recentStageStore(api).get(workspace) || [])];
|
|
56
|
+
|
|
57
|
+
export const selectStageSession = (sessions = []) => sessions
|
|
58
|
+
.filter((session) => session.opencode_session_id)
|
|
59
|
+
.sort((left, right) => (SESSION_STATE_RANK[left.state] ?? 9) - (SESSION_STATE_RANK[right.state] ?? 9)
|
|
60
|
+
|| String(right.updated_at || right.started_at || "").localeCompare(String(left.updated_at || left.started_at || ""))
|
|
61
|
+
|| Number(right.ordinal || 0) - Number(left.ordinal || 0))[0] || null;
|
|
62
|
+
|
|
63
|
+
/** Read the current workspace, including terminal stages omitted from the overview modal. */
|
|
64
|
+
export const readStageSwitcherSnapshot = ({ projectRoot: root, sessionId } = {}) => {
|
|
65
|
+
try {
|
|
66
|
+
const context = contextFor(root, sessionId, "OpenCode TUI");
|
|
67
|
+
const current = context.sessionByOpenCodeId(sessionId, null, null, null) || context.sessionById(sessionId);
|
|
68
|
+
if (!current) return errorResult("STAGE_CONTEXT_REQUIRED", "The current OpenCode session is not associated with a work-context stage");
|
|
69
|
+
const listed = context.listStages(current.workspace).data;
|
|
70
|
+
const workspace = context.listWorkspaces().data.find((item) => item.workspace === current.workspace);
|
|
71
|
+
if (!workspace) return errorResult("NOT_FOUND", "The current work-context workspace no longer exists");
|
|
72
|
+
const completed = new Set(listed.stages.filter((stage) => stage.status === "completed").map((stage) => stage.stage));
|
|
73
|
+
return {
|
|
74
|
+
ok: true,
|
|
75
|
+
data: {
|
|
76
|
+
workspace: { id: current.workspace, title: workspace.title, status: workspace.status },
|
|
77
|
+
currentStage: current.stage,
|
|
78
|
+
stages: listed.stages.map((stage) => {
|
|
79
|
+
const sessions = listed.sessions.filter((session) => session.stage === stage.stage);
|
|
80
|
+
const blockers = (stage.depends_on || []).filter((dependency) => !completed.has(dependency));
|
|
81
|
+
return {
|
|
82
|
+
id: stage.stage,
|
|
83
|
+
title: stage.title,
|
|
84
|
+
description: stage.description,
|
|
85
|
+
status: stage.status,
|
|
86
|
+
current: stage.stage === current.stage,
|
|
87
|
+
blockers,
|
|
88
|
+
blocked: blockers.length > 0,
|
|
89
|
+
sessions,
|
|
90
|
+
selectedSession: selectStageSession(sessions),
|
|
91
|
+
};
|
|
92
|
+
}),
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
} catch (error) {
|
|
96
|
+
return errorResult(error.code || "STORAGE_ERROR", error.message || "Cannot read work-context storage", error.details || {});
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const navigateToSession = (api, sessionID) => {
|
|
101
|
+
if (typeof api?.route?.navigate !== "function") return errorResult("SESSION_SWITCH_UNAVAILABLE", "This OpenCode host cannot switch sessions from a TUI plugin");
|
|
102
|
+
try {
|
|
103
|
+
api.ui?.dialog?.clear?.();
|
|
104
|
+
api.route.navigate("session", { sessionID });
|
|
105
|
+
return { ok: true, data: { opencode_session_id: sessionID, created: false } };
|
|
106
|
+
} catch (error) {
|
|
107
|
+
return errorResult(error.code || "SESSION_SWITCH_ERROR", error.message || "OpenCode could not open the selected session");
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
export const startStageSession = async (api, { workspace, stage, title }, { readContext = contextFor } = {}) => {
|
|
112
|
+
const root = projectRoot(api);
|
|
113
|
+
if (!root) return errorResult("PROJECT_ROOT_REQUIRED", "The OpenCode project root is unavailable");
|
|
114
|
+
if (typeof api?.client?.session?.create !== "function") return errorResult("SESSION_CREATE_UNAVAILABLE", "This OpenCode host cannot create sessions from a TUI plugin");
|
|
115
|
+
if (typeof api?.client?.session?.command !== "function") return errorResult("SESSION_COMMAND_UNAVAILABLE", "This OpenCode host cannot run the work-context resume command in a new session");
|
|
116
|
+
let opencodeSessionId;
|
|
117
|
+
try {
|
|
118
|
+
const response = await api.client.session.create({
|
|
119
|
+
directory: root,
|
|
120
|
+
title,
|
|
121
|
+
metadata: { work_context_workspace: workspace, work_context_stage: stage },
|
|
122
|
+
}, { throwOnError: true });
|
|
123
|
+
const created = response?.data || response;
|
|
124
|
+
opencodeSessionId = created?.id;
|
|
125
|
+
if (!opencodeSessionId) return errorResult("SESSION_CREATE_ERROR", "OpenCode did not return the created session ID");
|
|
126
|
+
const switched = navigateToSession(api, opencodeSessionId);
|
|
127
|
+
if (!switched.ok) throw Object.assign(new Error(switched.error.message), { code: switched.error.code });
|
|
128
|
+
await api.client.session.command({
|
|
129
|
+
sessionID: opencodeSessionId,
|
|
130
|
+
directory: root,
|
|
131
|
+
command: "wc",
|
|
132
|
+
arguments: `resume ${workspace} ${stage}`,
|
|
133
|
+
}, { throwOnError: true });
|
|
134
|
+
const context = readContext(root, opencodeSessionId, "OpenCode TUI");
|
|
135
|
+
const bound = context.sessionByOpenCodeId(opencodeSessionId, workspace, stage, null);
|
|
136
|
+
if (!bound) return errorResult("SESSION_START_INCOMPLETE", "The resume command completed without binding the new OpenCode session", { opencode_session_id: opencodeSessionId });
|
|
137
|
+
return { ok: true, data: { ...bound, opencode_session_id: opencodeSessionId, created: true, opened: true } };
|
|
138
|
+
} catch (error) {
|
|
139
|
+
const current = currentSessionId(api);
|
|
140
|
+
if (opencodeSessionId && current !== opencodeSessionId && typeof api?.client?.session?.delete === "function") {
|
|
141
|
+
try { await api.client.session.delete({ sessionID: opencodeSessionId, directory: root }, { throwOnError: true }); } catch {}
|
|
142
|
+
}
|
|
143
|
+
return errorResult(error.code || "SESSION_START_ERROR", error.message || "Could not start the work-context session", error.details || {});
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
export const switchToStage = async (api, stage, options = {}) => {
|
|
148
|
+
if (typeof api?.route?.navigate !== "function") return errorResult("SESSION_SWITCH_UNAVAILABLE", "This OpenCode host cannot switch sessions from a TUI plugin");
|
|
149
|
+
const existing = stage.selectedSession || selectStageSession(stage.sessions);
|
|
150
|
+
if (existing) {
|
|
151
|
+
const switched = navigateToSession(api, existing.opencode_session_id);
|
|
152
|
+
if (switched.ok) {
|
|
153
|
+
rememberRecentStage(api, options.workspace, stage.id);
|
|
154
|
+
rememberRecentStage(api, options.workspace, options.currentStage);
|
|
155
|
+
}
|
|
156
|
+
return switched;
|
|
157
|
+
}
|
|
158
|
+
if (TERMINAL_STATUSES.has(stage.status)) return errorResult("INVALID_STATE", `Cannot create a session for a ${stage.status} stage`);
|
|
159
|
+
if (stage.blocked) return errorResult("INVALID_STATE", `Complete dependencies ${stage.blockers.join(", ")} before starting this stage`, { blockers: stage.blockers });
|
|
160
|
+
const started = await (options.start || startStageSession)(api, { workspace: options.workspace, stage: stage.id, title: stage.title });
|
|
161
|
+
if (!started.ok) return started;
|
|
162
|
+
if (!started.data.opened) {
|
|
163
|
+
const switched = navigateToSession(api, started.data.opencode_session_id);
|
|
164
|
+
if (!switched.ok) return switched;
|
|
165
|
+
}
|
|
166
|
+
rememberRecentStage(api, options.workspace, stage.id);
|
|
167
|
+
rememberRecentStage(api, options.workspace, options.currentStage);
|
|
168
|
+
return { ok: true, data: { ...started.data, created: true } };
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
export const createStageSwitcherFlow = (api, { read = readStageSwitcherSnapshot, start = startStageSession } = {}) => {
|
|
172
|
+
const toast = (message, variant = "warning") => api?.ui?.toast?.({ message, variant });
|
|
173
|
+
const open = async () => {
|
|
174
|
+
let result;
|
|
175
|
+
try { result = await read({ projectRoot: projectRoot(api), sessionId: currentSessionId(api) }); }
|
|
176
|
+
catch (error) { result = errorResult(error.code || "STORAGE_ERROR", error.message || "Cannot read work-context storage"); }
|
|
177
|
+
if (!result?.ok) { toast(`${result?.error?.code || "STORAGE_ERROR"}: ${result?.error?.message || "Cannot read work-context storage"}`, "error"); return result; }
|
|
178
|
+
const { workspace, stages } = result.data;
|
|
179
|
+
rememberRecentStage(api, workspace.id, result.data.currentStage);
|
|
180
|
+
const recent = recentStageIds(api, workspace.id)
|
|
181
|
+
.map((id) => stages.find((stage) => stage.id === id))
|
|
182
|
+
.filter((stage) => stage && !stage.current);
|
|
183
|
+
const optionFor = (stage, category) => {
|
|
184
|
+
const available = (stage.sessions || []).filter((session) => session.opencode_session_id).length;
|
|
185
|
+
const state = stage.blocked ? `blocked by ${stage.blockers.join(", ")}` : stage.status;
|
|
186
|
+
return {
|
|
187
|
+
title: `${stage.current ? ">" : " "} ${stage.id}. ${stage.title}`,
|
|
188
|
+
description: `${state} · ${available ? `${available} session${available === 1 ? "" : "s"}` : TERMINAL_STATUSES.has(stage.status) || stage.blocked ? "no session available" : "new session"}`,
|
|
189
|
+
category,
|
|
190
|
+
disabled: (TERMINAL_STATUSES.has(stage.status) || stage.blocked) && !available,
|
|
191
|
+
value: stage,
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
api.ui.dialog.setSize?.("medium");
|
|
195
|
+
api.ui.dialog.replace(() => api.ui.DialogSelect({
|
|
196
|
+
title: `Switch stage · ${workspace.id} ${workspace.title}`,
|
|
197
|
+
placeholder: "Search stages",
|
|
198
|
+
options: [
|
|
199
|
+
...recent.map((stage) => optionFor(stage, "Recent")),
|
|
200
|
+
...stages.map((stage) => optionFor(stage, stage.current ? "Current" : stage.status)),
|
|
201
|
+
],
|
|
202
|
+
onSelect: (option) => void (async () => {
|
|
203
|
+
const switched = await switchToStage(api, option.value, { workspace: workspace.id, currentStage: result.data.currentStage, start });
|
|
204
|
+
if (!switched.ok) toast(`${switched.error.code}: ${switched.error.message}`, "error");
|
|
205
|
+
else toast(switched.data.created ? "Stage session created" : "Stage session opened", "success");
|
|
206
|
+
})(),
|
|
207
|
+
}));
|
|
208
|
+
return result;
|
|
209
|
+
};
|
|
210
|
+
return { open };
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
export const openStageSwitcher = (api, options = {}) => {
|
|
214
|
+
if (typeof api?.ui?.DialogSelect !== "function" || typeof api?.ui?.dialog?.replace !== "function") return false;
|
|
215
|
+
void createStageSwitcherFlow(api, options).open();
|
|
216
|
+
return true;
|
|
217
|
+
};
|
package/plugin/stages-tui.js
CHANGED
|
@@ -30,6 +30,10 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime) => !result
|
|
|
30
30
|
...renderStagesPanel(result).split("\n").slice(1).map((line) => runtime.jsx("text", { children: line })),
|
|
31
31
|
]
|
|
32
32
|
: [
|
|
33
|
+
runtime.jsx("box", {
|
|
34
|
+
marginBottom: 1,
|
|
35
|
+
children: runtime.jsx("text", { wrapMode: "word", children: runtime.jsx("b", { children: result.data.workspace.title }) }),
|
|
36
|
+
}),
|
|
33
37
|
runtime.jsx("box", {
|
|
34
38
|
flexDirection: "row",
|
|
35
39
|
children: [
|
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { readWorkContextSnapshot } from "../src/work-context-snapshot.js";
|
|
4
|
+
import { normalizeStageId, normalizeWorkspaceId } from "../src/identifiers.js";
|
|
4
5
|
import { jsx } from "@opentui/solid/jsx-runtime";
|
|
5
6
|
import { createSignal } from "solid-js";
|
|
7
|
+
import { openStageSwitcher } from "./stage-switcher.js";
|
|
8
|
+
import { openWorkspaceSwitcher } from "./workspace-switcher.js";
|
|
9
|
+
import { openSessionSwitcher } from "./session-switcher.js";
|
|
6
10
|
|
|
7
11
|
const COMMAND_NAME = "work_context.open";
|
|
8
|
-
const
|
|
12
|
+
const ACTIONS_COMMAND_NAME = "work_context.actions";
|
|
13
|
+
const SHORTCUT = "<leader>w";
|
|
14
|
+
const STAGE_SHORTCUT = "<leader>s";
|
|
15
|
+
const WORKSPACE_SHORTCUT = "<leader>o";
|
|
16
|
+
const SESSION_SHORTCUT = "<leader>e";
|
|
9
17
|
const DEBOUNCE_MS = 150;
|
|
10
18
|
const POLL_MS = 1000;
|
|
11
19
|
const MARKERS = { planned: "[ ]", in_progress: "[•]", completed: "[✓]", cancelled: "[!]" };
|
|
@@ -14,6 +22,9 @@ const activeTuiInstances = new WeakMap();
|
|
|
14
22
|
|
|
15
23
|
export const WORK_CONTEXT_ACTIONS = [
|
|
16
24
|
{ value: "help", title: "Help", description: "Show work-context command help", category: "General" },
|
|
25
|
+
{ value: "switch.stage", title: "Switch stage", description: "Open a stage session in the current workspace", footer: "ctrl+x s", category: "Navigation" },
|
|
26
|
+
{ value: "switch.workspace", title: "Switch workspace", description: "Open a workspace session", footer: "ctrl+x o", category: "Navigation" },
|
|
27
|
+
{ value: "switch.session", title: "Switch session", description: "Open an active or historical work session", footer: "ctrl+x e", category: "Navigation" },
|
|
17
28
|
{ value: "list", title: "Browse workspaces", description: "Search workspaces and their stages", category: "General" },
|
|
18
29
|
{ value: "browse.stages", title: "Browse stages", description: "Search stages across every workspace", category: "General" },
|
|
19
30
|
{ value: "browse.sessions", title: "Browse sessions", description: "Search active and historical work sessions", category: "General" },
|
|
@@ -43,17 +54,19 @@ const closeDialog = (api) => api?.ui?.dialog?.clear?.();
|
|
|
43
54
|
const textOf = (value) => String(value || "").toLocaleLowerCase();
|
|
44
55
|
const matches = (value, query) => !query || textOf(value).includes(textOf(query));
|
|
45
56
|
|
|
46
|
-
const
|
|
47
|
-
|
|
57
|
+
const normalizedId = (normalize, value) => {
|
|
58
|
+
try { return normalize(value); } catch { return null; }
|
|
59
|
+
};
|
|
48
60
|
|
|
49
61
|
/** Prepare a canonical command without parsing or executing it. */
|
|
50
62
|
export const prepareWorkContextCommand = (action, workspace, stage) => {
|
|
51
|
-
|
|
63
|
+
const normalizedWorkspace = normalizedId(normalizeWorkspaceId, workspace);
|
|
64
|
+
if (!normalizedWorkspace) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Invalid workspace ID" } };
|
|
52
65
|
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 ${
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
return { ok: true, command: `/wc ${COMMANDS[action]} ${
|
|
66
|
+
if (action === "list") return { ok: true, command: `/wc workspace list ${normalizedWorkspace}` };
|
|
67
|
+
const normalizedStage = normalizedId(normalizeStageId, stage);
|
|
68
|
+
if (!normalizedStage) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Invalid stage ID" } };
|
|
69
|
+
return { ok: true, command: `/wc ${COMMANDS[action]} ${normalizedWorkspace} ${normalizedStage}` };
|
|
57
70
|
};
|
|
58
71
|
|
|
59
72
|
/** Use only a host-provided prompt append bridge; never submit the prompt. */
|
|
@@ -277,31 +290,32 @@ export const buildWorkContextActionCommand = (action, { workspace, stage, value,
|
|
|
277
290
|
if (action === "session.rename") return value?.trim()
|
|
278
291
|
? { ok: true, command: `/wc session rename ${quoteWorkContextArgument(value.trim())}` }
|
|
279
292
|
: { ok: false, error: { code: "INVALID_ARGUMENT", message: "Summary is required" } };
|
|
280
|
-
|
|
281
|
-
if (
|
|
282
|
-
if (action === "workspace.
|
|
293
|
+
const normalizedWorkspace = normalizedId(normalizeWorkspaceId, workspace);
|
|
294
|
+
if (!normalizedWorkspace) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Invalid workspace ID" } };
|
|
295
|
+
if (action === "workspace.list") return { ok: true, command: `/wc workspace list ${normalizedWorkspace}` };
|
|
296
|
+
if (action === "workspace.finish") return { ok: true, command: `/wc workspace finish ${normalizedWorkspace}` };
|
|
283
297
|
if (action === "workspace.rename") return value?.trim()
|
|
284
|
-
? { ok: true, command: `/wc workspace rename ${
|
|
298
|
+
? { ok: true, command: `/wc workspace rename ${normalizedWorkspace} ${quoteWorkContextArgument(value.trim())}` }
|
|
285
299
|
: { ok: false, error: { code: "INVALID_ARGUMENT", message: "Title is required" } };
|
|
286
300
|
if (action === "stage.add") {
|
|
287
301
|
if (!value?.trim()) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Title is required" } };
|
|
288
|
-
return { ok: true, command: `/wc stage add ${
|
|
302
|
+
return { ok: true, command: `/wc stage add ${normalizedWorkspace} ${quoteWorkContextArgument(value.trim())}${prompt?.trim() ? ` ${quoteWorkContextArgument(prompt.trim())}` : ""}` };
|
|
289
303
|
}
|
|
290
|
-
|
|
291
|
-
|
|
304
|
+
const normalizedStage = normalizedId(normalizeStageId, stage);
|
|
305
|
+
if (!normalizedStage) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Invalid stage ID" } };
|
|
292
306
|
const commandName = action.replace(".", " ");
|
|
293
|
-
if (["resume", "stage.archive", "stage.handoff", "stage.abandon", "stage.finish"].includes(action)) return { ok: true, command: `/wc ${commandName} ${
|
|
307
|
+
if (["resume", "stage.archive", "stage.handoff", "stage.abandon", "stage.finish"].includes(action)) return { ok: true, command: `/wc ${commandName} ${normalizedWorkspace} ${normalizedStage}` };
|
|
294
308
|
const inputCommands = { "stage.rename": "title", "stage.update": "description", "stage.update-prompt": "prompt", "stage.update-result": "result" };
|
|
295
309
|
if (Object.hasOwn(inputCommands, action)) return value?.trim()
|
|
296
|
-
? { ok: true, command: `/wc ${commandName} ${
|
|
310
|
+
? { ok: true, command: `/wc ${commandName} ${normalizedWorkspace} ${normalizedStage} ${quoteWorkContextArgument(value.trim())}` }
|
|
297
311
|
: { ok: false, error: { code: "INVALID_ARGUMENT", message: `${inputCommands[action][0].toUpperCase()}${inputCommands[action].slice(1)} is required` } };
|
|
298
312
|
return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Unsupported work-context action" } };
|
|
299
313
|
};
|
|
300
314
|
|
|
301
|
-
export const createWorkContextActionFlow = (api, { projectRoot, sessionId, read = readWorkContextSnapshot } = {}) => {
|
|
315
|
+
export const createWorkContextActionFlow = (api, { projectRoot, sessionId, read = readWorkContextSnapshot, openStage = openStageSwitcher } = {}) => {
|
|
302
316
|
const stack = api?.ui?.dialog;
|
|
303
317
|
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 }));
|
|
318
|
+
const showSelect = (title, options, onSelect, props = {}) => stack.replace(() => api.ui.DialogSelect({ title, placeholder: "Search", options, onSelect, ...props }));
|
|
305
319
|
const showPrompt = (title, placeholder, onConfirm) => stack.replace(() => api.ui.DialogPrompt({ title, placeholder, onConfirm }));
|
|
306
320
|
const insert = async (prepared) => {
|
|
307
321
|
if (!prepared.ok) { toast(prepared.error.message); return; }
|
|
@@ -476,6 +490,9 @@ export const createWorkContextActionFlow = (api, { projectRoot, sessionId, read
|
|
|
476
490
|
};
|
|
477
491
|
const selectAction = (action) => {
|
|
478
492
|
if (action === "help") void insert(buildWorkContextActionCommand(action));
|
|
493
|
+
else if (action === "switch.stage") openStage(api);
|
|
494
|
+
else if (action === "switch.workspace") openWorkspaceSwitcher(api);
|
|
495
|
+
else if (action === "switch.session") openSessionSwitcher(api);
|
|
479
496
|
else if (action === "list") void browseWorkspaces();
|
|
480
497
|
else if (action === "browse.stages") void browseStages();
|
|
481
498
|
else if (action === "browse.sessions") void browseSessions();
|
|
@@ -525,8 +542,20 @@ export const openCompatibilityDialog = (api, runtime = {}, options = {}) => {
|
|
|
525
542
|
|
|
526
543
|
export const registerWorkContextModal = (api, runtime = {}) => {
|
|
527
544
|
if (typeof api?.keymap?.registerLayer !== "function") return { supported: false, dispose: () => {} };
|
|
528
|
-
const command = { name: COMMAND_NAME, title: "Open Work Context", desc: "
|
|
529
|
-
const
|
|
545
|
+
const command = { name: COMMAND_NAME, title: "Open Work Context", desc: "Open work-context navigation and actions", category: "Work Context", namespace: "palette", run: () => openWorkContextActionDialog(api, runtime) };
|
|
546
|
+
const stageCommand = { name: "work_context.stage", title: "Switch Work Context Stage", desc: "Open a stage session in the current workspace", category: "Work Context", namespace: "palette", run: () => openStageSwitcher(api) };
|
|
547
|
+
const workspaceCommand = { name: "work_context.workspace", title: "Switch Work Context Workspace", desc: "Open a workspace session", category: "Work Context", namespace: "palette", run: () => openWorkspaceSwitcher(api) };
|
|
548
|
+
const sessionCommand = { name: "work_context.session", title: "Switch Work Context Session", desc: "Open an active or historical work session", category: "Work Context", namespace: "palette", run: () => openSessionSwitcher(api) };
|
|
549
|
+
const actions = { name: ACTIONS_COMMAND_NAME, title: "Open Work Context Actions", desc: "Prepare a work-context command", category: "Work Context", namespace: "palette", run: () => openWorkContextActionDialog(api, runtime) };
|
|
550
|
+
const registration = api.keymap.registerLayer({
|
|
551
|
+
commands: [command, stageCommand, workspaceCommand, sessionCommand, actions],
|
|
552
|
+
bindings: [
|
|
553
|
+
{ key: SHORTCUT, cmd: COMMAND_NAME, desc: command.title },
|
|
554
|
+
{ key: STAGE_SHORTCUT, cmd: stageCommand.name, desc: stageCommand.title },
|
|
555
|
+
{ key: WORKSPACE_SHORTCUT, cmd: workspaceCommand.name, desc: workspaceCommand.title },
|
|
556
|
+
{ key: SESSION_SHORTCUT, cmd: sessionCommand.name, desc: sessionCommand.title },
|
|
557
|
+
],
|
|
558
|
+
});
|
|
530
559
|
return { supported: true, dispose: () => disposeRegistration(registration) };
|
|
531
560
|
};
|
|
532
561
|
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { readWorkContextSnapshot } from "../src/work-context-snapshot.js";
|
|
2
|
+
|
|
3
|
+
const SESSION_STATE_RANK = { active: 0, handed_off: 1, abandoned: 2, closed: 3 };
|
|
4
|
+
const WORKSPACE_STATUS_RANK = { in_progress: 0, planned: 1, completed: 2, cancelled: 3 };
|
|
5
|
+
|
|
6
|
+
const errorResult = (code, message, details = {}) => ({ ok: false, error: { code, message, details } });
|
|
7
|
+
const currentSessionId = (api) => api?.route?.current?.params?.sessionID || api?.route?.current?.params?.sessionId;
|
|
8
|
+
const projectRoot = (api) => api?.state?.path?.worktree || api?.state?.path?.directory;
|
|
9
|
+
|
|
10
|
+
/** Select the best existing OpenCode session without changing work-context state. */
|
|
11
|
+
export const selectWorkspaceSession = (sessions = []) => sessions
|
|
12
|
+
.filter((session) => session.opencode_session_id)
|
|
13
|
+
.sort((left, right) => (SESSION_STATE_RANK[left.state] ?? 9) - (SESSION_STATE_RANK[right.state] ?? 9)
|
|
14
|
+
|| String(right.updated_at || right.started_at || "").localeCompare(String(left.updated_at || left.started_at || ""))
|
|
15
|
+
|| Number(right.ordinal || 0) - Number(left.ordinal || 0))[0] || null;
|
|
16
|
+
|
|
17
|
+
export const sortWorkspaceSwitcherEntries = (workspaces = [], currentWorkspace = null) => [...workspaces].sort((left, right) => {
|
|
18
|
+
if (left.id === currentWorkspace) return -1;
|
|
19
|
+
if (right.id === currentWorkspace) return 1;
|
|
20
|
+
return (WORKSPACE_STATUS_RANK[left.status] ?? 9) - (WORKSPACE_STATUS_RANK[right.status] ?? 9)
|
|
21
|
+
|| left.id.localeCompare(right.id);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const navigateToSession = (api, sessionID) => {
|
|
25
|
+
if (typeof api?.route?.navigate !== "function") return errorResult("SESSION_SWITCH_UNAVAILABLE", "This OpenCode host cannot switch sessions from a TUI plugin");
|
|
26
|
+
try {
|
|
27
|
+
api.ui?.dialog?.clear?.();
|
|
28
|
+
api.route.navigate("session", { sessionID });
|
|
29
|
+
return { ok: true, data: { opencode_session_id: sessionID, created: false } };
|
|
30
|
+
} catch (error) {
|
|
31
|
+
return errorResult(error.code || "SESSION_SWITCH_ERROR", error.message || "OpenCode could not open the selected session");
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export const switchToWorkspace = (api, workspace) => {
|
|
36
|
+
const session = workspace.selectedSession || selectWorkspaceSession(workspace.sessions);
|
|
37
|
+
if (!session) return errorResult("WORKSPACE_SESSION_UNAVAILABLE", "This workspace has no OpenCode-backed session to open", { workspace: workspace.id });
|
|
38
|
+
return navigateToSession(api, session.opencode_session_id);
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export const createWorkspaceSwitcherFlow = (api, { read = readWorkContextSnapshot } = {}) => {
|
|
42
|
+
const toast = (message, variant = "warning") => api?.ui?.toast?.({ message, variant });
|
|
43
|
+
const open = async () => {
|
|
44
|
+
let result;
|
|
45
|
+
try { result = await read({ projectRoot: projectRoot(api), sessionId: currentSessionId(api) }); }
|
|
46
|
+
catch (error) { result = errorResult(error.code || "STORAGE_ERROR", error.message || "Cannot read work-context storage"); }
|
|
47
|
+
if (!result?.ok) {
|
|
48
|
+
toast(`${result?.error?.code || "STORAGE_ERROR"}: ${result?.error?.message || "Cannot read work-context storage"}`, "error");
|
|
49
|
+
return result;
|
|
50
|
+
}
|
|
51
|
+
const data = result.data || {};
|
|
52
|
+
const workspaces = sortWorkspaceSwitcherEntries(data.workspaces || [], data.currentWorkspace)
|
|
53
|
+
.map((workspace) => ({ ...workspace, selectedSession: selectWorkspaceSession(workspace.sessions) }));
|
|
54
|
+
if (!workspaces.length) {
|
|
55
|
+
toast("No workspaces found");
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
58
|
+
api.ui.dialog.setSize?.("medium");
|
|
59
|
+
api.ui.dialog.replace(() => api.ui.DialogSelect({
|
|
60
|
+
title: "Switch workspace",
|
|
61
|
+
placeholder: "Search workspaces",
|
|
62
|
+
options: workspaces.map((workspace) => ({
|
|
63
|
+
title: `${workspace.id} ${workspace.title}${workspace.id === data.currentWorkspace ? " · current" : ""}`,
|
|
64
|
+
description: workspace.selectedSession
|
|
65
|
+
? `${workspace.status} · ${workspace.selectedSession.state || "unknown"} session`
|
|
66
|
+
: `${workspace.status} · no OpenCode session available`,
|
|
67
|
+
footer: workspace.selectedSession?.opencode_session_id,
|
|
68
|
+
category: workspace.id === data.currentWorkspace ? "Current" : workspace.status,
|
|
69
|
+
disabled: !workspace.selectedSession,
|
|
70
|
+
value: workspace,
|
|
71
|
+
})),
|
|
72
|
+
onSelect: (option) => {
|
|
73
|
+
const switched = switchToWorkspace(api, option.value);
|
|
74
|
+
if (!switched.ok) toast(`${switched.error.code}: ${switched.error.message}`, "error");
|
|
75
|
+
else toast("Workspace session opened", "success");
|
|
76
|
+
},
|
|
77
|
+
}));
|
|
78
|
+
return result;
|
|
79
|
+
};
|
|
80
|
+
return { open };
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
export const openWorkspaceSwitcher = (api, options = {}) => {
|
|
84
|
+
if (typeof api?.ui?.DialogSelect !== "function" || typeof api?.ui?.dialog?.replace !== "function") return false;
|
|
85
|
+
void createWorkspaceSwitcherFlow(api, options).open();
|
|
86
|
+
return true;
|
|
87
|
+
};
|
package/src/core.js
CHANGED
|
@@ -6,13 +6,8 @@ import { ERROR_CODES, fail } from "./errors.js";
|
|
|
6
6
|
import { event, reduceSessions, activeSession, assertActive } from "./sessions.js";
|
|
7
7
|
import { generateProjections, renderSessions } from "./projections.js";
|
|
8
8
|
import { nextKnowledgeId, parseKnowledge, renderKnowledge, validateKnowledgeInput, validateKnowledgeRecords } from "./knowledge.js";
|
|
9
|
+
import { normalizeStageId, normalizeWorkspaceId } from "./identifiers.js";
|
|
9
10
|
|
|
10
|
-
const id = (value, digits) => {
|
|
11
|
-
const normalized = String(value);
|
|
12
|
-
if (!new RegExp(`^\\d{${digits}}$`).test(normalized)) fail(ERROR_CODES.INVALID_ARGUMENT, `Expected ${digits}-digit identifier`);
|
|
13
|
-
return normalized;
|
|
14
|
-
};
|
|
15
|
-
const stageId = (value) => id(String(value).padStart(2, "0"), 2);
|
|
16
11
|
const actor = (options) => options.actor || "OpenCode";
|
|
17
12
|
const activeKnowledge = (records) => records
|
|
18
13
|
.filter((record) => record.status === "active")
|
|
@@ -96,7 +91,7 @@ export class WorkContext {
|
|
|
96
91
|
|
|
97
92
|
listStages(workspace) {
|
|
98
93
|
this.storage.assertNoSymlinks();
|
|
99
|
-
|
|
94
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
100
95
|
const dir = path.join(this.storage.workspaceDir(workspace), "stages");
|
|
101
96
|
if (!fs.existsSync(dir)) fail(ERROR_CODES.NOT_FOUND, "Workspace not found");
|
|
102
97
|
const stages = fs.readdirSync(dir).filter((file) => /^\d{2}\.md$/.test(file)).map((file) => {
|
|
@@ -121,7 +116,7 @@ export class WorkContext {
|
|
|
121
116
|
}
|
|
122
117
|
|
|
123
118
|
finishWorkspace(workspace) {
|
|
124
|
-
|
|
119
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
125
120
|
return this.transact(`workspace-${workspace}`, () => {
|
|
126
121
|
const record = this.storage.readWorkspace(workspace);
|
|
127
122
|
const stages = this.listStages(workspace).data.stages;
|
|
@@ -163,8 +158,7 @@ export class WorkContext {
|
|
|
163
158
|
if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Title is required");
|
|
164
159
|
const requestedWorkspace = options.workspace;
|
|
165
160
|
return this.transact("workspace-create", () => {
|
|
166
|
-
const workspace = requestedWorkspace
|
|
167
|
-
id(workspace, 6);
|
|
161
|
+
const workspace = requestedWorkspace === undefined ? this.nextWorkspace() : normalizeWorkspaceId(requestedWorkspace);
|
|
168
162
|
const now = new Date().toISOString();
|
|
169
163
|
if (fs.existsSync(this.storage.workspaceDir(workspace))) fail(ERROR_CODES.CONFLICT, "Workspace already exists");
|
|
170
164
|
fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
|
|
@@ -202,7 +196,7 @@ export class WorkContext {
|
|
|
202
196
|
}
|
|
203
197
|
|
|
204
198
|
renameWorkspace(workspace, title) {
|
|
205
|
-
|
|
199
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
206
200
|
if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Title is required");
|
|
207
201
|
return this.transact(`workspace-${workspace}`, () => {
|
|
208
202
|
const record = this.storage.readWorkspace(workspace);
|
|
@@ -222,8 +216,8 @@ export class WorkContext {
|
|
|
222
216
|
}
|
|
223
217
|
|
|
224
218
|
startSession(workspace, stage, options = {}) {
|
|
225
|
-
|
|
226
|
-
stage =
|
|
219
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
220
|
+
stage = normalizeStageId(stage);
|
|
227
221
|
const sessionId = options.sessionId || randomUUID();
|
|
228
222
|
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
229
223
|
const stageRecord = this.storage.readStage(workspace, stage);
|
|
@@ -285,10 +279,11 @@ export class WorkContext {
|
|
|
285
279
|
}
|
|
286
280
|
|
|
287
281
|
addStage(workspace, title, options = {}) {
|
|
288
|
-
|
|
282
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
289
283
|
if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Title is required");
|
|
290
|
-
|
|
291
|
-
|
|
284
|
+
if (!Array.isArray(options.dependsOn || [])) fail(ERROR_CODES.INVALID_ARGUMENT, "dependsOn must contain unique stage IDs");
|
|
285
|
+
const dependsOn = (options.dependsOn || []).map(normalizeStageId);
|
|
286
|
+
if (new Set(dependsOn).size !== dependsOn.length) fail(ERROR_CODES.INVALID_ARGUMENT, "dependsOn must contain unique stage IDs");
|
|
292
287
|
return this.transact(`workspace-${workspace}`, () => {
|
|
293
288
|
const stages = this.listStages(workspace).data.stages;
|
|
294
289
|
if (stages.length >= 99) fail(ERROR_CODES.INVALID_STATE, "A workspace cannot contain more than 99 stages");
|
|
@@ -300,13 +295,13 @@ export class WorkContext {
|
|
|
300
295
|
const metadata = { schema: 1, workspace, stage, title: title.trim(), status: "planned", goal: options.goal || title.trim(), ...(prompt ? { prompt } : {}), depends_on: dependsOn, owner: options.owner || actor(this.options), created_at: now, updated_at: now, tracker_links: [] };
|
|
301
296
|
this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), metadata, body(title, options.goal || title, prompt));
|
|
302
297
|
generateProjections(this.storage);
|
|
303
|
-
return this.result({ workspace, stage }, [stage]);
|
|
298
|
+
return this.result({ workspace, stage, status: "planned", session_started: false, resume_required: true }, [stage]);
|
|
304
299
|
});
|
|
305
300
|
}
|
|
306
301
|
|
|
307
302
|
renameStage(workspace, stage, title) {
|
|
308
|
-
|
|
309
|
-
stage =
|
|
303
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
304
|
+
stage = normalizeStageId(stage);
|
|
310
305
|
if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Title is required");
|
|
311
306
|
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
312
307
|
const record = this.storage.readStage(workspace, stage);
|
|
@@ -321,8 +316,8 @@ export class WorkContext {
|
|
|
321
316
|
}
|
|
322
317
|
|
|
323
318
|
updateStage(workspace, stage, description) {
|
|
324
|
-
|
|
325
|
-
stage =
|
|
319
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
320
|
+
stage = normalizeStageId(stage);
|
|
326
321
|
if (!description?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Description is required");
|
|
327
322
|
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
328
323
|
const record = this.storage.readStage(workspace, stage);
|
|
@@ -337,8 +332,8 @@ export class WorkContext {
|
|
|
337
332
|
}
|
|
338
333
|
|
|
339
334
|
updateStagePrompt(workspace, stage, prompt) {
|
|
340
|
-
|
|
341
|
-
stage =
|
|
335
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
336
|
+
stage = normalizeStageId(stage);
|
|
342
337
|
if (!prompt?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Prompt is required");
|
|
343
338
|
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
344
339
|
const record = this.storage.readStage(workspace, stage);
|
|
@@ -353,8 +348,8 @@ export class WorkContext {
|
|
|
353
348
|
}
|
|
354
349
|
|
|
355
350
|
updateStageResult(workspace, stage, result) {
|
|
356
|
-
|
|
357
|
-
stage =
|
|
351
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
352
|
+
stage = normalizeStageId(stage);
|
|
358
353
|
if (!result?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Result is required");
|
|
359
354
|
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
360
355
|
const record = this.storage.readStage(workspace, stage);
|
|
@@ -371,8 +366,8 @@ export class WorkContext {
|
|
|
371
366
|
}
|
|
372
367
|
|
|
373
368
|
archiveStage(workspace, stage) {
|
|
374
|
-
|
|
375
|
-
stage =
|
|
369
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
370
|
+
stage = normalizeStageId(stage);
|
|
376
371
|
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
377
372
|
const record = this.storage.readStage(workspace, stage);
|
|
378
373
|
if (record.data.status === "archived") return this.result({ workspace, stage, status: "archived" }, []);
|
|
@@ -386,7 +381,7 @@ export class WorkContext {
|
|
|
386
381
|
}
|
|
387
382
|
|
|
388
383
|
listKnowledge(workspace) {
|
|
389
|
-
|
|
384
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
390
385
|
this.storage.assertNoSymlinks();
|
|
391
386
|
this.storage.readWorkspace(workspace);
|
|
392
387
|
const text = this.storage.readKnowledge(workspace);
|
|
@@ -394,7 +389,7 @@ export class WorkContext {
|
|
|
394
389
|
}
|
|
395
390
|
|
|
396
391
|
addKnowledge(workspace, input) {
|
|
397
|
-
|
|
392
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
398
393
|
validateKnowledgeInput(input);
|
|
399
394
|
return this.transact(`workspace-${workspace}`, () => {
|
|
400
395
|
const records = this.listKnowledge(workspace).data;
|
|
@@ -406,7 +401,7 @@ export class WorkContext {
|
|
|
406
401
|
}
|
|
407
402
|
|
|
408
403
|
updateKnowledge(workspace, knowledgeId, input) {
|
|
409
|
-
|
|
404
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
410
405
|
validateKnowledgeInput(input, true);
|
|
411
406
|
return this.transact(`workspace-${workspace}`, () => {
|
|
412
407
|
const records = this.listKnowledge(workspace).data;
|
|
@@ -427,10 +422,10 @@ export class WorkContext {
|
|
|
427
422
|
}
|
|
428
423
|
|
|
429
424
|
linkIssue(workspace, url, stage = null) {
|
|
430
|
-
const normalizedWorkspace =
|
|
431
|
-
const normalizedStage = stage ?
|
|
425
|
+
const normalizedWorkspace = normalizeWorkspaceId(workspace);
|
|
426
|
+
const normalizedStage = stage === null || stage === undefined ? null : normalizeStageId(stage);
|
|
432
427
|
const parsed = parseIssue(url);
|
|
433
|
-
return this.transact(`link-${
|
|
428
|
+
return this.transact(`link-${normalizedWorkspace}-${normalizedStage || "workspace"}`, () => {
|
|
434
429
|
const file = normalizedStage ? this.storage.stageFile(normalizedWorkspace, normalizedStage) : this.storage.workspaceFile(normalizedWorkspace);
|
|
435
430
|
const current = normalizedStage ? this.storage.readStage(normalizedWorkspace, normalizedStage) : this.storage.readWorkspace(normalizedWorkspace);
|
|
436
431
|
const links = current.data.tracker_links || [];
|
|
@@ -446,7 +441,8 @@ export class WorkContext {
|
|
|
446
441
|
|
|
447
442
|
renameSession(workspace, stage, sessionId, summary) {
|
|
448
443
|
if (!summary?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Summary is required");
|
|
449
|
-
|
|
444
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
445
|
+
stage = normalizeStageId(stage);
|
|
450
446
|
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
451
447
|
const session = assertActive(this.storage.readEvents(), workspace, stage, sessionId);
|
|
452
448
|
if (session.summary === summary.trim()) return this.result({ session_id: sessionId, summary: summary.trim() }, []);
|
|
@@ -456,7 +452,8 @@ export class WorkContext {
|
|
|
456
452
|
}
|
|
457
453
|
|
|
458
454
|
closeSession(workspace, stage, sessionId, reason = "closed", state = "closed") {
|
|
459
|
-
|
|
455
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
456
|
+
stage = normalizeStageId(stage);
|
|
460
457
|
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
461
458
|
const session = assertActive(this.storage.readEvents(), workspace, stage, sessionId);
|
|
462
459
|
this.writeEvents([event(`session.${state}`, workspace, stage, session.ordinal, sessionId, actor(this.options), { reason })]);
|
|
@@ -465,8 +462,8 @@ export class WorkContext {
|
|
|
465
462
|
}
|
|
466
463
|
|
|
467
464
|
forceCloseSession(workspace, stage, sessionId, reason, confirmation) {
|
|
468
|
-
|
|
469
|
-
stage =
|
|
465
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
466
|
+
stage = normalizeStageId(stage);
|
|
470
467
|
if (!sessionId?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Session ID is required");
|
|
471
468
|
if (!reason?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Force-close reason is required");
|
|
472
469
|
if (confirmation !== "FORCE_CLOSE") fail(ERROR_CODES.CONFIRMATION_REQUIRED, "Force close requires confirmation FORCE_CLOSE", { expected: "FORCE_CLOSE" });
|
|
@@ -484,7 +481,8 @@ export class WorkContext {
|
|
|
484
481
|
}
|
|
485
482
|
|
|
486
483
|
handoff(workspace, stage, sessionId, options = {}) {
|
|
487
|
-
|
|
484
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
485
|
+
stage = normalizeStageId(stage);
|
|
488
486
|
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
489
487
|
const session = assertActive(this.storage.readEvents(), workspace, stage, sessionId);
|
|
490
488
|
this.writeEvents([event("session.handed_off", workspace, stage, session.ordinal, sessionId, actor(this.options), { reason: options.reason || "handoff" })]);
|
|
@@ -498,7 +496,8 @@ export class WorkContext {
|
|
|
498
496
|
}
|
|
499
497
|
|
|
500
498
|
finish(workspace, stage, sessionId, options = {}) {
|
|
501
|
-
|
|
499
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
500
|
+
stage = normalizeStageId(stage);
|
|
502
501
|
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
503
502
|
const events = this.storage.readEvents();
|
|
504
503
|
const current = this.storage.readStage(workspace, stage);
|
|
@@ -518,10 +517,10 @@ export class WorkContext {
|
|
|
518
517
|
current.data.updated_at = new Date().toISOString();
|
|
519
518
|
this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), current.data, `${current.body}\n\n## Result\n\n${options.result || "Stage completed."}`);
|
|
520
519
|
generateProjections(this.storage);
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
520
|
+
const promptReview = this.listStages(workspace).data.stages
|
|
521
|
+
.filter((item) => Number(item.stage) > Number(stage) && !["completed", "archived"].includes(item.status))
|
|
522
|
+
.map(({ stage: id, title, description, prompt, status }) => ({ stage: id, title, description, prompt: prompt || null, status }));
|
|
523
|
+
const data = { session_id: sessionId, workspace, stage, state: "closed", status: "completed", next_stage_started: false, knowledge_review: knowledgeReview, knowledge_entries: knowledgeEntries.length, active_knowledge_entries: activeKnowledge(knowledgeEntries).length, prompt_review: promptReview };
|
|
525
524
|
const incompleteStages = this.listStages(workspace).data.stages.filter((item) => !["completed", "archived"].includes(item.status));
|
|
526
525
|
const next = incompleteStages.length ? null : {
|
|
527
526
|
action: "workspace_finish",
|
|
@@ -534,7 +533,7 @@ export class WorkContext {
|
|
|
534
533
|
}
|
|
535
534
|
|
|
536
535
|
help(command = "") {
|
|
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
|
|
536
|
+
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; explicit workspace and stage positions accept padded or unpadded positive integer IDs and structured results remain canonical; zero, signs, decimals, whitespace, and overlong identifiers are invalid; 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 local prompt and only creates a planned stage; entering any added stage requires an explicit resume in a new OpenCode session; 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 closes only the current stage session and returns downstream stages for informational prompt review without starting one; 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." }, []);
|
|
538
537
|
}
|
|
539
538
|
|
|
540
539
|
result(data, changed, next = null) {
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ERROR_CODES, fail } from "./errors.js";
|
|
2
|
+
|
|
3
|
+
const normalizeIdentifier = (value, { name, digits }) => {
|
|
4
|
+
const input = typeof value === "string" ? value : "";
|
|
5
|
+
if (!new RegExp(`^\\d{1,${digits}}$`).test(input) || Number(input) === 0) {
|
|
6
|
+
fail(ERROR_CODES.INVALID_ARGUMENT, `${name} ID must be an integer from 1 to ${"9".repeat(digits)}`);
|
|
7
|
+
}
|
|
8
|
+
return input.padStart(digits, "0");
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export const normalizeWorkspaceId = (value) => normalizeIdentifier(value, { name: "Workspace", digits: 6 });
|
|
12
|
+
export const normalizeStageId = (value) => normalizeIdentifier(value, { name: "Stage", digits: 2 });
|
package/src/index.js
CHANGED
package/src/opencode-adapter.js
CHANGED
|
@@ -12,6 +12,6 @@ export function titleFor(context, workspace, stage, sessionId, knownSession = nu
|
|
|
12
12
|
if (!current) return null;
|
|
13
13
|
const meta = context.storage.readWorkspace(workspace).data;
|
|
14
14
|
const stageMeta = context.storage.readStage(workspace, stage).data;
|
|
15
|
-
return renderTitle({ workspace,
|
|
15
|
+
return renderTitle({ workspace, stageTitle: stageMeta.title, stage, ordinal: current.ordinal, state: current.state, trackerLinks: stageMeta.tracker_links?.length ? stageMeta.tracker_links : meta.tracker_links, issuePrefix: context.storage.config.title?.issue_prefix || "short" });
|
|
16
16
|
}
|
|
17
17
|
export const packageRoot = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
package/src/stages-renderer.js
CHANGED
|
@@ -12,6 +12,8 @@ export function renderStagesPanel(result) {
|
|
|
12
12
|
if (!snapshot.workspace) return `work-context stages\n(no workspace for this session)${result.stale ? `\n! stale: ${result.error?.code || "STORAGE_ERROR"}` : ""}`;
|
|
13
13
|
|
|
14
14
|
const lines = [
|
|
15
|
+
snapshot.workspace.title,
|
|
16
|
+
"",
|
|
15
17
|
`Stages · ${snapshot.workspace.status}`,
|
|
16
18
|
];
|
|
17
19
|
for (const stage of snapshot.stages) {
|
package/src/title.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export function renderTitle({ workspace,
|
|
1
|
+
export function renderTitle({ workspace, stageTitle, stage, ordinal, state = "active", trackerLinks = [], issuePrefix = "short" }) {
|
|
2
2
|
const link = trackerLinks[0]; let prefix = "";
|
|
3
3
|
if (link && issuePrefix !== "none") {
|
|
4
4
|
const identifier = link.key || link.iid;
|
|
@@ -6,5 +6,6 @@ export function renderTitle({ workspace, workspaceTitle, stage, ordinal, state =
|
|
|
6
6
|
prefix = issuePrefix === "full" ? `${link.project}#${identifier} | ` : `${short} | `;
|
|
7
7
|
}
|
|
8
8
|
const suffix = state === "active" ? "" : ` (${state})`;
|
|
9
|
-
|
|
9
|
+
const description = (stageTitle || stage).replace(/[\r\n|]+/g, " ").trim().slice(0, 80);
|
|
10
|
+
return `${description}\n${prefix}${workspace} ${stage}/${String(ordinal).padStart(2, "0")}${suffix}`;
|
|
10
11
|
}
|
package/src/tool-definitions.js
CHANGED
|
@@ -2,6 +2,7 @@ import { tool } from "@opencode-ai/plugin";
|
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
3
|
import { contextFor, titleFor } from "../src/opencode-adapter.js";
|
|
4
4
|
import { fail, ERROR_CODES } from "../src/errors.js";
|
|
5
|
+
import { normalizeStageId, normalizeWorkspaceId } from "../src/identifiers.js";
|
|
5
6
|
|
|
6
7
|
const run = (fn) => async (args, context) => {
|
|
7
8
|
try {
|
|
@@ -12,18 +13,18 @@ const run = (fn) => async (args, context) => {
|
|
|
12
13
|
return { output: JSON.stringify({ ok: false, error: { code: error.code || "STORAGE_ERROR", message: error.message, details: error.details || {} } }), metadata: { code: error.code || "STORAGE_ERROR" } };
|
|
13
14
|
}
|
|
14
15
|
};
|
|
15
|
-
const common = { workspace: tool.schema.string()
|
|
16
|
-
const contextualStage = { workspace: tool.schema.string().
|
|
16
|
+
const common = { workspace: tool.schema.string(), stage: tool.schema.string() };
|
|
17
|
+
const contextualStage = { workspace: tool.schema.string().optional(), stage: tool.schema.string().optional() };
|
|
17
18
|
const sessionFromContext = (ctx, workspace) => ctx.sessionByOpenCodeId(ctx.options.sessionId, workspace || null, null, null)
|
|
18
19
|
|| (!workspace ? ctx.sessionById(ctx.options.sessionId) : null);
|
|
19
20
|
const workspaceFromSession = (ctx, workspace) => {
|
|
20
|
-
if (workspace) return workspace;
|
|
21
|
+
if (workspace !== undefined) return normalizeWorkspaceId(workspace);
|
|
21
22
|
const session = sessionFromContext(ctx);
|
|
22
23
|
if (!session) fail(ERROR_CODES.INVALID_ARGUMENT, "Workspace is required when the current session is not associated with a workspace");
|
|
23
24
|
return session.workspace;
|
|
24
25
|
};
|
|
25
26
|
const stageFromSession = (ctx, workspace, stage) => {
|
|
26
|
-
if (stage) return stage;
|
|
27
|
+
if (stage !== undefined) return normalizeStageId(stage);
|
|
27
28
|
const session = sessionFromContext(ctx, workspace);
|
|
28
29
|
if (!session) fail(ERROR_CODES.STAGE_CONTEXT_REQUIRED, "Stage is required when the current session is not associated with a stage");
|
|
29
30
|
return session.stage;
|
|
@@ -32,33 +33,20 @@ const sessionFor = (ctx, oc, workspace, stage) => ctx.sessionById(oc.sessionID)?
|
|
|
32
33
|
&& ctx.sessionById(oc.sessionID)?.stage === stage
|
|
33
34
|
? oc.sessionID
|
|
34
35
|
: ctx.sessionByOpenCodeId(oc.sessionID, workspace, stage)?.session_id || oc.sessionID;
|
|
35
|
-
const addStageFromTool = (ctx, args
|
|
36
|
+
const addStageFromTool = (ctx, args) => {
|
|
36
37
|
const workspace = workspaceFromSession(ctx, args.workspace);
|
|
37
|
-
|
|
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
|
-
};
|
|
38
|
+
return ctx.addStage(workspace, args.title, { goal: args.goal, prompt: args.prompt, dependsOn: args.dependsOn });
|
|
51
39
|
};
|
|
52
40
|
export const work_context_list_workspaces = tool({ description: "List work-context workspaces.", args: {}, execute: run((ctx) => ctx.listWorkspaces()) });
|
|
53
|
-
export const work_context_workspace_list = tool({ description: "List a workspace with stage descriptions and sessions.", args: { workspace: tool.schema.string()
|
|
54
|
-
export const work_context_rename_workspace = tool({ description: "Rename a workspace.", args: { workspace: tool.schema.string()
|
|
55
|
-
export const work_context_workspace_finish = tool({ description: "Finish a workspace after all stages are completed.", args: { workspace: tool.schema.string()
|
|
41
|
+
export const work_context_workspace_list = tool({ description: "List a workspace with stage descriptions and sessions.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.listStages(a.workspace)) });
|
|
42
|
+
export const work_context_rename_workspace = tool({ description: "Rename a workspace.", args: { workspace: tool.schema.string(), title: tool.schema.string() }, execute: run((ctx, a) => ctx.renameWorkspace(a.workspace, a.title)) });
|
|
43
|
+
export const work_context_workspace_finish = tool({ description: "Finish a workspace after all stages are completed.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.finishWorkspace(a.workspace)) });
|
|
56
44
|
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
45
|
const currentSession = ctx.sessionByOpenCodeId(oc.sessionID);
|
|
58
46
|
return ctx.createWorkspace(a.title, { sessionId: randomUUID(), ...(currentSession ? {} : { opencodeSessionId: oc.sessionID }) });
|
|
59
47
|
}) });
|
|
60
48
|
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
|
|
49
|
+
export const work_context_add_stage = tool({ description: "Add a planned stage without starting it; use resume explicitly in a new OpenCode session to enter the stage.", args: { workspace: tool.schema.string().optional(), title: tool.schema.string(), goal: tool.schema.string().optional(), prompt: tool.schema.string().optional(), dependsOn: tool.schema.array(tool.schema.string()).optional() }, execute: run(addStageFromTool) });
|
|
62
50
|
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
51
|
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
52
|
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); }) });
|
|
@@ -67,7 +55,7 @@ export const work_context_archive_stage = tool({ description: "Archive a stage w
|
|
|
67
55
|
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)) });
|
|
68
56
|
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
57
|
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)); }) });
|
|
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()
|
|
58
|
+
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(), stage: tool.schema.string(), 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)) });
|
|
71
59
|
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
60
|
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
61
|
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 }); }) });
|