opencode-work-context 0.10.3 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -7
- package/bin/opencode-work-context.js +20 -10
- package/commands/commited.md +16 -0
- package/commands/wc.md +5 -1
- package/package.json +1 -1
- package/plugin/session-model.js +22 -0
- package/plugin/stages-tui.js +80 -38
- package/plugin/work-context-modal.js +5 -4
- package/src/capability-profiles.js +1 -1
- package/src/core.js +16 -3
- package/src/errors.js +4 -0
- package/src/git-acknowledgement.js +99 -0
- package/src/index.js +1 -0
- package/src/protocol.js +2 -2
- package/src/stages-renderer.js +20 -11
- package/src/stages-snapshot.js +4 -0
- package/src/tool-definitions.js +6 -1
- package/tools/work_context_acknowledge_commit.js +1 -0
package/README.md
CHANGED
|
@@ -70,6 +70,28 @@ only when the workspace Planning-stage prompt includes this standalone line:
|
|
|
70
70
|
AUTO_STAGE_FINISH: allowed
|
|
71
71
|
```
|
|
72
72
|
|
|
73
|
+
### Acknowledge A Manual Commit
|
|
74
|
+
|
|
75
|
+
When you commit shared in-progress work while an active stage is running, tell
|
|
76
|
+
the agent about the exact commit using the short hash printed by Git:
|
|
77
|
+
|
|
78
|
+
```text
|
|
79
|
+
/commited f86f75a
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`commited` is intentionally spelled with one `t`. It is a compact, explicit
|
|
83
|
+
acknowledgement rather than an ownership claim: Work Context requires that hash
|
|
84
|
+
to resolve to the current `HEAD`, verifies the session's original attached
|
|
85
|
+
branch and fast-forward checkpoint, and rejects rebases, branch changes,
|
|
86
|
+
detached `HEAD`, and active Git operations. The checkpoint is per active
|
|
87
|
+
session in ignored `.work-context/local/` state; no canonical workspace data,
|
|
88
|
+
candidate state, file, hunk, or stage ownership is changed.
|
|
89
|
+
|
|
90
|
+
The generated command asks OpenCode to execute this deterministic structured
|
|
91
|
+
tool as a light control-plane operation. OpenCode does not expose a package API
|
|
92
|
+
that selects a model for individual slash commands, so the package does not
|
|
93
|
+
claim to force a particular local light-tier mapping.
|
|
94
|
+
|
|
73
95
|
To correct a completed stage without discarding its result or session history,
|
|
74
96
|
use `/wc stage reopen <workspace> <stage> "reason"`. Reopening leaves
|
|
75
97
|
downstream stages unchanged and requires a separate-session explicit resume.
|
|
@@ -147,8 +169,10 @@ The resulting user-local mappings live only in the ignored
|
|
|
147
169
|
```
|
|
148
170
|
|
|
149
171
|
Expanded stage details render one compact line such as `implementation · deep ·
|
|
150
|
-
Sol
|
|
151
|
-
|
|
172
|
+
Sol`. Without a mapping, the TUI shows the actual model name for the current
|
|
173
|
+
OpenCode session; other stages show only capability and depth rather than an
|
|
174
|
+
ambiguous `current model` label. Optional `review_profile` metadata neither
|
|
175
|
+
resolves a model nor controls separately configured subagents.
|
|
152
176
|
Targets are bounded opaque labels and never enter tracked data. Invalid entries
|
|
153
177
|
produce bounded warnings. The plugin never changes an active model or agent,
|
|
154
178
|
invokes a reviewer, creates a replacement session, or blocks resume. `init`,
|
|
@@ -506,6 +530,12 @@ When a stage has execution state, resume also includes it in
|
|
|
506
530
|
checkpoint. The ledger remains local to that stage and is not injected into
|
|
507
531
|
unrelated stages or promoted to workspace knowledge. Existing stages without a
|
|
508
532
|
ledger retain their previous resume shape and are not rewritten.
|
|
533
|
+
When sidebar details are enabled with `Ctrl+X D`, the current stage also shows a
|
|
534
|
+
compact Todo summary derived from that same ledger. `Ctrl+X 2` opens its
|
|
535
|
+
read-only checklist, grouping the current item, queued work, completed work,
|
|
536
|
+
blockers, verification, and any useful scope or decisions. Checklist actions
|
|
537
|
+
never mutate storage; agents advance work through the existing atomic execution
|
|
538
|
+
update operation after reading its latest revision.
|
|
509
539
|
Finishing a stage closes its current session and may report downstream stages
|
|
510
540
|
whose prompts need review, but it never starts or resumes one of them. Any
|
|
511
541
|
downstream work begins only in a separate OpenCode session through an explicit
|
|
@@ -570,7 +600,8 @@ records without strategy or stage-reference metadata remain readable; new
|
|
|
570
600
|
candidates default to `exact` with no related stages.
|
|
571
601
|
|
|
572
602
|
The sidebar reads only candidate metadata and shows a compact
|
|
573
|
-
`Candidates
|
|
603
|
+
`Candidates …<draft-count> ✓<ready-count>` line when either count is nonzero;
|
|
604
|
+
zero-valued states are omitted.
|
|
574
605
|
With sidebar details enabled (`Ctrl+X D`), a stage with explicitly related active
|
|
575
606
|
candidates also shows `Pending:` metadata. One related candidate includes its
|
|
576
607
|
lifecycle status, strategy, and other related stage IDs; several candidates are
|
|
@@ -616,15 +647,15 @@ stages. Planning-stage resume receives a bounded `delivery_context` when committ
|
|
|
616
647
|
candidates or environment checkpoints exist. The sidebar renders metadata only:
|
|
617
648
|
|
|
618
649
|
```text
|
|
619
|
-
Delivery
|
|
620
|
-
Delivery
|
|
621
|
-
Delivery
|
|
650
|
+
Delivery 4 commits · ! plan
|
|
651
|
+
Delivery production · 2 tracked pending
|
|
652
|
+
Delivery production · 0 tracked pending
|
|
622
653
|
```
|
|
623
654
|
|
|
624
655
|
`tracked pending` compares committed candidate metadata with the recorded local
|
|
625
656
|
checkpoint; it is not a live Git reachability claim. A reset, rebase, force-push,
|
|
626
657
|
or external deployment change requires an explicit range inspection before acting.
|
|
627
|
-
Malformed or inconsistent checkpoint metadata renders `Delivery
|
|
658
|
+
Malformed or inconsistent checkpoint metadata renders `Delivery ! unavailable`
|
|
628
659
|
instead of claiming a clean delivery state.
|
|
629
660
|
|
|
630
661
|
When asked how to deploy, the Planning agent must inspect the exact commit range
|
|
@@ -45,12 +45,14 @@ const tuiConfig = JSON.stringify({
|
|
|
45
45
|
plugin: ["./tui-plugins/work-context-stages.js"],
|
|
46
46
|
}, null, 2) + "\n";
|
|
47
47
|
const command = fs.readFileSync(path.join(packageRoot, "commands", "wc.md"), "utf8");
|
|
48
|
+
const commitAcknowledgementCommand = fs.readFileSync(path.join(packageRoot, "commands", "commited.md"), "utf8");
|
|
48
49
|
const configRelative = path.join(".work-context", "config.yaml");
|
|
49
50
|
const tuiConfigRelative = path.join(".opencode", "tui.json");
|
|
50
51
|
const tuiPluginEntry = "./tui-plugins/work-context-stages.js";
|
|
51
52
|
const generated = new Map([
|
|
52
53
|
[configRelative, defaultConfig()],
|
|
53
54
|
[path.join(".opencode", "commands", "wc.md"), command],
|
|
55
|
+
[path.join(".opencode", "commands", "commited.md"), commitAcknowledgementCommand],
|
|
54
56
|
[path.join(".opencode", "plugins", "work-context.js"), `// Thin project integration; tools remain in the installed npm package.
|
|
55
57
|
${pluginLoader}`],
|
|
56
58
|
[path.join(".opencode", "tui-plugins", "work-context-stages.js"), tuiLoader],
|
|
@@ -155,6 +157,7 @@ function activate(enabled, force) {
|
|
|
155
157
|
[configRelative, JSON.stringify(config, null, 2) + "\n"],
|
|
156
158
|
[managedTuiConfigRelative, JSON.stringify(managedTuiConfig, null, 2) + "\n"],
|
|
157
159
|
[path.join(".opencode", "commands", "wc.md"), command],
|
|
160
|
+
[path.join(".opencode", "commands", "commited.md"), commitAcknowledgementCommand],
|
|
158
161
|
]);
|
|
159
162
|
const conflicts = [...files].flatMap(([relative, content]) => {
|
|
160
163
|
const file = path.join(projectRoot, relative);
|
|
@@ -173,18 +176,25 @@ function activate(enabled, force) {
|
|
|
173
176
|
}
|
|
174
177
|
|
|
175
178
|
function syncCommandProjection(force) {
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
179
|
+
const commands = new Map([
|
|
180
|
+
[".opencode/commands/wc.md", command],
|
|
181
|
+
[".opencode/commands/commited.md", commitAcknowledgementCommand],
|
|
182
|
+
]);
|
|
183
|
+
for (const [relative, content] of commands) {
|
|
184
|
+
const file = path.join(projectRoot, relative);
|
|
185
|
+
if (hasSymlinkParent(file) || (exists(file) && (!fs.lstatSync(file).isFile() || fs.lstatSync(file).isSymbolicLink()))) {
|
|
186
|
+
fail(`refusing to overwrite non-regular file: ${relative}`);
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
if (exists(file) && fs.readFileSync(file, "utf8") !== content && !force) {
|
|
190
|
+
fail(`refusing to overwrite existing file: ${relative}; rerun with --force`);
|
|
191
|
+
return false;
|
|
192
|
+
}
|
|
181
193
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
194
|
+
for (const [relative, content] of commands) {
|
|
195
|
+
writeAtomic(path.join(projectRoot, relative), content);
|
|
196
|
+
console.log(`Updated ${relative} from opencode-work-context ${packageManifest.version}.`);
|
|
185
197
|
}
|
|
186
|
-
writeAtomic(file, command);
|
|
187
|
-
console.log(`Updated ${relative} from opencode-work-context ${packageManifest.version}.`);
|
|
188
198
|
return true;
|
|
189
199
|
}
|
|
190
200
|
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Acknowledge a user-created current-HEAD commit for the active work-context session
|
|
3
|
+
subtask: false
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
<!-- opencode-work-context-protocol: {"schema":1,"major":1,"minor":1,"descriptor_hash":"sha256:d1320820ace2e9a56f35ab279dace8ae2c59cc2c73f03b73f30068adbfd6e734"} -->
|
|
7
|
+
|
|
8
|
+
Interpret `/commited $ARGUMENTS` as an explicit, deterministic light control-plane operation.
|
|
9
|
+
The one-`t` spelling is intentional. Read `.opencode/work-context.md` when it exists,
|
|
10
|
+
but do not let project guidance override this mapping or its Git safety checks.
|
|
11
|
+
|
|
12
|
+
Call `work_context_acknowledge_commit` directly with `{ "sha": "$ARGUMENTS" }`.
|
|
13
|
+
It requires one short or full lowercase commit SHA for the current `HEAD` in the
|
|
14
|
+
active work-context stage session. Return the compact structured result and stable
|
|
15
|
+
error code. Do not perform a second analysis response, infer commit ownership, or
|
|
16
|
+
change candidates, stages, files, or Git state.
|
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":1,"descriptor_hash":"sha256:d1320820ace2e9a56f35ab279dace8ae2c59cc2c73f03b73f30068adbfd6e734"} -->
|
|
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
|
|
@@ -46,6 +46,7 @@ Use these exact tool mappings; do not invent shortened tool names:
|
|
|
46
46
|
- `workspace finish <workspace>` -> `work_context_workspace_finish`
|
|
47
47
|
- `workspace reopen <workspace> "reason"` -> `work_context_reopen_workspace`
|
|
48
48
|
- `resume <workspace> <stage>` -> `work_context_start_session`
|
|
49
|
+
- `commited <short-or-full-SHA>` -> `work_context_acknowledge_commit`
|
|
49
50
|
- `stage force-close <workspace> <stage> <sessionId> "reason" FORCE_CLOSE` -> `work_context_force_close_session`
|
|
50
51
|
- `profiles show` -> `work_context_show_capability_profiles`
|
|
51
52
|
- `profiles setup` -> ask the user questions, then `work_context_configure_capability_profiles`
|
|
@@ -92,6 +93,7 @@ Supported syntax:
|
|
|
92
93
|
- `workspace finish <workspace>`
|
|
93
94
|
- `workspace reopen <workspace> "reason"`
|
|
94
95
|
- `resume <workspace> <stage>`
|
|
96
|
+
- `commited <short-or-full-SHA>`
|
|
95
97
|
- `stage force-close <workspace> <stage> <sessionId> "reason" FORCE_CLOSE`
|
|
96
98
|
- `profiles show`
|
|
97
99
|
- `profiles setup`
|
|
@@ -136,6 +138,7 @@ Supported syntax:
|
|
|
136
138
|
- 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
|
|
137
139
|
- 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
|
|
138
140
|
- 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
|
|
141
|
+
- after completing a meaningful remaining checklist item, read the latest revision and atomically remove that exact item from `remaining` while adding it to `completed` in one execution update; retain ordering and briefly report the transition in normal output
|
|
139
142
|
- `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
|
|
140
143
|
- 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
|
|
141
144
|
- do not expose raw workspace/stage/session identifiers, ordinals, `ok` flags, or absent error codes in the user-facing resume summary
|
|
@@ -152,6 +155,7 @@ Supported syntax:
|
|
|
152
155
|
- `stage add` creates a stage; when the current OpenCode session is not associated with a workspace, it also enters the new stage in that session
|
|
153
156
|
- when `stage add` is invoked from an associated session, it only creates a planned stage and leaves the current stage unchanged; enter it later with an explicit `resume <workspace> <stage>` in a separate OpenCode session
|
|
154
157
|
- `resume` returns `resume.next_action` and `resume.instruction`; begin or continue implementation when the stage prompt is non-empty unless it explicitly requires confirmation or contains an unresolved decision that genuinely blocks progress
|
|
158
|
+
- `commited` is intentionally spelled with one `t`. It is a deterministic light control-plane acknowledgement for a user-created current-HEAD commit in the active stage session. Call the structured tool directly and return its compact result without a second analysis response. It validates the supplied short or full SHA, attached branch, fast-forward checkpoint, and absence of Git operations; it never infers ownership or changes candidates.
|
|
155
159
|
- when `resume.next_action` is `ask_questions`, do not inspect or modify application code and ask the user focused questions needed to make the prompt actionable
|
|
156
160
|
- before `stage finish`, review durable findings: add new knowledge, update changed knowledge, supersede obsolete knowledge, or explicitly use `knowledgeReview=none` when the stage produced no durable findings; use `knowledgeReview=added` after ledger changes
|
|
157
161
|
- invoke `stage finish` only when the user explicitly requests that lifecycle command; do not infer the request from completed work, tests, or a final report
|
package/package.json
CHANGED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const modelRef = (session) => session?.model || (session?.modelID || session?.providerID ? session : null);
|
|
2
|
+
|
|
3
|
+
export const sessionModelLabel = (api, sessionId) => {
|
|
4
|
+
if (!sessionId) return null;
|
|
5
|
+
const session = api?.data?.session?.get?.(sessionId);
|
|
6
|
+
const ref = modelRef(session);
|
|
7
|
+
const modelID = ref?.id || ref?.modelID;
|
|
8
|
+
if (!modelID) return null;
|
|
9
|
+
const providerID = ref.providerID;
|
|
10
|
+
const models = api?.data?.location?.model?.list?.(session?.location) || [];
|
|
11
|
+
const model = models.find((item) => (!providerID || item.providerID === providerID)
|
|
12
|
+
&& (item.id === modelID || item.modelID === modelID));
|
|
13
|
+
return model?.name || [providerID, modelID].filter(Boolean).join("/");
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const capitalize = (value) => value ? `${value[0].toUpperCase()}${value.slice(1)}` : value;
|
|
17
|
+
|
|
18
|
+
export const capabilitySummaryText = (stage, sessionModel) => {
|
|
19
|
+
if (!stage?.execution_profile || !stage.execution_depth) return null;
|
|
20
|
+
const model = stage.recommended_model ? capitalize(stage.recommended_model) : sessionModel;
|
|
21
|
+
return [capitalize(stage.execution_profile), capitalize(stage.execution_depth), model].filter(Boolean).join(" · ");
|
|
22
|
+
};
|
package/plugin/stages-tui.js
CHANGED
|
@@ -2,13 +2,14 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { readStagesSnapshot } from "../src/stages-snapshot.js";
|
|
4
4
|
import { contextFor, titleFor } from "../src/opencode-adapter.js";
|
|
5
|
-
import { formatStageIds, renderDependencyTree, renderStagesPanel } from "../src/stages-renderer.js";
|
|
5
|
+
import { formatStageIds, renderDependencyTree, renderStagesPanel, workspaceStatusLines } from "../src/stages-renderer.js";
|
|
6
6
|
import { jsx } from "@opentui/solid/jsx-runtime";
|
|
7
7
|
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
11
|
import { resolveProjectRoot, withProjectRoot } from "./project-root.js";
|
|
12
|
+
import { capabilitySummaryText, sessionModelLabel } from "./session-model.js";
|
|
12
13
|
|
|
13
14
|
const DEBOUNCE_MS = 150;
|
|
14
15
|
const POLL_MS = 1000;
|
|
@@ -21,6 +22,8 @@ const DEPENDENCIES_COMMAND = "work_context.toggle_dependencies";
|
|
|
21
22
|
const DEPENDENCIES_SHORTCUT = "<leader>d";
|
|
22
23
|
const TREE_COMMAND = "work_context.show_dependency_tree";
|
|
23
24
|
const TREE_SHORTCUT = "<leader>t";
|
|
25
|
+
const CHECKLIST_COMMAND = "work_context.show_checklist";
|
|
26
|
+
const CHECKLIST_SHORTCUT = "<leader>2";
|
|
24
27
|
const statusMarker = (status) => ({
|
|
25
28
|
planned: "[ ]",
|
|
26
29
|
in_progress: "[•]",
|
|
@@ -34,26 +37,6 @@ const trackerLinkText = (link) => {
|
|
|
34
37
|
if (link.provider === "github") return `GH#${identifier}`;
|
|
35
38
|
return `JIRA ${identifier}`;
|
|
36
39
|
};
|
|
37
|
-
const candidateSummaryText = (workspace) => workspace.candidates && (workspace.candidates.pending || workspace.candidates.ready)
|
|
38
|
-
? `Candidates · ${workspace.candidates.pending} draft · ${workspace.candidates.ready} ready`
|
|
39
|
-
: null;
|
|
40
|
-
const deliverySummaryText = (workspace) => {
|
|
41
|
-
const delivery = workspace.delivery;
|
|
42
|
-
if (!delivery) return null;
|
|
43
|
-
if (delivery.unavailable) return "Delivery · unavailable";
|
|
44
|
-
if (delivery.plan_needed) return `Delivery · ${delivery.committed} commits · plan needed`;
|
|
45
|
-
if (delivery.environments.length === 1) {
|
|
46
|
-
const [environment] = delivery.environments;
|
|
47
|
-
return `Delivery · ${environment.environment} · ${environment.pending} tracked pending`;
|
|
48
|
-
}
|
|
49
|
-
const pending = delivery.environments.reduce((total, environment) => total + environment.pending, 0);
|
|
50
|
-
return `Delivery · ${delivery.environments.length} environments · ${pending} tracked pending`;
|
|
51
|
-
};
|
|
52
|
-
const workspaceSummaryText = (workspace, attention) => [
|
|
53
|
-
attention && `Attention · ${attention}`,
|
|
54
|
-
candidateSummaryText(workspace),
|
|
55
|
-
deliverySummaryText(workspace),
|
|
56
|
-
].filter(Boolean).join(" · ");
|
|
57
40
|
const stageCandidateText = (stage) => {
|
|
58
41
|
const projection = stage.candidates;
|
|
59
42
|
if (!projection || !(projection.draft || projection.ready)) return null;
|
|
@@ -62,7 +45,18 @@ const stageCandidateText = (stage) => {
|
|
|
62
45
|
const others = candidate.related_stages.filter((related) => related !== stage.id);
|
|
63
46
|
return `Pending: ${candidate.status} · ${candidate.strategy}${others.length ? ` · also ${others.join(", ")}` : ""}`;
|
|
64
47
|
};
|
|
65
|
-
const
|
|
48
|
+
export const checklistSummaryText = (execution) => {
|
|
49
|
+
if (!execution) return null;
|
|
50
|
+
const done = execution.completed?.length || 0;
|
|
51
|
+
const remaining = execution.remaining?.length || 0;
|
|
52
|
+
const total = done + remaining;
|
|
53
|
+
const parts = [];
|
|
54
|
+
if (total) parts.push(`✓ ${done}/${total}`);
|
|
55
|
+
if (remaining) parts.push(`• ${done + 1}/${total}`);
|
|
56
|
+
if (remaining > 1) parts.push(`… ${remaining - 1}`);
|
|
57
|
+
if (execution.blockers?.length) parts.push(`! ${execution.blockers.length}`);
|
|
58
|
+
return parts.length ? `Todo · ${parts.join(" · ")}` : null;
|
|
59
|
+
};
|
|
66
60
|
const visibleAttentionSnapshot = (attention, workspace, stages) => {
|
|
67
61
|
const byStage = new Map(stages.map((stage) => [stage.id, attention?.attentionForStage?.(workspace, stage.id) || null]));
|
|
68
62
|
const bySession = new Map();
|
|
@@ -76,23 +70,22 @@ const visibleAttentionSnapshot = (attention, workspace, stages) => {
|
|
|
76
70
|
export { readStagesSnapshot, renderStagesPanel };
|
|
77
71
|
|
|
78
72
|
const defaultRuntime = { jsx };
|
|
79
|
-
const renderStagesContent = (result, theme, runtime = defaultRuntime, attention, showDependencies = true, onStageSelect, activityFrame = () => LOADER_FRAMES[0]) => {
|
|
73
|
+
const renderStagesContent = (result, theme, runtime = defaultRuntime, attention, showDependencies = true, onStageSelect, activityFrame = () => LOADER_FRAMES[0], currentModel = () => null) => {
|
|
80
74
|
if (!result?.ok || !result.data?.workspace) return [
|
|
81
75
|
runtime.jsx("text", { children: runtime.jsx("b", { children: "Stages" }) }),
|
|
82
76
|
...renderStagesPanel(result).split("\n").slice(1).map((line) => runtime.jsx("text", { children: line })),
|
|
83
77
|
];
|
|
84
78
|
const attentionSnapshot = visibleAttentionSnapshot(attention, result.data.workspace.id, result.data.stages);
|
|
85
79
|
const workspaceAttention = attentionSummaryText(attentionSnapshot.workspace, { alwaysCount: true });
|
|
86
|
-
const
|
|
80
|
+
const workspaceStatus = workspaceStatusLines(result.data.workspace, workspaceAttention);
|
|
87
81
|
return [
|
|
88
82
|
runtime.jsx("box", {
|
|
89
83
|
marginBottom: 1,
|
|
90
84
|
flexDirection: "column",
|
|
91
85
|
children: [
|
|
92
86
|
runtime.jsx("text", { wrapMode: "word", children: runtime.jsx("b", { children: result.data.workspace.title }) }),
|
|
93
|
-
runtime.jsx("text", { fg: theme?.current?.textMuted, children:
|
|
94
|
-
|
|
95
|
-
].filter(Boolean),
|
|
87
|
+
...workspaceStatus.map((line) => runtime.jsx("text", { wrapMode: "word", fg: theme?.current?.textMuted, children: line })),
|
|
88
|
+
],
|
|
96
89
|
}),
|
|
97
90
|
runtime.jsx("box", {
|
|
98
91
|
flexDirection: "row",
|
|
@@ -104,16 +97,14 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
|
|
|
104
97
|
...result.data.stages.flatMap((stage) => {
|
|
105
98
|
const unread = attentionSnapshot.byStage.get(stage.id);
|
|
106
99
|
const working = attention?.activityForStage?.(result.data.workspace.id, stage.id);
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
: null;
|
|
100
|
+
const current = stage.current || stage.id === result.data.currentStage;
|
|
101
|
+
const recommendation = capabilitySummaryText(stage, current ? currentModel() : null);
|
|
110
102
|
const stageMetadata = [
|
|
111
103
|
stage.tracker_links?.length && `Tasks: ${stage.tracker_links.map(trackerLinkText).join(", ")}`,
|
|
112
104
|
stage.depends_on?.length && `Deps: ${formatStageIds(stage.depends_on)}`,
|
|
113
105
|
].filter(Boolean).join(" · ");
|
|
114
|
-
const metadata = showDependencies ? [recommendation, stageMetadata, stageCandidateText(stage)].filter(Boolean).join("\n") : "";
|
|
106
|
+
const metadata = showDependencies ? [recommendation, stageMetadata, stageCandidateText(stage), stage.current && checklistSummaryText(stage.execution)].filter(Boolean).join("\n") : "";
|
|
115
107
|
const attentionSignal = attentionSummaryText(unread);
|
|
116
|
-
const current = stage.current || stage.id === result.data.currentStage;
|
|
117
108
|
const onMouseDown = (event) => {
|
|
118
109
|
if (event?.button != null && event.button !== 0) return;
|
|
119
110
|
return onStageSelect?.(stage);
|
|
@@ -135,7 +126,7 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
|
|
|
135
126
|
flexDirection: "column",
|
|
136
127
|
children: [
|
|
137
128
|
runtime.jsx("text", { wrapMode: "word", fg: current ? theme?.current?.warning : theme?.current?.text, children: `${stage.id}. ${stage.title}` }),
|
|
138
|
-
metadata && runtime.jsx("text", { wrapMode: "
|
|
129
|
+
metadata && runtime.jsx("text", { wrapMode: "none", fg: theme?.current?.textMuted, children: metadata }),
|
|
139
130
|
].filter(Boolean),
|
|
140
131
|
}),
|
|
141
132
|
],
|
|
@@ -145,10 +136,10 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
|
|
|
145
136
|
];
|
|
146
137
|
};
|
|
147
138
|
|
|
148
|
-
export const renderStagesElement = (result, theme, runtime = defaultRuntime, attention, showDependencies = true, onStageSelect, activityFrame) => {
|
|
139
|
+
export const renderStagesElement = (result, theme, runtime = defaultRuntime, attention, showDependencies = true, onStageSelect, activityFrame, currentModel) => {
|
|
149
140
|
return runtime.jsx("box", {
|
|
150
141
|
flexDirection: "column",
|
|
151
|
-
children: () => renderStagesContent(typeof result === "function" ? result() : result, theme, runtime, attention, typeof showDependencies === "function" ? showDependencies() : showDependencies, onStageSelect, activityFrame),
|
|
142
|
+
children: () => renderStagesContent(typeof result === "function" ? result() : result, theme, runtime, attention, typeof showDependencies === "function" ? showDependencies() : showDependencies, onStageSelect, activityFrame, currentModel),
|
|
152
143
|
});
|
|
153
144
|
};
|
|
154
145
|
|
|
@@ -310,9 +301,9 @@ export const createStagesTuiController = ({ projectRoot, read = readStagesSnapsh
|
|
|
310
301
|
|
|
311
302
|
export { resolveProjectRoot } from "./project-root.js";
|
|
312
303
|
|
|
313
|
-
const renderStagesSlot = (controller, theme, sessionId, runtime = defaultRuntime, attention, onStageSelect) => runtime.jsx("box", {
|
|
304
|
+
const renderStagesSlot = (controller, theme, sessionId, runtime = defaultRuntime, attention, onStageSelect, currentModel) => runtime.jsx("box", {
|
|
314
305
|
flexDirection: "column",
|
|
315
|
-
children: renderStagesElement(() => controller.resultFor(sessionId), theme, runtime, attention, controller.showDependencies, onStageSelect, controller.activityFrame),
|
|
306
|
+
children: renderStagesElement(() => controller.resultFor(sessionId), theme, runtime, attention, controller.showDependencies, onStageSelect, controller.activityFrame, currentModel),
|
|
316
307
|
});
|
|
317
308
|
|
|
318
309
|
const updateSessionTitle = async (api, projectRoot) => {
|
|
@@ -380,6 +371,39 @@ export const openDependencyTreeDialog = (api, result) => {
|
|
|
380
371
|
return true;
|
|
381
372
|
};
|
|
382
373
|
|
|
374
|
+
export const checklistOptions = (execution, width = 80) => {
|
|
375
|
+
if (!execution) return [{ title: "No checklist is available for the current stage.", value: "empty", disabled: true }];
|
|
376
|
+
const compact = width < 50;
|
|
377
|
+
const truncate = (text) => compact && text.length > Math.max(12, width - 12) ? `${text.slice(0, Math.max(9, width - 15))}...` : text;
|
|
378
|
+
const options = [];
|
|
379
|
+
if (execution.remaining?.[0]) options.push({ title: `[•] ${truncate(execution.remaining[0])}`, value: "current", category: "Current" });
|
|
380
|
+
for (const item of execution.remaining?.slice(1) || []) options.push({ title: `[ ] ${truncate(item)}`, value: `queued-${item}`, category: "Queued" });
|
|
381
|
+
for (const item of execution.completed || []) options.push({ title: `[✓] ${truncate(item)}`, value: `completed-${item}`, category: "Completed" });
|
|
382
|
+
for (const item of execution.blockers || []) options.push({ title: `[!] ${truncate(item)}`, value: `blocker-${item}`, category: "Blockers" });
|
|
383
|
+
for (const item of execution.verification || []) options.push({ title: `[ ] ${truncate(item)}`, value: `verification-${item}`, category: "Verification" });
|
|
384
|
+
if (execution.scope?.length) options.push(...execution.scope.map((item) => ({ title: truncate(item), value: `scope-${item}`, category: "Scope" })));
|
|
385
|
+
if (execution.decisions?.length) options.push(...execution.decisions.map((item) => ({ title: truncate(item), value: `decision-${item}`, category: "Decisions" })));
|
|
386
|
+
return options.length ? [{ title: "Close", value: "close", category: "Checklist" }, ...options] : [{ title: "Checklist is empty.", value: "empty", disabled: true }];
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
export const openChecklistDialog = (api, result) => {
|
|
390
|
+
if (typeof api?.ui?.DialogSelect !== "function" || typeof api?.ui?.dialog?.replace !== "function") return false;
|
|
391
|
+
const current = result?.data?.stages?.find((stage) => stage.current || stage.id === result.data.currentStage);
|
|
392
|
+
if (!result?.ok || !result.data?.workspace || !current?.execution) {
|
|
393
|
+
api.ui?.toast?.({ message: "No checklist is available for the current stage", variant: "warning" });
|
|
394
|
+
return false;
|
|
395
|
+
}
|
|
396
|
+
const width = api.renderer?.width || 80;
|
|
397
|
+
api.ui.dialog.setSize?.(width < 50 ? "small" : "large");
|
|
398
|
+
api.ui.dialog.replace(() => api.ui.DialogSelect({
|
|
399
|
+
title: `Checklist · ${current.title}`,
|
|
400
|
+
placeholder: "Checklist",
|
|
401
|
+
options: checklistOptions(current.execution, width),
|
|
402
|
+
onSelect: (option) => { if (option.value === "close") api.ui.dialog.clear?.(); },
|
|
403
|
+
}));
|
|
404
|
+
return true;
|
|
405
|
+
};
|
|
406
|
+
|
|
383
407
|
const registerDependencyTree = (api, controller, sessionId) => {
|
|
384
408
|
if (typeof api?.keymap?.registerLayer !== "function") return () => {};
|
|
385
409
|
const command = {
|
|
@@ -396,6 +420,22 @@ const registerDependencyTree = (api, controller, sessionId) => {
|
|
|
396
420
|
});
|
|
397
421
|
};
|
|
398
422
|
|
|
423
|
+
const registerChecklist = (api, controller, sessionId) => {
|
|
424
|
+
if (typeof api?.keymap?.registerLayer !== "function") return () => {};
|
|
425
|
+
const command = {
|
|
426
|
+
name: CHECKLIST_COMMAND,
|
|
427
|
+
title: "Show current stage checklist",
|
|
428
|
+
desc: "Open the current stage's read-only checklist",
|
|
429
|
+
category: "Work Context",
|
|
430
|
+
namespace: "palette",
|
|
431
|
+
run: () => openChecklistDialog(api, controller.resultFor(sessionId())),
|
|
432
|
+
};
|
|
433
|
+
return api.keymap.registerLayer({
|
|
434
|
+
commands: [command],
|
|
435
|
+
bindings: [{ key: CHECKLIST_SHORTCUT, cmd: CHECKLIST_COMMAND, desc: command.title }],
|
|
436
|
+
});
|
|
437
|
+
};
|
|
438
|
+
|
|
399
439
|
const ACTIVE_WORKSPACE_SESSION = "__active_" + "work" + "_context_workspace__";
|
|
400
440
|
|
|
401
441
|
// Optional TUI entry point. It is deliberately not imported by the server plugin.
|
|
@@ -424,6 +464,7 @@ export const tui = async (api, options = {}) => {
|
|
|
424
464
|
const unregisterDependencyToggle = registerDependencyToggle(api, controller, projectRoot);
|
|
425
465
|
let currentSessionId = initialSessionId;
|
|
426
466
|
const unregisterDependencyTree = registerDependencyTree(api, controller, () => currentSessionId || ACTIVE_WORKSPACE_SESSION);
|
|
467
|
+
const unregisterChecklist = registerChecklist(api, controller, () => currentSessionId || ACTIVE_WORKSPACE_SESSION);
|
|
427
468
|
await controller.load(initialSessionId);
|
|
428
469
|
let storageWatcher;
|
|
429
470
|
const refreshAttention = () => { void api.workContextAttention?.refresh?.(); };
|
|
@@ -443,7 +484,7 @@ export const tui = async (api, options = {}) => {
|
|
|
443
484
|
sidebar_content: (slotContext = {}, slotState = {}) => {
|
|
444
485
|
const sessionId = sessionIdForSlot(api, initialSessionId, slotContext, slotState) || ACTIVE_WORKSPACE_SESSION;
|
|
445
486
|
currentSessionId = sessionId;
|
|
446
|
-
return renderStagesSlot(controller, api.theme, sessionId, options.runtime, api.workContextAttention, (stage) => stageSwitcher.select(stage.id));
|
|
487
|
+
return renderStagesSlot(controller, api.theme, sessionId, options.runtime, api.workContextAttention, (stage) => stageSwitcher.select(stage.id), () => sessionModelLabel(api, sessionId));
|
|
447
488
|
},
|
|
448
489
|
},
|
|
449
490
|
});
|
|
@@ -471,6 +512,7 @@ export const tui = async (api, options = {}) => {
|
|
|
471
512
|
disposeRegistration(unregisterSlot);
|
|
472
513
|
disposeRegistration(unregisterDependencyToggle);
|
|
473
514
|
disposeRegistration(unregisterDependencyTree);
|
|
515
|
+
disposeRegistration(unregisterChecklist);
|
|
474
516
|
};
|
|
475
517
|
api[ACTIVE_TUI_KEY] = cleanup;
|
|
476
518
|
activeTuiInstances.set(api, cleanup);
|
|
@@ -9,6 +9,7 @@ import { openWorkspaceSwitcher } from "./workspace-switcher.js";
|
|
|
9
9
|
import { openSessionSwitcher } from "./session-switcher.js";
|
|
10
10
|
import { attentionForSession, attentionIndicatorText, attentionReasonText } from "./attention.js";
|
|
11
11
|
import { resolveProjectRoot, withProjectRoot } from "./project-root.js";
|
|
12
|
+
import { capabilitySummaryText, sessionModelLabel } from "./session-model.js";
|
|
12
13
|
|
|
13
14
|
const COMMAND_NAME = "work_context.open";
|
|
14
15
|
const ACTIONS_COMMAND_NAME = "work_context.actions";
|
|
@@ -21,7 +22,6 @@ const POLL_MS = 1000;
|
|
|
21
22
|
const MARKERS = { planned: "[ ]", in_progress: "[•]", completed: "[✓]", cancelled: "[!]" };
|
|
22
23
|
const COMMANDS = { list: "list", resume: "resume", handoff: "stage handoff", finish: "stage finish" };
|
|
23
24
|
const activeTuiInstances = new WeakMap();
|
|
24
|
-
const capitalize = (value) => value ? `${value[0].toUpperCase()}${value.slice(1)}` : value;
|
|
25
25
|
|
|
26
26
|
export const WORK_CONTEXT_ACTIONS = [
|
|
27
27
|
{ value: "help", title: "Help", description: "Show work-context command help", category: "General" },
|
|
@@ -224,7 +224,7 @@ export const createWorkContextModalController = ({
|
|
|
224
224
|
const line = (runtime, children, props = {}) => runtime.jsx("text", { ...props, children });
|
|
225
225
|
const marker = (status) => MARKERS[status] || "[?]";
|
|
226
226
|
|
|
227
|
-
export const renderWorkContextModal = (controller, theme, runtime = { jsx }, { maxListHeight = 24 } = {}) => {
|
|
227
|
+
export const renderWorkContextModal = (controller, theme, runtime = { jsx }, { maxListHeight = 24, currentModel = () => null } = {}) => {
|
|
228
228
|
let workspaceScroll;
|
|
229
229
|
let stageScroll;
|
|
230
230
|
controller.onSelectionChange?.(() => queueMicrotask(() => {
|
|
@@ -239,6 +239,7 @@ export const renderWorkContextModal = (controller, theme, runtime = { jsx }, { m
|
|
|
239
239
|
const selected = controller.selectedWorkspace();
|
|
240
240
|
const stage = controller.selectedStage();
|
|
241
241
|
const data = result?.data;
|
|
242
|
+
const capability = capabilitySummaryText(stage, stage?.current ? currentModel() : null);
|
|
242
243
|
const status = result?.stale ? `STALE · ${result.error?.code || "STORAGE_ERROR"}` : result?.ok === false ? `ERROR · ${result.error?.code || "STORAGE_ERROR"}` : "LIVE";
|
|
243
244
|
const muted = theme?.current?.textMuted;
|
|
244
245
|
const selectedWorkspaceIndex = selected ? workspaces.indexOf(selected) : -1;
|
|
@@ -290,7 +291,7 @@ export const renderWorkContextModal = (controller, theme, runtime = { jsx }, { m
|
|
|
290
291
|
...(controller.details() && stage ? [
|
|
291
292
|
line(runtime, "Details", { marginTop: 1, fg: muted }),
|
|
292
293
|
line(runtime, stage.description || "No description.", { wrapMode: "word", fg: theme?.current?.text }),
|
|
293
|
-
|
|
294
|
+
capability && line(runtime, capability, { wrapMode: "word", fg: muted }),
|
|
294
295
|
line(runtime, `Sessions ${(selected.sessions || []).length}`, { fg: muted }),
|
|
295
296
|
...(selected.sessions || []).map((session) => {
|
|
296
297
|
const unread = controller.attention?.attentionFor?.(session.opencode_session_id);
|
|
@@ -583,7 +584,7 @@ export const openCompatibilityDialog = (api, runtime = {}, options = {}) => {
|
|
|
583
584
|
const controller = createWorkContextModalController({ projectRoot, sessionId, read: options.read || readWorkContextSnapshot, createSignal: runtime.createSignal, attention: api.workContextAttention, onClose: close, onCommand: (command) => insertPromptCommand(api, command) });
|
|
584
585
|
try { watcher = projectRoot && fs.watch(path.join(projectRoot, ".work-context"), { recursive: true }, () => controller.scheduleRefresh?.()); } catch {}
|
|
585
586
|
const maxListHeight = Math.max(8, Math.floor((api.renderer?.height || 60) / 2) - 6);
|
|
586
|
-
const render = () => renderWorkContextModal(controller, api.theme, runtime, { maxListHeight });
|
|
587
|
+
const render = () => renderWorkContextModal(controller, api.theme, runtime, { maxListHeight, currentModel: () => sessionModelLabel(api, sessionId) });
|
|
587
588
|
stack.replace(render, close);
|
|
588
589
|
return true;
|
|
589
590
|
};
|
|
@@ -68,7 +68,7 @@ export const stageCapabilityProfiles = (storage, stage, localMappings) => {
|
|
|
68
68
|
...(stage.execution_depth ? { execution_depth: stage.execution_depth } : {}),
|
|
69
69
|
...(stage.execution_classification ? { execution_classification: stage.execution_classification } : {}),
|
|
70
70
|
...(stage.review_profile ? { review_profile: stage.review_profile } : {}),
|
|
71
|
-
...(recommendation ? { recommended_model: recommendation.target
|
|
71
|
+
...(recommendation?.target ? { recommended_model: recommendation.target } : {}),
|
|
72
72
|
};
|
|
73
73
|
};
|
|
74
74
|
|
package/src/core.js
CHANGED
|
@@ -13,6 +13,7 @@ import { DeliveryStore } from "./delivery.js";
|
|
|
13
13
|
import { doctorDelivery as runDeliveryDoctor } from "./delivery-doctor.js";
|
|
14
14
|
import { applyExecutionPatch, assertExecutionSize, executionState, normalizeExecutionState } from "./stage-execution.js";
|
|
15
15
|
import { CAPABILITY_CLASSIFICATIONS, CAPABILITY_DEPTHS, CAPABILITY_MAPPINGS_FILE, CAPABILITY_PROFILES, capabilityProfileMode, capabilityRecommendations, readCapabilityMappings, validateCapabilityMappings } from "./capability-profiles.js";
|
|
16
|
+
import { acknowledgeGitCommit, initializeGitCheckpoint } from "./git-acknowledgement.js";
|
|
16
17
|
|
|
17
18
|
const actor = (options) => options.actor || "OpenCode";
|
|
18
19
|
const workspaceMode = (data) => data.mode || "standard";
|
|
@@ -243,9 +244,10 @@ export class WorkContext {
|
|
|
243
244
|
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));
|
|
244
245
|
const sessionId = options.sessionId || randomUUID();
|
|
245
246
|
const workflowPolicy = mode === "startup" && options.opencodeSessionId ? startupWorkflowPolicy() : null;
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
247
|
+
if (this.storage.readEvents().some((item) => item.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
|
|
248
|
+
this.writeEvents([event("session.started", workspace, "01", 1, sessionId, actor(this.options), { summary: `planning ${title.trim()}`, opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
|
|
249
|
+
initializeGitCheckpoint(this.storage, { workspace, stage: "01", sessionId });
|
|
250
|
+
generateProjections(this.storage);
|
|
249
251
|
return this.result({
|
|
250
252
|
workspace,
|
|
251
253
|
mode,
|
|
@@ -388,6 +390,7 @@ export class WorkContext {
|
|
|
388
390
|
this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), stageRecord.data, stageRecord.body);
|
|
389
391
|
}
|
|
390
392
|
this.writeEvents([event("session.started", workspace, stage, ordinal, sessionId, actor(this.options), { summary: options.summary || "continued work", opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
|
|
393
|
+
initializeGitCheckpoint(this.storage, { workspace, stage, sessionId });
|
|
391
394
|
generateProjections(this.storage);
|
|
392
395
|
const previousSession = previous.at(-1) || null;
|
|
393
396
|
const previousSessionSummary = previousSession?.summary && previousSession.summary !== "continued work"
|
|
@@ -452,6 +455,16 @@ export class WorkContext {
|
|
|
452
455
|
});
|
|
453
456
|
}
|
|
454
457
|
|
|
458
|
+
acknowledgeCommit(workspace, stage, sessionId, sha) {
|
|
459
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
460
|
+
stage = normalizeStageId(stage);
|
|
461
|
+
this.storage.assertSafeRoots();
|
|
462
|
+
return withLock(this.storage.lockPath("git-acknowledgement"), () => {
|
|
463
|
+
assertActive(this.storage.readEvents(), workspace, stage, sessionId);
|
|
464
|
+
return this.result(acknowledgeGitCommit(this.storage, { workspace, stage, sessionId, sha }), ["local:git-checkpoint"]);
|
|
465
|
+
}, { session: sessionId, owner: actor(this.options) });
|
|
466
|
+
}
|
|
467
|
+
|
|
455
468
|
addStage(workspace, title, options = {}) {
|
|
456
469
|
workspace = normalizeWorkspaceId(workspace);
|
|
457
470
|
if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Title is required");
|
package/src/errors.js
CHANGED
|
@@ -5,6 +5,10 @@ export const ERROR_CODES = Object.freeze({
|
|
|
5
5
|
ADAPTER_UNAVAILABLE: "ADAPTER_UNAVAILABLE", STORAGE_ERROR: "STORAGE_ERROR", CONFIRMATION_REQUIRED: "CONFIRMATION_REQUIRED",
|
|
6
6
|
STAGE_CONTEXT_REQUIRED: "STAGE_CONTEXT_REQUIRED",
|
|
7
7
|
GIT_UNAVAILABLE: "GIT_UNAVAILABLE", NOT_GIT_REPOSITORY: "NOT_GIT_REPOSITORY",
|
|
8
|
+
GIT_ACKNOWLEDGEMENT_INVALID_SHA: "GIT_ACKNOWLEDGEMENT_INVALID_SHA", GIT_ACKNOWLEDGEMENT_CHECKPOINT_MISSING: "GIT_ACKNOWLEDGEMENT_CHECKPOINT_MISSING",
|
|
9
|
+
GIT_ACKNOWLEDGEMENT_NOT_HEAD: "GIT_ACKNOWLEDGEMENT_NOT_HEAD", GIT_ACKNOWLEDGEMENT_REF_CHANGED: "GIT_ACKNOWLEDGEMENT_REF_CHANGED",
|
|
10
|
+
GIT_ACKNOWLEDGEMENT_NON_FAST_FORWARD: "GIT_ACKNOWLEDGEMENT_NON_FAST_FORWARD", GIT_ACKNOWLEDGEMENT_DETACHED_HEAD: "GIT_ACKNOWLEDGEMENT_DETACHED_HEAD",
|
|
11
|
+
GIT_ACKNOWLEDGEMENT_GIT_OPERATION: "GIT_ACKNOWLEDGEMENT_GIT_OPERATION",
|
|
8
12
|
CANDIDATE_MODE_REQUIRED: "CANDIDATE_MODE_REQUIRED", CANDIDATE_INVALID_PATCH: "CANDIDATE_INVALID_PATCH",
|
|
9
13
|
CANDIDATE_UNSUPPORTED: "CANDIDATE_UNSUPPORTED", CANDIDATE_STALE_BASE: "CANDIDATE_STALE_BASE",
|
|
10
14
|
CANDIDATE_CONFLICT: "CANDIDATE_CONFLICT", CANDIDATE_DETACHED_HEAD: "CANDIDATE_DETACHED_HEAD",
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { ERROR_CODES, fail } from "./errors.js";
|
|
6
|
+
import { atomicWrite } from "./storage.js";
|
|
7
|
+
|
|
8
|
+
const git = (root, args, options = {}) => {
|
|
9
|
+
const result = spawnSync("git", args, { cwd: root, encoding: "utf8", maxBuffer: 1024 * 1024, ...options });
|
|
10
|
+
if (result.error?.code === "ENOENT") fail(ERROR_CODES.GIT_UNAVAILABLE, "Git executable is unavailable");
|
|
11
|
+
if (result.error) fail(ERROR_CODES.GIT_UNAVAILABLE, "Cannot execute Git");
|
|
12
|
+
return result;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const repository = (projectRoot) => {
|
|
16
|
+
const rootResult = git(projectRoot, ["rev-parse", "--show-toplevel"]);
|
|
17
|
+
if (rootResult.status !== 0) fail(ERROR_CODES.NOT_GIT_REPOSITORY, "Work context is not at a Git repository root");
|
|
18
|
+
const root = fs.realpathSync(rootResult.stdout.trim());
|
|
19
|
+
if (root !== fs.realpathSync(projectRoot)) fail(ERROR_CODES.NOT_GIT_REPOSITORY, "Work context must be at the Git repository root");
|
|
20
|
+
const headResult = git(root, ["rev-parse", "--verify", "HEAD"]);
|
|
21
|
+
if (headResult.status !== 0) fail(ERROR_CODES.GIT_ACKNOWLEDGEMENT_CHECKPOINT_MISSING, "Git repository has no valid HEAD");
|
|
22
|
+
const refResult = git(root, ["symbolic-ref", "--quiet", "HEAD"]);
|
|
23
|
+
if (refResult.status !== 0 || !refResult.stdout.trim().startsWith("refs/heads/")) {
|
|
24
|
+
fail(ERROR_CODES.GIT_ACKNOWLEDGEMENT_DETACHED_HEAD, "Commit acknowledgement requires an attached local branch");
|
|
25
|
+
}
|
|
26
|
+
return { root, head: headResult.stdout.trim(), ref: refResult.stdout.trim() };
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const checkpointPath = (personalRoot, sessionId) => path.join(personalRoot, "git-checkpoints", `${createHash("sha256").update(sessionId).digest("hex")}.json`);
|
|
30
|
+
const checkpointFor = (personalRoot, sessionId) => {
|
|
31
|
+
const file = checkpointPath(personalRoot, sessionId);
|
|
32
|
+
try {
|
|
33
|
+
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
34
|
+
if (!value || value.schema !== 1 || value.session_id !== sessionId || typeof value.head !== "string" || !/^[0-9a-f]{40,64}$/.test(value.head) || typeof value.ref !== "string" || !value.ref.startsWith("refs/heads/")) {
|
|
35
|
+
fail(ERROR_CODES.STORAGE_ERROR, "Invalid Git acknowledgement checkpoint");
|
|
36
|
+
}
|
|
37
|
+
return { file, value };
|
|
38
|
+
} catch (error) {
|
|
39
|
+
if (error.code === "ENOENT") return { file, value: null };
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const gitOperationInProgress = (root) => {
|
|
45
|
+
const gitDir = git(root, ["rev-parse", "--git-dir"]);
|
|
46
|
+
if (gitDir.status !== 0) return true;
|
|
47
|
+
const directory = path.resolve(root, gitDir.stdout.trim());
|
|
48
|
+
return ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "BISECT_LOG", "rebase-apply", "rebase-merge", "sequencer"]
|
|
49
|
+
.some((entry) => fs.existsSync(path.join(directory, entry)));
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const assertAcknowledgementHash = (value) => {
|
|
53
|
+
if (typeof value !== "string" || !/^[0-9a-f]{4,64}$/.test(value)) {
|
|
54
|
+
fail(ERROR_CODES.GIT_ACKNOWLEDGEMENT_INVALID_SHA, "Commit acknowledgement requires a short or full lowercase commit hash");
|
|
55
|
+
}
|
|
56
|
+
return value;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const resolveCommit = (root, value) => {
|
|
60
|
+
const result = git(root, ["rev-parse", "--verify", "--quiet", `${value}^{commit}`]);
|
|
61
|
+
if (result.status !== 0) fail(ERROR_CODES.GIT_ACKNOWLEDGEMENT_INVALID_SHA, "Commit hash does not resolve to one commit");
|
|
62
|
+
return result.stdout.trim();
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const isAncestor = (root, ancestor, descendant) => git(root, ["merge-base", "--is-ancestor", ancestor, descendant]).status === 0;
|
|
66
|
+
|
|
67
|
+
export function initializeGitCheckpoint(storage, { workspace, stage, sessionId }) {
|
|
68
|
+
let state;
|
|
69
|
+
try { state = repository(storage.projectRoot); } catch (error) {
|
|
70
|
+
if ([ERROR_CODES.NOT_GIT_REPOSITORY, ERROR_CODES.GIT_ACKNOWLEDGEMENT_CHECKPOINT_MISSING, ERROR_CODES.GIT_ACKNOWLEDGEMENT_DETACHED_HEAD].includes(error.code)) return null;
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
const checkpoint = checkpointFor(storage.personalRoot, sessionId);
|
|
74
|
+
if (checkpoint.value) return checkpoint.value;
|
|
75
|
+
const now = new Date().toISOString();
|
|
76
|
+
const value = { schema: 1, session_id: sessionId, workspace, stage, head: state.head, ref: state.ref, created_at: now, updated_at: now };
|
|
77
|
+
atomicWrite(checkpoint.file, `${JSON.stringify(value, null, 2)}\n`);
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function acknowledgeGitCommit(storage, { workspace, stage, sessionId, sha }) {
|
|
82
|
+
const input = assertAcknowledgementHash(sha);
|
|
83
|
+
const checkpoint = checkpointFor(storage.personalRoot, sessionId);
|
|
84
|
+
if (!checkpoint.value) fail(ERROR_CODES.GIT_ACKNOWLEDGEMENT_CHECKPOINT_MISSING, "No Git checkpoint exists for this active session");
|
|
85
|
+
if (checkpoint.value.workspace !== workspace || checkpoint.value.stage !== stage) fail(ERROR_CODES.STORAGE_ERROR, "Git acknowledgement checkpoint does not match the active stage");
|
|
86
|
+
const state = repository(storage.projectRoot);
|
|
87
|
+
if (gitOperationInProgress(state.root)) fail(ERROR_CODES.GIT_ACKNOWLEDGEMENT_GIT_OPERATION, "Commit acknowledgement is unavailable while a Git operation is in progress");
|
|
88
|
+
if (checkpoint.value.ref !== state.ref) fail(ERROR_CODES.GIT_ACKNOWLEDGEMENT_REF_CHANGED, "Attached Git branch changed since this session started");
|
|
89
|
+
const commit = resolveCommit(state.root, input);
|
|
90
|
+
if (commit !== state.head) fail(ERROR_CODES.GIT_ACKNOWLEDGEMENT_NOT_HEAD, "Acknowledged commit must be the current HEAD");
|
|
91
|
+
if (!isAncestor(state.root, checkpoint.value.head, state.head)) fail(ERROR_CODES.GIT_ACKNOWLEDGEMENT_NON_FAST_FORWARD, "Git history no longer advances from this session checkpoint");
|
|
92
|
+
const verified = repository(storage.projectRoot);
|
|
93
|
+
if (verified.head !== state.head || verified.ref !== state.ref || gitOperationInProgress(verified.root)) {
|
|
94
|
+
fail(ERROR_CODES.GIT_ACKNOWLEDGEMENT_REF_CHANGED, "Git state changed while acknowledging the commit");
|
|
95
|
+
}
|
|
96
|
+
const value = { ...checkpoint.value, head: state.head, updated_at: new Date().toISOString() };
|
|
97
|
+
atomicWrite(checkpoint.file, `${JSON.stringify(value, null, 2)}\n`);
|
|
98
|
+
return { acknowledged: true, commit: state.head };
|
|
99
|
+
}
|
package/src/index.js
CHANGED
|
@@ -12,6 +12,7 @@ export * from "./stages-snapshot.js";
|
|
|
12
12
|
export * from "./stages-renderer.js";
|
|
13
13
|
export * from "./work-context-snapshot.js";
|
|
14
14
|
export * from "./git-candidates.js";
|
|
15
|
+
export * from "./git-acknowledgement.js";
|
|
15
16
|
export * from "./candidates.js";
|
|
16
17
|
export * from "./delivery.js";
|
|
17
18
|
export * from "./delivery-contracts.js";
|
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: 1,
|
|
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"]),
|
|
16
|
+
operations: Object.freeze(["delivery.doctor", "commit.acknowledge"]),
|
|
17
17
|
});
|
|
18
18
|
|
|
19
19
|
export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR_BYTES = JSON.stringify(WORK_CONTEXT_PROTOCOL_DESCRIPTOR);
|
package/src/stages-renderer.js
CHANGED
|
@@ -17,15 +17,28 @@ const candidateSummary = (stage) => {
|
|
|
17
17
|
};
|
|
18
18
|
const deliverySummary = (delivery) => {
|
|
19
19
|
if (!delivery) return null;
|
|
20
|
-
if (delivery.unavailable) return "Delivery
|
|
21
|
-
if (delivery.plan_needed) return `Delivery
|
|
20
|
+
if (delivery.unavailable) return "Delivery ! unavailable";
|
|
21
|
+
if (delivery.plan_needed) return `Delivery ${delivery.committed} commits · ! plan`;
|
|
22
22
|
if (delivery.environments.length === 1) {
|
|
23
23
|
const [environment] = delivery.environments;
|
|
24
|
-
return `Delivery
|
|
24
|
+
return `Delivery ${environment.environment} · ${environment.pending} tracked pending`;
|
|
25
25
|
}
|
|
26
26
|
const pending = delivery.environments.reduce((total, environment) => total + environment.pending, 0);
|
|
27
|
-
return `Delivery
|
|
27
|
+
return `Delivery ${delivery.environments.length} environments · ${pending} tracked pending`;
|
|
28
28
|
};
|
|
29
|
+
const workspaceCandidateSummary = (candidates) => {
|
|
30
|
+
if (!candidates || !(candidates.pending || candidates.ready)) return null;
|
|
31
|
+
const states = [
|
|
32
|
+
candidates.pending ? `…${candidates.pending}` : null,
|
|
33
|
+
candidates.ready ? `✓${candidates.ready}` : null,
|
|
34
|
+
].filter(Boolean);
|
|
35
|
+
return `Candidates ${states.join(" ")}`;
|
|
36
|
+
};
|
|
37
|
+
export const workspaceStatusLines = (workspace, attention = "") => [
|
|
38
|
+
`${workspace.mode || "standard"}${attention ? ` · Attention ${attention}` : ""}`,
|
|
39
|
+
workspaceCandidateSummary(workspace.candidates),
|
|
40
|
+
deliverySummary(workspace.delivery),
|
|
41
|
+
].filter(Boolean);
|
|
29
42
|
const capitalize = (value) => value ? `${value[0].toUpperCase()}${value.slice(1)}` : value;
|
|
30
43
|
export const formatStageIds = (ids = []) => {
|
|
31
44
|
const ranges = [];
|
|
@@ -44,8 +57,8 @@ export const formatStageIds = (ids = []) => {
|
|
|
44
57
|
return ranges.join(", ");
|
|
45
58
|
};
|
|
46
59
|
const profileSummary = (stage) => {
|
|
47
|
-
return stage.execution_profile && stage.execution_depth
|
|
48
|
-
?
|
|
60
|
+
return stage.execution_profile && stage.execution_depth
|
|
61
|
+
? [capitalize(stage.execution_profile), capitalize(stage.execution_depth), stage.recommended_model && capitalize(stage.recommended_model)].filter(Boolean).join(" · ")
|
|
49
62
|
: null;
|
|
50
63
|
};
|
|
51
64
|
|
|
@@ -97,12 +110,8 @@ export function renderStagesPanel(result) {
|
|
|
97
110
|
|
|
98
111
|
const lines = [
|
|
99
112
|
snapshot.workspace.title,
|
|
100
|
-
|
|
113
|
+
...workspaceStatusLines(snapshot.workspace),
|
|
101
114
|
];
|
|
102
|
-
const candidates = snapshot.workspace.candidates;
|
|
103
|
-
if (candidates && (candidates.pending || candidates.ready)) lines.push(`Candidates · ${candidates.pending} draft · ${candidates.ready} ready`);
|
|
104
|
-
const delivery = deliverySummary(snapshot.workspace.delivery);
|
|
105
|
-
if (delivery) lines.push(delivery);
|
|
106
115
|
lines.push("", `Stages · ${snapshot.workspace.status}`);
|
|
107
116
|
for (const stage of snapshot.stages) {
|
|
108
117
|
const pending = candidateSummary(stage);
|
package/src/stages-snapshot.js
CHANGED
|
@@ -59,6 +59,10 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
|
|
|
59
59
|
current: stage.stage === session.stage,
|
|
60
60
|
}));
|
|
61
61
|
const currentStage = stages.some((stage) => stage.current) ? session.stage : null;
|
|
62
|
+
if (currentStage) {
|
|
63
|
+
const execution = context.readStageExecution(session.workspace, currentStage).data;
|
|
64
|
+
if (execution.revision > 0) Object.assign(stages.find((stage) => stage.id === currentStage), { execution });
|
|
65
|
+
}
|
|
62
66
|
|
|
63
67
|
return {
|
|
64
68
|
ok: true,
|
package/src/tool-definitions.js
CHANGED
|
@@ -118,6 +118,11 @@ export const work_context_create_workspace = tool({ description: "Create a works
|
|
|
118
118
|
return ctx.createWorkspace(a.title, { sessionId: randomUUID(), mode: a.mode, ...(currentSession ? {} : { opencodeSessionId: oc.sessionID }) });
|
|
119
119
|
}) });
|
|
120
120
|
export const work_context_start_session = tool({ description: "Start a new active session for a stage and return its human-oriented presentation, prompt, active workspace knowledge, and startup policy when applicable.", args: { ...common, summary: tool.schema.string().optional() }, execute: run((ctx, a, oc) => ctx.startSession(a.workspace, a.stage, { sessionId: randomUUID(), opencodeSessionId: oc.sessionID, summary: a.summary, takeover: true })) });
|
|
121
|
+
export const work_context_acknowledge_commit = tool({ description: "Acknowledge a user-created current-HEAD commit for the active session using a short or full commit hash. This is a deterministic light control-plane operation and does not infer ownership.", args: { sha: tool.schema.string() }, execute: run((ctx, a) => {
|
|
122
|
+
const session = sessionFromContext(ctx);
|
|
123
|
+
if (!session) fail(ERROR_CODES.STAGE_CONTEXT_REQUIRED, "An active work-context stage is required to acknowledge a commit");
|
|
124
|
+
return ctx.acknowledgeCommit(session.workspace, session.stage, session.session_id, a.sha);
|
|
125
|
+
}) });
|
|
121
126
|
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) });
|
|
122
127
|
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 } : {}) }); }) });
|
|
123
128
|
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 })) });
|
|
@@ -148,7 +153,7 @@ export const work_context_add_knowledge = tool({ description: "Add a durable kno
|
|
|
148
153
|
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)) });
|
|
149
154
|
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) ) });
|
|
150
155
|
|
|
151
|
-
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_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_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_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 };
|
|
156
|
+
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_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_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 };
|
|
152
157
|
|
|
153
158
|
export function createToolDefinitions(options = {}) {
|
|
154
159
|
return { ...defaultTools, work_context_doctor_delivery: createDoctorDeliveryTool(options) };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { work_context_acknowledge_commit as default } from "../src/tool-definitions.js";
|