opencode-work-context 0.4.12 → 0.4.14

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
@@ -138,6 +138,57 @@ stage. Use explicit workspace and stage positions for unpadded workspace IDs.
138
138
 
139
139
  ## Install
140
140
 
141
+ ### Managed Package Activation
142
+
143
+ For one managed package installation shared by OpenCode while keeping activation
144
+ explicit per project, run this in each project that should use work-context:
145
+
146
+ ```sh
147
+ npx opencode-work-context activate
148
+ ```
149
+
150
+ `activate` writes `.opencode/opencode.json` with the supported package plugin
151
+ entry `opencode-work-context` and installs the `/wc` command contract. OpenCode
152
+ resolves, caches, and updates configured package plugins through its supported
153
+ plugin manager; the project does not import an npm-global path, create a local
154
+ `node_modules`, or create `.work-context` data merely by being activated. The
155
+ package's server and optional TUI parts are loaded together by OpenCode, so this
156
+ also works on server-only hosts.
157
+
158
+ Activation is opt-in. Projects without this entry stay inactive. If a machine
159
+ administrator or user has configured the package globally, a project can add
160
+ the explicit opt-out entry with:
161
+
162
+ ```sh
163
+ npx opencode-work-context deactivate
164
+ ```
165
+
166
+ This appends `"-work-context"` to the project plugin list, which OpenCode
167
+ processes after global configuration. `activate` and `deactivate` merge a plain
168
+ JSON `.opencode/opencode.json` plugin array without replacing other settings.
169
+ For an existing JSONC configuration, add the equivalent entry manually:
170
+
171
+ ```jsonc
172
+ {
173
+ "plugins": ["opencode-work-context"] // or "-work-context" to opt out
174
+ }
175
+ ```
176
+
177
+ Restart OpenCode after changing plugin configuration. OpenCode checks unpinned
178
+ configured packages through its managed plugin flow; use the OpenCode plugin
179
+ management command available in your installed OpenCode version when you need
180
+ to refresh it immediately. Pinned plugin entries are intentionally not updated
181
+ automatically.
182
+
183
+ Do not activate the managed package in a project already configured through
184
+ the local installer below. The command refuses that combination so server tools
185
+ and TUI registrations cannot be duplicated. To migrate a local project, remove
186
+ the generated local server loader, TUI loader, and its `tui.json` entry, then
187
+ run `activate`; its existing `.work-context` data remains intact. To return to
188
+ the pinned local workflow, remove the managed package entry and run `init`.
189
+
190
+ ### Pinned Local Installation
191
+
141
192
  Run from the root of a standalone OpenCode project:
142
193
 
