opencode-work-context 0.4.16 → 0.5.1

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
@@ -108,6 +108,15 @@ without touching project configuration or loaders:
108
108
  npx opencode-work-context sync-command --force
109
109
  ```
110
110
 
111
+ The generated `.opencode/commands/wc.md` and package-owned plugin loaders are
112
+ replaceable package projections. Do not add project-specific workflow logic to
113
+ them. Put additive project guidance in `.opencode/work-context.md`; `/wc` reads
114
+ that file when present and merges it into the package command context. Local
115
+ guidance can specialize project workflow, but cannot replace structured tool
116
+ mapping, storage safety, or explicit lifecycle rules. Implement executable
117
+ project extensions as separate project plugins rather than modifying generated
118
+ loaders.
119
+
111
120
  Useful commands:
112
121
 
113
122
  ```text
@@ -147,14 +156,20 @@ explicit per project, run this in each project that should use work-context:
147
156
  npx opencode-work-context activate
148
157
  ```
149
158
 
150
- `activate` writes `.opencode/opencode.json` with the supported package plugin
151
- entry `opencode-work-context` and installs the `/wc` command contract. OpenCode
159
+ `activate` writes `.opencode/opencode.json` with the supported `plugin` entry
160
+ `opencode-work-context` and installs the `/wc` command contract. OpenCode
152
161
  resolves, caches, and updates configured package plugins through its supported
153
162
  plugin manager; the project does not import an npm-global path, create a local
154
163
  `node_modules`, or create `.work-context` data merely by being activated. The
155
164
  package's server and optional TUI parts are loaded together by OpenCode, so this
156
165
  also works on server-only hosts.
157
166
 
167
+ Managed activation has two scopes: it enables the plugin only in the current
168
+ project, while OpenCode keeps the package in its shared managed cache for every
169
+ activated project. It does not require `npm install -g` or a project-local npm
170
+ dependency. Restart OpenCode after publishing a new unpinned package version so
171
+ the managed plugin flow can refresh the shared copy.
172
+
158
173
  Activation is opt-in. Projects without this entry stay inactive. If a machine
159
174
  administrator or user has configured the package globally, a project can add
160
175
  the explicit opt-out entry with:
@@ -170,10 +185,14 @@ For an existing JSONC configuration, add the equivalent entry manually:
170
185
 
171
186
  ```jsonc
172
187
  {
173
- "plugins": ["opencode-work-context"] // or "-work-context" to opt out
188
+ "plugin": ["opencode-work-context"] // or "-work-context" to opt out
174
189
  }
175
190
  ```
176
191
 
192
+ Re-running `activate` also migrates work-context entries previously generated
193
+ under the unsupported legacy `plugins` field. Unrelated legacy entries are
194
+ preserved rather than activated or removed implicitly.
195
+
177
196
  Restart OpenCode after changing plugin configuration. OpenCode checks unpinned
178
197
  configured packages through its managed plugin flow; use the OpenCode plugin
179
198
  management command available in your installed OpenCode version when you need
@@ -240,12 +259,18 @@ refresh mechanisms.
240
259
  Use a specific version instead of `latest` when you need a pinned upgrade, for
241
260
  example `npx --yes opencode-work-context@0.1.10 init --force`.
242
261
 
243
- Generated files:
244
-
245
- - `.work-context/config.yaml` for filesystem configuration;
246
- - `.opencode/commands/wc.md` for the `/wc` command contract;
247
- - `.opencode/plugins/work-context.js` as a thin loader from the installed package;
248
- - `.opencode/tui-plugins/work-context-stages.js` as the reactive stages-panel loader;
262
+ Installed files and project state:
263
+
264
+ - `.work-context/config.yaml` is project-owned filesystem configuration; `init`
265
+ creates it once and preserves subsequent project changes, including with
266
+ `--force`;
267
+ - `.opencode/commands/wc.md` is the package-managed `/wc` command contract;
268
+ - `.opencode/plugins/work-context.js` is a package-managed thin server loader;
269
+ - `.opencode/tui-plugins/work-context-stages.js` is a package-managed reactive
270
+ stages-panel loader;
271
+ - `.opencode/tui.json` is shared project configuration; `init` merges the
272
+ work-context TUI entry and preserves other settings and plugin entries;
273
+ - `.opencode/work-context.md` is the optional project-owned instruction overlay;
249
274
  - `.work-context/local/` in `.gitignore` for personal session events.
250
275
  - `<workspace>/KNOWLEDGE.md` is the canonical durable knowledge ledger and is
251
276
  created on the first explicit knowledge operation.
@@ -391,6 +416,71 @@ accepted only after every stage is `completed`. Use `/wc workspace list <workspa
391
416
  to list stages with their descriptions. Workspace titles can be changed with
392
417
  `/wc workspace rename <workspace> "title"`, and existing stage descriptions can
393
418
  be changed with `/wc stage update <workspace> <stage> "description"`.
419
+ Workspaces use `standard` mode by default. Switch deliberately to the shared-tree
420
+ startup workflow with `/wc workspace mode <workspace> startup`; switch back with
421
+ `/wc workspace mode <workspace> standard`. The active workflow is shown below the
422
+ workspace title in the sidebar. Standard mode keeps the existing conservative
423
+ worktree behavior. When an OpenCode session is associated with a startup-mode
424
+ workspace, every resume also supplies the agent with the startup policy:
425
+
426
+ - a shared dirty worktree and concurrent stages are expected;
427
+ - stages do not own files or commits;
428
+ - ready work is captured promptly as an explicit commit candidate;
429
+ - mixed-stage provenance alone is not a reason to stop;
430
+ - a concrete overlapping or stale candidate patch is a reason to stop and report
431
+ the conflict.
432
+
433
+ Startup-mode workspaces can snapshot an explicit ready subset as a local commit
434
+ candidate without creating a commit or modifying the ordinary Git index:
435
+
436
+ ```text
437
+ /wc candidate create 000123 "Ship parser fix" "Fix parser edge cases"
438
+ /wc candidate capture 000123 CC-000001 paths src/parser.js test/parser.test.js
439
+ /wc candidate preview 000123 CC-000001
440
+ /wc candidate ready 000123 CC-000001
441
+ /wc candidate commit 000123 CC-000001
442
+ ```
443
+
444
+ A typical shared-tree sequence can keep unrelated work moving:
445
+
446
+ 1. Change `a.txt`, create candidate A, and capture only `a.txt`.
447
+ 2. Continue unfinished work in `b.txt` after A has been captured.
448
+ 3. Preview and mark candidate A ready, then commit it explicitly.
449
+ 4. The new commit contains `a.txt`; `b.txt` remains unchanged as working-tree WIP.
450
+
451
+ The sidebar reads only candidate metadata and shows a compact
452
+ `Candidates · pending <count> · ready <count>` line when either count is nonzero.
453
+ It does not inspect Git state, patches, paths, or candidate freshness. A `ready`
454
+ label therefore means lifecycle status, not a guarantee that a later publication
455
+ cannot encounter a conflict.
456
+
457
+ Capture accepts either complete repository paths or one exact Git unified patch,
458
+ which permits selecting individual hunks. Candidate metadata and patches are
459
+ stored only in `.work-context/local/candidates/`; they are not written to tracked
460
+ workspace projections. Preview reconstructs the recorded base in a temporary
461
+ `GIT_INDEX_FILE`, so the normal index, unrelated files, and unrelated hunks remain
462
+ unchanged. Binary patches, paths outside the repository, malformed patches,
463
+ repositories without `HEAD`, and candidate operations in `standard` mode are
464
+ rejected. A preview reports when the current `HEAD` differs from the recorded
465
+ base. `candidate commit` requires a ready candidate and uses its stored message;
466
+ an optional final argument overrides that message. Publication reconstructs the
467
+ current `HEAD` in another temporary index, reapplies a stale candidate only when
468
+ its exact patch still applies cleanly, creates the commit, and compare-and-swaps
469
+ the attached branch ref. Overlap, detached `HEAD`, or a ref race leaves candidate
470
+ metadata, the worktree, the ordinary index, and the branch ref unchanged by the
471
+ operation. Commit publication uses `git commit-tree`, so it deliberately bypasses
472
+ Git hooks and signing rather than invoking interactive policy.
473
+
474
+ Candidate publication is serialized by the repository-scoped `candidate-git`
475
+ lock. Any operation that needs both locks acquires `candidate-git` before the
476
+ work-context `write` lock; integrations must preserve this ordering to avoid
477
+ deadlocks. Lock owners are released after success or failure. Existing stale-lock
478
+ handling remains explicit rather than removing an unknown owner's lock.
479
+
480
+ Use `/wc candidate show`, `/wc candidate list`, and `/wc candidate discard` to
481
+ inspect or retire local candidates. Candidate patches may contain source code or
482
+ secrets and follow the same local-only handling requirements as other files under
483
+ `.work-context/local/`.
394
484
  `/wc workspace reopen <workspace> "reason"` records a recovery entry and returns
395
485
  only a completed workspace to `in_progress`.
396
486
 
@@ -18,12 +18,14 @@ 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 = `// Server tools and lifecycle hooks stay in the installed package.
21
+ const pluginLoader = `// Package-managed loader: keep project extensions in separate plugin files.
22
+ // Server tools and lifecycle hooks stay in the installed package.
22
23
  import serverPlugin from "${packageManifest.name}/server";
