opencode-work-context 0.1.10 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,8 +3,8 @@
3
3
  Keep the context of a task between OpenCode sessions.
4
4
 
5
5
  Create one workspace for one task, split it into stages, and return to the
6
- exact stage where you stopped. The optional sidebar shows the current task and
7
- its progress at a glance.
6
+ exact stage where you stopped. The optional sidebar and modal show the current
7
+ task and its progress at a glance.
8
8
 
9
9
  ![OpenCode Work Context stages sidebar](docs/assets/opencode-work-context.png)
10
10
 
@@ -14,6 +14,12 @@ 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,6 +80,25 @@ Useful commands:
68
80
  /wc stage finish 000001 02
69
81
  ```
70
82
 
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:
87
+
88
+ ```text
89
+ /wc workspace list 000004
90
+ /wc workspace list 4
91
+ /wc resume 000004 02
92
+ /wc resume 4 2
93
+ /wc stage handoff 000004 02
94
+ /wc stage finish 4 2
95
+ ```
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
+
71
102
  ## Install
72
103
 
73
104
  Run from the root of a standalone OpenCode project:
@@ -85,7 +116,7 @@ with a new `package.json` when neither exists. Package files, lockfiles, and
85
116
  `.gitignore` always belong to the project root.
86
117
 
87
118
  The installer ensures that the dependency-root package uses `"type": "module"`
88
- and generates an ESM plugin loader. OpenCode loads local plugins as JavaScript
119
+ and generates ESM server and TUI loaders. OpenCode loads local plugins as JavaScript
89
120
  modules; keeping the generated `.js` integration path ESM avoids a CommonJS
90
121
  interop failure before custom tools are registered.
91
122
  It does not create a workspace. Start one explicitly with `/wc create "Title"`.
@@ -94,6 +125,30 @@ Use `--force` to replace a conflicting package-owned generated file or package
94
125
  version. Without it, existing files are never silently overwritten. Re-running
95
126
  with unchanged files is safe and idempotent.
96
127
 
128
+ ## Update
129
+
130
+ Run the update from the root of the OpenCode project that has the plugin
131
+ installed:
132
+
133
+ ```sh
134
+ npx --yes opencode-work-context@latest init --force
135
+ ```
136
+
137
+ This installs the latest package version as an exact devDependency and refreshes
138
+ the package-owned server and TUI loaders. It preserves the project's
139
+ `.work-context` data. Check the installed version with:
140
+
141
+ ```sh
142
+ npm ls opencode-work-context --depth=0
143
+ ```
144
+
145
+ Restart OpenCode after updating so it reloads the new server plugin, TUI loader,
146
+ keymap, and modal code. A restart is required after changing package code or
147
+ `.opencode/tui.json`; lifecycle data changes are picked up by the existing
148
+ refresh mechanisms.
149
+ Use a specific version instead of `latest` when you need a pinned upgrade, for
150
+ example `npx --yes opencode-work-context@0.1.10 init --force`.
151
+
97
152
  Generated files:
98
153
 
99
154
  - `.work-context/config.yaml` for filesystem configuration;
@@ -104,7 +159,7 @@ Generated files:
104
159
  - `<workspace>/KNOWLEDGE.md` is the canonical durable knowledge ledger and is
105
160
  created on the first explicit knowledge operation.
106
161
 
107
- The optional read-only stages panel is a separate TUI plugin. `init` installs a
162
+ The optional stages panel, action modal, and stage switcher are a separate TUI plugin. `init` installs a
108
163
  project-local loader outside OpenCode's server-plugin autoscan at
109
164
  `.opencode/tui-plugins/work-context-stages.js` and enables it in `.opencode/tui.json`:
110
165
 
@@ -118,21 +173,58 @@ Enable that loader explicitly in `.opencode/tui.json`:
118
173
  { "$schema": "https://opencode.ai/tui.json", "plugin": ["./tui-plugins/work-context-stages.js"] }
119
174
  ```
120
175
 