143
194
  ```sh
@@ -157,6 +208,9 @@ and generates ESM server and TUI loaders. OpenCode loads local plugins as JavaSc
157
208
  modules; keeping the generated `.js` integration path ESM avoids a CommonJS
158
209
  interop failure before custom tools are registered.
159
210
  It does not create a workspace. Start one explicitly with `/wc create "Title"`.
211
+ This local setup takes precedence by remaining the only configured integration
212
+ for its project, and it preserves the exact version in the project's package
213
+ manifest.
160
214
 
161
215
  Use `--force` to replace a conflicting package-owned generated file or package
162
216
  version. Without it, existing files are never silently overwritten. Re-running
@@ -79,12 +79,65 @@ function parseArgs(args) {
79
79
  if (unknown.length) return fail(`unknown option: ${unknown[0]}`);
80
80
  return { syncCommand: true, force: args.includes("--force") };
81
81
  }
82
- if (args[0] !== "init") return fail("usage: opencode-work-context init [--force] | sync-command");
82
+ if (args[0] === "activate" || args[0] === "deactivate") {
83
+ const unknown = args.slice(1).filter((arg) => arg !== "--force");
84
+ if (unknown.length) return fail(`unknown option: ${unknown[0]}`);
85
+ return { activation: args[0] === "activate", force: args.includes("--force") };
86
+ }
87
+ if (args[0] !== "init") return fail("usage: opencode-work-context init [--force] | activate [--force] | deactivate [--force] | sync-command");
83
88
  const unknown = args.slice(1).filter((arg) => arg !== "--force");
84
89
  if (unknown.length) return fail(`unknown option: ${unknown[0]}`);
85
90
  return { force: args.includes("--force") };
86
91
  }
87
92
 
93
+ function activate(enabled, force) {
94
+ const localLoader = path.join(projectRoot, ".opencode", "plugins", "work-context.js");
95
+ if (exists(localLoader)) {
96
+ fail("project-local integration is already active; keep using it or remove its generated loaders before activating the managed package");
97
+ return;
98
+ }
99
+ const configRelative = path.join(".opencode", "opencode.json");
100
+ const configFile = path.join(projectRoot, configRelative);
101
+ const jsoncFile = path.join(projectRoot, ".opencode", "opencode.jsonc");
102
+ if (exists(jsoncFile)) {
103
+ fail("cannot update .opencode/opencode.jsonc; add the plugin entry manually or use .opencode/opencode.json");
104
+ return;
105
+ }
106
+ let config = { $schema: "https://opencode.ai/config.json" };
107
+ if (exists(configFile)) {
108
+ if (hasSymlinkParent(configFile) || !fs.lstatSync(configFile).isFile() || fs.lstatSync(configFile).isSymbolicLink()) {
109
+ fail(`refusing to overwrite non-regular file: ${configRelative}`);
110
+ return;
111
+ }
112
+ try { config = JSON.parse(fs.readFileSync(configFile, "utf8")); }
113
+ catch { fail(`cannot update invalid JSON: ${configRelative}`); return; }
114
+ if (!config || typeof config !== "object" || Array.isArray(config) || (config.plugins !== undefined && !Array.isArray(config.plugins))) {
115
+ fail(`cannot update unsupported configuration: ${configRelative}`);
116
+ return;
117
+ }
118
+ }
119
+ const entry = enabled ? packageManifest.name : "-work-context";
120
+ config.plugins = [...(config.plugins || []).filter((item) => item !== entry), entry];
121
+ const files = new Map([
122
+ [configRelative, JSON.stringify(config, null, 2) + "\n"],
123
+ [path.join(".opencode", "commands", "wc.md"), command],
124
+ ]);
125
+ const conflicts = [...files].flatMap(([relative, content]) => {
126
+ const file = path.join(projectRoot, relative);
127
+ if (hasSymlinkParent(file) || (exists(file) && (!fs.lstatSync(file).isFile() || fs.lstatSync(file).isSymbolicLink()))) return [relative];
128
+ return relative !== configRelative && !force && exists(file) && fs.readFileSync(file, "utf8") !== content ? [relative] : [];
129
+ });
130
+ if (conflicts.length) {
131
+ fail(`refusing to overwrite existing files: ${conflicts.join(", ")}; rerun with --force`);
132
+ return;
133
+ }
134
+ for (const [relative, content] of files) {
135
+ const file = path.join(projectRoot, relative);
136
+ if (!exists(file) || fs.readFileSync(file, "utf8") !== content) writeAtomic(file, content);
137
+ }
138
+ console.log(`${enabled ? "Activated" : "Deactivated"} opencode-work-context for this project.`);
139
+ }
140
+
88
141
  function syncCommandProjection(force) {
89
142
  const relative = ".opencode/commands/wc.md";
90
143
  const file = path.join(projectRoot, relative);
@@ -301,6 +354,8 @@ if (options?.syncCommand) {
301
354
  catch (error) { fail(`command sync failed: ${error.message}`); }
302
355
  finally { releaseInitLock(initLock); }
303
356
  }
357
+ } else if (options?.activation !== undefined) {
358
+ activate(options.activation, options.force);
304
359
  } else if (options) {
305
360
  const initLock = acquireInitLock();
306
361
  if (initLock.failed) process.exitCode = 1;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-work-context",
3
3
  "type": "module",
4
- "version": "0.4.12",
4
+ "version": "0.4.14",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -272,25 +272,29 @@ const currentSessionId = (api) => api?.route?.current?.name === "session"
272
272
  : undefined;
273
273
  const linkedSessionIds = (snapshot) => new Set((snapshot?.data?.workspaces || []).flatMap((workspace) =>
274
274
  (workspace.sessions || []).map((session) => session.opencode_session_id).filter(Boolean)));
275
+ const visibleSessionRecords = (snapshot, sessionId) => (snapshot?.workspaces || []).flatMap((workspace) => {
276
+ const visibleStages = new Set((workspace.stages || [])
277
+ .filter((stage) => stage.status !== "archived")
278
+ .map((stage) => stage.id));
279
+ return (workspace.sessions || [])
280
+ .filter((session) => session.opencode_session_id === sessionId && visibleStages.has(session.stage))
281
+ .map((session) => ({ workspace, session }));
282
+ });
275
283
  const notificationContexts = (snapshot, sessionId, reason) => {
276
284
  const contexts = [];
277
285
  const seen = new Set();
278
- for (const workspace of snapshot?.workspaces || []) {
279
- for (const session of workspace.sessions || []) {
280
- if (session.opencode_session_id !== sessionId || !session.stage) continue;
281
- const key = `${workspace.id}:${session.stage}`;
282
- if (seen.has(key)) continue;
283
- const stage = (workspace.stages || []).find((item) => item.id === session.stage);
284
- if (!stage) continue;
285
- seen.add(key);
286
- contexts.push({
287
- workspaceId: workspace.id,
288
- workspaceTitle: workspace.title,
289
- stageId: stage.id,
290
- stageTitle: stage.title,
291
- reason,
292
- });
293
- }
286
+ for (const { workspace, session } of visibleSessionRecords(snapshot, sessionId)) {
287
+ const key = `${workspace.id}:${session.stage}`;
288
+ if (seen.has(key)) continue;
289
+ const stage = workspace.stages.find((item) => item.id === session.stage);
290
+ seen.add(key);
291
+ contexts.push({
292
+ workspaceId: workspace.id,
293
+ workspaceTitle: workspace.title,
294
+ stageId: stage.id,
295
+ stageTitle: stage.title,
296
+ reason,
297
+ });
294
298
  }
295
299
  return contexts;
296
300
  };
@@ -359,9 +363,7 @@ export const createAttentionTuiController = ({ api, projectRoot, read = readWork
359
363
  const current = currentSessionId(api);
360
364
  for (const attention of engine.list()) {
361
365
  if (attention.sessionId === current) continue;
362
- const records = (snapshot?.workspaces || []).flatMap((workspace) => (workspace.sessions || [])
363
- .filter((session) => session.opencode_session_id === attention.sessionId)
364
- .map((session) => ({ workspace, session })));
366
+ const records = visibleSessionRecords(snapshot, attention.sessionId);
365
367
  if (records.some(matches)) bySession.set(attention.sessionId, attention);
366
368
  }
367
369
  const items = [...bySession.values()];
@@ -4,7 +4,8 @@ import { readWorkContextSnapshot } from "../src/work-context-snapshot.js";
4
4
  import { normalizeStageId, normalizeWorkspaceId } from "../src/identifiers.js";
5
5
  import { jsx } from "@opentui/solid/jsx-runtime";
6
6
  import { createSignal } from "solid-js";
7
- import { openStageSwitcher } from "./stage-switcher.js";
7
+ import { contextFor } from "../src/opencode-adapter.js";
8
+ import { openStageSwitcher, startStageSession } from "./stage-switcher.js";
8
9
  import { openWorkspaceSwitcher } from "./workspace-switcher.js";
9
10
  import { openSessionSwitcher } from "./session-switcher.js";
10
11
  import { attentionForSession, attentionReasonText } from "./attention.js";
@@ -15,6 +16,8 @@ const SHORTCUT = "<leader>w";
15
16
  const STAGE_SHORTCUT = "<leader>s";
16
17
  const WORKSPACE_SHORTCUT = "<leader>o";
17
18
  const SESSION_SHORTCUT = "<leader>e";
19
+ const CREATE_STAGE_COMMAND = "work_context.create_stage";
20
+ const CREATE_STAGE_SHORTCUT = "<leader>a";
18
21
  const DEBOUNCE_MS = 150;
19
22
  const POLL_MS = 1000;
20
23
  const MARKERS = { planned: "[ ]", in_progress: "[•]", completed: "[✓]", cancelled: "[!]" };
@@ -563,6 +566,67 @@ export const openWorkContextActionDialog = (api, runtime = {}, options = {}) =>
563
566
  return true;
564
567
  };
565
568
 
569
+ const currentSessionId = (api) => api?.route?.current?.params?.sessionID || api?.route?.current?.params?.sessionId;
570
+ const projectRoot = (api) => api?.state?.path?.worktree || api?.state?.path?.directory;
571
+
572
+ /** Create a planned stage directly, without routing the request through a chat command. */
573
+ export const addStageForCurrentWorkspace = (api, title, { readContext = contextFor } = {}) => {
574
+ if (!title?.trim()) return { ok: false, error: { code: "INVALID_ARGUMENT", message: "Title is required" } };
575
+ const root = projectRoot(api);
576
+ const sessionId = currentSessionId(api);
577
+ if (!root || !sessionId) return { ok: false, error: { code: "STAGE_CONTEXT_REQUIRED", message: "The current session is not associated with a work-context stage" } };
578
+ try {
579
+ const context = readContext(root, sessionId, "OpenCode TUI");
580
+ const current = context.sessionByOpenCodeId(sessionId, null, null, null) || context.sessionById(sessionId);
581
+ if (!current) return { ok: false, error: { code: "STAGE_CONTEXT_REQUIRED", message: "The current session is not associated with a work-context stage" } };
582
+ return context.addStage(current.workspace, title.trim());
583
+ } catch (error) {
584
+ return { ok: false, error: { code: error.code || "STORAGE_ERROR", message: error.message || "Could not create the stage" } };
585
+ }
586
+ };
587
+
588
+ export const openCreateStageDialog = (api, options = {}) => {
589
+ if (typeof api?.ui?.DialogPrompt !== "function" || typeof api?.ui?.DialogSelect !== "function" || typeof api?.ui?.dialog?.replace !== "function") return false;
590
+ const create = async (title, open) => {
591
+ const result = addStageForCurrentWorkspace(api, title, options);
592
+ if (!result.ok) {
593
+ api.ui?.toast?.({ message: `${result.error.code}: ${result.error.message}`, variant: "error" });
594
+ openCreateStageDialog(api, options);
595
+ return;
596
+ }
597
+ if (open) {
598
+ const started = await startStageSession(api, {
599
+ workspace: result.data.workspace,
600
+ stage: result.data.stage,
601
+ title: title.trim(),
602
+ });
603
+ if (!started.ok) {
604
+ api.ui?.toast?.({ message: `${started.error.code}: ${started.error.message}`, variant: "error" });
605
+ return;
606
+ }
607
+ }
608
+ api.ui.dialog.clear?.();
609
+ api.ui?.toast?.({ message: open ? `Stage ${result.data.stage} created and opened` : `Stage ${result.data.stage} created`, variant: "success" });
610
+ };
611
+ api.ui.dialog.replace(() => api.ui.DialogPrompt({
612
+ title: "Create stage",
613
+ placeholder: "Stage title",
614
+ onConfirm: (title) => {
615
+ if (!title?.trim()) { openCreateStageDialog(api, options); return; }
616
+ api.ui.dialog.replace(() => api.ui.DialogSelect({
617
+ title: "Create stage",
618
+ placeholder: "Choose what happens next",
619
+ options: [
620
+ { title: "Create stage", description: "Keep working in the current stage", value: false },
621
+ { title: "Create and open stage", description: "Start the new stage in a new session", value: true },
622
+ ],
623
+ onSelect: (option) => void create(title, option.value),
624
+ }));
625
+ },
626
+ }));
627
+ return true;
628
+ };
629
+
566
630
  export const openCompatibilityDialog = (api, runtime = {}, options = {}) => {
567
631
  const stack = api?.ui?.dialog;
568
632
  if (!stack || typeof runtime.jsx !== "function" || typeof stack.replace !== "function") return false;
@@ -591,14 +655,16 @@ export const registerWorkContextModal = (api, runtime = {}) => {
591
655
  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) };
592
656
  const workspaceCommand = { name: "work_context.workspace", title: "Switch Work Context Workspace", desc: "Open a workspace session", category: "Work Context", namespace: "palette", run: () => openWorkspaceSwitcher(api) };
593
657
  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) };
658
+ const createStageCommand = { name: CREATE_STAGE_COMMAND, title: "Create Work Context Stage", desc: "Create a stage in the current workspace", category: "Work Context", namespace: "palette", run: () => openCreateStageDialog(api) };
594
659
  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) };
595
660
  const registration = api.keymap.registerLayer({
596
- commands: [command, stageCommand, workspaceCommand, sessionCommand, actions],
661
+ commands: [command, stageCommand, workspaceCommand, sessionCommand, createStageCommand, actions],
597
662
  bindings: [
598
663
  { key: SHORTCUT, cmd: COMMAND_NAME, desc: command.title },
599
664
  { key: STAGE_SHORTCUT, cmd: stageCommand.name, desc: stageCommand.title },
600
665
  { key: WORKSPACE_SHORTCUT, cmd: workspaceCommand.name, desc: workspaceCommand.title },
601
666
  { key: SESSION_SHORTCUT, cmd: sessionCommand.name, desc: sessionCommand.title },
667
+ { key: CREATE_STAGE_SHORTCUT, cmd: createStageCommand.name, desc: createStageCommand.title },
602
668
  ],
603
669
  });
604
670
  return { supported: true, dispose: () => disposeRegistration(registration) };
package/src/core.js CHANGED
@@ -111,7 +111,7 @@ export class WorkContext {
111
111
  workspace = normalizeWorkspaceId(workspace);
112
112
  const dir = path.join(this.storage.workspaceDir(workspace), "stages");
113
113
  if (!fs.existsSync(dir)) fail(ERROR_CODES.NOT_FOUND, "Workspace not found");
114
- const stages = fs.readdirSync(dir).filter((file) => /^\d{2}\.md$/.test(file)).map((file) => {
114
+ const stages = fs.readdirSync(dir).filter((file) => /^\d{2}\.md$/.test(file)).sort().map((file) => {
115
115
  const stage = this.storage.readStage(workspace, file.slice(0, 2)).data;
116
116
  return { ...stage, description: stage.goal };
117
117
  });