23
24
 
24
25
  export default serverPlugin.server;
25
26
  `;
26
- const tuiLoader = `// TUI integration stays in the installed package; do not copy src/ or tools.
27
+ const tuiLoader = `// Package-managed loader: keep project extensions in separate TUI plugin files.
28
+ // TUI integration stays in the installed package; do not copy src/ or tools.
27
29
  import { createSignal } from "solid-js";
28
30
  import { jsx } from "@opentui/solid/jsx-runtime";
29
31
  import plugin from "${packageManifest.name}/tui";
@@ -43,13 +45,16 @@ const tuiConfig = JSON.stringify({
43
45
  plugin: ["./tui-plugins/work-context-stages.js"],
44
46
  }, null, 2) + "\n";
45
47
  const command = fs.readFileSync(path.join(packageRoot, "commands", "wc.md"), "utf8");
48
+ const configRelative = path.join(".work-context", "config.yaml");
49
+ const tuiConfigRelative = path.join(".opencode", "tui.json");
50
+ const tuiPluginEntry = "./tui-plugins/work-context-stages.js";
46
51
  const generated = new Map([
47
- [path.join(".work-context", "config.yaml"), defaultConfig()],
52
+ [configRelative, defaultConfig()],
48
53
  [path.join(".opencode", "commands", "wc.md"), command],
49
54
  [path.join(".opencode", "plugins", "work-context.js"), `// Thin project integration; tools remain in the installed npm package.
50
55
  ${pluginLoader}`],
51
56
  [path.join(".opencode", "tui-plugins", "work-context-stages.js"), tuiLoader],
52
- [path.join(".opencode", "tui.json"), tuiConfig],
57
+ [tuiConfigRelative, tuiConfig],
53
58
  ]);
54
59
 
55
60
  const fail = (message) => {
@@ -111,13 +116,24 @@ function activate(enabled, force) {
111
116
  }
112
117
  try { config = JSON.parse(fs.readFileSync(configFile, "utf8")); }
113
118
  catch { fail(`cannot update invalid JSON: ${configRelative}`); return; }
114
- if (!config || typeof config !== "object" || Array.isArray(config) || (config.plugins !== undefined && !Array.isArray(config.plugins))) {
119
+ if (!config || typeof config !== "object" || Array.isArray(config)
120
+ || (config.plugin !== undefined && !Array.isArray(config.plugin))
121
+ || (config.plugins !== undefined && !Array.isArray(config.plugins))) {
115
122
  fail(`cannot update unsupported configuration: ${configRelative}`);
116
123
  return;
117
124
  }
118
125
  }
119
126
  const entry = enabled ? packageManifest.name : "-work-context";
120
- config.plugins = [...(config.plugins || []).filter((item) => item !== entry), entry];
127
+ const isWorkContextEntry = (item) => typeof item === "string" && (
128
+ item === packageManifest.name
129
+ || item.startsWith(`${packageManifest.name}@`)
130
+ || item === "-work-context"
131
+ );
132
+ config.plugin = [...(config.plugin || []).filter((item) => !isWorkContextEntry(item)), entry];
133
+ if (config.plugins) {
134
+ config.plugins = config.plugins.filter((item) => !isWorkContextEntry(item));
135
+ if (config.plugins.length === 0) delete config.plugins;
136
+ }
121
137
  const files = new Map([
122
138
  [configRelative, JSON.stringify(config, null, 2) + "\n"],
123
139
  [path.join(".opencode", "commands", "wc.md"), command],
@@ -171,6 +187,16 @@ function ensureModuleScope() {
171
187
  }
172
188
 
173
189
  function checkConflicts(force) {
190
+ const sharedTuiConfig = path.join(projectRoot, tuiConfigRelative);
191
+ if (exists(sharedTuiConfig) && fs.lstatSync(sharedTuiConfig).isFile() && !fs.lstatSync(sharedTuiConfig).isSymbolicLink()) {
192
+ try {
193
+ const config = JSON.parse(fs.readFileSync(sharedTuiConfig, "utf8"));
194
+ if (!config || typeof config !== "object" || Array.isArray(config) || (config.plugin !== undefined && (!Array.isArray(config.plugin) || config.plugin.some((item) => typeof item !== "string")))) throw new Error("unsupported shape");
195
+ } catch {
196
+ fail(`cannot merge unsupported configuration: ${tuiConfigRelative}`);
197
+ return false;
198
+ }
199
+ }
174
200
  const conflicts = ["package.json", "package-lock.json", "npm-shrinkwrap.json"].flatMap((relative) => {
175
201
  const file = path.join(dependencyRoot, relative);
176
202
  if (!exists(file)) return [];
@@ -184,6 +210,8 @@ function checkConflicts(force) {
184
210
  if (!exists(file)) return [];
185
211
  const stat = fs.lstatSync(file);
186
212
  if (!stat.isFile() || stat.isSymbolicLink()) return [relative];
213
+ if (relative === configRelative) return [];
214
+ if (relative === tuiConfigRelative) return [];
187
215
  return !force && fs.readFileSync(file, "utf8") !== content ? [relative] : [];
188
216
  }));
189
217
  const gitignore = path.join(projectRoot, ".gitignore");
@@ -337,6 +365,14 @@ function installPackage(snapshot) {
337
365
  function writeGenerated() {
338
366
  for (const [relative, content] of generated) {
339
367
  const file = path.join(projectRoot, relative);
368
+ if (relative === configRelative && exists(file)) continue;
369
+ if (relative === tuiConfigRelative && exists(file)) {
370
+ const config = JSON.parse(fs.readFileSync(file, "utf8"));
371
+ config.plugin = [...(config.plugin || []).filter((item) => item !== tuiPluginEntry), tuiPluginEntry];
372
+ const merged = JSON.stringify(config, null, 2) + "\n";
373
+ if (fs.readFileSync(file, "utf8") !== merged) writeAtomic(file, merged);
374
+ continue;
375
+ }
340
376
  if (!exists(file) || fs.readFileSync(file, "utf8") !== content) writeAtomic(file, content);
341
377
  }
342
378
  const gitignore = path.join(projectRoot, ".gitignore");
package/commands/wc.md CHANGED
@@ -10,8 +10,17 @@ other than `resume`, report the structured result and stable error code. For
10
10
  `resume`, follow its human-oriented presentation rules instead. Use `work_context_help` when
11
11
  the syntax is missing or ambiguous.
12
12
 
13
+ `.opencode/commands/wc.md` is package-managed and may be replaced during install,
14
+ activation, or `sync-command`. Never store project-specific workflow logic in this
15
+ file or generated plugin loaders. Keep additive project instructions in
16
+ `.opencode/work-context.md`; when that file exists, read it before dispatching the
17
+ operation and merge its guidance into this command context. Project guidance may
18
+ specialize local workflow, but it must not override this tool mapping, structured
19
+ arguments, storage safety, or explicit lifecycle requirements.
20
+
13
21
  For `workspace list <workspace>` (or `<workspace> list`), report the workspace
14
- status and every stage as `stage - status - title - description`.
22
+ status and workflow mode, then every stage as
23
+ `stage - status - title - description`.
15
24
 
16
25
  Use these exact tool mappings; do not invent shortened tool names:
17
26
 
@@ -19,6 +28,15 @@ Use these exact tool mappings; do not invent shortened tool names:
19
28
  - `list` -> `work_context_list_workspaces`
20
29
  - `workspace list <workspace>` or `<workspace> list` -> `work_context_workspace_list`
21
30
  - `workspace rename <workspace> "title"` -> `work_context_rename_workspace`
31
+ - `workspace mode <workspace> <standard|startup>` -> `work_context_set_workspace_mode`
32
+ - `candidate create <workspace> "title" ["message"]` -> `work_context_create_candidate`
33
+ - `candidate capture <workspace> <candidateId> paths <path>...` or `candidate capture <workspace> <candidateId> patch "patch"` -> `work_context_capture_candidate`
34
+ - `candidate preview <workspace> <candidateId>` -> `work_context_preview_candidate`
35
+ - `candidate show <workspace> <candidateId>` -> `work_context_show_candidate`
36
+ - `candidate list <workspace>` -> `work_context_list_candidates`
37
+ - `candidate ready <workspace> <candidateId>` -> `work_context_ready_candidate`
38
+ - `candidate commit <workspace> <candidateId> ["message"]` -> `work_context_commit_candidate`
39
+ - `candidate discard <workspace> <candidateId>` -> `work_context_discard_candidate`
22
40
  - `workspace finish <workspace>` -> `work_context_workspace_finish`
23
41
  - `workspace reopen <workspace> "reason"` -> `work_context_reopen_workspace`
24
42
  - `resume <workspace> <stage>` -> `work_context_start_session`
@@ -43,6 +61,16 @@ Supported syntax:
43
61
  - `list` or `<workspace> list`
44
62
  - `workspace list <workspace>`
45
63
  - `workspace rename <workspace> "title"`
64
+ - `workspace mode <workspace> <standard|startup>`
65
+ - `candidate create <workspace> "title" ["message"]`
66
+ - `candidate capture <workspace> <candidateId> paths <path>...`
67
+ - `candidate capture <workspace> <candidateId> patch "patch"`
68
+ - `candidate preview <workspace> <candidateId>`
69
+ - `candidate show <workspace> <candidateId>`
70
+ - `candidate list <workspace>`
71
+ - `candidate ready <workspace> <candidateId>`
72
+ - `candidate commit <workspace> <candidateId> ["message"]`
73
+ - `candidate discard <workspace> <candidateId>`
46
74
  - `workspace finish <workspace>`
47
75
  - `workspace reopen <workspace> "reason"`
48
76
  - `resume <workspace> <stage>`
@@ -72,6 +100,8 @@ Supported syntax:
72
100
  - when the saved prompt contains several clear deliverables, add `In this stage we will` with 2-5 short outcome-oriented bullets derived only from the prompt, previous result, and workspace knowledge; do not invent scope, and omit this block for a small stage
73
101
  - do not expose raw workspace/stage/session identifiers, ordinals, `ok` flags, or absent error codes in the user-facing resume summary
74
102
  - `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
