opencode-work-context 0.7.0 → 0.8.0
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 +31 -0
- package/commands/wc.md +12 -0
- package/package.json +1 -1
- package/plugin/attention.js +2 -1
- package/plugin/project-root.js +49 -0
- package/plugin/stages-tui.js +5 -25
- package/plugin/work-context-modal.js +12 -7
- package/src/core.js +67 -5
- package/src/errors.js +1 -0
- package/src/index.js +1 -0
- package/src/stage-execution.js +88 -0
- package/src/storage.js +14 -0
- package/src/tool-definitions.js +12 -1
- package/tools/work_context_read_stage_execution.js +1 -0
- package/tools/work_context_replace_stage_execution.js +1 -0
- package/tools/work_context_update_stage_execution.js +1 -0
package/README.md
CHANGED
|
@@ -101,6 +101,27 @@ Resume a stage with:
|
|
|
101
101
|
/wc resume 000001 02
|
|
102
102
|
```
|
|
103
103
|
|
|
104
|
+
Long-running stages may keep a bounded execution ledger separate from the
|
|
105
|
+
original prompt, workspace knowledge, session summaries, and final result. It
|
|
106
|
+
tracks current scope, completed and remaining work, stage-local decisions,
|
|
107
|
+
blockers, and pending verification. Read it before changing it, then use the
|
|
108
|
+
returned revision as an optimistic concurrency guard:
|
|
109
|
+
|
|
110
|
+
```text
|
|
111
|
+
/wc stage execution read 000001 02
|
|
112
|
+
/wc stage execution replace 000001 02 0 "{\"scope\":[\"Add CSV export\"],\"remaining\":[\"Implement endpoint\",\"Add tests\"]}"
|
|
113
|
+
/wc stage execution update 000001 02 1 "{\"add\":{\"completed\":[\"Implement endpoint\"]},\"remove\":{\"remaining\":[\"Implement endpoint\"]}}"
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
`replace` replaces the complete logical state; any omitted section becomes empty. `update`
|
|
117
|
+
atomically adds and removes exact normalized items. Mutations require the active
|
|
118
|
+
stage session. A stale revision fails with `EXECUTION_REVISION_CONFLICT` rather
|
|
119
|
+
than overwriting newer work. Each section is limited to 50 items, the complete
|
|
120
|
+
state to 200 items and 32,768 serialized bytes, and each item to 500 characters.
|
|
121
|
+
Update the ledger at meaningful boundaries, not after every edit. Checklist
|
|
122
|
+
state never completes a stage: explicit stage finish reports unfinished ledger
|
|
123
|
+
entries as warnings and preserves the final record.
|
|
124
|
+
|
|
104
125
|
After updating the npm package, refresh the generated slash-command contract
|
|
105
126
|
without touching project configuration or loaders:
|
|
106
127
|
|
|
@@ -277,6 +298,9 @@ Installed files and project state:
|
|
|
277
298
|
- `.work-context/local/` in `.gitignore` for personal session events.
|
|
278
299
|
- `<workspace>/KNOWLEDGE.md` is the canonical durable knowledge ledger and is
|
|
279
300
|
created on the first explicit knowledge operation.
|
|
301
|
+
- `<workspace>/stages/<stage>.execution.json` is the optional canonical,
|
|
302
|
+
stage-local execution ledger and is created on the first explicit replacement
|
|
303
|
+
or incremental update.
|
|
280
304
|
|
|
281
305
|
The optional stages panel, action modal, and stage switcher are a separate TUI plugin. `init` installs a
|
|
282
306
|
project-local loader outside OpenCode's server-plugin autoscan at
|
|
@@ -407,6 +431,8 @@ Tools are registered by the installed server export and are not copied into the
|
|
|
407
431
|
project. Core and storage remain in the installed package; projects should not
|
|
408
432
|
copy `src/` or `tools/`. `.work-context` Markdown, JSONL, `INDEX.md`, and
|
|
409
433
|
`SESSIONS.md` are generated projections and must never be edited manually.
|
|
434
|
+
Canonical execution JSON is also owned by structured tools and must not be
|
|
435
|
+
edited directly.
|
|
410
436
|
Tracker links support GitLab issues (`/-/issues/<number>`) and work items
|
|
411
437
|
(`/-/work_items/<number>`), GitHub issues (`/issues/<number>`), and Jira issues
|
|
412
438
|
(`/browse/KEY-123`). They are URL-based references only; the plugin does not
|
|
@@ -422,6 +448,11 @@ Every stage start/resume includes all active entries in
|
|
|
422
448
|
workspace-wide context and avoid repeating earlier analysis unless an entry is
|
|
423
449
|
incomplete, contradicted, or requires verification. Superseded entries and full
|
|
424
450
|
stage results are not injected into later stages.
|
|
451
|
+
When a stage has execution state, resume also includes it in
|
|
452
|
+
`resume.context.execution_state` and highlights it as the current operational
|
|
453
|
+
checkpoint. The ledger remains local to that stage and is not injected into
|
|
454
|
+
unrelated stages or promoted to workspace knowledge. Existing stages without a
|
|
455
|
+
ledger retain their previous resume shape and are not rewritten.
|
|
425
456
|
Finishing a stage closes its current session and may report downstream stages
|
|
426
457
|
whose prompts need review, but it never starts or resumes one of them. Any
|
|
427
458
|
downstream work begins only in a separate OpenCode session through an explicit
|
package/commands/wc.md
CHANGED
|
@@ -48,6 +48,9 @@ Use these exact tool mappings; do not invent shortened tool names:
|
|
|
48
48
|
- `stage update [<workspace>] [<stage>] "description"` -> `work_context_update_stage`
|
|
49
49
|
- `stage update-prompt [<workspace>] [<stage>] "prompt"` -> `work_context_update_stage_prompt`
|
|
50
50
|
- `stage update-result [<workspace>] [<stage>] "result"` -> `work_context_update_stage_result`
|
|
51
|
+
- `stage execution read [<workspace>] [<stage>]` -> `work_context_read_stage_execution`
|
|
52
|
+
- `stage execution replace [<workspace>] [<stage>] <expectedRevision> "state JSON"` -> `work_context_replace_stage_execution`
|
|
53
|
+
- `stage execution update [<workspace>] [<stage>] <expectedRevision> "changes JSON"` -> `work_context_update_stage_execution`
|
|
51
54
|
- `stage archive [<workspace>] [<stage>]` -> `work_context_archive_stage`
|
|
52
55
|
- `stage handoff [<workspace>] [<stage>]` -> `work_context_handoff_stage`
|
|
53
56
|
- `stage abandon [<workspace>] [<stage>]` -> `work_context_abandon_stage`
|
|
@@ -82,6 +85,9 @@ Supported syntax:
|
|
|
82
85
|
- `stage update [<workspace>] [<stage>] "description"`
|
|
83
86
|
- `stage update-prompt [<workspace>] [<stage>] "prompt"`
|
|
84
87
|
- `stage update-result [<workspace>] [<stage>] "result"`
|
|
88
|
+
- `stage execution read [<workspace>] [<stage>]`
|
|
89
|
+
- `stage execution replace [<workspace>] [<stage>] <expectedRevision> "state JSON"`
|
|
90
|
+
- `stage execution update [<workspace>] [<stage>] <expectedRevision> "changes JSON"`
|
|
85
91
|
- `stage archive [<workspace>] [<stage>]`
|
|
86
92
|
- `stage handoff [<workspace>] [<stage>]`
|
|
87
93
|
- `stage abandon [<workspace>] [<stage>]`
|
|
@@ -96,10 +102,15 @@ Supported syntax:
|
|
|
96
102
|
- explicit workspace and stage positions accept canonical padded IDs or unpadded positive integers (`1..999999` and `1..99`); results and generated commands remain padded
|
|
97
103
|
- zero, signs, decimals, whitespace, overlong values, and other non-digit identifier forms are invalid; a lone unpadded workspace ID is not reinterpreted under the one-identifier rule
|
|
98
104
|
- `stage update-result` replaces an existing result and does not create a result for an unfinished stage
|
|
105
|
+
- stage execution state has `scope`, `completed`, `remaining`, `decisions`, `blockers`, and `verification` string-array sections; `replace` accepts the complete state object, while `update` accepts an object with `add` and/or `remove` section objects
|
|
106
|
+
- read stage execution state first and pass its revision as `expectedRevision`; absent legacy state has revision `0`, and a stale mutation returns `EXECUTION_REVISION_CONFLICT` without changing newer state
|
|
107
|
+
- execution mutations require the active stage session, trim and deduplicate items, reject overlap between `completed` and `remaining`, and enforce bounded item counts, lengths, and serialized size
|
|
108
|
+
- update execution state after meaningful scope changes, decisions, substantial work, blockers, or verification changes and before handoff; do not update it for every trivial edit or tool call
|
|
99
109
|
- `resume` returns `resume.presentation` and `resume.context`; before doing any work, report a concise human-oriented summary in the user's language with the stage title, a plain-language Goal, previous progress when useful, and the immediate next action
|
|
100
110
|
- 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
|
|
101
111
|
- do not expose raw workspace/stage/session identifiers, ordinals, `ok` flags, or absent error codes in the user-facing resume summary
|
|
102
112
|
- `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
|
|
113
|
+
- when stage execution state exists, `resume.context.execution_state` is the current stage-local operational checkpoint; continue from it without rewriting the original prompt, and never copy it automatically into workspace knowledge or unrelated stages
|
|
103
114
|
- 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, and ready work should be captured promptly into an explicit candidate; prefer an `exact` candidate when safely separable, use `shared_foundation` when several stages use one coherent change, and use `integration` when intertwined changes form one reviewable and testable result; mixed provenance and complete files containing unrelated stage work are not reasons to require prior commits or stop; stop only for a concrete patch conflict, an incoherent candidate boundary, or failed required verification
|
|
104
115
|
- standard-mode and unassociated core sessions do not receive startup policy; retain the existing conservative worktree behavior there
|
|
105
116
|
- after presenting the summary, continue work immediately when `resume.next_action` is `start_work`; do not ask for generic confirmation
|
|
@@ -114,6 +125,7 @@ Supported syntax:
|
|
|
114
125
|
- automatic completion is allowed only when the current workspace's Planning-stage prompt contains an exact standalone line `AUTO_STAGE_FINISH: allowed`; otherwise leave the stage in progress and report that the work is ready for the user's lifecycle decision
|
|
115
126
|
- `stage finish` closes and completes only the current stage session; it never starts, resumes, or binds the same OpenCode session to a downstream stage
|
|
116
127
|
- `stage finish` always validates the Knowledge Base and returns total and active entry counts plus downstream unfinished stages for informational prompt review; do not begin a downstream stage until the user explicitly resumes it in a separate OpenCode session
|
|
128
|
+
- execution checklist state never finishes a stage; explicit `stage finish` reports remaining items, blockers, and pending verification as warnings and preserves the final execution record for history
|
|
117
129
|
- `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
|
|
118
130
|
- `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`.
|
|
119
131
|
- `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.
|
package/package.json
CHANGED
package/plugin/attention.js
CHANGED
|
@@ -7,6 +7,7 @@ import { createAttentionActivator } from "./attention-activation.js";
|
|
|
7
7
|
import { createDesktopNotifier } from "./notifier.js";
|
|
8
8
|
import { createTuiFocusTracker } from "./tui-focus.js";
|
|
9
9
|
import { readTuiState, updateTuiState } from "./tui-state.js";
|
|
10
|
+
import { resolveProjectRoot } from "./project-root.js";
|
|
10
11
|
|
|
11
12
|
const ATTENTION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
12
13
|
const MAX_SEEN_EVENTS = 500;
|
|
@@ -489,7 +490,7 @@ export const createAttentionTuiController = ({ api, projectRoot, read = readWork
|
|
|
489
490
|
export const tui = async (api, options = {}) => {
|
|
490
491
|
if (!api?.event?.on) return;
|
|
491
492
|
if (activeControllers.has(api) || api[ACTIVE_ATTENTION_KEY]) return activeControllers.get(api) || api[ACTIVE_ATTENTION_KEY];
|
|
492
|
-
const projectRoot = api
|
|
493
|
+
const projectRoot = await resolveProjectRoot(api, options);
|
|
493
494
|
if (!projectRoot) return;
|
|
494
495
|
const ownsDesktopNotifier = !options.desktopNotifier;
|
|
495
496
|
const desktopNotifier = options.desktopNotifier || createDesktopNotifier({ enabled: desktopNotificationsEnabled(projectRoot), ...options.notifierOptions });
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
const PATH_TIMEOUT_MS = 5000;
|
|
2
|
+
const PATH_POLL_MS = 25;
|
|
3
|
+
const usableDirectory = (value) => typeof value === "string" && value && value !== "/";
|
|
4
|
+
|
|
5
|
+
const sleep = (milliseconds, signal) => new Promise((resolve) => {
|
|
6
|
+
const timer = setTimeout(resolve, milliseconds);
|
|
7
|
+
const onAbort = () => { clearTimeout(timer); resolve(); };
|
|
8
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
9
|
+
if (signal) setTimeout(() => signal.removeEventListener("abort", onAbort), milliseconds);
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
const locationWithDeadline = (api, timeoutMs, signal) => new Promise((resolve) => {
|
|
13
|
+
let settled = false;
|
|
14
|
+
const finish = (value) => {
|
|
15
|
+
if (settled) return;
|
|
16
|
+
settled = true;
|
|
17
|
+
clearTimeout(timer);
|
|
18
|
+
signal?.removeEventListener("abort", onAbort);
|
|
19
|
+
resolve(value);
|
|
20
|
+
};
|
|
21
|
+
const timer = setTimeout(() => finish(null), timeoutMs);
|
|
22
|
+
const onAbort = () => finish(null);
|
|
23
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
24
|
+
Promise.resolve().then(() => api.client.location.get({})).then(finish, () => finish(null));
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
export const resolveProjectRoot = async (api, { timeoutMs = PATH_TIMEOUT_MS, pollMs = PATH_POLL_MS } = {}) => {
|
|
28
|
+
const directory = api?.state?.path?.directory;
|
|
29
|
+
if (!usableDirectory(api?.state?.path?.worktree) && usableDirectory(directory)) return directory;
|
|
30
|
+
if (!api?.state?.path && !api?.client?.location?.get) return null;
|
|
31
|
+
const signal = api?.lifecycle?.signal;
|
|
32
|
+
const deadline = Date.now() + timeoutMs;
|
|
33
|
+
while (!signal?.aborted && Date.now() <= deadline) {
|
|
34
|
+
const worktree = api?.state?.path?.worktree;
|
|
35
|
+
if (usableDirectory(worktree)) return worktree;
|
|
36
|
+
if (usableDirectory(directory)) return directory;
|
|
37
|
+
const remaining = deadline - Date.now();
|
|
38
|
+
if (remaining <= 0) break;
|
|
39
|
+
const location = await locationWithDeadline(api, remaining, signal);
|
|
40
|
+
const locationDirectory = location?.data?.directory || location?.data?.project?.directory;
|
|
41
|
+
if (usableDirectory(locationDirectory)) return locationDirectory;
|
|
42
|
+
await sleep(pollMs, signal);
|
|
43
|
+
}
|
|
44
|
+
return null;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export const withProjectRoot = (api, projectRoot) => projectRoot
|
|
48
|
+
? Object.assign(Object.create(api), { state: { ...api.state, path: { ...api.state?.path, directory: projectRoot, worktree: projectRoot } } })
|
|
49
|
+
: api;
|
package/plugin/stages-tui.js
CHANGED
|
@@ -8,13 +8,12 @@ import { createSignal } from "solid-js";
|
|
|
8
8
|
import { attentionSummaryText } from "./attention.js";
|
|
9
9
|
import { createStageSwitcherFlow } from "./stage-switcher.js";
|
|
10
10
|
import { readTuiState, updateTuiState } from "./tui-state.js";
|
|
11
|
+
import { resolveProjectRoot, withProjectRoot } from "./project-root.js";
|
|
11
12
|
|
|
12
13
|
const DEBOUNCE_MS = 150;
|
|
13
14
|
const POLL_MS = 1000;
|
|
14
15
|
const LOADER_MS = 80;
|
|
15
16
|
const LOADER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
16
|
-
const PATH_TIMEOUT_MS = 5000;
|
|
17
|
-
const PATH_POLL_MS = 25;
|
|
18
17
|
const WORK_CONTEXT_PREFIX = "work" + "_" + "context_";
|
|
19
18
|
const activeTuiInstances = new WeakMap();
|
|
20
19
|
const ACTIVE_TUI_KEY = Symbol.for("opencode-work-context.stages-tui");
|
|
@@ -262,28 +261,7 @@ export const createStagesTuiController = ({ projectRoot, read = readStagesSnapsh
|
|
|
262
261
|
};
|
|
263
262
|
};
|
|
264
263
|
|
|
265
|
-
|
|
266
|
-
const timer = setTimeout(resolve, milliseconds);
|
|
267
|
-
const onAbort = () => { clearTimeout(timer); resolve(); };
|
|
268
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
269
|
-
if (signal) setTimeout(() => signal.removeEventListener("abort", onAbort), milliseconds);
|
|
270
|
-
});
|
|
271
|
-
|
|
272
|
-
export const resolveProjectRoot = async (api, { timeoutMs = PATH_TIMEOUT_MS, pollMs = PATH_POLL_MS } = {}) => {
|
|
273
|
-
if (!api?.slots?.register) return null;
|
|
274
|
-
const signal = api.lifecycle?.signal;
|
|
275
|
-
const deadline = Date.now() + timeoutMs;
|
|
276
|
-
while (!signal?.aborted && Date.now() <= deadline) {
|
|
277
|
-
if (api.state?.path?.worktree) return api.state.path.worktree;
|
|
278
|
-
try {
|
|
279
|
-
const location = await api.client?.location?.get?.({});
|
|
280
|
-
const directory = location?.data?.directory || location?.data?.project?.directory;
|
|
281
|
-
if (directory) return directory;
|
|
282
|
-
} catch {}
|
|
283
|
-
await sleep(pollMs, signal);
|
|
284
|
-
}
|
|
285
|
-
return null;
|
|
286
|
-
};
|
|
264
|
+
export { resolveProjectRoot } from "./project-root.js";
|
|
287
265
|
|
|
288
266
|
const renderStagesSlot = (controller, theme, sessionId, runtime = defaultRuntime, attention, onStageSelect) => runtime.jsx("box", {
|
|
289
267
|
flexDirection: "column",
|
|
@@ -376,8 +354,10 @@ const ACTIVE_WORKSPACE_SESSION = "__active_" + "work" + "_context_workspace__";
|
|
|
376
354
|
// Optional TUI entry point. It is deliberately not imported by the server plugin.
|
|
377
355
|
export const tui = async (api, options = {}) => {
|
|
378
356
|
if (activeTuiInstances.has(api) || api?.[ACTIVE_TUI_KEY]) return activeTuiInstances.get(api) || api[ACTIVE_TUI_KEY];
|
|
357
|
+
if (!api?.slots?.register) return;
|
|
379
358
|
const projectRoot = await resolveProjectRoot(api, options);
|
|
380
359
|
if (!projectRoot) return;
|
|
360
|
+
const projectApi = withProjectRoot(api, projectRoot);
|
|
381
361
|
|
|
382
362
|
const initialSessionId = api.route?.current?.name === "session"
|
|
383
363
|
? api.route.current.params?.sessionID
|
|
@@ -393,7 +373,7 @@ export const tui = async (api, options = {}) => {
|
|
|
393
373
|
createSignal: options.runtime?.createSignal,
|
|
394
374
|
attention: api.workContextAttention,
|
|
395
375
|
});
|
|
396
|
-
const stageSwitcher = createStageSwitcherFlow(
|
|
376
|
+
const stageSwitcher = createStageSwitcherFlow(projectApi);
|
|
397
377
|
const unregisterDependencyToggle = registerDependencyToggle(api, controller, projectRoot);
|
|
398
378
|
let currentSessionId = initialSessionId;
|
|
399
379
|
const unregisterDependencyTree = registerDependencyTree(api, controller, () => currentSessionId || ACTIVE_WORKSPACE_SESSION);
|
|
@@ -8,6 +8,7 @@ import { openStageSwitcher } from "./stage-switcher.js";
|
|
|
8
8
|
import { openWorkspaceSwitcher } from "./workspace-switcher.js";
|
|
9
9
|
import { openSessionSwitcher } from "./session-switcher.js";
|
|
10
10
|
import { attentionForSession, attentionIndicatorText, attentionReasonText } from "./attention.js";
|
|
11
|
+
import { resolveProjectRoot, withProjectRoot } from "./project-root.js";
|
|
11
12
|
|
|
12
13
|
const COMMAND_NAME = "work_context.open";
|
|
13
14
|
const ACTIONS_COMMAND_NAME = "work_context.actions";
|
|
@@ -585,13 +586,14 @@ export const openCompatibilityDialog = (api, runtime = {}, options = {}) => {
|
|
|
585
586
|
return true;
|
|
586
587
|
};
|
|
587
588
|
|
|
588
|
-
export const registerWorkContextModal = (api, runtime = {}) => {
|
|
589
|
+
export const registerWorkContextModal = (api, runtime = {}, options = {}) => {
|
|
589
590
|
if (typeof api?.keymap?.registerLayer !== "function") return { supported: false, dispose: () => {} };
|
|
590
|
-
const
|
|
591
|
-
const
|
|
592
|
-
const
|
|
593
|
-
const
|
|
594
|
-
const
|
|
591
|
+
const projectApi = withProjectRoot(api, options.projectRoot);
|
|
592
|
+
const command = { name: COMMAND_NAME, title: "Open Work Context", desc: "Open work-context navigation and actions", category: "Work Context", namespace: "palette", run: () => openWorkContextActionDialog(projectApi, runtime) };
|
|
593
|
+
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(projectApi) };
|
|
594
|
+
const workspaceCommand = { name: "work_context.workspace", title: "Switch Work Context Workspace", desc: "Open a workspace session", category: "Work Context", namespace: "palette", run: () => openWorkspaceSwitcher(projectApi) };
|
|
595
|
+
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(projectApi) };
|
|
596
|
+
const actions = { name: ACTIONS_COMMAND_NAME, title: "Open Work Context Actions", desc: "Prepare a work-context command", category: "Work Context", namespace: "palette", run: () => openWorkContextActionDialog(projectApi, runtime) };
|
|
595
597
|
const registration = api.keymap.registerLayer({
|
|
596
598
|
commands: [command, stageCommand, workspaceCommand, sessionCommand, actions],
|
|
597
599
|
bindings: [
|
|
@@ -606,7 +608,10 @@ export const registerWorkContextModal = (api, runtime = {}) => {
|
|
|
606
608
|
|
|
607
609
|
export const tui = async (api, options = {}) => {
|
|
608
610
|
activeTuiInstances.get(api)?.();
|
|
609
|
-
|
|
611
|
+
if (typeof api?.keymap?.registerLayer !== "function") return;
|
|
612
|
+
const projectRoot = await resolveProjectRoot(api, options);
|
|
613
|
+
if (!projectRoot) return;
|
|
614
|
+
const registration = registerWorkContextModal(api, options.runtime || options, { projectRoot });
|
|
610
615
|
if (!registration.supported) return;
|
|
611
616
|
let disposed = false;
|
|
612
617
|
const cleanup = () => {
|
package/src/core.js
CHANGED
|
@@ -9,6 +9,7 @@ import { nextKnowledgeId, parseKnowledge, renderKnowledge, validateKnowledgeInpu
|
|
|
9
9
|
import { normalizeStageId, normalizeWorkspaceId } from "./identifiers.js";
|
|
10
10
|
import { isDependencySatisfied } from "./stage-status.js";
|
|
11
11
|
import { CandidateStore } from "./candidates.js";
|
|
12
|
+
import { applyExecutionPatch, assertExecutionSize, executionState, normalizeExecutionState } from "./stage-execution.js";
|
|
12
13
|
|
|
13
14
|
const actor = (options) => options.actor || "OpenCode";
|
|
14
15
|
const workspaceMode = (data) => data.mode || "standard";
|
|
@@ -48,6 +49,7 @@ const resumePresentationInstruction = ({ confirmationRequired }) => `Before doin
|
|
|
48
49
|
- Mention previous progress only when presentation.previous_result or presentation.previous_session_summary contains useful information.
|
|
49
50
|
- State the immediate next action in one sentence.
|
|
50
51
|
${confirmationRequired ? "- Ask for the explicitly required confirmation and wait before inspecting or changing application code." : "- Then continue with the work immediately. Do not ask for generic confirmation; ask a focused question only when an unresolved decision genuinely blocks progress."}`;
|
|
52
|
+
const executionInstruction = (record) => record ? `\n\nCurrent stage execution state:\n${JSON.stringify(record, null, 2)}\nTreat this bounded stage-local ledger as the current operational checkpoint. Update it after meaningful scope changes, decisions, substantial work, blockers, or verification changes, and before handoff; do not update it for trivial tool calls.` : "";
|
|
51
53
|
const assertNoSymlinkPath = (file) => { let current = path.parse(file).root; for (const part of file.slice(current.length).split(path.sep).filter(Boolean)) { current = path.join(current, part); try { if (fs.lstatSync(current).isSymbolicLink()) fail(ERROR_CODES.STORAGE_ERROR, `Symlink path component is not supported: ${current}`); } catch (error) { if (error.code !== "ENOENT") throw error; break; } } };
|
|
52
54
|
|
|
53
55
|
function parseIssue(url) {
|
|
@@ -361,6 +363,7 @@ export class WorkContext {
|
|
|
361
363
|
const workspaceTitle = workspaceRecord.title;
|
|
362
364
|
const workflowPolicy = workspaceMode(workspaceRecord) === "startup" && options.opencodeSessionId ? startupWorkflowPolicy() : null;
|
|
363
365
|
const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
|
|
366
|
+
const execution = this.storage.readStageExecution(workspace, stage);
|
|
364
367
|
const automaticFinish = automaticFinishAllowed(this.storage, workspace);
|
|
365
368
|
return this.result({
|
|
366
369
|
workspace,
|
|
@@ -383,18 +386,20 @@ export class WorkContext {
|
|
|
383
386
|
scope: stageRecord.data.prompt || null,
|
|
384
387
|
previous_result: previousResult,
|
|
385
388
|
previous_session_summary: previousSessionSummary,
|
|
389
|
+
...(execution ? { execution_state: execution } : {}),
|
|
386
390
|
},
|
|
387
391
|
context: {
|
|
388
392
|
essence: stageRecord.data.goal || stageRecord.data.title,
|
|
389
393
|
previous: previousSessionSummary || previousResult || "No previous progress was recorded.",
|
|
390
394
|
now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
|
|
391
|
-
|
|
395
|
+
workspace_knowledge: workspaceKnowledge,
|
|
396
|
+
...(execution ? { execution_state: execution } : {}),
|
|
392
397
|
...(workflowPolicy ? { workflow_policy: workflowPolicy } : {}),
|
|
393
398
|
lifecycle: { automatic_finish_allowed: automaticFinish },
|
|
394
399
|
},
|
|
395
400
|
next_action: hasPrompt ? confirmationRequired ? "await_confirmation" : "start_work" : "ask_questions",
|
|
396
401
|
instruction: `${hasPrompt
|
|
397
|
-
? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${startupWorkflowInstruction(workflowPolicy)}`
|
|
402
|
+
? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${executionInstruction(execution)}${startupWorkflowInstruction(workflowPolicy)}`
|
|
398
403
|
: `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.`,
|
|
399
404
|
},
|
|
400
405
|
}, [workspace, stage]);
|
|
@@ -491,6 +496,57 @@ export class WorkContext {
|
|
|
491
496
|
});
|
|
492
497
|
}
|
|
493
498
|
|
|
499
|
+
readStageExecution(workspace, stage) {
|
|
500
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
501
|
+
stage = normalizeStageId(stage);
|
|
502
|
+
this.storage.assertNoSymlinks();
|
|
503
|
+
this.storage.readStage(workspace, stage);
|
|
504
|
+
const record = this.storage.readStageExecution(workspace, stage);
|
|
505
|
+
return { ok: true, data: record || { schema: 1, workspace, stage, revision: 0, exists: false, ...normalizeExecutionState({}) } };
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
replaceStageExecution(workspace, stage, sessionId, expectedRevision, input) {
|
|
509
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
510
|
+
stage = normalizeStageId(stage);
|
|
511
|
+
if (!Number.isInteger(expectedRevision) || expectedRevision < 0) fail(ERROR_CODES.INVALID_ARGUMENT, "expectedRevision must be a non-negative integer");
|
|
512
|
+
const state = normalizeExecutionState(input);
|
|
513
|
+
return this.transact(`stage-execution-${workspace}-${stage}`, () => {
|
|
514
|
+
const stageRecord = this.storage.readStage(workspace, stage);
|
|
515
|
+
if (!["planned", "in_progress"].includes(stageRecord.data.status)) fail(ERROR_CODES.INVALID_STATE, "Execution state can only change for an actionable stage", { status: stageRecord.data.status });
|
|
516
|
+
assertActive(this.storage.readEvents(), workspace, stage, sessionId);
|
|
517
|
+
const current = this.storage.readStageExecution(workspace, stage);
|
|
518
|
+
const revision = current?.revision || 0;
|
|
519
|
+
if (revision !== expectedRevision) fail(ERROR_CODES.EXECUTION_REVISION_CONFLICT, "Stage execution state changed since it was read", { expectedRevision, actualRevision: revision });
|
|
520
|
+
if (current && JSON.stringify(executionState(current)) === JSON.stringify(state)) return this.result(current, []);
|
|
521
|
+
const timestamp = new Date().toISOString();
|
|
522
|
+
const record = { schema: 1, workspace, stage, revision: revision + 1, created_at: current?.created_at || timestamp, updated_at: timestamp, updated_by: actor(this.options), ...state };
|
|
523
|
+
assertExecutionSize(record);
|
|
524
|
+
this.storage.writeStageExecution(workspace, stage, record);
|
|
525
|
+
return this.result(record, [this.storage.stageExecutionFile(workspace, stage)]);
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
updateStageExecution(workspace, stage, sessionId, expectedRevision, patch) {
|
|
530
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
531
|
+
stage = normalizeStageId(stage);
|
|
532
|
+
if (!Number.isInteger(expectedRevision) || expectedRevision < 0) fail(ERROR_CODES.INVALID_ARGUMENT, "expectedRevision must be a non-negative integer");
|
|
533
|
+
return this.transact(`stage-execution-${workspace}-${stage}`, () => {
|
|
534
|
+
const stageRecord = this.storage.readStage(workspace, stage);
|
|
535
|
+
if (!["planned", "in_progress"].includes(stageRecord.data.status)) fail(ERROR_CODES.INVALID_STATE, "Execution state can only change for an actionable stage", { status: stageRecord.data.status });
|
|
536
|
+
assertActive(this.storage.readEvents(), workspace, stage, sessionId);
|
|
537
|
+
const current = this.storage.readStageExecution(workspace, stage);
|
|
538
|
+
const revision = current?.revision || 0;
|
|
539
|
+
if (revision !== expectedRevision) fail(ERROR_CODES.EXECUTION_REVISION_CONFLICT, "Stage execution state changed since it was read", { expectedRevision, actualRevision: revision });
|
|
540
|
+
const state = applyExecutionPatch(current ? executionState(current) : normalizeExecutionState({}), patch);
|
|
541
|
+
if (current && JSON.stringify(executionState(current)) === JSON.stringify(state)) return this.result(current, []);
|
|
542
|
+
const timestamp = new Date().toISOString();
|
|
543
|
+
const record = { schema: 1, workspace, stage, revision: revision + 1, created_at: current?.created_at || timestamp, updated_at: timestamp, updated_by: actor(this.options), ...state };
|
|
544
|
+
assertExecutionSize(record);
|
|
545
|
+
this.storage.writeStageExecution(workspace, stage, record);
|
|
546
|
+
return this.result(record, [this.storage.stageExecutionFile(workspace, stage)]);
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
|
|
494
550
|
archiveStage(workspace, stage) {
|
|
495
551
|
workspace = normalizeWorkspaceId(workspace);
|
|
496
552
|
stage = normalizeStageId(stage);
|
|
@@ -718,6 +774,12 @@ export class WorkContext {
|
|
|
718
774
|
const knowledgeReview = options.knowledgeReview || "auto";
|
|
719
775
|
if (!['auto', 'added', 'none'].includes(knowledgeReview)) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge review must be 'auto', 'added' or 'none'");
|
|
720
776
|
const knowledgeEntries = this.listKnowledge(workspace).data;
|
|
777
|
+
const execution = this.storage.readStageExecution(workspace, stage);
|
|
778
|
+
const executionWarnings = execution ? [
|
|
779
|
+
...(execution.remaining.length ? [`${execution.remaining.length} remaining item(s)`] : []),
|
|
780
|
+
...(execution.blockers.length ? [`${execution.blockers.length} blocker(s) or open question(s)`] : []),
|
|
781
|
+
...(execution.verification.length ? [`${execution.verification.length} pending verification item(s)`] : []),
|
|
782
|
+
] : [];
|
|
721
783
|
const active = activeSession(events, workspace, stage);
|
|
722
784
|
if (!active || active.session_id !== sessionId) fail(active ? ERROR_CODES.ACTIVE_SESSION_EXISTS : ERROR_CODES.SESSION_NOT_ACTIVE, active ? "Another active session owns this stage" : "Session is not active");
|
|
723
785
|
this.writeEvents([event("session.closed", workspace, stage, active.ordinal, sessionId, actor(this.options), { reason: "stage_completed" })]);
|
|
@@ -728,7 +790,7 @@ export class WorkContext {
|
|
|
728
790
|
const promptReview = this.listStages(workspace).data.stages
|
|
729
791
|
.filter((item) => Number(item.stage) > Number(stage) && !["completed", "archived"].includes(item.status))
|
|
730
792
|
.map(({ stage: id, title, description, prompt, status }) => ({ stage: id, title, description, prompt: prompt || null, status }));
|
|
731
|
-
const data = { session_id: sessionId, workspace, stage, state: "closed", status: "completed", next_stage_started: false, knowledge_review: knowledgeReview, knowledge_entries: knowledgeEntries.length, active_knowledge_entries: activeKnowledge(knowledgeEntries).length, prompt_review: promptReview };
|
|
793
|
+
const data = { session_id: sessionId, workspace, stage, state: "closed", status: "completed", next_stage_started: false, knowledge_review: knowledgeReview, knowledge_entries: knowledgeEntries.length, active_knowledge_entries: activeKnowledge(knowledgeEntries).length, prompt_review: promptReview, ...(execution ? { execution_state: execution, execution_warnings: executionWarnings } : {}) };
|
|
732
794
|
const incompleteStages = this.listStages(workspace).data.stages.filter((item) => !["completed", "archived"].includes(item.status));
|
|
733
795
|
const next = incompleteStages.length ? null : {
|
|
734
796
|
action: "workspace_finish",
|
|
@@ -743,8 +805,8 @@ export class WorkContext {
|
|
|
743
805
|
help(command = "") {
|
|
744
806
|
return this.result({
|
|
745
807
|
command,
|
|
746
|
-
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]",
|
|
747
|
-
note: "associated OpenCode sessions in startup-mode workspaces receive the shared-worktree and commit-candidate policy on resume; standard mode remains conservative; candidate strategies are exact, shared_foundation, and integration, with optional related stage references for traceability only; 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.",
|
|
808
|
+
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 execution read|stage execution replace|stage execution update|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]",
|
|
809
|
+
note: "stage execution state is a bounded stage-local operational checkpoint; replace and update require the current revision and active stage session, while read is available without mutation; checklist state never completes a stage, and explicit stage finish reports remaining execution work while preserving the final ledger; associated OpenCode sessions in startup-mode workspaces receive the shared-worktree and commit-candidate policy on resume; standard mode remains conservative; candidate strategies are exact, shared_foundation, and integration, with optional related stage references for traceability only; 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.",
|
|
748
810
|
}, []);
|
|
749
811
|
}
|
|
750
812
|
|
package/src/errors.js
CHANGED
|
@@ -9,6 +9,7 @@ export const ERROR_CODES = Object.freeze({
|
|
|
9
9
|
CANDIDATE_UNSUPPORTED: "CANDIDATE_UNSUPPORTED", CANDIDATE_STALE_BASE: "CANDIDATE_STALE_BASE",
|
|
10
10
|
CANDIDATE_CONFLICT: "CANDIDATE_CONFLICT", CANDIDATE_DETACHED_HEAD: "CANDIDATE_DETACHED_HEAD",
|
|
11
11
|
CANDIDATE_REF_RACE: "CANDIDATE_REF_RACE", CANDIDATE_COMMIT_FAILED: "CANDIDATE_COMMIT_FAILED",
|
|
12
|
+
EXECUTION_REVISION_CONFLICT: "EXECUTION_REVISION_CONFLICT", EXECUTION_LIMIT_EXCEEDED: "EXECUTION_LIMIT_EXCEEDED",
|
|
12
13
|
});
|
|
13
14
|
|
|
14
15
|
export class WorkContextError extends Error {
|
package/src/index.js
CHANGED
|
@@ -7,6 +7,7 @@ export * from "./projections.js";
|
|
|
7
7
|
export * from "./title.js";
|
|
8
8
|
export * from "./core.js";
|
|
9
9
|
export * from "./knowledge.js";
|
|
10
|
+
export * from "./stage-execution.js";
|
|
10
11
|
export * from "./stages-snapshot.js";
|
|
11
12
|
export * from "./stages-renderer.js";
|
|
12
13
|
export * from "./work-context-snapshot.js";
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer";
|
|
2
|
+
import { ERROR_CODES, fail } from "./errors.js";
|
|
3
|
+
|
|
4
|
+
export const EXECUTION_SECTIONS = Object.freeze([
|
|
5
|
+
"scope",
|
|
6
|
+
"completed",
|
|
7
|
+
"remaining",
|
|
8
|
+
"decisions",
|
|
9
|
+
"blockers",
|
|
10
|
+
"verification",
|
|
11
|
+
]);
|
|
12
|
+
|
|
13
|
+
export const EXECUTION_LIMITS = Object.freeze({
|
|
14
|
+
itemsPerSection: 50,
|
|
15
|
+
totalItems: 200,
|
|
16
|
+
itemLength: 500,
|
|
17
|
+
bytes: 32768,
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
const exactKeys = (value, allowed) => Object.keys(value).every((key) => allowed.includes(key));
|
|
21
|
+
const validTimestamp = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
22
|
+
|
|
23
|
+
const normalizeItems = (items, section) => {
|
|
24
|
+
if (!Array.isArray(items)) fail(ERROR_CODES.INVALID_ARGUMENT, `${section} must be an array of strings`);
|
|
25
|
+
if (items.length > EXECUTION_LIMITS.itemsPerSection) fail(ERROR_CODES.EXECUTION_LIMIT_EXCEEDED, `${section} cannot contain more than ${EXECUTION_LIMITS.itemsPerSection} items`);
|
|
26
|
+
const normalized = [];
|
|
27
|
+
for (const item of items) {
|
|
28
|
+
if (typeof item !== "string" || !item.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, `${section} must contain non-empty strings`);
|
|
29
|
+
const value = item.trim();
|
|
30
|
+
if (value.length > EXECUTION_LIMITS.itemLength) fail(ERROR_CODES.EXECUTION_LIMIT_EXCEEDED, `Execution items cannot exceed ${EXECUTION_LIMITS.itemLength} characters`);
|
|
31
|
+
if (!normalized.includes(value)) normalized.push(value);
|
|
32
|
+
}
|
|
33
|
+
return normalized;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export function normalizeExecutionState(input) {
|
|
37
|
+
if (!input || typeof input !== "object" || Array.isArray(input) || !exactKeys(input, EXECUTION_SECTIONS)) fail(ERROR_CODES.INVALID_ARGUMENT, "Execution state contains unsupported fields");
|
|
38
|
+
const state = Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, normalizeItems(input[section] ?? [], section)]));
|
|
39
|
+
const total = EXECUTION_SECTIONS.reduce((count, section) => count + state[section].length, 0);
|
|
40
|
+
if (total > EXECUTION_LIMITS.totalItems) fail(ERROR_CODES.EXECUTION_LIMIT_EXCEEDED, `Execution state cannot contain more than ${EXECUTION_LIMITS.totalItems} items`);
|
|
41
|
+
const remaining = new Set(state.remaining);
|
|
42
|
+
const overlap = state.completed.find((item) => remaining.has(item));
|
|
43
|
+
if (overlap) fail(ERROR_CODES.INVALID_ARGUMENT, "An item cannot be both completed and remaining", { item: overlap });
|
|
44
|
+
return state;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function applyExecutionPatch(current, patch) {
|
|
48
|
+
if (!patch || typeof patch !== "object" || Array.isArray(patch) || !exactKeys(patch, ["add", "remove"]) || (!patch.add && !patch.remove)) fail(ERROR_CODES.INVALID_ARGUMENT, "Execution update requires add or remove changes");
|
|
49
|
+
const validateChanges = (changes, operation) => {
|
|
50
|
+
if (changes === undefined) return {};
|
|
51
|
+
if (!changes || typeof changes !== "object" || Array.isArray(changes) || !exactKeys(changes, EXECUTION_SECTIONS)) fail(ERROR_CODES.INVALID_ARGUMENT, `Execution ${operation} changes contain unsupported fields`);
|
|
52
|
+
return Object.fromEntries(Object.entries(changes).map(([section, items]) => [section, normalizeItems(items, section)]));
|
|
53
|
+
};
|
|
54
|
+
const add = validateChanges(patch.add, "add");
|
|
55
|
+
const remove = validateChanges(patch.remove, "remove");
|
|
56
|
+
const next = {};
|
|
57
|
+
for (const section of EXECUTION_SECTIONS) {
|
|
58
|
+
const removed = new Set(remove[section] || []);
|
|
59
|
+
next[section] = [...current[section].filter((item) => !removed.has(item)), ...(add[section] || [])];
|
|
60
|
+
}
|
|
61
|
+
return normalizeExecutionState(next);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function validateExecutionRecord(record, workspace, stage) {
|
|
65
|
+
const allowed = ["schema", "workspace", "stage", "revision", "created_at", "updated_at", "updated_by", ...EXECUTION_SECTIONS];
|
|
66
|
+
if (!record || typeof record !== "object" || Array.isArray(record) || !exactKeys(record, allowed)
|
|
67
|
+
|| record.schema !== 1 || record.workspace !== workspace || record.stage !== stage
|
|
68
|
+
|| !Number.isInteger(record.revision) || record.revision < 1
|
|
69
|
+
|| !validTimestamp(record.created_at) || !validTimestamp(record.updated_at)
|
|
70
|
+
|| Date.parse(record.updated_at) < Date.parse(record.created_at)
|
|
71
|
+
|| typeof record.updated_by !== "string" || !record.updated_by.trim()) {
|
|
72
|
+
fail(ERROR_CODES.STORAGE_ERROR, "Invalid stage execution state");
|
|
73
|
+
}
|
|
74
|
+
let state;
|
|
75
|
+
try { state = normalizeExecutionState(Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, record[section]]))); }
|
|
76
|
+
catch (error) { fail(ERROR_CODES.STORAGE_ERROR, "Invalid stage execution state", { cause: error.message }); }
|
|
77
|
+
if (EXECUTION_SECTIONS.some((section) => JSON.stringify(state[section]) !== JSON.stringify(record[section]))) fail(ERROR_CODES.STORAGE_ERROR, "Stage execution state is not normalized");
|
|
78
|
+
if (Buffer.byteLength(JSON.stringify(record), "utf8") > EXECUTION_LIMITS.bytes) fail(ERROR_CODES.STORAGE_ERROR, "Stage execution state exceeds its storage limit");
|
|
79
|
+
return record;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function executionState(record) {
|
|
83
|
+
return Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, record[section]]));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function assertExecutionSize(record) {
|
|
87
|
+
if (Buffer.byteLength(JSON.stringify(record), "utf8") > EXECUTION_LIMITS.bytes) fail(ERROR_CODES.EXECUTION_LIMIT_EXCEEDED, `Execution state cannot exceed ${EXECUTION_LIMITS.bytes} bytes`);
|
|
88
|
+
}
|
package/src/storage.js
CHANGED
|
@@ -3,6 +3,7 @@ import path from "node:path";
|
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
4
|
import { WorkContextError, ERROR_CODES, fail } from "./errors.js";
|
|
5
5
|
import { parseFrontmatter, renderMarkdown } from "./markdown.js";
|
|
6
|
+
import { validateExecutionRecord } from "./stage-execution.js";
|
|
6
7
|
|
|
7
8
|
const now = () => new Date().toISOString();
|
|
8
9
|
const ensure = (dir) => fs.mkdirSync(dir, { recursive: true });
|
|
@@ -148,10 +149,23 @@ export class FileStorage {
|
|
|
148
149
|
workspaceFile(id) { return path.join(this.workspaceDir(id), "workspace.md"); }
|
|
149
150
|
knowledgeFile(id) { return path.join(this.workspaceDir(id), "KNOWLEDGE.md"); }
|
|
150
151
|
stageFile(id, stage) { return path.join(this.workspaceDir(id), "stages", `${stage}.md`); }
|
|
152
|
+
stageExecutionFile(id, stage) { return path.join(this.workspaceDir(id), "stages", `${stage}.execution.json`); }
|
|
151
153
|
sessionFile() { return path.join(this.personalRoot, "sessions.jsonl"); }
|
|
152
154
|
lockPath(name = "write") { return path.join(this.root, ".locks", `${name}.lock`); }
|
|
153
155
|
readWorkspace(id) { const record = this.readCanonical(this.workspaceFile(id)); validateMetadata(record.data, "workspace", id); return record; }
|
|
154
156
|
readStage(id, stage) { const record = this.readCanonical(this.stageFile(id, stage)); validateMetadata(record.data, "stage", id, stage); return record; }
|
|
157
|
+
readStageExecution(id, stage) {
|
|
158
|
+
try { return validateExecutionRecord(JSON.parse(fs.readFileSync(this.stageExecutionFile(id, stage), "utf8")), id, stage); }
|
|
159
|
+
catch (error) {
|
|
160
|
+
if (error.code === "ENOENT") return null;
|
|
161
|
+
if (error.code === ERROR_CODES.STORAGE_ERROR) throw error;
|
|
162
|
+
fail(ERROR_CODES.STORAGE_ERROR, "Invalid stage execution state", { cause: error.message });
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
writeStageExecution(id, stage, record) {
|
|
166
|
+
validateExecutionRecord(record, id, stage);
|
|
167
|
+
atomicWrite(this.stageExecutionFile(id, stage), `${JSON.stringify(record, null, 2)}\n`);
|
|
168
|
+
}
|
|
155
169
|
readKnowledge(id) { try { return fs.readFileSync(this.knowledgeFile(id), "utf8"); } catch (error) { if (error.code === "ENOENT") return null; throw error; } }
|
|
156
170
|
transactionFile() { return path.join(this.root, ".locks", "transaction.json"); }
|
|
157
171
|
writeTransaction(snapshot) { atomicWrite(this.transactionFile(), JSON.stringify({ schema: 1, files: snapshot.files.map((item) => ({ file: item.file, content: item.content.toString("base64") })), externalRoots: snapshot.externalRoots }) + "\n"); }
|
package/src/tool-definitions.js
CHANGED
|
@@ -19,6 +19,14 @@ const run = (fn) => async (args, context) => {
|
|
|
19
19
|
};
|
|
20
20
|
const common = { workspace: tool.schema.string(), stage: tool.schema.string() };
|
|
21
21
|
const contextualStage = { workspace: tool.schema.string().optional(), stage: tool.schema.string().optional() };
|
|
22
|
+
const executionSections = {
|
|
23
|
+
scope: tool.schema.array(tool.schema.string()).optional(),
|
|
24
|
+
completed: tool.schema.array(tool.schema.string()).optional(),
|
|
25
|
+
remaining: tool.schema.array(tool.schema.string()).optional(),
|
|
26
|
+
decisions: tool.schema.array(tool.schema.string()).optional(),
|
|
27
|
+
blockers: tool.schema.array(tool.schema.string()).optional(),
|
|
28
|
+
verification: tool.schema.array(tool.schema.string()).optional(),
|
|
29
|
+
};
|
|
22
30
|
const sessionFromContext = (ctx, workspace) => ctx.sessionByOpenCodeId(ctx.options.sessionId, workspace || null, null, null)
|
|
23
31
|
|| (!workspace ? ctx.sessionById(ctx.options.sessionId) : null);
|
|
24
32
|
const workspaceFromSession = (ctx, workspace) => {
|
|
@@ -77,6 +85,9 @@ export const work_context_rename_stage = tool({ description: "Rename a stage whi
|
|
|
77
85
|
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); }) });
|
|
78
86
|
export const work_context_update_stage_prompt = tool({ description: "Update the optional working prompt of an existing stage; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, prompt: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.updateStagePrompt(workspace, stageFromSession(ctx, workspace, a.stage), a.prompt); }) });
|
|
79
87
|
export const work_context_update_stage_result = tool({ description: "Update an existing stage result; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, result: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.updateStageResult(workspace, stageFromSession(ctx, workspace, a.stage), a.result); }) });
|
|
88
|
+
export const work_context_read_stage_execution = tool({ description: "Read the bounded stage-local execution state; workspace and stage can be omitted in the current OpenCode session.", args: contextualStage, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.readStageExecution(workspace, stageFromSession(ctx, workspace, a.stage)); }) });
|
|
89
|
+
export const work_context_replace_stage_execution = tool({ description: "Replace all stage-local execution sections using an optimistic revision guard. Requires the active stage session.", args: { ...contextualStage, expectedRevision: tool.schema.number().int().nonnegative(), state: tool.schema.object(executionSections) }, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.replaceStageExecution(workspace, stage, sessionFor(ctx, oc, workspace, stage), a.expectedRevision, a.state); }) });
|
|
90
|
+
export const work_context_update_stage_execution = tool({ description: "Atomically add and remove stage-local execution items using an optimistic revision guard. Requires the active stage session.", args: { ...contextualStage, expectedRevision: tool.schema.number().int().nonnegative(), add: tool.schema.object(executionSections).optional(), remove: tool.schema.object(executionSections).optional() }, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.updateStageExecution(workspace, stage, sessionFor(ctx, oc, workspace, stage), a.expectedRevision, { add: a.add, remove: a.remove }); }) });
|
|
80
91
|
export const work_context_archive_stage = tool({ description: "Archive a stage while preserving its ID and history; workspace and stage can be omitted in the current OpenCode session.", args: contextualStage, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.archiveStage(workspace, stageFromSession(ctx, workspace, a.stage)); }) });
|
|
81
92
|
export const work_context_reopen_stage = tool({ description: "Reopen a completed stage with a reason. This preserves completion history and requires explicit resume in a separate OpenCode session.", args: { ...common, reason: tool.schema.string() }, execute: run((ctx, a) => ctx.reopenStage(a.workspace, a.stage, a.reason)) });
|
|
82
93
|
export const work_context_restore_stage = tool({ description: "Restore an archived stage to its saved pre-archive status with a required reason. Actionable stages require explicit resume in a separate OpenCode session.", args: { ...common, reason: tool.schema.string() }, execute: run((ctx, a) => ctx.restoreStage(a.workspace, a.stage, a.reason)) });
|
|
@@ -94,4 +105,4 @@ export const work_context_add_knowledge = tool({ description: "Add a durable kno
|
|
|
94
105
|
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)) });
|
|
95
106
|
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) ) });
|
|
96
107
|
|
|
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 };
|
|
108
|
+
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_read_stage_execution, work_context_replace_stage_execution, work_context_update_stage_execution, 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 };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { work_context_read_stage_execution as default } from "../src/tool-definitions.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { work_context_replace_stage_execution as default } from "../src/tool-definitions.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { work_context_update_stage_execution as default } from "../src/tool-definitions.js";
|