opencode-work-context 0.12.1 → 0.14.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 +46 -1
- package/commands/wc.md +13 -4
- package/package.json +1 -1
- package/plugin/stages-tui.js +36 -4
- package/src/core.js +88 -19
- package/src/protocol.js +2 -2
- package/src/stage-execution.js +56 -16
- package/src/stages-renderer.js +5 -3
- package/src/stages-snapshot.js +4 -2
- package/src/storage.js +3 -2
- package/src/tool-definitions.js +7 -3
- package/src/work-context-snapshot.js +3 -0
- package/tools/work_context_read_effective_commit_mode.js +1 -0
- package/tools/work_context_set_stage_commit_mode.js +1 -0
- package/tools/work_context_set_workspace_commit_mode.js +1 -0
package/README.md
CHANGED
|
@@ -196,17 +196,62 @@ returned revision as an optimistic concurrency guard:
|
|
|
196
196
|
/wc stage execution read 000001 02
|
|
197
197
|
/wc stage execution replace 000001 02 0 "{\"scope\":[\"Add CSV export\"],\"remaining\":[\"Implement endpoint\",\"Add tests\"]}"
|
|
198
198
|
/wc stage execution update 000001 02 1 "{\"add\":{\"completed\":[\"Implement endpoint\"]},\"remove\":{\"remaining\":[\"Implement endpoint\"]}}"
|
|
199
|
+
/wc stage execution update 000001 02 2 "{\"edit\":{\"remaining\":[{\"id\":\"item-id\",\"details\":\"Handle authorization and return a paginated response.\"}]}}"
|
|
199
200
|
```
|
|
200
201
|
|
|
201
202
|
`replace` replaces the complete logical state; any omitted section becomes empty. `update`
|
|
202
203
|
atomically adds and removes exact normalized items. Mutations require the active
|
|
203
204
|
stage session. A stale revision fails with `EXECUTION_REVISION_CONFLICT` rather
|
|
204
205
|
than overwriting newer work. Each section is limited to 50 items, the complete
|
|
205
|
-
state to 200 items and 32,768 serialized bytes, and each item to 500 characters.
|
|
206
|
+
state to 200 items and 32,768 serialized bytes, and each item label to 500 characters.
|
|
206
207
|
The first Remaining item is `Current`; later items are `Queued`. Agents work only
|
|
207
208
|
on Current by default and do not combine Queued work into the same change set
|
|
208
209
|
unless the user explicitly requests it. The read model includes stable item IDs,
|
|
209
210
|
so Current and Queued remain unambiguous even when text is duplicated or revised.
|
|
211
|
+
Structured items may also carry optional `details` (up to 4,000 characters) for
|
|
212
|
+
self-contained intent and completion guidance. Details are returned on the
|
|
213
|
+
structured item, shown explicitly for Current on resume, and available from the
|
|
214
|
+
read-only checklist dialog without expanding the sidebar or queued labels.
|
|
215
|
+
Schema 1 string arrays and schema 2 `{ id, text }` records remain readable.
|
|
216
|
+
Schema 3 is selected when details first appear and remains the record version if
|
|
217
|
+
the final detail is later cleared. Set structured edit `details` to `null` to
|
|
218
|
+
clear it.
|
|
219
|
+
|
|
220
|
+
### Checklist Commit Mode
|
|
221
|
+
|
|
222
|
+
Workspace metadata persists `commit_mode` as `manual` (the default) or
|
|
223
|
+
`per_item`. A stage may override this setting, or clear its override to inherit
|
|
224
|
+
the workspace value:
|
|
225
|
+
|
|
226
|
+
```text
|
|
227
|
+
/wc workspace commit-mode 000001 per_item
|
|
228
|
+
/wc stage commit-mode 000001 02 manual
|
|
229
|
+
/wc stage commit-mode 000001 02 clear
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Legacy schema-1 workspace and stage records without `commit_mode` remain
|
|
233
|
+
readable as `manual`; reads do not migrate them. The effective mode and whether
|
|
234
|
+
it comes from the workspace or stage are returned on resume.
|
|
235
|
+
|
|
236
|
+
`per_item` is persistent authorization, not an implicit Git side effect. Before
|
|
237
|
+
each direct commit or candidate fallback, the agent must read the effective mode
|
|
238
|
+
again and proceed only while it returns `per_item`. This is an agent-policy
|
|
239
|
+
preflight, not atomic Git enforcement. Before completing Current, the agent must
|
|
240
|
+
define an explicit patch boundary, run relevant verification, and create a safe
|
|
241
|
+
direct commit. Candidate publication remains separate. The user-only
|
|
242
|
+
`commited <SHA>` acknowledgement contract is independent of agent-created
|
|
243
|
+
per-item commits.
|
|
244
|
+
|
|
245
|
+
In startup mode, the agent first inspects pending candidates related to the
|
|
246
|
+
current stage and assesses direct publication. Only a ready `exact` candidate
|
|
247
|
+
explicitly related to the current stage may substitute when direct publication
|
|
248
|
+
is unsafe but the patch is separable. `shared_foundation` and `integration`
|
|
249
|
+
candidates do not satisfy Current completion. A real patch or merge conflict,
|
|
250
|
+
failed verification, or incoherent boundary remains a blocker and Current must
|
|
251
|
+
not be completed. This policy never authorizes unrelated changes.
|
|
252
|
+
|
|
253
|
+
`complete-current` remains an atomic ledger-only operation: it never runs Git
|
|
254
|
+
or creates a commit itself.
|
|
210
255
|
After completing Current, read the latest revision and use `complete-current` to
|
|
211
256
|
move it to Completed and promote the next Queued item. Update the ledger at
|
|
212
257
|
meaningful boundaries, not after every edit. Checklist state never completes a
|
package/commands/wc.md
CHANGED
|
@@ -3,7 +3,7 @@ description: Explicit work-context lifecycle commands backed by structured tools
|
|
|
3
3
|
subtask: false
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
<!-- opencode-work-context-protocol: {"schema":1,"major":1,"minor":
|
|
6
|
+
<!-- opencode-work-context-protocol: {"schema":1,"major":1,"minor":5,"descriptor_hash":"sha256:69c90783d3bc08ffd46dc764ba93a0feabaaf10f1e4d7fe0b170c633e6dd20e0"} -->
|
|
7
7
|
|
|
8
8
|
Interpret `/wc $ARGUMENTS` as an explicit work-context operation. Use the matching
|
|
9
9
|
`work_context_*` custom tool registered by the installed package plugin with structured arguments. Never edit work-context
|
|
@@ -31,6 +31,8 @@ Use these exact tool mappings; do not invent shortened tool names:
|
|
|
31
31
|
- `workspace list <workspace>` or `<workspace> list` -> `work_context_workspace_list`
|
|
32
32
|
- `workspace rename <workspace> "title"` -> `work_context_rename_workspace`
|
|
33
33
|
- `workspace mode <workspace> <standard|startup>` -> `work_context_set_workspace_mode`
|
|
34
|
+
- `workspace commit-mode <workspace> <manual|per_item>` -> `work_context_set_workspace_commit_mode`
|
|
35
|
+
- `stage commit-mode read [<workspace>] [<stage>]` -> `work_context_read_effective_commit_mode`
|
|
34
36
|
- `candidate create <workspace> "title" ["message"] [strategy <exact|shared_foundation|integration>] [stages <stage>...]` -> `work_context_create_candidate`
|
|
35
37
|
- `candidate capture <workspace> <candidateId> paths <path>...` or `candidate capture <workspace> <candidateId> patch "patch"` -> `work_context_capture_candidate`
|
|
36
38
|
- `candidate preview <workspace> <candidateId>` -> `work_context_preview_candidate`
|
|
@@ -55,6 +57,7 @@ Use these exact tool mappings; do not invent shortened tool names:
|
|
|
55
57
|
- `profiles reset` -> ask for global or project scope and confirmation, then `work_context_reset_capability_profiles`
|
|
56
58
|
- `stage add [<workspace>] ...` -> `work_context_add_stage` (optional `prompt`; infer missing execution capability and depth from the complete stage context before calling the tool)
|
|
57
59
|
- `stage profiles [<workspace>] [<stage>] [execution <routine|implementation|architecture|security|review> depth <light|standard|deep>|clear] [review <routine|implementation|architecture|security|review|clear>]` -> `work_context_set_stage_profiles`
|
|
60
|
+
- `stage commit-mode [<workspace>] [<stage>] <manual|per_item|clear>` -> `work_context_set_stage_commit_mode`
|
|
58
61
|
- `stage profiles refresh <workspace> [<stage>] [--include-explicit]` -> inspect current stage context, infer classifications, then `work_context_refresh_stage_profiles`
|
|
59
62
|
- `stage reopen <workspace> <stage> "reason"` -> `work_context_reopen_stage`
|
|
60
63
|
- `stage restore <workspace> <stage> "reason"` -> `work_context_restore_stage`
|
|
@@ -80,6 +83,8 @@ Supported syntax:
|
|
|
80
83
|
- `workspace list <workspace>`
|
|
81
84
|
- `workspace rename <workspace> "title"`
|
|
82
85
|
- `workspace mode <workspace> <standard|startup>`
|
|
86
|
+
- `workspace commit-mode <workspace> <manual|per_item>`
|
|
87
|
+
- `stage commit-mode read [<workspace>] [<stage>]`
|
|
83
88
|
- `candidate create <workspace> "title" ["message"] [strategy <exact|shared_foundation|integration>] [stages <stage>...]`
|
|
84
89
|
- `candidate capture <workspace> <candidateId> paths <path>...`
|
|
85
90
|
- `candidate capture <workspace> <candidateId> patch "patch"`
|
|
@@ -105,6 +110,7 @@ Supported syntax:
|
|
|
105
110
|
- `profiles reset`
|
|
106
111
|
- `stage add [<workspace>] "title" ["prompt"] [execution <routine|implementation|architecture|security|review> depth <light|standard|deep>] [review <routine|implementation|architecture|security|review>]`
|
|
107
112
|
- `stage profiles [<workspace>] [<stage>] [execution <routine|implementation|architecture|security|review> depth <light|standard|deep>|clear] [review <routine|implementation|architecture|security|review|clear>]`
|
|
113
|
+
- `stage commit-mode [<workspace>] [<stage>] <manual|per_item|clear>`
|
|
108
114
|
- `stage profiles refresh <workspace> [<stage>] [--include-explicit]`
|
|
109
115
|
- `stage reopen <workspace> <stage> "reason"`
|
|
110
116
|
- `stage restore <workspace> <stage> "reason"`
|
|
@@ -141,21 +147,24 @@ Supported syntax:
|
|
|
141
147
|
- `profiles setup` must use interactive questions for mode and light/standard/deep labels, apply mode and mappings in separate atomic structured calls, then offer to refresh unfinished stages; `profiles reset` requires explicit confirmation and removes mappings without changing stage metadata or mode
|
|
142
148
|
- expanded stage details show one unlabeled line `<capability> · <depth> · <model>`; review metadata is not displayed as a model recommendation
|
|
143
149
|
- capability recommendations never select a model or agent, create a replacement session, block resume, or persist mapping targets in tracked workspace data
|
|
144
|
-
- stage execution state preserves string-array section compatibility while exposing stable `{ id, text }` identities in `items`; `current` is the first remaining item and `queued` contains later remaining items in order. `replace` accepts strings or structured items, while `update` accepts `add`, `remove`, and `edit` changes; use IDs for duplicate or reworded text
|
|
150
|
+
- stage execution state preserves string-array section compatibility while exposing stable `{ id, text, details? }` identities in `items`; `text` is the compact label and optional `details` contains self-contained guidance. `current` is the first remaining item and `queued` contains later remaining items in order. `replace` accepts strings or structured items, while `update` accepts `add`, `remove`, and `edit` changes; use IDs for duplicate or reworded text, and set an edit's `details` to `null` to clear it
|
|
145
151
|
- 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
|
|
146
152
|
- 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
|
|
147
153
|
- 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
|
|
148
154
|
- work only on Current by default. Do not combine Queued items into one change set unless the user explicitly asks to batch them
|
|
149
155
|
- after completing a meaningful Current item, read the latest revision and call `stage execution complete-current`; it atomically moves only Current to Completed and promotes the next queued item. Retain ordering and briefly report the transition in normal output
|
|
156
|
+
- workspace `commit_mode` is persistent checklist commit authorization with `manual` as the default and `per_item` as the only commit policy. A stage may override it or use `clear` to inherit. It does not make `stage execution complete-current` perform Git work.
|
|
157
|
+
- in effective `per_item` mode, immediately before each direct commit or candidate fallback, call `stage commit-mode read` and proceed only when it still returns `per_item`. This is an agent-policy preflight, not atomic Git enforcement. Define an explicit patch boundary, run relevant verification, and create a safe direct commit before complete-current. Candidate publication remains separate.
|
|
158
|
+
- in startup plus `per_item` mode, inspect pending candidates related to the current stage and assess direct publication first. Only a ready `exact` candidate explicitly related to the current stage may substitute when direct publication is unsafe but separable; `shared_foundation` and `integration` candidates do not satisfy Current completion. Reconcile stale related candidate intent after a direct commit. A true patch or merge conflict, failed verification, or incoherent boundary is a blocker: record it and do not complete Current. Authorization never includes unrelated changes.
|
|
150
159
|
- `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
|
|
151
160
|
- 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
|
|
152
161
|
- do not expose raw workspace/stage/session identifiers, ordinals, `ok` flags, or absent error codes in the user-facing resume summary
|
|
153
162
|
- `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
|
|
154
|
-
- when stage execution state exists, `resume.context.execution_state` is the current stage-local operational checkpoint. Its structured `current` and `queued` fields identify the active item and its ordered backlog;
|
|
163
|
+
- when stage execution state exists, `resume.context.execution_state` is the current stage-local operational checkpoint. Its structured `current` and `queued` fields identify the active item and its ordered backlog; Current details are explicit on resume while queued presentation remains compact. Continue from it without rewriting the original prompt, and never copy it automatically into workspace knowledge or unrelated stages
|
|
155
164
|
- Planning-stage resume may include `resume.context.delivery_context`, a bounded workspace-level summary of committed candidates and environment checkpoints; it is release coordination context, not stage ownership
|
|
156
165
|
- when the user asks how to deploy from Planning, inspect the exact commit range and the repository's own deployment documentation, scripts, infrastructure, migrations, container definitions, configuration examples, and CI; produce ordered prerequisites, deployment, verification, rollback, and unresolved blockers instead of assuming that push or one generic command is sufficient
|
|
157
166
|
- delivery planning must never persist secret values; mention only required secret or configuration names, ask one focused question when environment or baseline is ambiguous, and never mark delivery merely because commit, push, or CI succeeded
|
|
158
|
-
- an associated OpenCode session resumed in a `startup` workspace receives `resume.context.workflow_policy`; follow it as active agent policy
|
|
167
|
+
- an associated OpenCode session resumed in a `startup` workspace receives `resume.context.workflow_policy`; follow it as active agent policy. Under effective `manual` commit mode, 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; once a coherent commit intent exists, create or refresh its draft candidate before switching stages or handing off; on resume inspect `resume.context.pending_candidates` before creating a duplicate or another commit boundary; 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. Under effective `per_item` mode, use the direct-first and exact-related fallback policy above instead.
|
|
159
168
|
- standard-mode and unassociated core sessions do not receive startup policy; retain the existing conservative worktree behavior there
|
|
160
169
|
- after presenting the summary, continue work immediately when `resume.next_action` is `start_work`; do not ask for generic confirmation
|
|
161
170
|
- 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
|
package/package.json
CHANGED
package/plugin/stages-tui.js
CHANGED
|
@@ -103,7 +103,7 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
|
|
|
103
103
|
stage.tracker_links?.length && `Tasks: ${stage.tracker_links.map(trackerLinkText).join(", ")}`,
|
|
104
104
|
stage.depends_on?.length && `Deps: ${formatStageIds(stage.depends_on)}`,
|
|
105
105
|
].filter(Boolean).join(" · ");
|
|
106
|
-
const metadata = showDependencies ? [recommendation, stageMetadata, stageCandidateText(stage), stage.current && checklistSummaryText(stage.execution)].filter(Boolean).join("\n") : "";
|
|
106
|
+
const metadata = showDependencies ? [recommendation, stage.commit_mode && `Commits: ${stage.commit_mode.replace("_", "-")} (override)`, stageMetadata, stageCandidateText(stage), stage.current && checklistSummaryText(stage.execution)].filter(Boolean).join("\n") : "";
|
|
107
107
|
const attentionSignal = attentionSummaryText(unread);
|
|
108
108
|
const onMouseDown = (event) => {
|
|
109
109
|
if (event?.button != null && event.button !== 0) return;
|
|
@@ -381,7 +381,7 @@ export const checklistOptions = (execution, width = 80) => {
|
|
|
381
381
|
: value;
|
|
382
382
|
const option = (value, section, index, title, category) => {
|
|
383
383
|
const entry = item(value, section, index);
|
|
384
|
-
return { title: title(entry.text), value: `execution-${entry.id}`, category };
|
|
384
|
+
return { title: title(entry.text), value: `execution-${entry.id}`, category, ...(entry.details ? { details: entry.details } : {}) };
|
|
385
385
|
};
|
|
386
386
|
const options = [];
|
|
387
387
|
const current = execution.current || structuredItems("remaining")[0];
|
|
@@ -396,6 +396,29 @@ export const checklistOptions = (execution, width = 80) => {
|
|
|
396
396
|
return options.length ? [{ title: "Close", value: "close", category: "Checklist" }, ...options] : [{ title: "Checklist is empty.", value: "empty", disabled: true }];
|
|
397
397
|
};
|
|
398
398
|
|
|
399
|
+
export const checklistDetailsOptions = (details, width = 80) => {
|
|
400
|
+
const limit = Math.max(20, width - 12);
|
|
401
|
+
const lines = [];
|
|
402
|
+
for (const paragraph of details.split(/\r?\n/)) {
|
|
403
|
+
if (!paragraph) {
|
|
404
|
+
lines.push(" ");
|
|
405
|
+
continue;
|
|
406
|
+
}
|
|
407
|
+
let rest = paragraph;
|
|
408
|
+
while (rest.length > limit) {
|
|
409
|
+
let split = rest.lastIndexOf(" ", limit);
|
|
410
|
+
if (split < 1) split = limit;
|
|
411
|
+
lines.push(rest.slice(0, split));
|
|
412
|
+
rest = rest.slice(split).trimStart();
|
|
413
|
+
}
|
|
414
|
+
if (rest) lines.push(rest);
|
|
415
|
+
}
|
|
416
|
+
return [
|
|
417
|
+
{ title: "Back", value: "back", category: "Checklist" },
|
|
418
|
+
...lines.map((title, index) => ({ title, value: `details-${index}`, category: "Details" })),
|
|
419
|
+
];
|
|
420
|
+
};
|
|
421
|
+
|
|
399
422
|
export const openChecklistDialog = (api, result) => {
|
|
400
423
|
if (typeof api?.ui?.DialogSelect !== "function" || typeof api?.ui?.dialog?.replace !== "function") return false;
|
|
401
424
|
const current = result?.data?.stages?.find((stage) => stage.current || stage.id === result.data.currentStage);
|
|
@@ -405,12 +428,21 @@ export const openChecklistDialog = (api, result) => {
|
|
|
405
428
|
}
|
|
406
429
|
const width = api.renderer?.width || 80;
|
|
407
430
|
api.ui.dialog.setSize?.(width < 50 ? "small" : "large");
|
|
408
|
-
api.ui.dialog.replace(() => api.ui.DialogSelect({
|
|
431
|
+
const showChecklist = () => api.ui.dialog.replace(() => api.ui.DialogSelect({
|
|
409
432
|
title: `Checklist · ${current.title}`,
|
|
410
433
|
placeholder: "Checklist",
|
|
411
434
|
options: checklistOptions(current.execution, width),
|
|
412
|
-
onSelect: (option) => {
|
|
435
|
+
onSelect: (option) => {
|
|
436
|
+
if (option.value === "close") api.ui.dialog.clear?.();
|
|
437
|
+
else if (option.details) api.ui.dialog.replace(() => api.ui.DialogSelect({
|
|
438
|
+
title: `Checklist details · ${option.title}`,
|
|
439
|
+
placeholder: "Details",
|
|
440
|
+
options: checklistDetailsOptions(option.details, width),
|
|
441
|
+
onSelect: (detailOption) => { if (detailOption.value === "back") showChecklist(); },
|
|
442
|
+
}));
|
|
443
|
+
},
|
|
413
444
|
}));
|
|
445
|
+
showChecklist();
|
|
414
446
|
return true;
|
|
415
447
|
};
|
|
416
448
|
|
package/src/core.js
CHANGED
|
@@ -11,13 +11,22 @@ import { isDependencySatisfied } from "./stage-status.js";
|
|
|
11
11
|
import { CandidateStore } from "./candidates.js";
|
|
12
12
|
import { DeliveryStore } from "./delivery.js";
|
|
13
13
|
import { doctorDelivery as runDeliveryDoctor } from "./delivery-doctor.js";
|
|
14
|
-
import { applyExecutionItemPatch, applyExecutionTextPatchItems, assertExecutionSize, EXECUTION_SECTIONS, executionInputUsesItems, executionItems, executionItemsFromState, executionPatchUsesItems, executionReadModel, normalizeExecutionItemState, normalizeExecutionState } from "./stage-execution.js";
|
|
14
|
+
import { applyExecutionItemPatch, applyExecutionTextPatchItems, assertExecutionSize, EXECUTION_SECTIONS, executionInputUsesItems, executionItems, executionItemsFromState, executionPatchUsesItems, executionReadModel, executionSchemaFor, normalizeExecutionItemState, normalizeExecutionState } from "./stage-execution.js";
|
|
15
15
|
import { CAPABILITY_CLASSIFICATIONS, CAPABILITY_DEPTHS, CAPABILITY_PROFILES, capabilityProfileMode, capabilityRecommendations, configureCapabilityMappings, readCapabilityMappings, resetCapabilityMappings, validateCapabilityMappings } from "./capability-profiles.js";
|
|
16
16
|
import { acknowledgeGitCommit, initializeGitCheckpoint } from "./git-acknowledgement.js";
|
|
17
17
|
import { rollbackCommitRef } from "./git-candidates.js";
|
|
18
18
|
|
|
19
19
|
const actor = (options) => options.actor || "OpenCode";
|
|
20
20
|
const workspaceMode = (data) => data.mode || "standard";
|
|
21
|
+
const COMMIT_MODES = ["manual", "per_item"];
|
|
22
|
+
const workspaceCommitMode = (data) => data.commit_mode || "manual";
|
|
23
|
+
const effectiveCommitMode = (workspace, stage) => ({
|
|
24
|
+
mode: stage.commit_mode || workspaceCommitMode(workspace),
|
|
25
|
+
source: stage.commit_mode ? "stage" : "workspace",
|
|
26
|
+
});
|
|
27
|
+
const assertCommitMode = (value, name = "commit mode") => {
|
|
28
|
+
if (!COMMIT_MODES.includes(value)) fail(ERROR_CODES.INVALID_ARGUMENT, `${name} must be one of: ${COMMIT_MODES.join(", ")}`);
|
|
29
|
+
};
|
|
21
30
|
const assertCapabilityProfile = (value, name) => {
|
|
22
31
|
if (value !== undefined && value !== null && !CAPABILITY_PROFILES.includes(value)) fail(ERROR_CODES.INVALID_ARGUMENT, `${name} must be one of: ${CAPABILITY_PROFILES.join(", ")}`);
|
|
23
32
|
};
|
|
@@ -45,9 +54,16 @@ const preservedStageResult = (record) => stageResult(record)
|
|
|
45
54
|
const appendHistory = (bodyText, heading, entry) => `${bodyText.trimEnd()}${bodyText.includes(`\n## ${heading}\n`) ? "" : `\n\n## ${heading}\n`}\n- ${entry}\n`;
|
|
46
55
|
const automaticFinishAllowed = (storage, workspace) => /(?:^|\n)AUTO_STAGE_FINISH:\s*allowed\s*$/mi.test(storage.readStage(workspace, "01").data.prompt || "");
|
|
47
56
|
const resumeConfirmationRequired = (prompt) => /(?:^|\r?\n)RESUME_CONFIRMATION: required(?=\r?\n|$)/.test(prompt || "");
|
|
48
|
-
const startupWorkflowPolicy = () => ({
|
|
57
|
+
const startupWorkflowPolicy = (commitMode = { mode: "manual" }) => ({
|
|
49
58
|
mode: "startup",
|
|
50
|
-
guidance: [
|
|
59
|
+
guidance: commitMode.mode === "per_item" ? [
|
|
60
|
+
"A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
|
|
61
|
+
"Before each direct commit or candidate fallback, read the effective commit mode again. Proceed only while per_item remains effective; this is an agent policy preflight, not atomic Git enforcement.",
|
|
62
|
+
"Inspect pending candidates related to this stage, then assess direct publication of the explicit Current-item patch first.",
|
|
63
|
+
"Only a ready exact candidate explicitly related to this stage may substitute when direct publication is unsafe but the patch is separable. Shared foundation and integration candidates do not satisfy Current completion.",
|
|
64
|
+
"After a direct commit, reconcile any stale related candidate intent before completing Current.",
|
|
65
|
+
"A true patch or merge conflict, failed required verification, or incoherent boundary is a blocker; record it and do not complete Current.",
|
|
66
|
+
] : [
|
|
51
67
|
"A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
|
|
52
68
|
"Capture ready work promptly as an explicit commit candidate while unrelated work remains in progress.",
|
|
53
69
|
"Once a coherent commit intent exists, create or refresh its draft candidate before switching stages or handing off so pending publication remains visible in related stage context.",
|
|
@@ -69,12 +85,16 @@ ${confirmationRequired ? "- Ask for the explicitly required confirmation and wai
|
|
|
69
85
|
const executionInstruction = (record) => {
|
|
70
86
|
if (!record) return "";
|
|
71
87
|
const execution = executionReadModel(record);
|
|
72
|
-
const current = execution.current ? `\nCurrent checklist item: ${execution.current.text}` : "\nCurrent checklist item: none";
|
|
88
|
+
const current = execution.current ? `\nCurrent checklist item: ${execution.current.text}${execution.current.details ? `\nCurrent checklist details: ${execution.current.details}` : ""}` : "\nCurrent checklist item: none";
|
|
73
89
|
const queued = execution.queued.length
|
|
74
90
|
? `\nQueued checklist items: ${execution.queued.map((item) => item.text).join(" | ")}`
|
|
75
91
|
: "\nQueued checklist items: none";
|
|
76
92
|
return `\n\nCurrent stage execution state:${current}${queued}\n${JSON.stringify(execution, null, 2)}\nTreat this bounded stage-local ledger as the current operational checkpoint. Work only on the Current checklist item by default. Do not combine Queued items into the same change set unless the user explicitly asks. Update it after meaningful scope changes, decisions, substantial work, blockers, or verification changes, and before handoff; do not update it for trivial tool calls.`;
|
|
77
93
|
};
|
|
94
|
+
const commitModeInstruction = (commitMode) => {
|
|
95
|
+
if (commitMode.mode !== "per_item") return "";
|
|
96
|
+
return `\n\nChecklist commit policy: per_item (${commitMode.source}). This is persistent authorization to publish an explicit, coherent Current-item patch; it never authorizes unrelated changes. Immediately before each direct commit or candidate fallback, call work_context_read_effective_commit_mode and proceed only if it still returns per_item. This is an agent policy preflight, not atomic Git enforcement. Before completing Current, define its explicit patch boundary and run relevant verification. When a direct commit is safe, create it before complete-current. Candidate publication remains separate. A true patch or merge conflict, failed verification, or incoherent boundary is a blocker: record it and do not complete Current.`;
|
|
97
|
+
};
|
|
78
98
|
const deliveryPlanningInstruction = `\n\nDelivery planning policy:\n- When the user asks how to deploy, treat this as workspace-level delivery planning across all relevant committed changes, not as ownership by the current stage.\n- Inspect the exact commit range and the repository's own deployment documentation, scripts, infrastructure, migrations, container definitions, configuration examples, and CI before proposing commands.\n- Produce an ordered plan covering prerequisites, deployment, verification, rollback, and unresolved blockers. Ask one focused question when the target environment or baseline is genuinely ambiguous.\n- Never persist secret values. Mention only required secret or configuration names.\n- Never mark delivery from a successful commit or push alone. Use explicit delivery confirmation only after the user confirms that the target environment was updated successfully.`;
|
|
79
99
|
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; } } };
|
|
80
100
|
|
|
@@ -149,7 +169,7 @@ export class WorkContext {
|
|
|
149
169
|
.filter((entry) => entry.isDirectory() && /^\d{6}$/.test(entry.name))
|
|
150
170
|
.map((entry) => {
|
|
151
171
|
const data = this.storage.readWorkspace(entry.name).data;
|
|
152
|
-
return { ...data, mode: workspaceMode(data) };
|
|
172
|
+
return { ...data, mode: workspaceMode(data), commit_mode: workspaceCommitMode(data) };
|
|
153
173
|
});
|
|
154
174
|
return { ok: true, data };
|
|
155
175
|
}
|
|
@@ -178,7 +198,7 @@ export class WorkContext {
|
|
|
178
198
|
};
|
|
179
199
|
for (const stage of ids) visit(stage);
|
|
180
200
|
const workspaceData = this.storage.readWorkspace(workspace).data;
|
|
181
|
-
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) } };
|
|
201
|
+
return { ok: true, data: { workspace, title: workspaceData.title, status: workspaceData.status, mode: workspaceMode(workspaceData), commit_mode: workspaceCommitMode(workspaceData), stages, sessions: reduceSessions(this.storage.readEvents()).filter((session) => session.workspace === workspace) } };
|
|
182
202
|
}
|
|
183
203
|
|
|
184
204
|
finishWorkspace(workspace) {
|
|
@@ -247,7 +267,7 @@ export class WorkContext {
|
|
|
247
267
|
const now = new Date().toISOString();
|
|
248
268
|
if (fs.existsSync(this.storage.workspaceDir(workspace))) fail(ERROR_CODES.CONFLICT, "Workspace already exists");
|
|
249
269
|
fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
|
|
250
|
-
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));
|
|
270
|
+
this.storage.writeMarkdown(this.storage.workspaceFile(workspace), { schema: 1, workspace, title: title.trim(), status: "in_progress", mode, commit_mode: "manual", created_at: now, updated_at: now, tracker_links: [] }, body(title));
|
|
251
271
|
const planningGoal = "Clarify the work goal and constraints";
|
|
252
272
|
const planningPrompt = "Diagnose and plan the task without functional changes. Planning stage 01 is a continuously available coordination surface, never a prerequisite gate: do not make implementation, research, review, or other working stages depend on it. 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.";
|
|
253
273
|
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));
|
|
@@ -259,7 +279,8 @@ export class WorkContext {
|
|
|
259
279
|
generateProjections(this.storage);
|
|
260
280
|
return this.result({
|
|
261
281
|
workspace,
|
|
262
|
-
|
|
282
|
+
mode,
|
|
283
|
+
commit_mode: "manual",
|
|
263
284
|
stage: "01",
|
|
264
285
|
session_id: sessionId,
|
|
265
286
|
ordinal: "01/01",
|
|
@@ -314,6 +335,30 @@ export class WorkContext {
|
|
|
314
335
|
});
|
|
315
336
|
}
|
|
316
337
|
|
|
338
|
+
setWorkspaceCommitMode(workspace, commitMode) {
|
|
339
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
340
|
+
assertCommitMode(commitMode, "commitMode");
|
|
341
|
+
return this.transact(`workspace-${workspace}`, () => {
|
|
342
|
+
const record = this.storage.readWorkspace(workspace);
|
|
343
|
+
if (workspaceCommitMode(record.data) === commitMode && record.data.commit_mode === commitMode) return this.result({ workspace, commit_mode: commitMode }, []);
|
|
344
|
+
record.data.commit_mode = commitMode;
|
|
345
|
+
record.data.updated_at = new Date().toISOString();
|
|
346
|
+
this.storage.writeMarkdown(this.storage.workspaceFile(workspace), record.data, record.body);
|
|
347
|
+
generateProjections(this.storage);
|
|
348
|
+
return this.result({ workspace, commit_mode: commitMode }, [workspace]);
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
readEffectiveCommitMode(workspace, stage) {
|
|
353
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
354
|
+
stage = normalizeStageId(stage);
|
|
355
|
+
this.storage.assertNoSymlinks();
|
|
356
|
+
const workspaceRecord = this.storage.readWorkspace(workspace).data;
|
|
357
|
+
const stageRecord = this.storage.readStage(workspace, stage).data;
|
|
358
|
+
const effective = effectiveCommitMode(workspaceRecord, stageRecord);
|
|
359
|
+
return { ok: true, data: { workspace, stage, mode: effective.mode, source: effective.source } };
|
|
360
|
+
}
|
|
361
|
+
|
|
317
362
|
candidates() { return new CandidateStore(this); }
|
|
318
363
|
deliveries() { return new DeliveryStore(this); }
|
|
319
364
|
|
|
@@ -435,7 +480,8 @@ export class WorkContext {
|
|
|
435
480
|
const previousResult = preservedStageResult(stageRecord);
|
|
436
481
|
const workspaceRecord = this.storage.readWorkspace(workspace).data;
|
|
437
482
|
const workspaceTitle = workspaceRecord.title;
|
|
438
|
-
|
|
483
|
+
const commitMode = effectiveCommitMode(workspaceRecord, stageRecord.data);
|
|
484
|
+
const workflowPolicy = workspaceMode(workspaceRecord) === "startup" && options.opencodeSessionId ? startupWorkflowPolicy(commitMode) : null;
|
|
439
485
|
const pendingCandidates = workflowPolicy ? this.candidates().activeProjection(workspace).by_stage[stage] || null : null;
|
|
440
486
|
const deliveryContext = stage === "01" ? this.deliveries().projection(workspace) : null;
|
|
441
487
|
const hasDeliveryContext = deliveryContext && (deliveryContext.committed.count || deliveryContext.environments.length || deliveryContext.unavailable);
|
|
@@ -463,7 +509,8 @@ export class WorkContext {
|
|
|
463
509
|
goal: stageRecord.data.goal || stageRecord.data.title,
|
|
464
510
|
scope: stageRecord.data.prompt || null,
|
|
465
511
|
previous_result: previousResult,
|
|
466
|
-
|
|
512
|
+
previous_session_summary: previousSessionSummary,
|
|
513
|
+
commit_mode: commitMode,
|
|
467
514
|
...(execution ? { execution_state: executionReadModel(execution) } : {}),
|
|
468
515
|
...(recommendations ? { capability_profiles: recommendations } : {}),
|
|
469
516
|
},
|
|
@@ -471,7 +518,8 @@ export class WorkContext {
|
|
|
471
518
|
essence: stageRecord.data.goal || stageRecord.data.title,
|
|
472
519
|
previous: previousSessionSummary || previousResult || "No previous progress was recorded.",
|
|
473
520
|
now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
|
|
474
|
-
|
|
521
|
+
workspace_knowledge: workspaceKnowledge,
|
|
522
|
+
commit_mode: commitMode,
|
|
475
523
|
...(execution ? { execution_state: executionReadModel(execution) } : {}),
|
|
476
524
|
...(recommendations ? { capability_profiles: recommendations } : {}),
|
|
477
525
|
...(pendingCandidates ? { pending_candidates: pendingCandidates } : {}),
|
|
@@ -480,9 +528,9 @@ export class WorkContext {
|
|
|
480
528
|
lifecycle: { automatic_finish_allowed: automaticFinish },
|
|
481
529
|
},
|
|
482
530
|
next_action: hasPrompt ? confirmationRequired ? "await_confirmation" : "start_work" : "ask_questions",
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
531
|
+
instruction: `${hasPrompt
|
|
532
|
+
? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${executionInstruction(execution)}${startupWorkflowInstruction(workflowPolicy)}${stage === "01" ? deliveryPlanningInstruction : ""}`
|
|
533
|
+
: `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.`}${commitModeInstruction(commitMode)}\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.`,
|
|
486
534
|
},
|
|
487
535
|
}, [workspace, stage]);
|
|
488
536
|
});
|
|
@@ -560,6 +608,27 @@ export class WorkContext {
|
|
|
560
608
|
});
|
|
561
609
|
}
|
|
562
610
|
|
|
611
|
+
setStageCommitMode(workspace, stage, commitMode) {
|
|
612
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
613
|
+
stage = normalizeStageId(stage);
|
|
614
|
+
if (commitMode !== null) assertCommitMode(commitMode, "commitMode");
|
|
615
|
+
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
616
|
+
const workspaceRecord = this.storage.readWorkspace(workspace).data;
|
|
617
|
+
const record = this.storage.readStage(workspace, stage);
|
|
618
|
+
let changed = false;
|
|
619
|
+
if (commitMode === null) {
|
|
620
|
+
if (record.data.commit_mode !== undefined) { delete record.data.commit_mode; changed = true; }
|
|
621
|
+
} else if (record.data.commit_mode !== commitMode) { record.data.commit_mode = commitMode; changed = true; }
|
|
622
|
+
if (changed) {
|
|
623
|
+
record.data.updated_at = new Date().toISOString();
|
|
624
|
+
this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, record.body);
|
|
625
|
+
generateProjections(this.storage);
|
|
626
|
+
}
|
|
627
|
+
const effective = effectiveCommitMode(workspaceRecord, record.data);
|
|
628
|
+
return this.result({ workspace, stage, commit_mode: record.data.commit_mode || null, effective_commit_mode: effective.mode, commit_mode_source: effective.source }, changed ? [workspace, stage] : []);
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
|
|
563
632
|
refreshStageProfiles(workspace, recommendations, options = {}) {
|
|
564
633
|
workspace = normalizeWorkspaceId(workspace);
|
|
565
634
|
if (!Array.isArray(recommendations) || !recommendations.length || recommendations.length > 99) fail(ERROR_CODES.INVALID_ARGUMENT, "recommendations must contain 1 to 99 stage classifications");
|
|
@@ -736,7 +805,7 @@ export class WorkContext {
|
|
|
736
805
|
const items = structured ? normalizeExecutionItemState(input, current) : executionItemsFromState(state, current);
|
|
737
806
|
if (current && JSON.stringify(executionItems(current)) === JSON.stringify(items)) return this.result(executionReadModel(current), []);
|
|
738
807
|
const timestamp = new Date().toISOString();
|
|
739
|
-
const record = { schema:
|
|
808
|
+
const record = { schema: executionSchemaFor(items, current), workspace, stage, revision: revision + 1, created_at: current?.created_at || timestamp, updated_at: timestamp, updated_by: actor(this.options), items };
|
|
740
809
|
assertExecutionSize(record);
|
|
741
810
|
this.storage.writeStageExecution(workspace, stage, record);
|
|
742
811
|
return this.result(executionReadModel(record), [this.storage.stageExecutionFile(workspace, stage)]);
|
|
@@ -759,7 +828,7 @@ export class WorkContext {
|
|
|
759
828
|
const items = structured ? applyExecutionItemPatch(current || empty, patch) : applyExecutionTextPatchItems(current || empty, patch);
|
|
760
829
|
if (current && JSON.stringify(executionItems(current)) === JSON.stringify(items)) return this.result(executionReadModel(current), []);
|
|
761
830
|
const timestamp = new Date().toISOString();
|
|
762
|
-
const record = { schema:
|
|
831
|
+
const record = { schema: executionSchemaFor(items, current), workspace, stage, revision: revision + 1, created_at: current?.created_at || timestamp, updated_at: timestamp, updated_by: actor(this.options), items };
|
|
763
832
|
assertExecutionSize(record);
|
|
764
833
|
this.storage.writeStageExecution(workspace, stage, record);
|
|
765
834
|
return this.result(executionReadModel(record), [this.storage.stageExecutionFile(workspace, stage)]);
|
|
@@ -783,7 +852,7 @@ export class WorkContext {
|
|
|
783
852
|
items.completed.push(currentItem);
|
|
784
853
|
const nextItems = normalizeExecutionItemState(items, current);
|
|
785
854
|
const timestamp = new Date().toISOString();
|
|
786
|
-
const record = { schema:
|
|
855
|
+
const record = { schema: executionSchemaFor(nextItems, current), workspace, stage, revision: revision + 1, created_at: current.created_at, updated_at: timestamp, updated_by: actor(this.options), items: nextItems };
|
|
787
856
|
assertExecutionSize(record);
|
|
788
857
|
this.storage.writeStageExecution(workspace, stage, record);
|
|
789
858
|
return this.result(executionReadModel(record), [this.storage.stageExecutionFile(workspace, stage)]);
|
|
@@ -1049,8 +1118,8 @@ export class WorkContext {
|
|
|
1049
1118
|
help(command = "") {
|
|
1050
1119
|
return this.result({
|
|
1051
1120
|
command,
|
|
1052
|
-
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|commit all|commit all confirm|delivery read|delivery explain|delivery doctor|delivery mark|profiles show|profiles setup|profiles reset|workspace finish|workspace reopen|resume|stage add|stage profiles|stage profiles refresh|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage execution read|stage execution replace|stage execution update|stage execution complete-current|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]",
|
|
1053
|
-
note: "
|
|
1121
|
+
syntax: "/wc [create|list|workspace list|workspace rename|workspace mode|workspace commit-mode|stage commit-mode|candidate create|candidate capture|candidate preview|candidate show|candidate list|candidate ready|candidate commit|candidate discard|commit all|commit all confirm|delivery read|delivery explain|delivery doctor|delivery mark|profiles show|profiles setup|profiles reset|workspace finish|workspace reopen|resume|stage add|stage profiles|stage profiles refresh|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage execution read|stage execution replace|stage execution update|stage execution complete-current|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]",
|
|
1122
|
+
note: "Workspace commit mode is manual or per_item; stages may override or clear to inherit it. Read the effective mode immediately before each direct commit or candidate fallback because this agent-policy preflight is not atomic Git enforcement. Per-item mode authorizes commits only for explicit coherent Current-item boundaries and does not make complete-current perform Git work. Execution recommendations combine a vendor-neutral capability with light, standard, or deep depth; Planning agents infer missing values before stage creation, ordinary refresh updates missing/inferred classifications while preserving explicit assignments, and local depth mappings resolve only an advisory model label; profiles setup gathers mode and mappings through questions, off mode suppresses presentation and resolution, and no profile operation changes a model, agent, reviewer, or session; delivery context is workspace-level local operational state; exact Git range inspection runs only for explicit immutable hashes; stage execution state is a bounded stage-local operational checkpoint; associated startup sessions receive the shared-worktree candidate policy; stage finish requires an explicit user lifecycle request unless Planning contains AUTO_STAGE_FINISH: allowed; recovery operations preserve lifecycle history.",
|
|
1054
1123
|
}, []);
|
|
1055
1124
|
}
|
|
1056
1125
|
|
package/src/protocol.js
CHANGED
|
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
|
|
|
3
3
|
export const WORK_CONTEXT_PROTOCOL = Object.freeze({
|
|
4
4
|
schema: 1,
|
|
5
5
|
major: 1,
|
|
6
|
-
minor:
|
|
6
|
+
minor: 5,
|
|
7
7
|
});
|
|
8
8
|
|
|
9
9
|
export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR = Object.freeze({
|
|
@@ -13,7 +13,7 @@ export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR = Object.freeze({
|
|
|
13
13
|
major: WORK_CONTEXT_PROTOCOL.major,
|
|
14
14
|
minor: WORK_CONTEXT_PROTOCOL.minor,
|
|
15
15
|
}),
|
|
16
|
-
operations: Object.freeze(["delivery.doctor", "commit.acknowledge", "commit.inspect_all", "commit.all", "execution.complete_current"]),
|
|
16
|
+
operations: Object.freeze(["delivery.doctor", "commit.acknowledge", "commit.inspect_all", "commit.all", "commit_mode.workspace.set", "commit_mode.stage.set", "commit_mode.effective.read", "execution.complete_current"]),
|
|
17
17
|
});
|
|
18
18
|
|
|
19
19
|
export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR_BYTES = JSON.stringify(WORK_CONTEXT_PROTOCOL_DESCRIPTOR);
|
package/src/stage-execution.js
CHANGED
|
@@ -15,6 +15,7 @@ export const EXECUTION_LIMITS = Object.freeze({
|
|
|
15
15
|
itemsPerSection: 50,
|
|
16
16
|
totalItems: 200,
|
|
17
17
|
itemLength: 500,
|
|
18
|
+
detailsLength: 4000,
|
|
18
19
|
bytes: 32768,
|
|
19
20
|
});
|
|
20
21
|
|
|
@@ -30,6 +31,13 @@ const normalizeText = (text, section, code = ERROR_CODES.INVALID_ARGUMENT) => {
|
|
|
30
31
|
return value;
|
|
31
32
|
};
|
|
32
33
|
|
|
34
|
+
const normalizeDetails = (details, section, code = ERROR_CODES.INVALID_ARGUMENT) => {
|
|
35
|
+
if (typeof details !== "string" || !details.trim()) fail(code, `${section} details must be non-empty text`);
|
|
36
|
+
const value = details.trim();
|
|
37
|
+
if (value.length > EXECUTION_LIMITS.detailsLength) fail(code === ERROR_CODES.STORAGE_ERROR ? code : ERROR_CODES.EXECUTION_LIMIT_EXCEEDED, `Execution item details cannot exceed ${EXECUTION_LIMITS.detailsLength} characters`);
|
|
38
|
+
return value;
|
|
39
|
+
};
|
|
40
|
+
|
|
33
41
|
const normalizeItems = (items, section) => {
|
|
34
42
|
if (!Array.isArray(items)) fail(ERROR_CODES.INVALID_ARGUMENT, `${section} must be an array of strings`);
|
|
35
43
|
if (items.length > EXECUTION_LIMITS.itemsPerSection) fail(ERROR_CODES.EXECUTION_LIMIT_EXCEEDED, `${section} cannot contain more than ${EXECUTION_LIMITS.itemsPerSection} items`);
|
|
@@ -87,16 +95,18 @@ const validateId = (id, code = ERROR_CODES.INVALID_ARGUMENT) => {
|
|
|
87
95
|
return id;
|
|
88
96
|
};
|
|
89
97
|
|
|
90
|
-
const normalizeStoredItems = (items) => {
|
|
98
|
+
const normalizeStoredItems = (items, allowDetails = false) => {
|
|
91
99
|
if (!items || typeof items !== "object" || Array.isArray(items) || !exactKeys(items, EXECUTION_SECTIONS)) fail(ERROR_CODES.STORAGE_ERROR, "Invalid stage execution state");
|
|
92
100
|
const normalized = {};
|
|
93
101
|
for (const section of EXECUTION_SECTIONS) {
|
|
94
102
|
if (!Array.isArray(items[section])) fail(ERROR_CODES.STORAGE_ERROR, "Invalid stage execution state");
|
|
95
103
|
normalized[section] = items[section].map((item) => {
|
|
96
|
-
if (!item || typeof item !== "object" || Array.isArray(item) || !exactKeys(item, ["id", "text"])) fail(ERROR_CODES.STORAGE_ERROR, "Invalid stage execution state");
|
|
104
|
+
if (!item || typeof item !== "object" || Array.isArray(item) || !exactKeys(item, allowDetails ? ["id", "text", "details"] : ["id", "text"])) fail(ERROR_CODES.STORAGE_ERROR, "Invalid stage execution state");
|
|
97
105
|
const text = normalizeText(item.text, section, ERROR_CODES.STORAGE_ERROR);
|
|
98
106
|
if (text !== item.text) fail(ERROR_CODES.STORAGE_ERROR, "Stage execution state is not normalized");
|
|
99
|
-
|
|
107
|
+
const details = Object.hasOwn(item, "details") ? normalizeDetails(item.details, section, ERROR_CODES.STORAGE_ERROR) : undefined;
|
|
108
|
+
if (details !== undefined && details !== item.details) fail(ERROR_CODES.STORAGE_ERROR, "Stage execution state is not normalized");
|
|
109
|
+
return { id: validateId(item.id, ERROR_CODES.STORAGE_ERROR), text, ...(details === undefined ? {} : { details }) };
|
|
100
110
|
});
|
|
101
111
|
}
|
|
102
112
|
assertItemCounts(normalized, ERROR_CODES.STORAGE_ERROR);
|
|
@@ -105,7 +115,7 @@ const normalizeStoredItems = (items) => {
|
|
|
105
115
|
};
|
|
106
116
|
|
|
107
117
|
export function executionItems(record) {
|
|
108
|
-
if (record.schema
|
|
118
|
+
if (record.schema >= 2) return Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, record.items[section].map((item) => ({ ...item }))]));
|
|
109
119
|
return Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, record[section].map((text, index) => ({ id: legacyItemId(section, index, text), text }))]));
|
|
110
120
|
}
|
|
111
121
|
|
|
@@ -130,13 +140,20 @@ export function executionState(record) {
|
|
|
130
140
|
return Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, executionItems(record)[section].map((item) => item.text)]));
|
|
131
141
|
}
|
|
132
142
|
|
|
143
|
+
const takePreviousItem = (previousItems, used, section, text) => {
|
|
144
|
+
const local = previousItems[section].filter((item) => item.text === text && !used.has(item.id));
|
|
145
|
+
if (local.length > 1) fail(ERROR_CODES.INVALID_ARGUMENT, "Text-only execution replacement is ambiguous; use item IDs", { text, matches: local.length });
|
|
146
|
+
if (local.length === 1) return local[0];
|
|
147
|
+
const acrossSections = EXECUTION_SECTIONS.flatMap((name) => previousItems[name]).filter((item) => item.text === text && !used.has(item.id));
|
|
148
|
+
if (acrossSections.length > 1) fail(ERROR_CODES.INVALID_ARGUMENT, "Text-only execution replacement is ambiguous; use item IDs", { text, matches: acrossSections.length });
|
|
149
|
+
return acrossSections[0];
|
|
150
|
+
};
|
|
151
|
+
|
|
133
152
|
export function executionItemsFromState(state, previous = null) {
|
|
134
153
|
const previousItems = previous ? executionItems(previous) : Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, []]));
|
|
135
154
|
const used = new Set();
|
|
136
|
-
const take = (section, text) => previousItems[section].find((item) => item.text === text && !used.has(item.id))
|
|
137
|
-
|| EXECUTION_SECTIONS.flatMap((name) => previousItems[name]).find((item) => item.text === text && !used.has(item.id));
|
|
138
155
|
const items = Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, state[section].map((text) => {
|
|
139
|
-
const previousItem =
|
|
156
|
+
const previousItem = takePreviousItem(previousItems, used, section, text);
|
|
140
157
|
if (previousItem) used.add(previousItem.id);
|
|
141
158
|
return previousItem || { id: randomUUID(), text };
|
|
142
159
|
})]));
|
|
@@ -148,6 +165,10 @@ export function executionInputUsesItems(input) {
|
|
|
148
165
|
return EXECUTION_SECTIONS.some((section) => Array.isArray(input?.[section]) && input[section].some((item) => typeof item !== "string"));
|
|
149
166
|
}
|
|
150
167
|
|
|
168
|
+
export function executionSchemaFor(items, previous = null) {
|
|
169
|
+
return previous?.schema === 3 || EXECUTION_SECTIONS.some((section) => items[section].some((item) => Object.hasOwn(item, "details"))) ? 3 : 2;
|
|
170
|
+
}
|
|
171
|
+
|
|
151
172
|
export function executionPatchUsesItems(patch) {
|
|
152
173
|
return Boolean(patch?.edit) || [patch?.add, patch?.remove].some((changes) => EXECUTION_SECTIONS.some((section) => Array.isArray(changes?.[section]) && changes[section].some((item) => typeof item !== "string")));
|
|
153
174
|
}
|
|
@@ -198,14 +219,15 @@ export function normalizeExecutionItemState(input, previous = null) {
|
|
|
198
219
|
items[section] = sectionItems.map((item) => {
|
|
199
220
|
if (typeof item === "string") {
|
|
200
221
|
const text = normalizeText(item, section);
|
|
201
|
-
const previousItem = previousItems
|
|
222
|
+
const previousItem = takePreviousItem(previousItems, used, section, text);
|
|
202
223
|
if (previousItem) used.add(previousItem.id);
|
|
203
224
|
return previousItem || { id: randomUUID(), text };
|
|
204
225
|
}
|
|
205
|
-
if (!item || typeof item !== "object" || Array.isArray(item) || !exactKeys(item, ["id", "text"]) || item.text === undefined) fail(ERROR_CODES.INVALID_ARGUMENT, `${section} contains an invalid execution item`);
|
|
226
|
+
if (!item || typeof item !== "object" || Array.isArray(item) || !exactKeys(item, ["id", "text", "details"]) || item.text === undefined) fail(ERROR_CODES.INVALID_ARGUMENT, `${section} contains an invalid execution item`);
|
|
206
227
|
const id = item.id === undefined ? randomUUID() : validateId(item.id);
|
|
207
228
|
used.add(id);
|
|
208
|
-
|
|
229
|
+
const details = Object.hasOwn(item, "details") ? normalizeDetails(item.details, section) : undefined;
|
|
230
|
+
return { id, text: normalizeText(item.text, section), ...(details === undefined ? {} : { details }) };
|
|
209
231
|
});
|
|
210
232
|
}
|
|
211
233
|
assertItemCounts(items);
|
|
@@ -229,8 +251,17 @@ const normalizeItemChanges = (changes, operation) => {
|
|
|
229
251
|
if (!item || typeof item !== "object" || Array.isArray(item) || !exactKeys(item, ["id"])) fail(ERROR_CODES.INVALID_ARGUMENT, "Structured execution removals require an item ID");
|
|
230
252
|
return { id: validateId(item.id) };
|
|
231
253
|
}
|
|
232
|
-
if (!item || typeof item !== "object" || Array.isArray(item) || !exactKeys(item, ["id", "text"])
|
|
233
|
-
|
|
254
|
+
if (!item || typeof item !== "object" || Array.isArray(item) || !exactKeys(item, ["id", "text", "details"])) fail(ERROR_CODES.INVALID_ARGUMENT, `Structured execution ${operation} changes contain an invalid item`);
|
|
255
|
+
if (operation === "add" && item.text === undefined) fail(ERROR_CODES.INVALID_ARGUMENT, "Structured execution additions require text");
|
|
256
|
+
if (operation === "edit" && item.id === undefined) fail(ERROR_CODES.INVALID_ARGUMENT, "Structured execution edits require an item ID");
|
|
257
|
+
if (operation === "edit" && item.text === undefined && !Object.hasOwn(item, "details")) fail(ERROR_CODES.INVALID_ARGUMENT, "Structured execution edits require text or details");
|
|
258
|
+
const result = { id: operation === "add" && item.id === undefined ? randomUUID() : validateId(item.id) };
|
|
259
|
+
if (item.text !== undefined) result.text = normalizeText(item.text, section);
|
|
260
|
+
if (Object.hasOwn(item, "details")) {
|
|
261
|
+
if (operation === "add" && item.details === null) fail(ERROR_CODES.INVALID_ARGUMENT, "Structured execution additions cannot clear details");
|
|
262
|
+
result.details = item.details === null ? null : normalizeDetails(item.details, section);
|
|
263
|
+
}
|
|
264
|
+
return result;
|
|
234
265
|
});
|
|
235
266
|
}
|
|
236
267
|
return result;
|
|
@@ -250,11 +281,20 @@ export function applyExecutionItemPatch(current, patch) {
|
|
|
250
281
|
if (matches.length !== 1) fail(ERROR_CODES.INVALID_ARGUMENT, "Text-only execution removal is ambiguous; use an item ID", { text: item.text, matches: matches.length });
|
|
251
282
|
return matches[0].id;
|
|
252
283
|
}));
|
|
253
|
-
const edits = new Map((edit[section] || []).map((item) => [item.id, item
|
|
284
|
+
const edits = new Map((edit[section] || []).map((item) => [item.id, item]));
|
|
254
285
|
for (const id of [...removed, ...edits.keys()]) if (!known.has(id)) fail(ERROR_CODES.INVALID_ARGUMENT, "Execution item ID was not found", { id });
|
|
255
286
|
items[section] = items[section]
|
|
256
287
|
.filter((item) => !removed.has(item.id))
|
|
257
|
-
.map((item) =>
|
|
288
|
+
.map((item) => {
|
|
289
|
+
const change = edits.get(item.id);
|
|
290
|
+
if (!change) return item;
|
|
291
|
+
const next = { ...item, ...(change.text === undefined ? {} : { text: change.text }) };
|
|
292
|
+
if (Object.hasOwn(change, "details")) {
|
|
293
|
+
if (change.details === null) delete next.details;
|
|
294
|
+
else next.details = change.details;
|
|
295
|
+
}
|
|
296
|
+
return next;
|
|
297
|
+
});
|
|
258
298
|
items[section].push(...(add[section] || []));
|
|
259
299
|
}
|
|
260
300
|
assertItemCounts(items);
|
|
@@ -266,7 +306,7 @@ export function validateExecutionRecord(record, workspace, stage) {
|
|
|
266
306
|
const legacyAllowed = ["schema", "workspace", "stage", "revision", "created_at", "updated_at", "updated_by", ...EXECUTION_SECTIONS];
|
|
267
307
|
const currentAllowed = ["schema", "workspace", "stage", "revision", "created_at", "updated_at", "updated_by", "items"];
|
|
268
308
|
if (!record || typeof record !== "object" || Array.isArray(record)
|
|
269
|
-
|| ![1, 2].includes(record.schema) || record.workspace !== workspace || record.stage !== stage
|
|
309
|
+
|| ![1, 2, 3].includes(record.schema) || record.workspace !== workspace || record.stage !== stage
|
|
270
310
|
|| !Number.isInteger(record.revision) || record.revision < 1
|
|
271
311
|
|| !validTimestamp(record.created_at) || !validTimestamp(record.updated_at)
|
|
272
312
|
|| Date.parse(record.updated_at) < Date.parse(record.created_at)
|
|
@@ -280,7 +320,7 @@ export function validateExecutionRecord(record, workspace, stage) {
|
|
|
280
320
|
if (EXECUTION_SECTIONS.some((section) => JSON.stringify(state[section]) !== JSON.stringify(record[section]))) fail(ERROR_CODES.STORAGE_ERROR, "Stage execution state is not normalized");
|
|
281
321
|
} else {
|
|
282
322
|
if (!exactKeys(record, currentAllowed)) fail(ERROR_CODES.STORAGE_ERROR, "Invalid stage execution state");
|
|
283
|
-
normalizeStoredItems(record.items);
|
|
323
|
+
normalizeStoredItems(record.items, record.schema === 3);
|
|
284
324
|
}
|
|
285
325
|
} catch (error) {
|
|
286
326
|
if (error.code === ERROR_CODES.STORAGE_ERROR) throw error;
|
package/src/stages-renderer.js
CHANGED
|
@@ -34,8 +34,10 @@ const workspaceCandidateSummary = (candidates) => {
|
|
|
34
34
|
].filter(Boolean);
|
|
35
35
|
return `Candidates ${states.join(" ")}`;
|
|
36
36
|
};
|
|
37
|
+
const commitModeLabel = (mode) => (mode || "manual").replace("_", "-");
|
|
37
38
|
export const workspaceStatusLines = (workspace, attention = "") => [
|
|
38
|
-
`${workspace.mode || "standard"}
|
|
39
|
+
`${workspace.mode || "standard"} · commits: ${commitModeLabel(workspace.commit_mode)}`,
|
|
40
|
+
attention ? `Attention ${attention}` : null,
|
|
39
41
|
workspaceCandidateSummary(workspace.candidates),
|
|
40
42
|
deliverySummary(workspace.delivery),
|
|
41
43
|
].filter(Boolean);
|
|
@@ -56,7 +58,7 @@ export const formatStageIds = (ids = []) => {
|
|
|
56
58
|
flush();
|
|
57
59
|
return ranges.join(", ");
|
|
58
60
|
};
|
|
59
|
-
const profileSummary = (stage) => {
|
|
61
|
+
const profileSummary = (stage) => {
|
|
60
62
|
return stage.execution_profile && stage.execution_depth
|
|
61
63
|
? [capitalize(stage.execution_profile), capitalize(stage.execution_depth), stage.recommended_model && capitalize(stage.recommended_model)].filter(Boolean).join(" · ")
|
|
62
64
|
: null;
|
|
@@ -116,7 +118,7 @@ export function renderStagesPanel(result) {
|
|
|
116
118
|
for (const stage of snapshot.stages) {
|
|
117
119
|
const pending = candidateSummary(stage);
|
|
118
120
|
const profiles = profileSummary(stage);
|
|
119
|
-
lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}${profiles ? `\n${profiles}` : ""}${stage.depends_on?.length ? `\nDeps: ${formatStageIds(stage.depends_on)}` : ""}${pending ? `\n${pending}` : ""}`);
|
|
121
|
+
lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}${profiles ? `\n${profiles}` : ""}${stage.commit_mode ? `\nCommits: ${commitModeLabel(stage.commit_mode)} (override)` : ""}${stage.depends_on?.length ? `\nDeps: ${formatStageIds(stage.depends_on)}` : ""}${pending ? `\n${pending}` : ""}`);
|
|
120
122
|
}
|
|
121
123
|
if (result.stale) lines.push(`! stale: ${result.error?.code || "STORAGE_ERROR"}`);
|
|
122
124
|
return lines.join("\n");
|
package/src/stages-snapshot.js
CHANGED
|
@@ -36,6 +36,7 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
|
|
|
36
36
|
|
|
37
37
|
const workspace = context.storage.readWorkspace(session.workspace).data;
|
|
38
38
|
const mode = workspace.mode || "standard";
|
|
39
|
+
const commitMode = workspace.commit_mode || "manual";
|
|
39
40
|
const candidateProjection = mode === "startup" ? context.candidates().activeProjection(session.workspace) : null;
|
|
40
41
|
const deliveryProjection = context.deliveries().projection(session.workspace);
|
|
41
42
|
const delivery = deliveryProjection.committed.count || deliveryProjection.environments.length || deliveryProjection.unavailable
|
|
@@ -53,7 +54,8 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
|
|
|
53
54
|
status: stage.status,
|
|
54
55
|
description: stage.description,
|
|
55
56
|
depends_on: stage.depends_on.filter((dependency) => visibleStageIds.has(dependency)),
|
|
56
|
-
|
|
57
|
+
tracker_links: stage.tracker_links || [],
|
|
58
|
+
...(stage.commit_mode ? { commit_mode: stage.commit_mode } : {}),
|
|
57
59
|
...stageCapabilityProfiles(context.storage, stage, capabilityMappings),
|
|
58
60
|
...(candidateProjection?.by_stage[stage.stage] ? { candidates: candidateProjection.by_stage[stage.stage] } : {}),
|
|
59
61
|
current: stage.stage === session.stage,
|
|
@@ -68,7 +70,7 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
|
|
|
68
70
|
ok: true,
|
|
69
71
|
data: {
|
|
70
72
|
schema: 1,
|
|
71
|
-
workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status, mode, ...(candidateProjection ? { candidates: candidateProjection.summary } : {}), ...(delivery ? { delivery } : {}) },
|
|
73
|
+
workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status, mode, commit_mode: commitMode, ...(candidateProjection ? { candidates: candidateProjection.summary } : {}), ...(delivery ? { delivery } : {}) },
|
|
72
74
|
stages,
|
|
73
75
|
currentStage,
|
|
74
76
|
generatedAt: new Date().toISOString(),
|
package/src/storage.js
CHANGED
|
@@ -91,13 +91,13 @@ const validateEventStream = (events) => {
|
|
|
91
91
|
}
|
|
92
92
|
};
|
|
93
93
|
function validateMetadata(data, kind, workspace, stage = null) {
|
|
94
|
-
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", "execution_profile", "execution_depth", "execution_classification", "review_profile", "created_at", "updated_at", "tracker_links", "reopen_history", "archive_history"];
|
|
94
|
+
const allowed = kind === "workspace" ? ["schema", "workspace", "title", "status", "mode", "commit_mode", "created_at", "updated_at", "tracker_links", "reopen_history"] : ["schema", "workspace", "stage", "title", "status", "goal", "prompt", "depends_on", "owner", "commit_mode", "execution_profile", "execution_depth", "execution_classification", "review_profile", "created_at", "updated_at", "tracker_links", "reopen_history", "archive_history"];
|
|
95
95
|
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`);
|
|
96
96
|
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`);
|
|
97
97
|
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`);
|
|
98
98
|
const statuses = kind === "workspace" ? ["in_progress", "completed", "cancelled"] : ["planned", "in_progress", "completed", "cancelled", "archived"];
|
|
99
99
|
if (!statuses.includes(data.status)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} status`);
|
|
100
|
-
const invalidWorkspaceHistory = kind === "workspace" && ((data.mode !== undefined && !["standard", "startup"].includes(data.mode)) || (data.reopen_history !== undefined && !validReopenHistory(data.reopen_history)));
|
|
100
|
+
const invalidWorkspaceHistory = kind === "workspace" && ((data.mode !== undefined && !["standard", "startup"].includes(data.mode)) || (data.commit_mode !== undefined && !["manual", "per_item"].includes(data.commit_mode)) || (data.reopen_history !== undefined && !validReopenHistory(data.reopen_history)));
|
|
101
101
|
const invalidStageMetadata = kind === "stage" && (
|
|
102
102
|
data.stage !== stage || !/^\d{2}$/.test(data.stage) || !requiredString(data, "goal")
|
|
103
103
|
|| (data.prompt !== undefined && !requiredString(data, "prompt")) || !requiredString(data, "owner")
|
|
@@ -109,6 +109,7 @@ function validateMetadata(data, kind, workspace, stage = null) {
|
|
|
109
109
|
|| (data.execution_depth !== undefined && !CAPABILITY_DEPTHS.includes(data.execution_depth))
|
|
110
110
|
|| (data.execution_classification !== undefined && !CAPABILITY_CLASSIFICATIONS.includes(data.execution_classification))
|
|
111
111
|
|| (data.review_profile !== undefined && !CAPABILITY_PROFILES.includes(data.review_profile))
|
|
112
|
+
|| (data.commit_mode !== undefined && !["manual", "per_item"].includes(data.commit_mode))
|
|
112
113
|
|| (data.execution_depth !== undefined && data.execution_profile === undefined)
|
|
113
114
|
|| (data.execution_classification !== undefined && (data.execution_profile === undefined || data.execution_depth === undefined))
|
|
114
115
|
|| (data.execution_profile !== undefined && data.execution_depth !== undefined && data.execution_classification === undefined)
|
package/src/tool-definitions.js
CHANGED
|
@@ -38,6 +38,7 @@ const common = { workspace: tool.schema.string(), stage: tool.schema.string() };
|
|
|
38
38
|
const contextualStage = { workspace: tool.schema.string().optional(), stage: tool.schema.string().optional() };
|
|
39
39
|
const capabilityProfile = tool.schema.enum(["routine", "implementation", "architecture", "security", "review"]);
|
|
40
40
|
const capabilityDepth = tool.schema.enum(["light", "standard", "deep"]);
|
|
41
|
+
const commitMode = tool.schema.enum(["manual", "per_item"]);
|
|
41
42
|
const deliveryFinding = tool.schema.object({
|
|
42
43
|
id: tool.schema.string(),
|
|
43
44
|
severity: tool.schema.enum(["info", "warning", "error"]),
|
|
@@ -46,9 +47,9 @@ const deliveryFinding = tool.schema.object({
|
|
|
46
47
|
remediation_ids: tool.schema.array(tool.schema.string()).optional(),
|
|
47
48
|
recommendation: tool.schema.string().optional(),
|
|
48
49
|
}).strict();
|
|
49
|
-
const executionItem = tool.schema.union([tool.schema.string(), tool.schema.object({ id: tool.schema.string().optional(), text: tool.schema.string() }).strict()]);
|
|
50
|
+
const executionItem = tool.schema.union([tool.schema.string(), tool.schema.object({ id: tool.schema.string().optional(), text: tool.schema.string(), details: tool.schema.string().optional() }).strict()]);
|
|
50
51
|
const executionRemoval = tool.schema.union([tool.schema.string(), tool.schema.object({ id: tool.schema.string() }).strict()]);
|
|
51
|
-
const executionEdit = tool.schema.object({ id: tool.schema.string(), text: tool.schema.string() }).strict();
|
|
52
|
+
const executionEdit = tool.schema.object({ id: tool.schema.string(), text: tool.schema.string().optional(), details: tool.schema.string().nullable().optional() }).strict().refine((item) => item.text !== undefined || item.details !== undefined, { message: "Structured execution edits require text or details" });
|
|
52
53
|
const executionSections = Object.fromEntries(["scope", "completed", "remaining", "decisions", "blockers", "verification"].map((section) => [section, tool.schema.array(executionItem).optional()]));
|
|
53
54
|
const executionRemovalSections = Object.fromEntries(["scope", "completed", "remaining", "decisions", "blockers", "verification"].map((section) => [section, tool.schema.array(executionRemoval).optional()]));
|
|
54
55
|
const executionEditSections = Object.fromEntries(["scope", "completed", "remaining", "decisions", "blockers", "verification"].map((section) => [section, tool.schema.array(executionEdit).optional()]));
|
|
@@ -90,6 +91,8 @@ export const work_context_list_workspaces = tool({ description: "List work-conte
|
|
|
90
91
|
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)) });
|
|
91
92
|
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)) });
|
|
92
93
|
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)) });
|
|
94
|
+
export const work_context_set_workspace_commit_mode = tool({ description: "Set persistent workspace checklist commit authorization.", args: { workspace: tool.schema.string(), commitMode }, execute: run((ctx, a) => ctx.setWorkspaceCommitMode(a.workspace, a.commitMode)) });
|
|
95
|
+
export const work_context_read_effective_commit_mode = tool({ description: "Read the effective checklist commit mode immediately before a direct commit or candidate fallback.", args: contextualStage, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.readEffectiveCommitMode(workspace, stageFromSession(ctx, workspace, a.stage)); }) });
|
|
93
96
|
export const work_context_create_candidate = tool({ description: "Create an exact, shared-foundation, or integration draft candidate. Related stages are optional traceability and never ownership.", args: { workspace: tool.schema.string(), title: tool.schema.string(), message: tool.schema.string().optional(), strategy: tool.schema.enum(["exact", "shared_foundation", "integration"]).optional(), relatedStages: tool.schema.array(tool.schema.string()).optional() }, execute: run((ctx, a) => ctx.createCandidate(a.workspace, a.title, a.message, { strategy: a.strategy, relatedStages: a.relatedStages })) });
|
|
94
97
|
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 })) });
|
|
95
98
|
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)) });
|
|
@@ -125,6 +128,7 @@ export const work_context_acknowledge_commit = tool({ description: "Acknowledge
|
|
|
125
128
|
}) });
|
|
126
129
|
export const work_context_add_stage = tool({ description: "Add a stage with an optional execution capability and depth. When the user did not specify them, infer both from the prompt and pass classification: inferred. Explicit user choices use classification: explicit.", 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(), executionProfile: capabilityProfile.optional(), executionDepth: capabilityDepth.optional(), classification: tool.schema.enum(["inferred", "explicit"]).optional(), reviewProfile: capabilityProfile.optional() }, execute: run(addStageFromTool) });
|
|
127
130
|
export const work_context_set_stage_profiles = tool({ description: "Explicitly set or clear a stage execution capability and depth. Omitted fields are unchanged; pass null for both execution fields to clear them. Review profile remains optional metadata.", args: { ...contextualStage, executionProfile: capabilityProfile.nullable().optional(), executionDepth: capabilityDepth.nullable().optional(), reviewProfile: capabilityProfile.nullable().optional() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.setStageProfiles(workspace, stageFromSession(ctx, workspace, a.stage), { ...(Object.hasOwn(a, "executionProfile") ? { executionProfile: a.executionProfile } : {}), ...(Object.hasOwn(a, "executionDepth") ? { executionDepth: a.executionDepth } : {}), ...(Object.hasOwn(a, "reviewProfile") ? { reviewProfile: a.reviewProfile } : {}) }); }) });
|
|
131
|
+
export const work_context_set_stage_commit_mode = tool({ description: "Set or clear a stage checklist commit-mode override; null inherits the workspace mode.", args: { ...contextualStage, commitMode: commitMode.nullable() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.setStageCommitMode(workspace, stageFromSession(ctx, workspace, a.stage), a.commitMode); }) });
|
|
128
132
|
export const work_context_refresh_stage_profiles = tool({ description: "Atomically apply agent-inferred execution capability and depth recommendations. Ordinary refresh preserves explicit classifications; includeExplicit permits an explicitly requested override.", args: { workspace: tool.schema.string(), recommendations: tool.schema.array(tool.schema.object({ stage: tool.schema.string(), executionProfile: capabilityProfile, executionDepth: capabilityDepth })), includeExplicit: tool.schema.boolean().optional() }, execute: run((ctx, a) => ctx.refreshStageProfiles(a.workspace, a.recommendations, { includeExplicit: a.includeExplicit })) });
|
|
129
133
|
export const work_context_show_capability_profiles = tool({ description: "Show capability recommendation mode and validated user-local depth mappings.", args: {}, execute: run((ctx) => ctx.showCapabilityProfiles()) });
|
|
130
134
|
export const work_context_configure_capability_profiles = tool({ description: "Atomically configure either capability recommendation mode or global/project light, standard, and deep advisory labels. Interactive setup calls it separately for mode and mappings after gathering preferences.", args: { mode: tool.schema.enum(["advisory", "off"]).optional(), mappings: tool.schema.object({ light: tool.schema.string().optional(), standard: tool.schema.string().optional(), deep: tool.schema.string().optional() }).strict().optional(), scope: tool.schema.enum(["global", "project"]).optional() }, execute: run((ctx, a) => ctx.configureCapabilityProfiles(a)) });
|
|
@@ -154,7 +158,7 @@ export const work_context_add_knowledge = tool({ description: "Add a durable kno
|
|
|
154
158
|
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)) });
|
|
155
159
|
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) ) });
|
|
156
160
|
|
|
157
|
-
const defaultTools = { 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_inspect_commit_all, work_context_commit_all, work_context_discard_candidate, work_context_read_delivery, work_context_explain_delivery, work_context_doctor_delivery, work_context_mark_delivery, work_context_workspace_finish, work_context_reopen_workspace, work_context_create_workspace, work_context_start_session, work_context_acknowledge_commit, work_context_add_stage, work_context_set_stage_profiles, work_context_refresh_stage_profiles, work_context_show_capability_profiles, work_context_configure_capability_profiles, work_context_reset_capability_profiles, 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_complete_current, 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 };
|
|
161
|
+
const defaultTools = { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_set_workspace_mode, work_context_set_workspace_commit_mode, work_context_read_effective_commit_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_inspect_commit_all, work_context_commit_all, work_context_discard_candidate, work_context_read_delivery, work_context_explain_delivery, work_context_doctor_delivery, work_context_mark_delivery, work_context_workspace_finish, work_context_reopen_workspace, work_context_create_workspace, work_context_start_session, work_context_acknowledge_commit, work_context_add_stage, work_context_set_stage_profiles, work_context_set_stage_commit_mode, work_context_refresh_stage_profiles, work_context_show_capability_profiles, work_context_configure_capability_profiles, work_context_reset_capability_profiles, 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_complete_current, 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 };
|
|
158
162
|
|
|
159
163
|
export function createToolDefinitions(options = {}) {
|
|
160
164
|
return { ...defaultTools, work_context_doctor_delivery: createDoctorDeliveryTool(options) };
|
|
@@ -33,6 +33,7 @@ const readWorkspace = (context, record, currentSession, capabilityMappings) => {
|
|
|
33
33
|
: sessions.find((session) => session.session_id === currentSession?.session_id);
|
|
34
34
|
const currentStage = matchingSession?.stage || null;
|
|
35
35
|
const mode = record.mode || "standard";
|
|
36
|
+
const commitMode = record.commit_mode || "manual";
|
|
36
37
|
const candidateProjection = mode === "startup" ? context.candidates().activeProjection(record.workspace) : null;
|
|
37
38
|
const deliveryProjection = context.deliveries().projection(record.workspace);
|
|
38
39
|
const delivery = deliveryProjection.committed.count || deliveryProjection.environments.length || deliveryProjection.unavailable
|
|
@@ -47,6 +48,7 @@ const readWorkspace = (context, record, currentSession, capabilityMappings) => {
|
|
|
47
48
|
title: record.title,
|
|
48
49
|
status: record.status,
|
|
49
50
|
mode,
|
|
51
|
+
commit_mode: commitMode,
|
|
50
52
|
...(candidateProjection ? { candidates: candidateProjection.summary } : {}),
|
|
51
53
|
...(delivery ? { delivery } : {}),
|
|
52
54
|
stages: visibleStages
|
|
@@ -57,6 +59,7 @@ const readWorkspace = (context, record, currentSession, capabilityMappings) => {
|
|
|
57
59
|
description: stage.description,
|
|
58
60
|
depends_on: stage.depends_on.filter((dependency) => visibleStageIds.has(dependency)),
|
|
59
61
|
tracker_links: stage.tracker_links || [],
|
|
62
|
+
...(stage.commit_mode ? { commit_mode: stage.commit_mode } : {}),
|
|
60
63
|
...stageCapabilityProfiles(context.storage, stage, capabilityMappings),
|
|
61
64
|
...(candidateProjection?.by_stage[stage.stage] ? { candidates: candidateProjection.by_stage[stage.stage] } : {}),
|
|
62
65
|
current: stage.stage === currentStage,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { work_context_read_effective_commit_mode as default } from "../src/tool-definitions.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { work_context_set_stage_commit_mode as default } from "../src/tool-definitions.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { work_context_set_workspace_commit_mode as default } from "../src/tool-definitions.js";
|