103
+ - an associated OpenCode session resumed in a `startup` workspace receives `resume.context.workflow_policy`; follow it as active agent policy: a shared dirty worktree and concurrent stages are expected, stages do not own files or commits, ready work should be captured promptly into an explicit candidate, mixed-stage provenance alone is not a reason to stop, and an actual overlapping or stale candidate conflict must stop with a concrete report
104
+ - standard-mode and unassociated core sessions do not receive startup policy; retain the existing conservative worktree behavior there
75
105
  - after presenting the summary, continue work immediately when `resume.next_action` is `start_work`; do not ask for generic confirmation
76
106
  - a stage may require confirmation only with an exact standalone `RESUME_CONFIRMATION: required` line in its saved prompt; when `resume.next_action` is `await_confirmation`, present the summary and wait before inspecting or modifying application code
77
107
  - `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
@@ -87,6 +117,7 @@ Supported syntax:
87
117
  - `stage reopen <workspace> <stage> "reason"` applies only to a completed stage, preserves its result and completion history, records the reason, changes it to `in_progress`, and does not start a session or affect downstream stages; use an explicit separate-session `resume` to work on it again
88
118
  - `stage restore <workspace> <stage> "reason"` applies only to an archived stage and restores its saved pre-archive status. New archives preserve that status; legacy archives restore to `in_progress`. It records the reason, preserves stage content and results, does not start a session, and requires explicit separate-session `resume` when restored to `planned` or `in_progress`.
89
119
  - `workspace reopen <workspace> "reason"` applies only to a completed workspace, changes it to `in_progress`, and records durable recovery history. Cancelled workspaces cannot be reopened.
120
+ - candidate operations require `startup` workflow mode and store metadata and patch payloads only under `.work-context/local/`; capture requires exactly one explicit list of complete paths or one Git unified patch and never infers stage ownership; commit requires a ready candidate, uses its stored message unless a non-empty override is supplied, serializes Git publication, bypasses hooks and signing, and never uses the ordinary Git index
90
121
  - `knowledge list|add|update|supersede <workspace> ...`
91
122
 
92
123
  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.4.16",
4
+ "version": "0.5.1",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -33,6 +33,9 @@ const trackerLinkText = (link) => {
33
33
  if (link.provider === "github") return `GH#${identifier}`;
34
34
  return `JIRA ${identifier}`;
35
35
  };
36
+ const candidateSummaryText = (workspace) => workspace.candidates && (workspace.candidates.pending || workspace.candidates.ready)
37
+ ? `Candidates · pending ${workspace.candidates.pending} · ready ${workspace.candidates.ready}`
38
+ : null;
36
39
 
37
40
  export { readStagesSnapshot, renderStagesPanel };
38
41
 