121
- The package keeps the
122
- existing `opencode-work-context/plugin` server export unchanged and exposes the
123
- panel as `opencode-work-context/tui`. The panel only reads canonical storage via
124
- `WorkContext.openExisting`; it does not create `.work-context`, call lifecycle
125
- tools, or modify Markdown/JSONL projections. Hosts without the TUI plugin API
126
- continue to load the server plugin and its tools normally.
127
-
128
- Tools are registered by the installed plugin and are not copied into the project.
176
+ The package keeps the existing `opencode-work-context/plugin` server export and
177
+ also exposes the explicit server entry as `opencode-work-context/server`.
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
+ `Ctrl+Alt+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+Alt+W`, remove or change the conflicting binding, or
203
+ disable this TUI loader; the package does not use an internal keymap fallback.
204
+
205
+ Tools are registered by the installed server export and are not copied into the
206
+ project. Core and storage remain in the installed package; projects should not
207
+ copy `src/` or `tools/`. `.work-context` Markdown, JSONL, `INDEX.md`, and
208
+ `SESSIONS.md` are generated projections and must never be edited manually.
129
209
  Tracker links support GitLab issues (`/-/issues/<number>`), GitHub issues
130
210
  (`/issues/<number>`), and Jira issues (`/browse/KEY-123`). They are URL-based
131
211
  references only; the plugin does not call provider APIs or synchronize issue
132
212
  metadata.
133
213
  Knowledge operations are explicit: list, add, update, and supersede. Finishing a
134
- stage automatically validates the Knowledge Base by default (`knowledgeReview=auto`);
135
- the legacy `added` and `none` modes remain accepted.
214
+ stage always validates the Knowledge Base and reports its total and active entry
215
+ counts. Before finishing, persist new durable findings, update changed entries,
216
+ supersede obsolete entries, or explicitly use `knowledgeReview=none` when no
217
+ durable findings were produced. The default `knowledgeReview=auto` remains
218
+ accepted, and `knowledgeReview=added` records that the ledger was changed.
219
+ Every stage start/resume includes all active entries in
220
+ `resume.context.workspace_knowledge`. Agents should treat this as established
221
+ workspace-wide context and avoid repeating earlier analysis unless an entry is
222
+ incomplete, contradicted, or requires verification. Superseded entries and full
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.
136
228
  Finish a workspace explicitly with `/wc workspace finish <workspace>`; it is
137
229
  accepted only after every stage is `completed`. Use `/wc workspace list <workspace>`
138
230
  to list stages with their descriptions. Workspace titles can be changed with
@@ -143,6 +235,37 @@ If the host `opencode.json` restricts `experimental.primary_tools`, add the
143
235
  registered `work_context_*` tool names to that allowlist; the installer does not
144
236
  rewrite project-specific agent policy.
145
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
+
146
269
  ## License
147
270
 
148
271
  MIT. Copyright (c) 2026 Nikita Mosiyash.
@@ -18,8 +18,13 @@ const dependencyRoot = fs.existsSync(path.join(projectRoot, "package.json"))
18
18
  const dependencyManifestFile = path.join(dependencyRoot, "package.json");
19
19
  let dependencyManifest = {};
20
20
  try { dependencyManifest = JSON.parse(fs.readFileSync(dependencyManifestFile, "utf8")); } catch {}
21
- const pluginLoader = `export { default } from "${packageManifest.name}/plugin";\n`;
22
- const tuiLoader = `import { createSignal } from "solid-js";
21
+ const pluginLoader = `// Server tools and lifecycle hooks stay in the installed package.
22
+ import serverPlugin from "${packageManifest.name}/server";
23
+
24
+ export default serverPlugin.server;
25
+ `;
26
+ const tuiLoader = `// TUI integration stays in the installed package; do not copy src/ or tools.
27
+ import { createSignal } from "solid-js";
23
28
  import { jsx } from "@opentui/solid/jsx-runtime";
24
29
  import plugin from "${packageManifest.name}/tui";
25
30
 
