opencode-work-context 0.8.0 → 0.9.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 +78 -4
- package/commands/wc.md +10 -2
- package/package.json +1 -1
- package/plugin/stages-tui.js +27 -5
- package/src/candidates.js +60 -5
- package/src/core.js +23 -4
- package/src/delivery.js +135 -0
- package/src/errors.js +1 -0
- package/src/git-candidates.js +44 -1
- package/src/index.js +1 -0
- package/src/stages-renderer.js +24 -2
- package/src/stages-snapshot.js +12 -5
- package/src/tool-definitions.js +3 -1
- package/src/work-context-snapshot.js +14 -6
- package/tools/work_context_mark_delivery.js +3 -0
- package/tools/work_context_read_delivery.js +3 -0
package/README.md
CHANGED
|
@@ -472,6 +472,8 @@ workspace, every resume also supplies the agent with the startup policy:
|
|
|
472
472
|
- a shared dirty worktree and concurrent stages are expected;
|
|
473
473
|
- stages do not own files or commits;
|
|
474
474
|
- ready work is captured promptly as an explicit commit candidate;
|
|
475
|
+
- once a coherent commit intent exists, its draft candidate is created or
|
|
476
|
+
refreshed before switching stages or handing off;
|
|
475
477
|
- exact, shared-foundation, and integration candidates express the intended
|
|
476
478
|
commit boundary without claiming stage ownership;
|
|
477
479
|
- mixed-stage provenance and complete files containing unrelated stage work are
|
|
@@ -515,10 +517,21 @@ records without strategy or stage-reference metadata remain readable; new
|
|
|
515
517
|
candidates default to `exact` with no related stages.
|
|
516
518
|
|
|
517
519
|
The sidebar reads only candidate metadata and shows a compact
|
|
518
|
-
`Candidates ·
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
520
|
+
`Candidates · <count> draft · <count> ready` line when either count is nonzero.
|
|
521
|
+
With sidebar details enabled (`Ctrl+X D`), a stage with explicitly related active
|
|
522
|
+
candidates also shows `Pending:` metadata. One related candidate includes its
|
|
523
|
+
lifecycle status, strategy, and other related stage IDs; several candidates are
|
|
524
|
+
shown as draft and ready counts. Resume exposes the same bounded metadata in
|
|
525
|
+
`resume.context.pending_candidates`, so an agent can continue an existing commit
|
|
526
|
+
intent instead of creating a duplicate. These projections do not assign
|
|
527
|
+
ownership. They never inspect Git state, patches, selected paths, or candidate
|
|
528
|
+
freshness. A `ready` label therefore means lifecycle status, not a guarantee that
|
|
529
|
+
a later publication cannot encounter a conflict, and uncaptured worktree changes
|
|
530
|
+
remain outside this projection. Per-stage projection counts remain complete, but
|
|
531
|
+
resume and snapshot item details are bounded to 10 candidates with titles limited
|
|
532
|
+
to 120 characters. Malformed local candidate records remain strict errors for
|
|
533
|
+
candidate operations but are omitted from best-effort sidebar and resume
|
|
534
|
+
projections so they cannot block unrelated stage work.
|
|
522
535
|
|
|
523
536
|
Capture accepts either complete repository paths or one exact Git unified patch,
|
|
524
537
|
which permits selecting individual hunks. Candidate metadata and patches are
|
|
@@ -542,6 +555,67 @@ separate those edits by provenance. Use an integration candidate only when the
|
|
|
542
555
|
combined patch is coherent and verified; otherwise stop and establish a safe
|
|
543
556
|
candidate boundary before publication.
|
|
544
557
|
|
|
558
|
+
### Delivery context
|
|
559
|
+
|
|
560
|
+
Committing or pushing does not prove that an environment was updated. Delivery is
|
|
561
|
+
a workspace-level concern that may aggregate committed candidates related to many
|
|
562
|
+
stages. Planning-stage resume receives a bounded `delivery_context` when committed
|
|
563
|
+
candidates or environment checkpoints exist. The sidebar renders metadata only:
|
|
564
|
+
|
|
565
|
+
```text
|
|
566
|
+
Delivery · 4 commits · plan needed
|
|
567
|
+
Delivery · production · 2 tracked pending
|
|
568
|
+
Delivery · production · 0 tracked pending
|
|
569
|
+
```
|
|
570
|
+
|
|
571
|
+
`tracked pending` compares committed candidate metadata with the recorded local
|
|
572
|
+
checkpoint; it is not a live Git reachability claim. A reset, rebase, force-push,
|
|
573
|
+
or external deployment change requires an explicit range inspection before acting.
|
|
574
|
+
Malformed or inconsistent checkpoint metadata renders `Delivery · unavailable`
|
|
575
|
+
instead of claiming a clean delivery state.
|
|
576
|
+
|
|
577
|
+
When asked how to deploy, the Planning agent must inspect the exact commit range
|
|
578
|
+
and the repository's own deployment documentation, scripts, infrastructure,
|
|
579
|
+
migrations, container definitions, configuration examples, and CI. It then
|
|
580
|
+
produces an ordered plan with prerequisites, deployment, verification, rollback,
|
|
581
|
+
and unresolved blockers. The package does not encode stack-specific commands and
|
|
582
|
+
does not assume that a push or one release command is sufficient.
|
|
583
|
+
|
|
584
|
+
Delivery state is local and mode-neutral under
|
|
585
|
+
`.work-context/local/delivery/<workspace>.json`. It stores only environment names,
|
|
586
|
+
confirmed commit hashes, timestamps, and committed candidate ID/hash pairs.
|
|
587
|
+
It never stores deployment commands, command output, hostnames, URLs, credentials,
|
|
588
|
+
tokens, or secret values. Secret and configuration requirements may be discussed
|
|
589
|
+
by name only. Each checkpoint carries an integrity checksum; malformed or edited
|
|
590
|
+
checkpoint data fails closed as unavailable.
|
|
591
|
+
|
|
592
|
+
Read metadata without inspecting Git:
|
|
593
|
+
|
|
594
|
+
```text
|
|
595
|
+
/wc delivery read 000123 production
|
|
596
|
+
```
|
|
597
|
+
|
|
598
|
+
Inspect one explicit immutable range:
|
|
599
|
+
|
|
600
|
+
```text
|
|
601
|
+
/wc delivery read 000123 production range <from-commit> <to-commit>
|
|
602
|
+
```
|
|
603
|
+
|
|
604
|
+
The range result is bounded to 500 commits and 500 changed paths and is returned
|
|
605
|
+
only to the explicit operation; changed-path output also has a 4 MiB subprocess
|
|
606
|
+
limit and fails with `DELIVERY_RANGE_TOO_LARGE` instead of consuming unbounded
|
|
607
|
+
memory. Snapshots and sidebar renderers never invoke Git.
|
|
608
|
+
After the user confirms that the target environment was updated successfully,
|
|
609
|
+
record the checkpoint explicitly:
|
|
610
|
+
|
|
611
|
+
```text
|
|
612
|
+
/wc delivery mark 000123 production <deployed-commit> DELIVERY_CONFIRMED
|
|
613
|
+
```
|
|
614
|
+
|
|
615
|
+
Marking validates that the commit is reachable from current `HEAD`, records which
|
|
616
|
+
committed candidates are included, and performs no deployment action. Checkpoints
|
|
617
|
+
are per environment, so staging and production can advance independently.
|
|
618
|
+
|
|
545
619
|
Candidate publication is serialized by the repository-scoped `candidate-git`
|
|
546
620
|
lock. Any operation that needs both locks acquires `candidate-git` before the
|
|
547
621
|
work-context `write` lock; integrations must preserve this ordering to avoid
|
package/commands/wc.md
CHANGED
|
@@ -37,6 +37,8 @@ Use these exact tool mappings; do not invent shortened tool names:
|
|
|
37
37
|
- `candidate ready <workspace> <candidateId>` -> `work_context_ready_candidate`
|
|
38
38
|
- `candidate commit <workspace> <candidateId> ["message"]` -> `work_context_commit_candidate`
|
|
39
39
|
- `candidate discard <workspace> <candidateId>` -> `work_context_discard_candidate`
|
|
40
|
+
- `delivery read <workspace> [<environment>] [range <from> <to>]` -> `work_context_read_delivery`
|
|
41
|
+
- `delivery mark <workspace> <environment> <commit> DELIVERY_CONFIRMED` -> `work_context_mark_delivery`
|
|
40
42
|
- `workspace finish <workspace>` -> `work_context_workspace_finish`
|
|
41
43
|
- `workspace reopen <workspace> "reason"` -> `work_context_reopen_workspace`
|
|
42
44
|
- `resume <workspace> <stage>` -> `work_context_start_session`
|
|
@@ -74,6 +76,8 @@ Supported syntax:
|
|
|
74
76
|
- `candidate ready <workspace> <candidateId>`
|
|
75
77
|
- `candidate commit <workspace> <candidateId> ["message"]`
|
|
76
78
|
- `candidate discard <workspace> <candidateId>`
|
|
79
|
+
- `delivery read <workspace> [<environment>] [range <from> <to>]`
|
|
80
|
+
- `delivery mark <workspace> <environment> <commit> DELIVERY_CONFIRMED`
|
|
77
81
|
- `workspace finish <workspace>`
|
|
78
82
|
- `workspace reopen <workspace> "reason"`
|
|
79
83
|
- `resume <workspace> <stage>`
|
|
@@ -111,7 +115,10 @@ Supported syntax:
|
|
|
111
115
|
- do not expose raw workspace/stage/session identifiers, ordinals, `ok` flags, or absent error codes in the user-facing resume summary
|
|
112
116
|
- `resume.context.workspace_knowledge` contains every active durable knowledge entry for the workspace; treat it as established shared context, and do not repeat earlier analysis unless an entry is incomplete, contradicted, or needs verification
|
|
113
117
|
- when stage execution state exists, `resume.context.execution_state` is the current stage-local operational checkpoint; continue from it without rewriting the original prompt, and never copy it automatically into workspace knowledge or unrelated stages
|
|
114
|
-
-
|
|
118
|
+
- 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
|
|
119
|
+
- 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
|
|
120
|
+
- 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
|
|
121
|
+
- an associated OpenCode session resumed in a `startup` workspace receives `resume.context.workflow_policy`; follow it as active agent policy: a shared dirty worktree and concurrent stages are expected, stages do not own files or commits, and ready work should be captured promptly into an explicit candidate; 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
|
|
115
122
|
- standard-mode and unassociated core sessions do not receive startup policy; retain the existing conservative worktree behavior there
|
|
116
123
|
- after presenting the summary, continue work immediately when `resume.next_action` is `start_work`; do not ask for generic confirmation
|
|
117
124
|
- 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
|
|
@@ -129,7 +136,8 @@ Supported syntax:
|
|
|
129
136
|
- `stage reopen <workspace> <stage> "reason"` applies only to a completed stage, preserves its result and completion history, records the reason, changes it to `in_progress`, and does not start a session or affect downstream stages; use an explicit separate-session `resume` to work on it again
|
|
130
137
|
- `stage restore <workspace> <stage> "reason"` applies only to an archived stage and restores its saved pre-archive status. New archives preserve that status; legacy archives restore to `in_progress`. It records the reason, preserves stage content and results, does not start a session, and requires explicit separate-session `resume` when restored to `planned` or `in_progress`.
|
|
131
138
|
- `workspace reopen <workspace> "reason"` applies only to a completed workspace, changes it to `in_progress`, and records durable recovery history. Cancelled workspaces cannot be reopened.
|
|
132
|
-
- candidate operations require `startup` workflow mode and store metadata and patch payloads only under `.work-context/local/`; create accepts an optional strategy and related stages, which are normalized references for traceability only and never ownership or lifecycle; capture requires exactly one explicit list of complete paths or one Git unified patch and never infers stage ownership; commit requires a ready candidate, uses its stored message unless a non-empty override is supplied, serializes Git publication, bypasses hooks and signing, and never uses the ordinary Git index
|
|
139
|
+
- candidate operations require `startup` workflow mode and store metadata and patch payloads only under `.work-context/local/`; create accepts an optional strategy and related stages, which are normalized references for traceability only and never ownership or lifecycle; active candidates explicitly related to the resumed stage appear as bounded metadata in `resume.context.pending_candidates` and in expanded sidebar details; capture requires exactly one explicit list of complete paths or one Git unified patch and never infers stage ownership; commit requires a ready candidate, uses its stored message unless a non-empty override is supplied, serializes Git publication, bypasses hooks and signing, and never uses the ordinary Git index
|
|
140
|
+
- delivery operations are mode-neutral local operational state and never execute deployment; `delivery read` without a range returns metadata only, exact Git inspection requires both immutable `from` and `to` hashes, and `delivery mark` requires the exact `DELIVERY_CONFIRMED` token only after the user confirms successful delivery to that environment
|
|
133
141
|
- `knowledge list|add|update|supersede <workspace> ...`
|
|
134
142
|
|
|
135
143
|
Arguments: $ARGUMENTS
|
package/package.json
CHANGED
package/plugin/stages-tui.js
CHANGED
|
@@ -35,8 +35,28 @@ const trackerLinkText = (link) => {
|
|
|
35
35
|
return `JIRA ${identifier}`;
|
|
36
36
|
};
|
|
37
37
|
const candidateSummaryText = (workspace) => workspace.candidates && (workspace.candidates.pending || workspace.candidates.ready)
|
|
38
|
-
? `Candidates ·
|
|
38
|
+
? `Candidates · ${workspace.candidates.pending} draft · ${workspace.candidates.ready} ready`
|
|
39
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 stageCandidateText = (stage) => {
|
|
53
|
+
const projection = stage.candidates;
|
|
54
|
+
if (!projection || !(projection.draft || projection.ready)) return null;
|
|
55
|
+
if (projection.draft + projection.ready > 1) return `Pending: ${projection.draft} draft · ${projection.ready} ready`;
|
|
56
|
+
const [candidate] = projection.items;
|
|
57
|
+
const others = candidate.related_stages.filter((related) => related !== stage.id);
|
|
58
|
+
return `Pending: ${candidate.status} · ${candidate.strategy}${others.length ? ` · also ${others.join(", ")}` : ""}`;
|
|
59
|
+
};
|
|
40
60
|
|
|
41
61
|
export { readStagesSnapshot, renderStagesPanel };
|
|
42
62
|
|
|
@@ -56,6 +76,7 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
|
|
|
56
76
|
runtime.jsx("text", { fg: theme?.current?.textMuted, children: `Workflow · ${result.data.workspace.mode || "standard"}` }),
|
|
57
77
|
workspaceAttention && runtime.jsx("text", { children: ["Attention · ", runtime.jsx("b", { children: workspaceAttention })] }),
|
|
58
78
|
candidateSummaryText(result.data.workspace) && runtime.jsx("text", { fg: theme?.current?.textMuted, children: candidateSummaryText(result.data.workspace) }),
|
|
79
|
+
deliverySummaryText(result.data.workspace) && runtime.jsx("text", { fg: theme?.current?.textMuted, children: deliverySummaryText(result.data.workspace) }),
|
|
59
80
|
].filter(Boolean),
|
|
60
81
|
}),
|
|
61
82
|
runtime.jsx("box", {
|
|
@@ -68,10 +89,11 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
|
|
|
68
89
|
...result.data.stages.map((stage) => {
|
|
69
90
|
const unread = attention?.attentionForStage?.(result.data.workspace.id, stage.id);
|
|
70
91
|
const working = attention?.activityForStage?.(result.data.workspace.id, stage.id);
|
|
71
|
-
const
|
|
92
|
+
const stageMetadata = [
|
|
72
93
|
stage.tracker_links?.length && `Tasks: ${stage.tracker_links.map(trackerLinkText).join(", ")}`,
|
|
73
94
|
stage.depends_on?.length && `Deps: ${stage.depends_on.join(", ")}`,
|
|
74
|
-
].filter(Boolean).join(" · ")
|
|
95
|
+
].filter(Boolean).join(" · ");
|
|
96
|
+
const metadata = showDependencies ? [stageMetadata, stageCandidateText(stage)].filter(Boolean).join("\n") : "";
|
|
75
97
|
const attentionSignal = attentionSummaryText(unread);
|
|
76
98
|
const stageText = [
|
|
77
99
|
`${stage.id}. ${stage.title}`,
|
|
@@ -286,8 +308,8 @@ const registerDependencyToggle = (api, controller, projectRoot) => {
|
|
|
286
308
|
if (typeof api?.keymap?.registerLayer !== "function") return () => {};
|
|
287
309
|
const command = {
|
|
288
310
|
name: DEPENDENCIES_COMMAND,
|
|
289
|
-
title: "Toggle sidebar
|
|
290
|
-
desc: "Show or hide
|
|
311
|
+
title: "Toggle sidebar details",
|
|
312
|
+
desc: "Show or hide stage tasks, dependencies, and pending candidates",
|
|
291
313
|
category: "Work Context",
|
|
292
314
|
namespace: "palette",
|
|
293
315
|
run: () => {
|
package/src/candidates.js
CHANGED
|
@@ -8,6 +8,9 @@ import { capturePatch, capturePaths, commitPatch, previewPatch, repositoryState
|
|
|
8
8
|
const candidatePattern = /^CC-(\d{6})$/;
|
|
9
9
|
const statuses = new Set(["draft", "ready", "discarded", "committed"]);
|
|
10
10
|
const strategies = new Set(["exact", "shared_foundation", "integration"]);
|
|
11
|
+
const projectionCandidateLimit = 10;
|
|
12
|
+
const projectionTitleLimit = 120;
|
|
13
|
+
const deliveryCandidateLimit = 20;
|
|
11
14
|
const timestamp = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
12
15
|
const metadataKeys = ["schema", "candidate", "workspace", "title", "message", "base_head", "status", "created_at", "updated_at", "selected_paths", "patch_file"];
|
|
13
16
|
const optionalMetadataKeys = ["strategy", "related_stages"];
|
|
@@ -106,11 +109,63 @@ export class CandidateStore {
|
|
|
106
109
|
}
|
|
107
110
|
|
|
108
111
|
summary(workspace) {
|
|
109
|
-
return this.
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
112
|
+
return this.activeProjection(workspace).summary;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
projectionRecords(workspace) {
|
|
116
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
117
|
+
this.context.storage.readWorkspace(workspace);
|
|
118
|
+
if (!fs.existsSync(this.directory)) return [];
|
|
119
|
+
return fs.readdirSync(this.directory)
|
|
120
|
+
.filter((file) => candidatePattern.test(file.slice(0, -5)) && file.endsWith(".json"))
|
|
121
|
+
.sort()
|
|
122
|
+
.flatMap((file) => {
|
|
123
|
+
try {
|
|
124
|
+
const data = JSON.parse(fs.readFileSync(path.join(this.directory, file), "utf8"));
|
|
125
|
+
if (data?.workspace !== workspace) return [];
|
|
126
|
+
return [validateCandidate(data, file.slice(0, -5))];
|
|
127
|
+
} catch { return []; }
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
activeProjection(workspace) {
|
|
132
|
+
const projection = { summary: { pending: 0, ready: 0 }, by_stage: {} };
|
|
133
|
+
workspace = this.assertStartup(workspace);
|
|
134
|
+
for (const candidate of this.projectionRecords(workspace)) {
|
|
135
|
+
if (!["draft", "ready"].includes(candidate.status)) continue;
|
|
136
|
+
if (candidate.status === "draft") projection.summary.pending += 1;
|
|
137
|
+
if (candidate.status === "ready") projection.summary.ready += 1;
|
|
138
|
+
const related = {
|
|
139
|
+
candidate: candidate.candidate,
|
|
140
|
+
title: candidate.title.slice(0, projectionTitleLimit),
|
|
141
|
+
status: candidate.status,
|
|
142
|
+
strategy: candidate.strategy || "exact",
|
|
143
|
+
related_stages: candidate.related_stages || [],
|
|
144
|
+
};
|
|
145
|
+
for (const stage of related.related_stages) {
|
|
146
|
+
const stageProjection = projection.by_stage[stage] ||= { draft: 0, ready: 0, items: [] };
|
|
147
|
+
stageProjection[candidate.status] += 1;
|
|
148
|
+
if (stageProjection.items.length < projectionCandidateLimit) stageProjection.items.push(related);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return projection;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
committedProjection(workspace) {
|
|
155
|
+
const records = this.projectionRecords(workspace)
|
|
156
|
+
.filter((candidate) => candidate.status === "committed")
|
|
157
|
+
.sort((left, right) => left.committed_at.localeCompare(right.committed_at) || left.candidate.localeCompare(right.candidate));
|
|
158
|
+
return {
|
|
159
|
+
count: records.length,
|
|
160
|
+
items: records.slice(-deliveryCandidateLimit).map((candidate) => ({
|
|
161
|
+
candidate: candidate.candidate,
|
|
162
|
+
title: candidate.title.slice(0, projectionTitleLimit),
|
|
163
|
+
strategy: candidate.strategy || "exact",
|
|
164
|
+
related_stages: candidate.related_stages || [],
|
|
165
|
+
commit_hash: candidate.commit_hash,
|
|
166
|
+
committed_at: candidate.committed_at,
|
|
167
|
+
})),
|
|
168
|
+
};
|
|
114
169
|
}
|
|
115
170
|
|
|
116
171
|
capture(workspace, id, input) {
|
package/src/core.js
CHANGED
|
@@ -9,6 +9,7 @@ import { nextKnowledgeId, parseKnowledge, renderKnowledge, validateKnowledgeInpu
|
|
|
9
9
|
import { normalizeStageId, normalizeWorkspaceId } from "./identifiers.js";
|
|
10
10
|
import { isDependencySatisfied } from "./stage-status.js";
|
|
11
11
|
import { CandidateStore } from "./candidates.js";
|
|
12
|
+
import { DeliveryStore } from "./delivery.js";
|
|
12
13
|
import { applyExecutionPatch, assertExecutionSize, executionState, normalizeExecutionState } from "./stage-execution.js";
|
|
13
14
|
|
|
14
15
|
const actor = (options) => options.actor || "OpenCode";
|
|
@@ -35,6 +36,8 @@ const startupWorkflowPolicy = () => ({
|
|
|
35
36
|
guidance: [
|
|
36
37
|
"A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
|
|
37
38
|
"Capture ready work promptly as an explicit commit candidate while unrelated work remains in progress.",
|
|
39
|
+
"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.",
|
|
40
|
+
"On resume, inspect related pending candidates before creating a duplicate or starting another commit boundary.",
|
|
38
41
|
"Choose an exact candidate when separable, a shared foundation candidate when several stages use one change, or an integration candidate when intertwined changes form one coherent reviewable result.",
|
|
39
42
|
"Mixed-stage provenance or complete files containing unrelated stage work are not reasons to stop, require prior commits, or reconstruct ownership after the fact.",
|
|
40
43
|
"Stop only for a concrete patch conflict, an incoherent candidate boundary, or failed required verification, and report it explicitly.",
|
|
@@ -50,6 +53,7 @@ const resumePresentationInstruction = ({ confirmationRequired }) => `Before doin
|
|
|
50
53
|
- State the immediate next action in one sentence.
|
|
51
54
|
${confirmationRequired ? "- Ask for the explicitly required confirmation and wait before inspecting or changing application code." : "- Then continue with the work immediately. Do not ask for generic confirmation; ask a focused question only when an unresolved decision genuinely blocks progress."}`;
|
|
52
55
|
const executionInstruction = (record) => record ? `\n\nCurrent stage execution state:\n${JSON.stringify(record, null, 2)}\nTreat this bounded stage-local ledger as the current operational checkpoint. Update it after meaningful scope changes, decisions, substantial work, blockers, or verification changes, and before handoff; do not update it for trivial tool calls.` : "";
|
|
56
|
+
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.`;
|
|
53
57
|
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; } } };
|
|
54
58
|
|
|
55
59
|
function parseIssue(url) {
|
|
@@ -248,7 +252,7 @@ export class WorkContext {
|
|
|
248
252
|
lifecycle: { automatic_finish_allowed: false },
|
|
249
253
|
},
|
|
250
254
|
next_action: "start_work",
|
|
251
|
-
instruction: `${planningPrompt}${startupWorkflowInstruction(workflowPolicy)}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
|
|
255
|
+
instruction: `${planningPrompt}${startupWorkflowInstruction(workflowPolicy)}${deliveryPlanningInstruction}\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.`,
|
|
252
256
|
},
|
|
253
257
|
}, [workspace, "01"]);
|
|
254
258
|
});
|
|
@@ -284,6 +288,7 @@ export class WorkContext {
|
|
|
284
288
|
}
|
|
285
289
|
|
|
286
290
|
candidates() { return new CandidateStore(this); }
|
|
291
|
+
deliveries() { return new DeliveryStore(this); }
|
|
287
292
|
|
|
288
293
|
createCandidate(workspace, title, message = null, options = {}) {
|
|
289
294
|
return this.transact("candidate-create", () => this.result(this.candidates().create(workspace, title, message, options), ["local:candidates"]));
|
|
@@ -319,6 +324,15 @@ export class WorkContext {
|
|
|
319
324
|
), { session: this.options.sessionId, owner: actor(this.options) });
|
|
320
325
|
}
|
|
321
326
|
|
|
327
|
+
readDelivery(workspace, options = {}) { return { ok: true, data: this.deliveries().readContext(workspace, options) }; }
|
|
328
|
+
|
|
329
|
+
markDelivery(workspace, environment, commit, confirmation) {
|
|
330
|
+
this.storage.assertSafeRoots();
|
|
331
|
+
return withLock(this.storage.lockPath("candidate-git"), () => this.transact("delivery-mark", () =>
|
|
332
|
+
this.result(this.deliveries().mark(workspace, environment, commit, confirmation), ["local:delivery"])
|
|
333
|
+
), { session: this.options.sessionId, owner: actor(this.options) });
|
|
334
|
+
}
|
|
335
|
+
|
|
322
336
|
nextWorkspace() {
|
|
323
337
|
const ids = this.listWorkspaces().data.map((workspace) => Number(workspace.workspace));
|
|
324
338
|
return String(Math.max(0, ...ids) + 1).padStart(6, "0");
|
|
@@ -362,6 +376,9 @@ export class WorkContext {
|
|
|
362
376
|
const workspaceRecord = this.storage.readWorkspace(workspace).data;
|
|
363
377
|
const workspaceTitle = workspaceRecord.title;
|
|
364
378
|
const workflowPolicy = workspaceMode(workspaceRecord) === "startup" && options.opencodeSessionId ? startupWorkflowPolicy() : null;
|
|
379
|
+
const pendingCandidates = workflowPolicy ? this.candidates().activeProjection(workspace).by_stage[stage] || null : null;
|
|
380
|
+
const deliveryContext = stage === "01" ? this.deliveries().projection(workspace) : null;
|
|
381
|
+
const hasDeliveryContext = deliveryContext && (deliveryContext.committed.count || deliveryContext.environments.length || deliveryContext.unavailable);
|
|
365
382
|
const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
|
|
366
383
|
const execution = this.storage.readStageExecution(workspace, stage);
|
|
367
384
|
const automaticFinish = automaticFinishAllowed(this.storage, workspace);
|
|
@@ -394,12 +411,14 @@ export class WorkContext {
|
|
|
394
411
|
now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
|
|
395
412
|
workspace_knowledge: workspaceKnowledge,
|
|
396
413
|
...(execution ? { execution_state: execution } : {}),
|
|
414
|
+
...(pendingCandidates ? { pending_candidates: pendingCandidates } : {}),
|
|
415
|
+
...(hasDeliveryContext ? { delivery_context: deliveryContext } : {}),
|
|
397
416
|
...(workflowPolicy ? { workflow_policy: workflowPolicy } : {}),
|
|
398
417
|
lifecycle: { automatic_finish_allowed: automaticFinish },
|
|
399
418
|
},
|
|
400
419
|
next_action: hasPrompt ? confirmationRequired ? "await_confirmation" : "start_work" : "ask_questions",
|
|
401
420
|
instruction: `${hasPrompt
|
|
402
|
-
? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${executionInstruction(execution)}${startupWorkflowInstruction(workflowPolicy)}`
|
|
421
|
+
? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${executionInstruction(execution)}${startupWorkflowInstruction(workflowPolicy)}${stage === "01" ? deliveryPlanningInstruction : ""}`
|
|
403
422
|
: `This stage has no non-empty prompt. Give the user a concise plain-language summary of the stage title and goal, then ask focused questions needed to define the intended outcome and scope. Do not inspect or modify application code yet. Do not report raw operation metadata or identifiers.`}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
|
|
404
423
|
},
|
|
405
424
|
}, [workspace, stage]);
|
|
@@ -805,8 +824,8 @@ export class WorkContext {
|
|
|
805
824
|
help(command = "") {
|
|
806
825
|
return this.result({
|
|
807
826
|
command,
|
|
808
|
-
syntax: "/wc [create|list|workspace list|workspace rename|workspace mode|candidate create|candidate capture|candidate preview|candidate show|candidate list|candidate ready|candidate commit|candidate discard|workspace finish|workspace reopen|resume|stage add|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage execution read|stage execution replace|stage execution update|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|unlink-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
|
|
809
|
-
note: "stage execution state is a bounded stage-local operational checkpoint; replace and update require the current revision and active stage session, while read is available without mutation; checklist state never completes a stage, and explicit stage finish reports remaining execution work while preserving the final ledger; associated OpenCode sessions in startup-mode workspaces receive the shared-worktree and commit-candidate policy on resume; standard mode remains conservative; candidate strategies are exact, shared_foundation, and integration, with optional related stage references for traceability only; commit candidates are local-only and require startup workflow mode; capture and commit use isolated Git indexes and never alter the ordinary index; candidate commit uses the stored message unless an explicit non-empty override is provided, and bypasses Git hooks and signing; stage finish requires an explicit user lifecycle request unless the Planning-stage prompt contains the exact line AUTO_STAGE_FINISH: allowed; stage reopen requires a completed stage and a reason; stage restore requires an archived stage and a reason, returns its saved pre-archive status (or in_progress for legacy archives), and requires explicit separate-session resume when actionable; workspace reopen requires a completed workspace and a reason.",
|
|
827
|
+
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|delivery read|delivery mark|workspace finish|workspace reopen|resume|stage add|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage execution read|stage execution replace|stage execution update|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|unlink-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
|
|
828
|
+
note: "delivery context is workspace-level local operational state; exact Git range inspection requires explicit immutable from and to hashes, while marking an environment requires DELIVERY_CONFIRMED after successful delivery and never executes deployment commands or stores secrets; stage execution state is a bounded stage-local operational checkpoint; replace and update require the current revision and active stage session, while read is available without mutation; checklist state never completes a stage, and explicit stage finish reports remaining execution work while preserving the final ledger; associated OpenCode sessions in startup-mode workspaces receive the shared-worktree and commit-candidate policy on resume; standard mode remains conservative; candidate strategies are exact, shared_foundation, and integration, with optional related stage references for traceability only; active candidates related to the resumed stage appear in resume.context.pending_candidates; commit candidates are local-only and require startup workflow mode; capture and commit use isolated Git indexes and never alter the ordinary index; candidate commit uses the stored message unless an explicit non-empty override is provided, and bypasses Git hooks and signing; stage finish requires an explicit user lifecycle request unless the Planning-stage prompt contains the exact line AUTO_STAGE_FINISH: allowed; stage reopen requires a completed stage and a reason; stage restore requires an archived stage and a reason, returns its saved pre-archive status (or in_progress for legacy archives), and requires explicit separate-session resume when actionable; workspace reopen requires a completed workspace and a reason.",
|
|
810
829
|
}, []);
|
|
811
830
|
}
|
|
812
831
|
|
package/src/delivery.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { atomicWrite } from "./storage.js";
|
|
5
|
+
import { ERROR_CODES, fail } from "./errors.js";
|
|
6
|
+
import { normalizeWorkspaceId } from "./identifiers.js";
|
|
7
|
+
import { inspectCommitRange, isCommitAncestor, repositoryState } from "./git-candidates.js";
|
|
8
|
+
|
|
9
|
+
const environmentPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
10
|
+
const hashPattern = /^[0-9a-f]{40,64}$/;
|
|
11
|
+
const candidatePattern = /^CC-\d{6}$/;
|
|
12
|
+
const timestamp = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
13
|
+
const maxEnvironments = 20;
|
|
14
|
+
const maxCandidates = 10000;
|
|
15
|
+
const checkpointIntegrity = (checkpoint) => createHash("sha256").update(JSON.stringify({
|
|
16
|
+
deployed_head: checkpoint.deployed_head,
|
|
17
|
+
deployed_at: checkpoint.deployed_at,
|
|
18
|
+
deployed_candidates: checkpoint.deployed_candidates,
|
|
19
|
+
})).digest("hex");
|
|
20
|
+
|
|
21
|
+
const normalizeEnvironment = (value) => {
|
|
22
|
+
if (typeof value !== "string" || !environmentPattern.test(value)) fail(ERROR_CODES.INVALID_ARGUMENT, "Environment must use 1-64 letters, digits, dots, underscores or hyphens");
|
|
23
|
+
return value;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export function validateDeliveryRecord(data, workspace) {
|
|
27
|
+
const valid = data && typeof data === "object" && !Array.isArray(data)
|
|
28
|
+
&& Object.keys(data).every((key) => ["schema", "workspace", "updated_at", "environments"].includes(key))
|
|
29
|
+
&& data.schema === 1 && data.workspace === workspace && /^\d{6}$/.test(data.workspace)
|
|
30
|
+
&& timestamp(data.updated_at) && data.environments && typeof data.environments === "object" && !Array.isArray(data.environments)
|
|
31
|
+
&& Object.keys(data.environments).length <= maxEnvironments
|
|
32
|
+
&& Object.entries(data.environments).every(([name, item]) => environmentPattern.test(name)
|
|
33
|
+
&& item && typeof item === "object" && !Array.isArray(item)
|
|
34
|
+
&& Object.keys(item).every((key) => ["deployed_head", "deployed_at", "deployed_candidates", "integrity"].includes(key))
|
|
35
|
+
&& hashPattern.test(item.deployed_head) && timestamp(item.deployed_at)
|
|
36
|
+
&& Array.isArray(item.deployed_candidates) && item.deployed_candidates.length <= maxCandidates
|
|
37
|
+
&& item.deployed_candidates.every((candidate) => candidate && typeof candidate === "object" && !Array.isArray(candidate)
|
|
38
|
+
&& Object.keys(candidate).length === 2 && candidatePattern.test(candidate.candidate) && hashPattern.test(candidate.commit_hash))
|
|
39
|
+
&& new Set(item.deployed_candidates.map((candidate) => candidate.candidate)).size === item.deployed_candidates.length
|
|
40
|
+
&& item.deployed_candidates.every((candidate, index) => index === 0 || item.deployed_candidates[index - 1].candidate < candidate.candidate)
|
|
41
|
+
&& typeof item.integrity === "string" && /^[0-9a-f]{64}$/.test(item.integrity)
|
|
42
|
+
&& item.integrity === checkpointIntegrity(item));
|
|
43
|
+
if (!valid) fail(ERROR_CODES.STORAGE_ERROR, "Invalid delivery checkpoint metadata");
|
|
44
|
+
return data;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class DeliveryStore {
|
|
48
|
+
constructor(context) {
|
|
49
|
+
this.context = context;
|
|
50
|
+
this.directory = path.join(context.storage.personalRoot, "delivery");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
file(workspace) { return path.join(this.directory, `${workspace}.json`); }
|
|
54
|
+
|
|
55
|
+
assertWorkspace(workspace) {
|
|
56
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
57
|
+
this.context.storage.readWorkspace(workspace);
|
|
58
|
+
return workspace;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
read(workspace) {
|
|
62
|
+
workspace = this.assertWorkspace(workspace);
|
|
63
|
+
try { return validateDeliveryRecord(JSON.parse(fs.readFileSync(this.file(workspace), "utf8")), workspace); }
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (error.code === "ENOENT") return null;
|
|
66
|
+
if (error.code === ERROR_CODES.STORAGE_ERROR) throw error;
|
|
67
|
+
fail(ERROR_CODES.STORAGE_ERROR, "Invalid delivery checkpoint metadata", { cause: error.message });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
projection(workspace) {
|
|
72
|
+
workspace = this.assertWorkspace(workspace);
|
|
73
|
+
let record;
|
|
74
|
+
try { record = this.read(workspace); } catch {
|
|
75
|
+
return { committed: this.context.candidates().committedProjection(workspace), plan_needed: false, environments: [], unavailable: true };
|
|
76
|
+
}
|
|
77
|
+
const candidateStore = this.context.candidates();
|
|
78
|
+
const committedRecords = candidateStore.projectionRecords(workspace).filter((candidate) => candidate.status === "committed");
|
|
79
|
+
const committed = candidateStore.committedProjection(workspace);
|
|
80
|
+
const committedById = new Map(committedRecords.map((candidate) => [candidate.candidate, candidate]));
|
|
81
|
+
const invalidCheckpoint = Object.values(record?.environments || {}).some((checkpoint) => checkpoint.deployed_candidates.some((candidate) => {
|
|
82
|
+
const metadata = committedById.get(candidate.candidate);
|
|
83
|
+
return !metadata || metadata.commit_hash !== candidate.commit_hash;
|
|
84
|
+
}));
|
|
85
|
+
if (invalidCheckpoint) return { committed, plan_needed: false, environments: [], unavailable: true };
|
|
86
|
+
const environments = Object.entries(record?.environments || {}).sort(([left], [right]) => left.localeCompare(right)).map(([environment, checkpoint]) => {
|
|
87
|
+
const delivered = new Set(checkpoint.deployed_candidates.map((candidate) => candidate.candidate));
|
|
88
|
+
return {
|
|
89
|
+
environment,
|
|
90
|
+
deployed_at: checkpoint.deployed_at,
|
|
91
|
+
pending: committedRecords.filter((candidate) => !delivered.has(candidate.candidate)).length,
|
|
92
|
+
};
|
|
93
|
+
});
|
|
94
|
+
return {
|
|
95
|
+
committed,
|
|
96
|
+
plan_needed: committed.count > 0 && environments.length === 0,
|
|
97
|
+
environments,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
readContext(workspace, options = {}) {
|
|
102
|
+
workspace = this.assertWorkspace(workspace);
|
|
103
|
+
const projection = this.projection(workspace);
|
|
104
|
+
const record = this.read(workspace);
|
|
105
|
+
const environment = options.environment === undefined ? null : normalizeEnvironment(options.environment);
|
|
106
|
+
const checkpoint = environment ? record?.environments?.[environment] || null : null;
|
|
107
|
+
const hasFrom = options.from !== undefined;
|
|
108
|
+
const hasTo = options.to !== undefined;
|
|
109
|
+
if (hasFrom !== hasTo) fail(ERROR_CODES.INVALID_ARGUMENT, "Delivery range requires both from and to commit hashes");
|
|
110
|
+
const range = hasFrom ? inspectCommitRange(this.context.storage.projectRoot, options.from, options.to) : null;
|
|
111
|
+
return { workspace, environment, checkpoint, ...projection, ...(range ? { range } : {}) };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
mark(workspace, environment, commit, confirmation) {
|
|
115
|
+
workspace = this.assertWorkspace(workspace);
|
|
116
|
+
environment = normalizeEnvironment(environment);
|
|
117
|
+
if (confirmation !== "DELIVERY_CONFIRMED") fail(ERROR_CODES.CONFIRMATION_REQUIRED, "Marking delivery requires DELIVERY_CONFIRMED confirmation");
|
|
118
|
+
if (typeof commit !== "string" || !hashPattern.test(commit)) fail(ERROR_CODES.INVALID_ARGUMENT, "Delivery commit must be a full commit hash");
|
|
119
|
+
const repository = repositoryState(this.context.storage.projectRoot);
|
|
120
|
+
if (!isCommitAncestor(repository.root, commit, repository.head)) fail(ERROR_CODES.DELIVERY_INVALID_RANGE, "Delivery commit must be available and reachable from current HEAD", { commit, currentHead: repository.head });
|
|
121
|
+
const committed = this.context.candidates().projectionRecords(workspace).filter((candidate) => candidate.status === "committed");
|
|
122
|
+
const deployedCandidates = committed.filter((candidate) => isCommitAncestor(repository.root, candidate.commit_hash, commit))
|
|
123
|
+
.map((candidate) => ({ candidate: candidate.candidate, commit_hash: candidate.commit_hash }))
|
|
124
|
+
.sort((left, right) => left.candidate.localeCompare(right.candidate));
|
|
125
|
+
const now = new Date().toISOString();
|
|
126
|
+
const record = this.read(workspace) || { schema: 1, workspace, updated_at: now, environments: {} };
|
|
127
|
+
record.updated_at = now;
|
|
128
|
+
const checkpoint = { deployed_head: commit, deployed_at: now, deployed_candidates: deployedCandidates };
|
|
129
|
+
checkpoint.integrity = checkpointIntegrity(checkpoint);
|
|
130
|
+
record.environments[environment] = checkpoint;
|
|
131
|
+
validateDeliveryRecord(record, workspace);
|
|
132
|
+
atomicWrite(this.file(workspace), `${JSON.stringify(record, null, 2)}\n`);
|
|
133
|
+
return { workspace, environment, checkpoint: record.environments[environment] };
|
|
134
|
+
}
|
|
135
|
+
}
|
package/src/errors.js
CHANGED
|
@@ -10,6 +10,7 @@ export const ERROR_CODES = Object.freeze({
|
|
|
10
10
|
CANDIDATE_CONFLICT: "CANDIDATE_CONFLICT", CANDIDATE_DETACHED_HEAD: "CANDIDATE_DETACHED_HEAD",
|
|
11
11
|
CANDIDATE_REF_RACE: "CANDIDATE_REF_RACE", CANDIDATE_COMMIT_FAILED: "CANDIDATE_COMMIT_FAILED",
|
|
12
12
|
EXECUTION_REVISION_CONFLICT: "EXECUTION_REVISION_CONFLICT", EXECUTION_LIMIT_EXCEEDED: "EXECUTION_LIMIT_EXCEEDED",
|
|
13
|
+
DELIVERY_INVALID_RANGE: "DELIVERY_INVALID_RANGE", DELIVERY_RANGE_TOO_LARGE: "DELIVERY_RANGE_TOO_LARGE",
|
|
13
14
|
});
|
|
14
15
|
|
|
15
16
|
export class WorkContextError extends Error {
|
package/src/git-candidates.js
CHANGED
|
@@ -10,9 +10,10 @@ const git = (root, args, options = {}) => {
|
|
|
10
10
|
encoding: options.encoding === null ? null : "utf8",
|
|
11
11
|
env: { ...process.env, ...options.env },
|
|
12
12
|
input: options.input,
|
|
13
|
-
maxBuffer: 64 * 1024 * 1024,
|
|
13
|
+
maxBuffer: options.maxBuffer ?? 64 * 1024 * 1024,
|
|
14
14
|
});
|
|
15
15
|
if (result.error?.code === "ENOENT") fail(ERROR_CODES.GIT_UNAVAILABLE, "Git executable is unavailable");
|
|
16
|
+
if (result.error?.code === "ENOBUFS") fail(options.code || ERROR_CODES.GIT_UNAVAILABLE, options.message || "Git output exceeded the supported limit", { maxBuffer: options.maxBuffer });
|
|
16
17
|
if (result.error) fail(ERROR_CODES.GIT_UNAVAILABLE, "Cannot execute Git", { cause: result.error.message });
|
|
17
18
|
if (result.status !== 0 && !options.allowFailure) {
|
|
18
19
|
fail(options.code || ERROR_CODES.CANDIDATE_INVALID_PATCH, options.message || "Git operation failed", {
|
|
@@ -36,6 +37,48 @@ export function repositoryState(projectRoot) {
|
|
|
36
37
|
return { root, head: head.stdout.trim() };
|
|
37
38
|
}
|
|
38
39
|
|
|
40
|
+
const assertCommitHash = (value, label) => {
|
|
41
|
+
if (typeof value !== "string" || !/^[0-9a-f]{40,64}$/.test(value)) fail(ERROR_CODES.INVALID_ARGUMENT, `${label} must be a full commit hash`);
|
|
42
|
+
return value;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const commitExists = (root, commit) => git(root, ["cat-file", "-e", `${commit}^{commit}`], { allowFailure: true }).status === 0;
|
|
46
|
+
|
|
47
|
+
export function isCommitAncestor(projectRoot, ancestor, descendant) {
|
|
48
|
+
const repository = repositoryState(projectRoot);
|
|
49
|
+
ancestor = assertCommitHash(ancestor, "Ancestor");
|
|
50
|
+
descendant = assertCommitHash(descendant, "Descendant");
|
|
51
|
+
if (!commitExists(repository.root, ancestor) || !commitExists(repository.root, descendant)) return false;
|
|
52
|
+
return git(repository.root, ["merge-base", "--is-ancestor", ancestor, descendant], { allowFailure: true }).status === 0;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function inspectCommitRange(projectRoot, from, to) {
|
|
56
|
+
const repository = repositoryState(projectRoot);
|
|
57
|
+
from = assertCommitHash(from, "Range start");
|
|
58
|
+
to = assertCommitHash(to, "Range end");
|
|
59
|
+
if (!commitExists(repository.root, from) || !commitExists(repository.root, to) || !isCommitAncestor(repository.root, from, to)) {
|
|
60
|
+
fail(ERROR_CODES.DELIVERY_INVALID_RANGE, "Delivery range must contain available commits in ancestor order", { from, to });
|
|
61
|
+
}
|
|
62
|
+
const commitCount = Number(git(repository.root, ["rev-list", "--count", `${from}..${to}`]).stdout.trim());
|
|
63
|
+
const commits = git(repository.root, ["rev-list", "--reverse", `--skip=${Math.max(0, commitCount - 500)}`, "--max-count=500", `${from}..${to}`]).stdout.trim().split("\n").filter(Boolean);
|
|
64
|
+
const names = git(repository.root, ["diff", "--name-only", "-z", from, to, "--"], {
|
|
65
|
+
encoding: null,
|
|
66
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
67
|
+
code: ERROR_CODES.DELIVERY_RANGE_TOO_LARGE,
|
|
68
|
+
message: "Delivery changed-path output exceeds the supported 4 MiB limit",
|
|
69
|
+
}).stdout.toString("utf8").split("\0").filter(Boolean);
|
|
70
|
+
return {
|
|
71
|
+
from,
|
|
72
|
+
to,
|
|
73
|
+
commit_count: commitCount,
|
|
74
|
+
commits,
|
|
75
|
+
commits_truncated: commitCount > commits.length,
|
|
76
|
+
changed_path_count: names.length,
|
|
77
|
+
changed_paths: names.slice(0, 500),
|
|
78
|
+
paths_truncated: names.length > 500,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
39
82
|
function withTemporaryIndex(root, base, fn) {
|
|
40
83
|
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "work-context-candidate-"));
|
|
41
84
|
const index = path.join(directory, "index");
|
package/src/index.js
CHANGED
package/src/stages-renderer.js
CHANGED
|
@@ -7,6 +7,25 @@ const statusMarker = (status) => ({
|
|
|
7
7
|
}[status] || "[?]");
|
|
8
8
|
|
|
9
9
|
const compareStageIds = (left, right) => Number(left.id) - Number(right.id);
|
|
10
|
+
const candidateSummary = (stage) => {
|
|
11
|
+
const projection = stage.candidates;
|
|
12
|
+
if (!projection || !(projection.draft || projection.ready)) return null;
|
|
13
|
+
if (projection.draft + projection.ready > 1) return `Pending: ${projection.draft} draft · ${projection.ready} ready`;
|
|
14
|
+
const [candidate] = projection.items;
|
|
15
|
+
const others = candidate.related_stages.filter((related) => related !== stage.id);
|
|
16
|
+
return `Pending: ${candidate.status} · ${candidate.strategy}${others.length ? ` · also ${others.join(", ")}` : ""}`;
|
|
17
|
+
};
|
|
18
|
+
const deliverySummary = (delivery) => {
|
|
19
|
+
if (!delivery) return null;
|
|
20
|
+
if (delivery.unavailable) return "Delivery · unavailable";
|
|
21
|
+
if (delivery.plan_needed) return `Delivery · ${delivery.committed} commits · plan needed`;
|
|
22
|
+
if (delivery.environments.length === 1) {
|
|
23
|
+
const [environment] = delivery.environments;
|
|
24
|
+
return `Delivery · ${environment.environment} · ${environment.pending} tracked pending`;
|
|
25
|
+
}
|
|
26
|
+
const pending = delivery.environments.reduce((total, environment) => total + environment.pending, 0);
|
|
27
|
+
return `Delivery · ${delivery.environments.length} environments · ${pending} tracked pending`;
|
|
28
|
+
};
|
|
10
29
|
|
|
11
30
|
/**
|
|
12
31
|
* Render normalized stages as a dependency-to-dependent forest. A stage may
|
|
@@ -59,10 +78,13 @@ export function renderStagesPanel(result) {
|
|
|
59
78
|
`Workflow · ${snapshot.workspace.mode || "standard"}`,
|
|
60
79
|
];
|
|
61
80
|
const candidates = snapshot.workspace.candidates;
|
|
62
|
-
if (candidates && (candidates.pending || candidates.ready)) lines.push(`Candidates ·
|
|
81
|
+
if (candidates && (candidates.pending || candidates.ready)) lines.push(`Candidates · ${candidates.pending} draft · ${candidates.ready} ready`);
|
|
82
|
+
const delivery = deliverySummary(snapshot.workspace.delivery);
|
|
83
|
+
if (delivery) lines.push(delivery);
|
|
63
84
|
lines.push("", `Stages · ${snapshot.workspace.status}`);
|
|
64
85
|
for (const stage of snapshot.stages) {
|
|
65
|
-
|
|
86
|
+
const pending = candidateSummary(stage);
|
|
87
|
+
lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}${stage.depends_on?.length ? `\nDeps: ${stage.depends_on.join(", ")}` : ""}${pending ? `\n${pending}` : ""}`);
|
|
66
88
|
}
|
|
67
89
|
if (result.stale) lines.push(`! stale: ${result.error?.code || "STORAGE_ERROR"}`);
|
|
68
90
|
return lines.join("\n");
|
package/src/stages-snapshot.js
CHANGED
|
@@ -35,17 +35,24 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
|
|
|
35
35
|
|
|
36
36
|
const workspace = context.storage.readWorkspace(session.workspace).data;
|
|
37
37
|
const mode = workspace.mode || "standard";
|
|
38
|
-
const
|
|
39
|
-
const
|
|
38
|
+
const candidateProjection = mode === "startup" ? context.candidates().activeProjection(session.workspace) : null;
|
|
39
|
+
const deliveryProjection = context.deliveries().projection(session.workspace);
|
|
40
|
+
const delivery = deliveryProjection.committed.count || deliveryProjection.environments.length || deliveryProjection.unavailable
|
|
41
|
+
? { committed: deliveryProjection.committed.count, plan_needed: deliveryProjection.plan_needed, environments: deliveryProjection.environments, ...(deliveryProjection.unavailable ? { unavailable: true } : {}) }
|
|
42
|
+
: null;
|
|
43
|
+
const visibleStages = context.listStages(session.workspace).data.stages
|
|
40
44
|
.filter((stage) => stage.status !== "archived")
|
|
41
|
-
.sort((left, right) => Number(left.stage) - Number(right.stage))
|
|
45
|
+
.sort((left, right) => Number(left.stage) - Number(right.stage));
|
|
46
|
+
const visibleStageIds = new Set(visibleStages.map((stage) => stage.stage));
|
|
47
|
+
const stages = visibleStages
|
|
42
48
|
.map((stage) => ({
|
|
43
49
|
id: stage.stage,
|
|
44
50
|
title: stage.title,
|
|
45
51
|
status: stage.status,
|
|
46
52
|
description: stage.description,
|
|
47
|
-
depends_on: stage.depends_on,
|
|
53
|
+
depends_on: stage.depends_on.filter((dependency) => visibleStageIds.has(dependency)),
|
|
48
54
|
tracker_links: stage.tracker_links || [],
|
|
55
|
+
...(candidateProjection?.by_stage[stage.stage] ? { candidates: candidateProjection.by_stage[stage.stage] } : {}),
|
|
49
56
|
current: stage.stage === session.stage,
|
|
50
57
|
}));
|
|
51
58
|
const currentStage = stages.some((stage) => stage.current) ? session.stage : null;
|
|
@@ -54,7 +61,7 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
|
|
|
54
61
|
ok: true,
|
|
55
62
|
data: {
|
|
56
63
|
schema: 1,
|
|
57
|
-
workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status, mode, ...(
|
|
64
|
+
workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status, mode, ...(candidateProjection ? { candidates: candidateProjection.summary } : {}), ...(delivery ? { delivery } : {}) },
|
|
58
65
|
stages,
|
|
59
66
|
currentStage,
|
|
60
67
|
generatedAt: new Date().toISOString(),
|
package/src/tool-definitions.js
CHANGED
|
@@ -73,6 +73,8 @@ export const work_context_list_candidates = tool({ description: "List local comm
|
|
|
73
73
|
export const work_context_ready_candidate = tool({ description: "Mark a captured draft candidate ready for a later explicit commit operation.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string() }, execute: run((ctx, a) => ctx.readyCandidate(a.workspace, a.candidateId)) });
|
|
74
74
|
export const work_context_commit_candidate = tool({ description: "Commit a ready candidate atomically without using the ordinary Git index. Uses its stored message unless message is provided.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string(), message: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.commitCandidate(a.workspace, a.candidateId, a.message)) });
|
|
75
75
|
export const work_context_discard_candidate = tool({ description: "Discard a local commit candidate without changing Git state.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string() }, execute: run((ctx, a) => ctx.discardCandidate(a.workspace, a.candidateId)) });
|
|
76
|
+
export const work_context_read_delivery = tool({ description: "Read workspace-level delivery context. Exact Git inspection runs only when both immutable from and to commit hashes are provided.", args: { workspace: tool.schema.string(), environment: tool.schema.string().optional(), from: tool.schema.string().optional(), to: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.readDelivery(a.workspace, { environment: a.environment, from: a.from, to: a.to })) });
|
|
77
|
+
export const work_context_mark_delivery = tool({ description: "Record a confirmed environment delivery checkpoint without executing deployment. Requires DELIVERY_CONFIRMED.", args: { workspace: tool.schema.string(), environment: tool.schema.string(), commit: tool.schema.string(), confirmation: tool.schema.string() }, execute: run((ctx, a) => ctx.markDelivery(a.workspace, a.environment, a.commit, a.confirmation)) });
|
|
76
78
|
export const work_context_workspace_finish = tool({ description: "Finish a workspace after all stages are completed.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.finishWorkspace(a.workspace)) });
|
|
77
79
|
export const work_context_reopen_workspace = tool({ description: "Reopen a completed workspace with a required reason and durable history.", args: { workspace: tool.schema.string(), reason: tool.schema.string() }, execute: run((ctx, a) => ctx.reopenWorkspace(a.workspace, a.reason)) });
|
|
78
80
|
export const work_context_create_workspace = tool({ description: "Create a workspace; enter its planning stage only when the current OpenCode session is not associated with a workspace.", args: { title: tool.schema.string(), mode: tool.schema.enum(["standard", "startup"]).optional() }, execute: run((ctx, a, oc) => {
|
|
@@ -105,4 +107,4 @@ export const work_context_add_knowledge = tool({ description: "Add a durable kno
|
|
|
105
107
|
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)) });
|
|
106
108
|
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) ) });
|
|
107
109
|
|
|
108
|
-
export default { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_set_workspace_mode, work_context_create_candidate, work_context_capture_candidate, work_context_preview_candidate, work_context_show_candidate, work_context_list_candidates, work_context_ready_candidate, work_context_commit_candidate, work_context_discard_candidate, work_context_workspace_finish, work_context_reopen_workspace, work_context_create_workspace, work_context_start_session, work_context_add_stage, work_context_rename_stage, work_context_update_stage, work_context_update_stage_prompt, work_context_update_stage_result, work_context_read_stage_execution, work_context_replace_stage_execution, work_context_update_stage_execution, work_context_archive_stage, work_context_reopen_stage, work_context_restore_stage, work_context_link_issue, work_context_unlink_issue, work_context_rename_session, work_context_close_session, work_context_force_close_session, work_context_handoff_stage, work_context_abandon_stage, work_context_finish_stage, work_context_help, work_context_list_knowledge, work_context_add_knowledge, work_context_update_knowledge, work_context_supersede_knowledge };
|
|
110
|
+
export default { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_set_workspace_mode, work_context_create_candidate, work_context_capture_candidate, work_context_preview_candidate, work_context_show_candidate, work_context_list_candidates, work_context_ready_candidate, work_context_commit_candidate, work_context_discard_candidate, work_context_read_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_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 };
|
|
@@ -32,23 +32,31 @@ const readWorkspace = (context, record, currentSession) => {
|
|
|
32
32
|
: sessions.find((session) => session.session_id === currentSession?.session_id);
|
|
33
33
|
const currentStage = matchingSession?.stage || null;
|
|
34
34
|
const mode = record.mode || "standard";
|
|
35
|
-
const
|
|
35
|
+
const candidateProjection = mode === "startup" ? context.candidates().activeProjection(record.workspace) : null;
|
|
36
|
+
const deliveryProjection = context.deliveries().projection(record.workspace);
|
|
37
|
+
const delivery = deliveryProjection.committed.count || deliveryProjection.environments.length || deliveryProjection.unavailable
|
|
38
|
+
? { committed: deliveryProjection.committed.count, plan_needed: deliveryProjection.plan_needed, environments: deliveryProjection.environments, ...(deliveryProjection.unavailable ? { unavailable: true } : {}) }
|
|
39
|
+
: null;
|
|
40
|
+
const visibleStages = listed.stages
|
|
41
|
+
.filter((stage) => stage.status !== "archived")
|
|
42
|
+
.sort((left, right) => Number(left.stage) - Number(right.stage));
|
|
43
|
+
const visibleStageIds = new Set(visibleStages.map((stage) => stage.stage));
|
|
36
44
|
return {
|
|
37
45
|
id: record.workspace,
|
|
38
46
|
title: record.title,
|
|
39
47
|
status: record.status,
|
|
40
48
|
mode,
|
|
41
|
-
...(
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
.sort((left, right) => Number(left.stage) - Number(right.stage))
|
|
49
|
+
...(candidateProjection ? { candidates: candidateProjection.summary } : {}),
|
|
50
|
+
...(delivery ? { delivery } : {}),
|
|
51
|
+
stages: visibleStages
|
|
45
52
|
.map((stage) => ({
|
|
46
53
|
id: stage.stage,
|
|
47
54
|
title: stage.title,
|
|
48
55
|
status: stage.status,
|
|
49
56
|
description: stage.description,
|
|
50
|
-
depends_on: stage.depends_on,
|
|
57
|
+
depends_on: stage.depends_on.filter((dependency) => visibleStageIds.has(dependency)),
|
|
51
58
|
tracker_links: stage.tracker_links || [],
|
|
59
|
+
...(candidateProjection?.by_stage[stage.stage] ? { candidates: candidateProjection.by_stage[stage.stage] } : {}),
|
|
52
60
|
current: stage.stage === currentStage,
|
|
53
61
|
})),
|
|
54
62
|
currentStage,
|