@@ -52,7 +55,12 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
52
55
  : [
53
56
  runtime.jsx("box", {
54
57
  marginBottom: 1,
55
- children: runtime.jsx("text", { wrapMode: "word", children: runtime.jsx("b", { children: `${attention?.attentionForWorkspace?.(result.data.workspace.id) ? "[ATTN] " : ""}${result.data.workspace.title}` }) }),
58
+ flexDirection: "column",
59
+ children: [
60
+ runtime.jsx("text", { wrapMode: "word", children: runtime.jsx("b", { children: `${attention?.attentionForWorkspace?.(result.data.workspace.id) ? "[ATTN] " : ""}${result.data.workspace.title}` }) }),
61
+ runtime.jsx("text", { fg: theme?.current?.textMuted, children: `Workflow · ${result.data.workspace.mode || "standard"}` }),
62
+ candidateSummaryText(result.data.workspace) && runtime.jsx("text", { fg: theme?.current?.textMuted, children: candidateSummaryText(result.data.workspace) }),
63
+ ],
56
64
  }),
57
65
  runtime.jsx("box", {
58
66
  flexDirection: "row",
@@ -0,0 +1,165 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { atomicWrite } from "./storage.js";
4
+ import { ERROR_CODES, fail } from "./errors.js";
5
+ import { normalizeWorkspaceId } from "./identifiers.js";
6
+ import { capturePatch, capturePaths, commitPatch, previewPatch, repositoryState } from "./git-candidates.js";
7
+
8
+ const candidatePattern = /^CC-(\d{6})$/;
9
+ const statuses = new Set(["draft", "ready", "discarded", "committed"]);
10
+ const timestamp = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
11
+ const metadataKeys = ["schema", "candidate", "workspace", "title", "message", "base_head", "status", "created_at", "updated_at", "selected_paths", "patch_file"];
12
+
13
+ function validateCandidate(data, expectedId = null) {
14
+ const valid = data && typeof data === "object" && !Array.isArray(data)
15
+ && metadataKeys.every((key) => Object.hasOwn(data, key))
16
+ && Object.keys(data).every((key) => metadataKeys.includes(key) || ["commit_hash", "committed_at"].includes(key))
17
+ && data.schema === 1 && candidatePattern.test(data.candidate) && (!expectedId || data.candidate === expectedId)
18
+ && /^\d{6}$/.test(data.workspace) && typeof data.title === "string" && data.title.trim()
19
+ && typeof data.message === "string" && data.message.trim() && /^[0-9a-f]{40,64}$/.test(data.base_head)
20
+ && statuses.has(data.status) && timestamp(data.created_at) && timestamp(data.updated_at)
21
+ && Date.parse(data.updated_at) >= Date.parse(data.created_at)
22
+ && Array.isArray(data.selected_paths) && data.selected_paths.every((item) => typeof item === "string" && item && !path.isAbsolute(item) && !item.split("/").includes(".."))
23
+ && new Set(data.selected_paths).size === data.selected_paths.length
24
+ && data.patch_file === `${data.candidate}.patch`
25
+ && (data.status === "committed"
26
+ ? /^[0-9a-f]{40,64}$/.test(data.commit_hash) && timestamp(data.committed_at)
27
+ : !Object.hasOwn(data, "commit_hash") && !Object.hasOwn(data, "committed_at"));
28
+ if (!valid) fail(ERROR_CODES.STORAGE_ERROR, "Invalid commit candidate metadata");
29
+ return data;
30
+ }
31
+
32
+ export class CandidateStore {
33
+ constructor(context) {
34
+ this.context = context;
35
+ this.directory = path.join(context.storage.personalRoot, "candidates");
36
+ }
37
+
38
+ assertStartup(workspace) {
39
+ this.context.storage.assertNoSymlinks();
40
+ workspace = normalizeWorkspaceId(workspace);
41
+ const record = this.context.storage.readWorkspace(workspace);
42
+ if ((record.data.mode || "standard") !== "startup") fail(ERROR_CODES.CANDIDATE_MODE_REQUIRED, "Commit candidates require startup workflow mode", { workspace });
43
+ return workspace;
44
+ }
45
+
46
+ metadataFile(id) { return path.join(this.directory, `${id}.json`); }
47
+ patchFile(id) { return path.join(this.directory, `${id}.patch`); }
48
+
49
+ nextId() {
50
+ if (!fs.existsSync(this.directory)) return "CC-000001";
51
+ const numbers = fs.readdirSync(this.directory).map((file) => file.match(/^CC-(\d{6})\.(?:json|patch)$/)?.[1]).filter(Boolean).map(Number);
52
+ const next = Math.max(0, ...numbers) + 1;
53
+ if (next > 999999) fail(ERROR_CODES.INVALID_STATE, "Commit candidate ID space is exhausted");
54
+ return `CC-${String(next).padStart(6, "0")}`;
55
+ }
56
+
57
+ read(id, workspace = null, includePatch = false) {
58
+ if (typeof id !== "string" || !candidatePattern.test(id)) fail(ERROR_CODES.INVALID_ARGUMENT, "Invalid commit candidate ID");
59
+ let data;
60
+ try { data = JSON.parse(fs.readFileSync(this.metadataFile(id), "utf8")); }
61
+ catch (error) { if (error.code === "ENOENT") fail(ERROR_CODES.NOT_FOUND, "Commit candidate not found", { candidate: id }); fail(ERROR_CODES.STORAGE_ERROR, "Invalid commit candidate metadata", { cause: error.message }); }
62
+ validateCandidate(data, id);
63
+ if (workspace && data.workspace !== normalizeWorkspaceId(workspace)) fail(ERROR_CODES.NOT_FOUND, "Commit candidate is not associated with this workspace", { candidate: id });
64
+ if (!includePatch) return data;
65
+ let patch;
66
+ try { patch = fs.readFileSync(this.patchFile(id), "utf8"); }
67
+ catch (error) { fail(ERROR_CODES.STORAGE_ERROR, "Commit candidate patch is unavailable", { cause: error.message }); }
68
+ return { ...data, patch };
69
+ }
70
+
71
+ write(data, patch = null) {
72
+ validateCandidate(data, data.candidate);
73
+ atomicWrite(this.metadataFile(data.candidate), `${JSON.stringify(data, null, 2)}\n`);
74
+ if (patch !== null) atomicWrite(this.patchFile(data.candidate), patch);
75
+ }
76
+
77
+ create(workspace, title, message = null) {
78
+ workspace = this.assertStartup(workspace);
79
+ if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Candidate title is required");
80
+ const repository = repositoryState(this.context.storage.projectRoot);
81
+ const id = this.nextId();
82
+ const now = new Date().toISOString();
83
+ const data = { schema: 1, candidate: id, workspace, title: title.trim(), message: message?.trim() || title.trim(), base_head: repository.head, status: "draft", created_at: now, updated_at: now, selected_paths: [], patch_file: `${id}.patch` };
84
+ this.write(data, "");
85
+ return data;
86
+ }
87
+
88
+ list(workspace) {
89
+ workspace = this.assertStartup(workspace);
90
+ if (!fs.existsSync(this.directory)) return [];
91
+ return fs.readdirSync(this.directory).filter((file) => candidatePattern.test(file.slice(0, -5)) && file.endsWith(".json"))
92
+ .map((file) => this.read(file.slice(0, -5))).filter((item) => item.workspace === workspace)
93
+ .sort((a, b) => a.candidate.localeCompare(b.candidate));
94
+ }
95
+
96
+ summary(workspace) {
97
+ return this.list(workspace).reduce((summary, candidate) => {
98
+ if (candidate.status === "draft") summary.pending += 1;
99
+ if (candidate.status === "ready") summary.ready += 1;
100
+ return summary;
101
+ }, { pending: 0, ready: 0 });
102
+ }
103
+
104
+ capture(workspace, id, input) {
105
+ workspace = this.assertStartup(workspace);
106
+ const data = this.read(id, workspace);
107
+ if (data.status !== "draft") fail(ERROR_CODES.INVALID_STATE, "Only draft candidates can be captured", { status: data.status });
108
+ const hasPaths = Array.isArray(input.paths);
109
+ const hasPatch = input.patch !== undefined;
110
+ if (hasPaths === hasPatch) fail(ERROR_CODES.INVALID_ARGUMENT, "Provide exactly one of paths or patch");
111
+ const root = repositoryState(this.context.storage.projectRoot).root;
112
+ const captured = hasPaths
113
+ ? capturePaths(root, this.context.storage.personalRoot, data.base_head, input.paths)
114
+ : capturePatch(root, this.context.storage.personalRoot, data.base_head, input.patch);
115
+ data.selected_paths = captured.paths;
116
+ data.updated_at = new Date().toISOString();
117
+ this.write(data, captured.patch);
118
+ return { ...data, patch: captured.patch };
119
+ }
120
+
121
+ preview(workspace, id) {
122
+ workspace = this.assertStartup(workspace);
123
+ const data = this.read(id, workspace, true);
124
+ if (!data.patch) fail(ERROR_CODES.INVALID_STATE, "Commit candidate has not captured a patch");
125
+ return { candidate: data, preview: previewPatch(this.context.storage.projectRoot, data.base_head, data.patch) };
126
+ }
127
+
128
+ setStatus(workspace, id, status) {
129
+ workspace = this.assertStartup(workspace);
130
+ const data = this.read(id, workspace, true);
131
+ if (status === "ready" && data.status !== "draft") fail(ERROR_CODES.INVALID_STATE, "Only draft candidates can become ready", { status: data.status });
132
+ if (status === "discarded" && data.status === "discarded") return data;
133
+ if (status === "discarded" && data.status === "committed") fail(ERROR_CODES.INVALID_STATE, "Committed candidates cannot be discarded", { status: data.status });
134
+ if (status === "ready" && !data.patch) fail(ERROR_CODES.INVALID_STATE, "Cannot ready a candidate without a captured patch");
135
+ data.status = status;
136
+ data.updated_at = new Date().toISOString();
137
+ const { patch, ...metadata } = data;
138
+ this.write(metadata);
139
+ return metadata;
140
+ }
141
+
142
+ commit(workspace, id, message = undefined, options = {}) {
143
+ workspace = this.assertStartup(workspace);
144
+ const data = this.read(id, workspace, true);
145
+ if (data.status !== "ready") fail(ERROR_CODES.INVALID_STATE, "Only ready candidates can be committed", { status: data.status });
146
+ if (message !== undefined && (typeof message !== "string" || !message.trim())) fail(ERROR_CODES.INVALID_ARGUMENT, "Commit message must be a non-empty string");
147
+ const commitMessage = message === undefined ? data.message : message.trim();
148
+ let metadata;
149
+ const published = commitPatch(this.context.storage.projectRoot, data.base_head, data.patch, commitMessage, {
150
+ beforeUpdateRef: (pending) => {
151
+ const committedAt = new Date().toISOString();
152
+ data.message = commitMessage;
153
+ data.status = "committed";
154
+ data.commit_hash = pending.commit;
155
+ data.committed_at = committedAt;
156
+ data.updated_at = committedAt;
157
+ const { patch, ...record } = data;
158
+ metadata = record;
159
+ this.write(metadata);
160
+ options.beforeUpdateRef?.(pending);
161
+ },
162
+ });
163
+ return { ...metadata, branch: published.branch, previous_head: published.previous_head, stale: published.stale };
164
+ }
165
+ }
package/src/core.js CHANGED
@@ -8,8 +8,10 @@ import { generateProjections, renderSessions } from "./projections.js";
8
8
  import { nextKnowledgeId, parseKnowledge, renderKnowledge, validateKnowledgeInput, validateKnowledgeRecords } from "./knowledge.js";
9
9
  import { normalizeStageId, normalizeWorkspaceId } from "./identifiers.js";
10
10
  import { isDependencySatisfied } from "./stage-status.js";
11
+ import { CandidateStore } from "./candidates.js";
11
12
 
12
13
  const actor = (options) => options.actor || "OpenCode";
14
+ const workspaceMode = (data) => data.mode || "standard";
13
15
  const activeKnowledge = (records) => records
14
16
  .filter((record) => record.status === "active")
15
17
  .map(({ id: knowledgeId, title, kind, text, sources }) => ({ id: knowledgeId, title, kind, text, sources }));
@@ -27,6 +29,16 @@ const preservedStageResult = (record) => stageResult(record)
27
29
  const appendHistory = (bodyText, heading, entry) => `${bodyText.trimEnd()}${bodyText.includes(`\n## ${heading}\n`) ? "" : `\n\n## ${heading}\n`}\n- ${entry}\n`;
28
30
  const automaticFinishAllowed = (storage, workspace) => /(?:^|\n)AUTO_STAGE_FINISH:\s*allowed\s*$/mi.test(storage.readStage(workspace, "01").data.prompt || "");
29
31
  const resumeConfirmationRequired = (prompt) => /(?:^|\r?\n)RESUME_CONFIRMATION: required(?=\r?\n|$)/.test(prompt || "");
32
+ const startupWorkflowPolicy = () => ({
33
+ mode: "startup",
34
+ guidance: [
35
+ "A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
36
+ "Capture ready work promptly as an explicit commit candidate while unrelated work remains in progress.",
37
+ "Mixed-stage provenance alone is not a reason to stop; do not reconstruct ownership after the fact.",
38
+ "Stop only for a concrete overlapping or stale candidate conflict, and report that conflict explicitly.",
39
+ ],
40
+ });
41
+ const startupWorkflowInstruction = (policy) => policy ? `\n\nStartup workflow policy:\n${policy.guidance.map((item) => `- ${item}`).join("\n")}` : "";
30
42
  const resumePresentationInstruction = ({ confirmationRequired }) => `Before doing any work, give the user a concise context summary:
31
43
  - Use the user's language.
32
44
  - Name the stage without reporting workspace IDs, stage IDs, session UUIDs, ordinals, ok flags, or absent error codes.
@@ -102,7 +114,10 @@ export class WorkContext {
102
114
  if (!fs.existsSync(this.storage.root)) return { ok: true, data: [] };
103
115
  const data = fs.readdirSync(this.storage.root, { withFileTypes: true })
104
116
  .filter((entry) => entry.isDirectory() && /^\d{6}$/.test(entry.name))
105
- .map((entry) => this.storage.readWorkspace(entry.name).data);
117
+ .map((entry) => {
118
+ const data = this.storage.readWorkspace(entry.name).data;
119
+ return { ...data, mode: workspaceMode(data) };
120
+ });
106
121
  return { ok: true, data };
107
122
  }
108
123
 
@@ -129,7 +144,8 @@ export class WorkContext {
129
144
  visiting.delete(stage); visited.add(stage);
130
145
  };
131
146
  for (const stage of ids) visit(stage);
132
- return { ok: true, data: { workspace, stages, sessions: reduceSessions(this.storage.readEvents()).filter((session) => session.workspace === workspace) } };
147
+ const workspaceData = this.storage.readWorkspace(workspace).data;
148
+ return { ok: true, data: { workspace, title: workspaceData.title, status: workspaceData.status, mode: workspaceMode(workspaceData), stages, sessions: reduceSessions(this.storage.readEvents()).filter((session) => session.workspace === workspace) } };
133
149
  }
134
150
 
135
151
  finishWorkspace(workspace) {
@@ -190,22 +206,26 @@ export class WorkContext {
190
206
 
191
207
  createWorkspace(title, options = {}) {
192
208
  if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Title is required");
209
+ const mode = options.mode === undefined ? "standard" : options.mode;
210
+ if (!["standard", "startup"].includes(mode)) fail(ERROR_CODES.INVALID_ARGUMENT, "Workspace mode must be 'standard' or 'startup'");
193
211
  const requestedWorkspace = options.workspace;
194
212
  return this.transact("workspace-create", () => {
195
213
  const workspace = requestedWorkspace === undefined ? this.nextWorkspace() : normalizeWorkspaceId(requestedWorkspace);
196
214
  const now = new Date().toISOString();
197
215
  if (fs.existsSync(this.storage.workspaceDir(workspace))) fail(ERROR_CODES.CONFLICT, "Workspace already exists");
198
216
  fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
199
- this.storage.writeMarkdown(this.storage.workspaceFile(workspace), { schema: 1, workspace, title: title.trim(), status: "in_progress", created_at: now, updated_at: now, tracker_links: [] }, body(title));
217
+ this.storage.writeMarkdown(this.storage.workspaceFile(workspace), { schema: 1, workspace, title: title.trim(), status: "in_progress", mode, created_at: now, updated_at: now, tracker_links: [] }, body(title));
200
218
  const planningGoal = "Clarify the work goal and constraints";
201
219
  const planningPrompt = "Diagnose and plan the task without functional changes. Discuss possible solutions, record durable workspace-wide facts, decisions, constraints, important files, and risks through explicit knowledge operations, and decompose the work into the following stages. For each new implementation stage, write a separate detailed prompt with local context, concrete actions, constraints, completion criteria, and the expected result; do not duplicate shared knowledge that every stage receives in resume.context.workspace_knowledge. Ask clarifying questions only when genuinely blocked. Stages must remain in progress until the user explicitly requests stage finish. If the user explicitly agrees to automatic completion for this workspace, add the exact standalone line AUTO_STAGE_FINISH: allowed to this Planning-stage prompt.";
202
220
  this.storage.writeMarkdown(this.storage.stageFile(workspace, "01"), { schema: 1, workspace, stage: "01", title: "Planning", status: "in_progress", goal: planningGoal, prompt: planningPrompt, depends_on: [], owner: actor(this.options), created_at: now, updated_at: now, tracker_links: [] }, body("Planning", planningGoal, planningPrompt));
203
221
  const sessionId = options.sessionId || randomUUID();
222
+ const workflowPolicy = mode === "startup" && options.opencodeSessionId ? startupWorkflowPolicy() : null;
204
223
  if (this.storage.readEvents().some((item) => item.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
205
224
  this.writeEvents([event("session.started", workspace, "01", 1, sessionId, actor(this.options), { summary: `planning ${title.trim()}`, opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
206
225
  generateProjections(this.storage);
207
226
  return this.result({
208
227
  workspace,
228
+ mode,
209
229
  stage: "01",
210
230
  session_id: sessionId,
211
231
  ordinal: "01/01",
@@ -220,11 +240,12 @@ export class WorkContext {
220
240
  essence: planningGoal,
221
241
  previous: "The previous session did not save a result; the stopping point needs to be clarified.",
222
242
  now: planningPrompt,
223
- workspace_knowledge: [],
224
- lifecycle: { automatic_finish_allowed: false },
243
+ workspace_knowledge: [],
244
+ ...(workflowPolicy ? { workflow_policy: workflowPolicy } : {}),
245
+ lifecycle: { automatic_finish_allowed: false },
225
246
  },
226
247
  next_action: "start_work",
227
- instruction: `${planningPrompt}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
248
+ instruction: `${planningPrompt}${startupWorkflowInstruction(workflowPolicy)}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
228
249
  },
229
250
  }, [workspace, "01"]);
230
251
  });
@@ -245,6 +266,56 @@ export class WorkContext {
245
266
  });
246
267
  }
247
268
 
269
+ setWorkspaceMode(workspace, mode) {
270
+ workspace = normalizeWorkspaceId(workspace);
271
+ if (!["standard", "startup"].includes(mode)) fail(ERROR_CODES.INVALID_ARGUMENT, "Workspace mode must be 'standard' or 'startup'");
272
+ return this.transact(`workspace-${workspace}`, () => {
273
+ const record = this.storage.readWorkspace(workspace);
274
+ if (workspaceMode(record.data) === mode && record.data.mode === mode) return this.result({ workspace, mode }, []);
275
+ record.data.mode = mode;
276
+ record.data.updated_at = new Date().toISOString();
277
+ this.storage.writeMarkdown(this.storage.workspaceFile(workspace), record.data, record.body);
278
+ generateProjections(this.storage);
279
+ return this.result({ workspace, mode }, [workspace]);
280
+ });
281
+ }
282
+
283
+ candidates() { return new CandidateStore(this); }
284
+
285
+ createCandidate(workspace, title, message = null) {
286
+ return this.transact("candidate-create", () => this.result(this.candidates().create(workspace, title, message), ["local:candidates"]));
287
+ }
288
+
289
+ listCandidates(workspace) { return { ok: true, data: this.candidates().list(workspace) }; }
290
+
291
+ showCandidate(workspace, candidate) {
292
+ const store = this.candidates();
293
+ workspace = store.assertStartup(workspace);
294
+ return { ok: true, data: store.read(candidate, workspace, true) };
295
+ }
296
+
297
+ captureCandidate(workspace, candidate, input) {
298
+ return this.transact("candidate-capture", () => this.result(this.candidates().capture(workspace, candidate, input), ["local:candidates"]));
299
+ }
300
+
301
+ previewCandidate(workspace, candidate) { return { ok: true, data: this.candidates().preview(workspace, candidate) }; }
302
+
303
+ readyCandidate(workspace, candidate) {
304
+ return this.transact("candidate-ready", () => this.result(this.candidates().setStatus(workspace, candidate, "ready"), ["local:candidates"]));
305
+ }
306
+
307
+ discardCandidate(workspace, candidate) {
308
+ return this.transact("candidate-discard", () => this.result(this.candidates().setStatus(workspace, candidate, "discarded"), ["local:candidates"]));
309
+ }
310
+
311
+ commitCandidate(workspace, candidate, message = undefined, options = {}) {
312
+ this.storage.assertSafeRoots();
313
+ // Operations needing both locks always acquire candidate-git before write.
314
+ return withLock(this.storage.lockPath("candidate-git"), () => this.transact("candidate-commit", () =>
315
+ this.result(this.candidates().commit(workspace, candidate, message, options), ["local:candidates"])
316
+ ), { session: this.options.sessionId, owner: actor(this.options) });
317
+ }
318
+
248
319
  nextWorkspace() {
249
320
  const ids = this.listWorkspaces().data.map((workspace) => Number(workspace.workspace));
250
321
  return String(Math.max(0, ...ids) + 1).padStart(6, "0");
@@ -285,7 +356,9 @@ export class WorkContext {
285
356
  const hasPrompt = Boolean(stageRecord.data.prompt?.trim());
286
357
  const confirmationRequired = hasPrompt && resumeConfirmationRequired(stageRecord.data.prompt);
287
358
  const previousResult = preservedStageResult(stageRecord);
288
- const workspaceTitle = this.storage.readWorkspace(workspace).data.title;
359
+ const workspaceRecord = this.storage.readWorkspace(workspace).data;
360
+ const workspaceTitle = workspaceRecord.title;
361
+ const workflowPolicy = workspaceMode(workspaceRecord) === "startup" && options.opencodeSessionId ? startupWorkflowPolicy() : null;
289
362
  const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
290
363
  const automaticFinish = automaticFinishAllowed(this.storage, workspace);
291
364
  return this.result({
@@ -314,12 +387,13 @@ export class WorkContext {
314
387
  essence: stageRecord.data.goal || stageRecord.data.title,
315
388
  previous: previousSessionSummary || previousResult || "No previous progress was recorded.",
316
389
  now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
317
- workspace_knowledge: workspaceKnowledge,
318
- lifecycle: { automatic_finish_allowed: automaticFinish },
390
+ workspace_knowledge: workspaceKnowledge,
391
+ ...(workflowPolicy ? { workflow_policy: workflowPolicy } : {}),
392
+ lifecycle: { automatic_finish_allowed: automaticFinish },
319
393
  },
320
394
  next_action: hasPrompt ? confirmationRequired ? "await_confirmation" : "start_work" : "ask_questions",
321
395
  instruction: `${hasPrompt
322
- ? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}`
396
+ ? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${startupWorkflowInstruction(workflowPolicy)}`
323
397
  : `This stage has no non-empty prompt. Give the user a concise plain-language summary of the stage title and goal, then ask focused questions needed to define the intended outcome and scope. Do not inspect or modify application code yet. Do not report raw operation metadata or identifiers.`}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
324
398
  },
325
399
  }, [workspace, stage]);