@@ -36,6 +41,7 @@ export default {
36
41
  const tuiConfig = JSON.stringify({
37
42
  $schema: "https://opencode.ai/tui.json",
38
43
  plugin: ["./tui-plugins/work-context-stages.js"],
44
+ keybinds: { leader: "ctrl+alt+w" },
39
45
  }, null, 2) + "\n";
40
46
  const command = fs.readFileSync(path.join(packageRoot, "commands", "wc.md"), "utf8");
41
47
  const generated = new Map([
package/commands/wc.md CHANGED
@@ -21,10 +21,11 @@ Use these exact tool mappings; do not invent shortened tool names:
21
21
  - `workspace finish <workspace>` -> `work_context_workspace_finish`
22
22
  - `resume <workspace> <stage>` -> `work_context_start_session`
23
23
  - `stage force-close <workspace> <stage> <sessionId> "reason" FORCE_CLOSE` -> `work_context_force_close_session`
24
- - `stage add [<workspace>] ...` -> `work_context_add_stage` (optional `prompt`; detailed prompt is expected for stages created from planning)
24
+ - `stage add [<workspace>] ...` -> `work_context_add_stage` (optional `prompt`; a detailed local prompt is expected for stages created from planning, while shared context belongs in workspace knowledge)
25
25
  - `stage rename [<workspace>] [<stage>] "title"` -> `work_context_rename_stage`
26
26
  - `stage update [<workspace>] [<stage>] "description"` -> `work_context_update_stage`
27
27
  - `stage update-prompt [<workspace>] [<stage>] "prompt"` -> `work_context_update_stage_prompt`
28
+ - `stage update-result [<workspace>] [<stage>] "result"` -> `work_context_update_stage_result`
28
29
  - `stage archive [<workspace>] [<stage>]` -> `work_context_archive_stage`
29
30
  - `stage handoff [<workspace>] [<stage>]` -> `work_context_handoff_stage`
30
31
  - `stage abandon [<workspace>] [<stage>]` -> `work_context_abandon_stage`
@@ -44,6 +45,7 @@ Supported syntax:
44
45
  - `stage rename [<workspace>] [<stage>] "title"`
45
46
  - `stage update [<workspace>] [<stage>] "description"`
46
47
  - `stage update-prompt [<workspace>] [<stage>] "prompt"`
48
+ - `stage update-result [<workspace>] [<stage>] "result"`
47
49
  - `stage archive [<workspace>] [<stage>]`
48
50
  - `stage handoff [<workspace>] [<stage>]`
49
51
  - `stage abandon [<workspace>] [<stage>]`
@@ -54,14 +56,21 @@ Supported syntax:
54
56
  - `stage abandon [<workspace>] <stage>`
55
57
  - `stage finish [<workspace>] <stage>` automatically reviews the Knowledge Base (`auto` by default)
56
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
61
+ - `stage update-result` replaces an existing result and does not create a result for an unfinished stage
57
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
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
58
64
  - on every subsequent resume, report the context and wait for explicit user confirmation; do not automatically continue implementation
59
65
  - when `resume.next_action` is `await_confirmation`, do not inspect or modify application code until the user confirms
60
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
61
- - `stage add` enters the newly created stage and returns its actionable `resume` context when the current OpenCode session is not yet in a workspace; otherwise it only creates the planned stage
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
62
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
63
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
64
- - `stage finish` returns downstream unfinished stages whose prompts should be reviewed after new findings
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
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
65
74
  - `knowledge list|add|update|supersede <workspace> ...`
66
75
 
67
76
  Arguments: $ARGUMENTS
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-work-context",
3
3
  "type": "module",
4
- "version": "0.1.10",
4
+ "version": "0.1.12",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -29,6 +29,8 @@
29
29
  "opencode-work-context": "bin/opencode-work-context.js"
30
30
  },
31
31
  "scripts": {
32
+ "check:language": "node scripts/check-repository-language.js",
33
+ "prepublishOnly": "npm run check:language",
32
34
  "test": "node --test",
33
35
  "test:integration": "node --test test/integration/*.test.js",
34
36
  "test:tui": "OPENCODE_TUI_SMOKE=1 bun --conditions=browser test test/stages-tui.test.js"
@@ -52,7 +54,7 @@
52
54
  "./adapter": "./src/opencode-adapter.js",
53
55
  "./plugin": "./plugin/work-context.js",
54
56
  "./server": "./plugin/server.js",
55
- "./tui": "./plugin/stages-tui.js",
57
+ "./tui": "./plugin/tui.js",
56
58
  "./tools/*": "./tools/*.js"
57
59
  }
58
60
  }
@@ -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
+ };