@@ -668,10 +742,9 @@ export class WorkContext {
668
742
  help(command = "") {
669
743
  return this.result({
670
744
  command,
671
- syntax: "/wc [create|list|workspace list|workspace rename|workspace finish|workspace reopen|resume|stage add|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|unlink-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
672
- note: "stage finish requires an explicit user lifecycle request unless the Planning-stage prompt contains the exact line AUTO_STAGE_FINISH: allowed; stage reopen requires a completed stage and a reason; stage restore requires an archived stage and a reason, returns its saved pre-archive status (or in_progress for legacy archives), and requires explicit separate-session resume when actionable; workspace reopen requires a completed workspace and a reason.",
745
+ syntax: "/wc [create|list|workspace list|workspace rename|workspace mode|candidate create|candidate capture|candidate preview|candidate show|candidate list|candidate ready|candidate commit|candidate discard|workspace finish|workspace reopen|resume|stage add|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|unlink-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
746
+ note: "associated OpenCode sessions in startup-mode workspaces receive the shared-worktree and commit-candidate policy on resume; standard mode remains conservative; commit candidates are local-only and require startup workflow mode; capture and commit use isolated Git indexes and never alter the ordinary index; candidate commit uses the stored message unless an explicit non-empty override is provided, and bypasses Git hooks and signing; stage finish requires an explicit user lifecycle request unless the Planning-stage prompt contains the exact line AUTO_STAGE_FINISH: allowed; stage reopen requires a completed stage and a reason; stage restore requires an archived stage and a reason, returns its saved pre-archive status (or in_progress for legacy archives), and requires explicit separate-session resume when actionable; workspace reopen requires a completed workspace and a reason.",
673
747
  }, []);
674
- 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; from an unassociated OpenCode session it also enters the new stage immediately, while an associated session remains on its current stage; 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." }, []);
675
748
  }
676
749
 
677
750
  result(data, changed, next = null) {
package/src/errors.js CHANGED
@@ -4,6 +4,11 @@ export const ERROR_CODES = Object.freeze({
4
4
  LOCKED: "LOCKED", STALE_LOCK: "STALE_LOCK", CONFLICT: "CONFLICT", INVALID_ISSUE_URL: "INVALID_ISSUE_URL",
5
5
  ADAPTER_UNAVAILABLE: "ADAPTER_UNAVAILABLE", STORAGE_ERROR: "STORAGE_ERROR", CONFIRMATION_REQUIRED: "CONFIRMATION_REQUIRED",
6
6
  STAGE_CONTEXT_REQUIRED: "STAGE_CONTEXT_REQUIRED",
7
+ GIT_UNAVAILABLE: "GIT_UNAVAILABLE", NOT_GIT_REPOSITORY: "NOT_GIT_REPOSITORY",
8
+ CANDIDATE_MODE_REQUIRED: "CANDIDATE_MODE_REQUIRED", CANDIDATE_INVALID_PATCH: "CANDIDATE_INVALID_PATCH",
9
+ CANDIDATE_UNSUPPORTED: "CANDIDATE_UNSUPPORTED", CANDIDATE_STALE_BASE: "CANDIDATE_STALE_BASE",
10
+ CANDIDATE_CONFLICT: "CANDIDATE_CONFLICT", CANDIDATE_DETACHED_HEAD: "CANDIDATE_DETACHED_HEAD",
11
+ CANDIDATE_REF_RACE: "CANDIDATE_REF_RACE", CANDIDATE_COMMIT_FAILED: "CANDIDATE_COMMIT_FAILED",
7
12
  });
8
13
 
9
14
  export class WorkContextError extends Error {
@@ -0,0 +1,163 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+ import { ERROR_CODES, fail } from "./errors.js";
6
+
7
+ const git = (root, args, options = {}) => {
8
+ const result = spawnSync("git", args, {
9
+ cwd: root,
10
+ encoding: options.encoding === null ? null : "utf8",
11
+ env: { ...process.env, ...options.env },
12
+ input: options.input,
13
+ maxBuffer: 64 * 1024 * 1024,
14
+ });
15
+ if (result.error?.code === "ENOENT") fail(ERROR_CODES.GIT_UNAVAILABLE, "Git executable is unavailable");
16
+ if (result.error) fail(ERROR_CODES.GIT_UNAVAILABLE, "Cannot execute Git", { cause: result.error.message });
17
+ if (result.status !== 0 && !options.allowFailure) {
18
+ fail(options.code || ERROR_CODES.CANDIDATE_INVALID_PATCH, options.message || "Git operation failed", {
19
+ stderr: String(result.stderr || "").trim(),
20
+ });
21
+ }
22
+ return result;
23
+ };
24
+
25
+ export function repositoryState(projectRoot) {
26
+ const rootResult = git(projectRoot, ["rev-parse", "--show-toplevel"], {
27
+ allowFailure: true,
28
+ });
29
+ if (rootResult.status !== 0) fail(ERROR_CODES.NOT_GIT_REPOSITORY, "Work context is not at a Git repository root");
30
+ const root = fs.realpathSync(rootResult.stdout.trim());
31
+ if (root !== fs.realpathSync(projectRoot)) fail(ERROR_CODES.NOT_GIT_REPOSITORY, "Work context must be at the Git repository root", { repositoryRoot: root });
32
+ const head = git(root, ["rev-parse", "--verify", "HEAD"], {
33
+ allowFailure: true,
34
+ });
35
+ if (head.status !== 0) fail(ERROR_CODES.CANDIDATE_STALE_BASE, "Git repository has no valid HEAD");
36
+ return { root, head: head.stdout.trim() };
37
+ }
38
+
39
+ function withTemporaryIndex(root, base, fn) {
40
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "work-context-candidate-"));
41
+ const index = path.join(directory, "index");
42
+ const env = { GIT_INDEX_FILE: index, GIT_OPTIONAL_LOCKS: "0", GIT_LITERAL_PATHSPECS: "1" };
43
+ try {
44
+ const baseCheck = git(root, ["cat-file", "-e", `${base}^{commit}`], { allowFailure: true });
45
+ if (baseCheck.status !== 0) fail(ERROR_CODES.CANDIDATE_STALE_BASE, "Candidate base commit is unavailable", { base });
46
+ git(root, ["read-tree", base], { env, code: ERROR_CODES.CANDIDATE_STALE_BASE, message: "Cannot populate the candidate index" });
47
+ return fn(env);
48
+ } finally {
49
+ fs.rmSync(directory, { recursive: true, force: true });
50
+ }
51
+ }
52
+
53
+ const currentBranch = (root) => {
54
+ const result = git(root, ["symbolic-ref", "--quiet", "HEAD"], { allowFailure: true });
55
+ const branch = result.stdout.trim();
56
+ if (result.status !== 0 || !branch.startsWith("refs/heads/")) {
57
+ fail(ERROR_CODES.CANDIDATE_DETACHED_HEAD, "Candidate commits require an attached local branch");
58
+ }
59
+ return branch;
60
+ };
61
+
62
+ const rejectUnsupportedPatch = (patchText) => {
63
+ if (typeof patchText !== "string" || !patchText.trim()) fail(ERROR_CODES.CANDIDATE_INVALID_PATCH, "A non-empty unified patch is required");
64
+ if (patchText.includes("\0") || /^(?:GIT binary patch|Binary files .* differ)$/m.test(patchText)) {
65
+ fail(ERROR_CODES.CANDIDATE_UNSUPPORTED, "Binary candidate patches are not supported");
66
+ }
67
+ if (/^(?:(?:old|new|new file|deleted file) mode 160000|index [0-9a-f]+\.\.[0-9a-f]+ 160000)$/m.test(patchText)) {
68
+ fail(ERROR_CODES.CANDIDATE_UNSUPPORTED, "Gitlink and submodule candidate patches are not supported");
69
+ }
70
+ if (!/^diff --git a\/.+ b\/.+/m.test(patchText)) fail(ERROR_CODES.CANDIDATE_INVALID_PATCH, "Expected a Git unified patch");
71
+ };
72
+
73
+ const patchFromIndex = (root, base, env) => {
74
+ const result = git(root, ["diff", "--cached", "--no-ext-diff", "--no-textconv", "--no-color", "--full-index", "--find-renames", base, "--"], { env });
75
+ rejectUnsupportedPatch(result.stdout);
76
+ return result.stdout;
77
+ };
78
+
79
+ export function normalizeCandidatePaths(root, personalRoot, values) {
80
+ if (!Array.isArray(values) || !values.length) fail(ERROR_CODES.INVALID_ARGUMENT, "At least one path is required");
81
+ const personal = fs.existsSync(personalRoot) ? fs.realpathSync(personalRoot) : path.resolve(personalRoot);
82
+ const normalized = values.map((value) => {
83
+ if (typeof value !== "string" || !value.trim() || value.includes("\0")) fail(ERROR_CODES.INVALID_ARGUMENT, "Candidate paths must be non-empty strings");
84
+ const absolute = path.resolve(root, value);
85
+ const relative = path.relative(root, absolute);
86
+ if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) fail(ERROR_CODES.INVALID_ARGUMENT, "Candidate path must be inside the repository", { path: value });
87
+ if (absolute === personal || absolute.startsWith(`${personal}${path.sep}`)) fail(ERROR_CODES.INVALID_ARGUMENT, "Candidate storage cannot be captured", { path: value });
88
+ return relative.split(path.sep).join("/");
89
+ });
90
+ return [...new Set(normalized)].sort();
91
+ }
92
+
93
+ export function capturePaths(root, personalRoot, base, values) {
94
+ const paths = normalizeCandidatePaths(root, personalRoot, values);
95
+ return withTemporaryIndex(root, base, (env) => {
96
+ const result = git(root, ["add", "-A", "--", ...paths], { env, allowFailure: true });
97
+ if (result.status !== 0) fail(ERROR_CODES.CANDIDATE_UNSUPPORTED, "Cannot capture one or more candidate paths", { stderr: result.stderr.trim() });
98
+ return { patch: patchFromIndex(root, base, env), paths };
99
+ });
100
+ }
101
+
102
+ export function capturePatch(root, personalRoot, base, patchText) {
103
+ rejectUnsupportedPatch(patchText);
104
+ const worktreeCheck = git(root, ["apply", "--check", "--reverse", "--whitespace=nowarn", "-"], { input: patchText, allowFailure: true });
105
+ if (worktreeCheck.status !== 0) fail(ERROR_CODES.CANDIDATE_INVALID_PATCH, "Patch does not match the current working tree", { stderr: worktreeCheck.stderr.trim() });
106
+ return withTemporaryIndex(root, base, (env) => {
107
+ const check = git(root, ["apply", "--cached", "--check", "--whitespace=nowarn", "-"], { env, input: patchText, allowFailure: true });
108
+ if (check.status !== 0) fail(ERROR_CODES.CANDIDATE_INVALID_PATCH, "Patch does not apply safely to the candidate base", { stderr: check.stderr.trim() });
109
+ git(root, ["apply", "--cached", "--whitespace=nowarn", "-"], { env, input: patchText });
110
+ const patch = patchFromIndex(root, base, env);
111
+ const names = git(root, ["diff", "--cached", "--name-only", "-z", base, "--"], { env, encoding: null }).stdout;
112
+ return { patch, paths: normalizeCandidatePaths(root, personalRoot, names.toString("utf8").split("\0").filter(Boolean)) };
113
+ });
114
+ }
115
+
116
+ export function previewPatch(root, base, patchText) {
117
+ rejectUnsupportedPatch(patchText);
118
+ return withTemporaryIndex(root, base, (env) => {
119
+ const applied = git(root, ["apply", "--cached", "--check", "--whitespace=nowarn", "-"], { env, input: patchText, allowFailure: true });
120
+ if (applied.status !== 0) fail(ERROR_CODES.CANDIDATE_INVALID_PATCH, "Stored candidate patch is invalid", { stderr: applied.stderr.trim() });
121
+ git(root, ["apply", "--cached", "--whitespace=nowarn", "-"], { env, input: patchText });
122
+ const patch = patchFromIndex(root, base, env);
123
+ const stat = git(root, ["diff", "--cached", "--stat", "--no-color", base, "--"], { env }).stdout.trimEnd();
124
+ const currentHead = repositoryState(root).head;
125
+ return { patch, stat, stale: currentHead !== base, current_head: currentHead };
126
+ });
127
+ }
128
+
129
+ export function commitPatch(root, base, patchText, message, options = {}) {
130
+ rejectUnsupportedPatch(patchText);
131
+ if (typeof message !== "string" || !message.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Commit message is required");
132
+ const repository = repositoryState(root);
133
+ const branch = currentBranch(repository.root);
134
+ const baseCheck = git(repository.root, ["cat-file", "-e", `${base}^{commit}`], { allowFailure: true });
135
+ if (baseCheck.status !== 0) fail(ERROR_CODES.CANDIDATE_STALE_BASE, "Candidate base commit is unavailable", { base });
136
+
137
+ return withTemporaryIndex(repository.root, repository.head, (env) => {
138
+ const applied = git(repository.root, ["apply", "--cached", "--check", "--whitespace=nowarn", "-"], { env, input: patchText, allowFailure: true });
139
+ if (applied.status !== 0) {
140
+ const stale = repository.head !== base;
141
+ fail(stale ? ERROR_CODES.CANDIDATE_CONFLICT : ERROR_CODES.CANDIDATE_INVALID_PATCH,
142
+ stale ? "Candidate overlaps changes made since its base" : "Stored candidate patch is invalid",
143
+ { base, currentHead: repository.head, stderr: applied.stderr.trim() });
144
+ }
145
+ git(repository.root, ["apply", "--cached", "--whitespace=nowarn", "-"], { env, input: patchText });
146
+ const tree = git(repository.root, ["write-tree"], { env, code: ERROR_CODES.CANDIDATE_COMMIT_FAILED, message: "Cannot write candidate tree" }).stdout.trim();
147
+ const commitResult = git(repository.root, ["commit-tree", tree, "-p", repository.head], {
148
+ env,
149
+ input: `${message.trim()}\n`,
150
+ allowFailure: true,
151
+ });
152
+ if (commitResult.status !== 0) fail(ERROR_CODES.CANDIDATE_COMMIT_FAILED, "Cannot create candidate commit", { stderr: commitResult.stderr.trim() });
153
+ const commit = commitResult.stdout.trim();
154
+ options.beforeUpdateRef?.({ branch, commit, head: repository.head });
155
+ const updated = git(repository.root, ["update-ref", branch, commit, repository.head], { allowFailure: true });
156
+ if (updated.status !== 0) fail(ERROR_CODES.CANDIDATE_REF_RACE, "Branch changed while publishing the candidate", {
157
+ branch,
158
+ expectedHead: repository.head,
159
+ stderr: updated.stderr.trim(),
160
+ });
161
+ return { branch, previous_head: repository.head, commit, stale: repository.head !== base };
162
+ });
163
+ }
package/src/index.js CHANGED
@@ -10,3 +10,5 @@ export * from "./knowledge.js";
10
10
  export * from "./stages-snapshot.js";
11
11
  export * from "./stages-renderer.js";
12
12
  export * from "./work-context-snapshot.js";
13
+ export * from "./git-candidates.js";
14
+ export * from "./candidates.js";
@@ -56,9 +56,11 @@ export function renderStagesPanel(result) {
56
56
 
57
57
  const lines = [
58
58
  snapshot.workspace.title,
59
- "",
60
- `Stages · ${snapshot.workspace.status}`,
59
+ `Workflow · ${snapshot.workspace.mode || "standard"}`,
61
60
  ];
61
+ const candidates = snapshot.workspace.candidates;
62
+ if (candidates && (candidates.pending || candidates.ready)) lines.push(`Candidates · pending ${candidates.pending} · ready ${candidates.ready}`);
63
+ lines.push("", `Stages · ${snapshot.workspace.status}`);
62
64
  for (const stage of snapshot.stages) {
63
65
  lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}${stage.depends_on?.length ? `\nDeps: ${stage.depends_on.join(", ")}` : ""}`);
64
66
  }
@@ -34,6 +34,8 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
34
34
  if (!session) return { ok: true, data: emptySnapshot() };
35
35
 
36
36
  const workspace = context.storage.readWorkspace(session.workspace).data;
37
+ const mode = workspace.mode || "standard";
38
+ const candidates = mode === "startup" ? context.candidates().summary(session.workspace) : null;
37
39
  const stages = context.listStages(session.workspace).data.stages
38
40
  .filter((stage) => stage.status !== "archived")
39
41
  .sort((left, right) => Number(left.stage) - Number(right.stage))
@@ -52,7 +54,7 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
52
54
  ok: true,
53
55
  data: {
54
56
  schema: 1,
55
- workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status },
57
+ workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status, mode, ...(candidates ? { candidates } : {}) },
56
58
  stages,
57
59
  currentStage,
58
60
  generatedAt: new Date().toISOString(),
package/src/storage.js CHANGED
@@ -88,13 +88,13 @@ const validateEventStream = (events) => {
88
88
  }
89
89
  };
90
90
  function validateMetadata(data, kind, workspace, stage = null) {
91
- const allowed = kind === "workspace" ? ["schema", "workspace", "title", "status", "created_at", "updated_at", "tracker_links", "reopen_history"] : ["schema", "workspace", "stage", "title", "status", "goal", "prompt", "depends_on", "owner", "created_at", "updated_at", "tracker_links", "reopen_history", "archive_history"];
91
+ const allowed = kind === "workspace" ? ["schema", "workspace", "title", "status", "mode", "created_at", "updated_at", "tracker_links", "reopen_history"] : ["schema", "workspace", "stage", "title", "status", "goal", "prompt", "depends_on", "owner", "created_at", "updated_at", "tracker_links", "reopen_history", "archive_history"];
92
92
  if (Object.keys(data).some((key) => !allowed.includes(key)) || data.schema !== 1 || !requiredString(data, "workspace") || !/^\d{6}$/.test(data.workspace) || data.workspace !== workspace) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} metadata`);
93
93
  if (!requiredString(data, "title") || !validTimestamp(data.created_at) || !validTimestamp(data.updated_at) || Date.parse(data.updated_at) < Date.parse(data.created_at) || !Array.isArray(data.tracker_links)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} metadata`);
94
94
  if (!validTrackerLinks(data.tracker_links) || data.tracker_links.some((link) => !link.provider.trim() || !link.project.trim() || ((link.provider === "gitlab" || link.provider === "github") ? (!Number.isInteger(link.iid) || link.iid < 1) : !link.key?.trim()))) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} tracker links`);
95
95
  const statuses = kind === "workspace" ? ["in_progress", "completed", "cancelled"] : ["planned", "in_progress", "completed", "cancelled", "archived"];
96
96
  if (!statuses.includes(data.status)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} status`);
97
- const invalidWorkspaceHistory = kind === "workspace" && data.reopen_history !== undefined && !validReopenHistory(data.reopen_history);
97
+ const invalidWorkspaceHistory = kind === "workspace" && ((data.mode !== undefined && !["standard", "startup"].includes(data.mode)) || (data.reopen_history !== undefined && !validReopenHistory(data.reopen_history)));
98
98
  const invalidStageMetadata = kind === "stage" && (
99
99
  data.stage !== stage || !/^\d{2}$/.test(data.stage) || !requiredString(data, "goal")
100
100
  || (data.prompt !== undefined && !requiredString(data, "prompt")) || !requiredString(data, "owner")
@@ -56,13 +56,22 @@ const addStageFromTool = (ctx, args, oc) => {
56
56
  export const work_context_list_workspaces = tool({ description: "List work-context workspaces.", args: {}, execute: run((ctx) => ctx.listWorkspaces()) });
57
57
  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)) });
58
58
  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)) });
59
+ export const work_context_set_workspace_mode = tool({ description: "Set a workspace workflow mode.", args: { workspace: tool.schema.string(), mode: tool.schema.enum(["standard", "startup"]) }, execute: run((ctx, a) => ctx.setWorkspaceMode(a.workspace, a.mode)) });
60
+ export const work_context_create_candidate = tool({ description: "Create a local draft commit candidate for a startup-mode workspace.", args: { workspace: tool.schema.string(), title: tool.schema.string(), message: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.createCandidate(a.workspace, a.title, a.message)) });
61
+ export const work_context_capture_candidate = tool({ description: "Capture explicit complete paths or an exact unified patch into a draft commit candidate.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string(), paths: tool.schema.array(tool.schema.string()).optional(), patch: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.captureCandidate(a.workspace, a.candidateId, { paths: a.paths, patch: a.patch })) });
62
+ export const work_context_preview_candidate = tool({ description: "Preview a candidate using an isolated temporary Git index.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string() }, execute: run((ctx, a) => ctx.previewCandidate(a.workspace, a.candidateId)) });
63
+ export const work_context_show_candidate = tool({ description: "Show local candidate metadata and its exact captured patch.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string() }, execute: run((ctx, a) => ctx.showCandidate(a.workspace, a.candidateId)) });
64
+ export const work_context_list_candidates = tool({ description: "List local commit candidates associated with a startup-mode workspace.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.listCandidates(a.workspace)) });
65
+ export const work_context_ready_candidate = tool({ description: "Mark a captured draft candidate ready for a later explicit commit operation.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string() }, execute: run((ctx, a) => ctx.readyCandidate(a.workspace, a.candidateId)) });
66
+ export const work_context_commit_candidate = tool({ description: "Commit a ready candidate atomically without using the ordinary Git index. Uses its stored message unless message is provided.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string(), message: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.commitCandidate(a.workspace, a.candidateId, a.message)) });
67
+ export const work_context_discard_candidate = tool({ description: "Discard a local commit candidate without changing Git state.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string() }, execute: run((ctx, a) => ctx.discardCandidate(a.workspace, a.candidateId)) });
59
68
  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)) });
60
69
  export const work_context_reopen_workspace = tool({ description: "Reopen a completed workspace with a required reason and durable history.", args: { workspace: tool.schema.string(), reason: tool.schema.string() }, execute: run((ctx, a) => ctx.reopenWorkspace(a.workspace, a.reason)) });
61
- 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) => {
70
+ 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(), mode: tool.schema.enum(["standard", "startup"]).optional() }, execute: run((ctx, a, oc) => {
62
71
  const currentSession = ctx.sessionByOpenCodeId(oc.sessionID);
63
- return ctx.createWorkspace(a.title, { sessionId: randomUUID(), ...(currentSession ? {} : { opencodeSessionId: oc.sessionID }) });
72
+ return ctx.createWorkspace(a.title, { sessionId: randomUUID(), mode: a.mode, ...(currentSession ? {} : { opencodeSessionId: oc.sessionID }) });
64
73
  }) });
65
- export const work_context_start_session = tool({ description: "Start a new active session for a stage and return its human-oriented presentation, prompt, and 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 })) });
74
+ export const work_context_start_session = tool({ description: "Start a new active session for a stage and return its human-oriented presentation, prompt, active workspace knowledge, and startup policy when applicable.", 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 })) });
66
75
  export const work_context_add_stage = tool({ description: "Add a stage; when the current OpenCode session is not associated with a workspace, enter the new stage in that session immediately.", 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) });
67
76
  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); }) });
68
77
  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); }) });
@@ -85,4 +94,4 @@ export const work_context_add_knowledge = tool({ description: "Add a durable kno
85
94
  export const work_context_update_knowledge = tool({ description: "Update a durable knowledge entry.", args: { workspace: tool.schema.string(), knowledgeId: tool.schema.string(), title: tool.schema.string().optional(), kind: tool.schema.string().optional(), status: tool.schema.string().optional(), text: tool.schema.string().optional(), sources: tool.schema.array(tool.schema.string()).optional(), replacement: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.updateKnowledge(a.workspace, a.knowledgeId, a)) });
86
95
  export const work_context_supersede_knowledge = tool({ description: "Supersede a durable knowledge entry.", args: { workspace: tool.schema.string(), knowledgeId: tool.schema.string(), replacement: tool.schema.string() }, execute: run((ctx, a) => ctx.supersedeKnowledge(a.workspace, a.knowledgeId, a.replacement) ) });
87
96
 
88
- export default { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_workspace_finish, work_context_reopen_workspace, work_context_create_workspace, work_context_start_session, work_context_add_stage, work_context_rename_stage, work_context_update_stage, work_context_update_stage_prompt, work_context_update_stage_result, work_context_archive_stage, work_context_reopen_stage, work_context_restore_stage, work_context_link_issue, work_context_unlink_issue, work_context_rename_session, work_context_close_session, work_context_force_close_session, work_context_handoff_stage, work_context_abandon_stage, work_context_finish_stage, work_context_help, work_context_list_knowledge, work_context_add_knowledge, work_context_update_knowledge, work_context_supersede_knowledge };
97
+ export default { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_set_workspace_mode, work_context_create_candidate, work_context_capture_candidate, work_context_preview_candidate, work_context_show_candidate, work_context_list_candidates, work_context_ready_candidate, work_context_commit_candidate, work_context_discard_candidate, work_context_workspace_finish, work_context_reopen_workspace, work_context_create_workspace, work_context_start_session, work_context_add_stage, work_context_rename_stage, work_context_update_stage, work_context_update_stage_prompt, work_context_update_stage_result, work_context_archive_stage, work_context_reopen_stage, work_context_restore_stage, work_context_link_issue, work_context_unlink_issue, work_context_rename_session, work_context_close_session, work_context_force_close_session, work_context_handoff_stage, work_context_abandon_stage, work_context_finish_stage, work_context_help, work_context_list_knowledge, work_context_add_knowledge, work_context_update_knowledge, work_context_supersede_knowledge };
@@ -31,10 +31,14 @@ const readWorkspace = (context, record, currentSession) => {
31
31
  ? currentSession
32
32
  : sessions.find((session) => session.session_id === currentSession?.session_id);
33
33
  const currentStage = matchingSession?.stage || null;
34
+ const mode = record.mode || "standard";
35
+ const candidates = mode === "startup" ? context.candidates().summary(record.workspace) : null;
34
36
  return {
35
37
  id: record.workspace,
36
38
  title: record.title,
37
39
  status: record.status,
40
+ mode,
41
+ ...(candidates ? { candidates } : {}),
38
42
  stages: listed.stages
39
43
  .filter((stage) => stage.status !== "archived")
40
44
  .sort((left, right) => Number(left.stage) - Number(right.stage))
@@ -0,0 +1,3 @@
1
+ import { work_context_capture_candidate } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_capture_candidate;
@@ -0,0 +1,3 @@
1
+ import { work_context_commit_candidate } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_commit_candidate;
@@ -0,0 +1,3 @@
1
+ import { work_context_create_candidate } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_create_candidate;
@@ -0,0 +1,3 @@
1
+ import { work_context_discard_candidate } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_discard_candidate;
@@ -0,0 +1,3 @@
1
+ import { work_context_list_candidates } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_list_candidates;
@@ -0,0 +1,3 @@
1
+ import { work_context_preview_candidate } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_preview_candidate;
@@ -0,0 +1,3 @@
1
+ import { work_context_ready_candidate } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_ready_candidate;
@@ -0,0 +1,3 @@
1
+ import { work_context_set_workspace_mode } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_set_workspace_mode;
@@ -0,0 +1,3 @@
1
+ import { work_context_show_candidate } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_show_candidate;