opencode-work-context 0.17.0 → 0.18.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 +24 -9
- package/commands/wc.md +6 -0
- package/package.json +1 -1
- package/plugin/work-context.js +4 -2
- package/src/candidates.js +31 -1
- package/src/command-help.js +3 -3
- package/src/core.js +50 -8
- package/src/errors.js +1 -0
- package/src/git-acknowledgement.js +15 -4
- package/src/tool-definitions.js +24 -6
package/README.md
CHANGED
|
@@ -55,12 +55,17 @@ Then create a task and its first stage in OpenCode:
|
|
|
55
55
|
/wc resume 000001 02
|
|
56
56
|
```
|
|
57
57
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
58
|
+
An explicit user-issued `/wc create` enters Planning, and an explicit
|
|
59
|
+
user-issued `/wc stage add` enters the new stage, when the invoking native
|
|
60
|
+
OpenCode session has no historical work-context affinity. This supports opening
|
|
61
|
+
a fresh native session before issuing either command. If the session already
|
|
62
|
+
has an affinity, creation remains session-neutral and the result directs the
|
|
63
|
+
user to resume in a separate native session.
|
|
64
|
+
|
|
65
|
+
Autonomous agent calls remain different: creating a workspace or adding a stage
|
|
66
|
+
without explicit user command intent never captures the invoking session. An
|
|
67
|
+
agent-added stage stays `planned`. Multiple sessions may work on the same
|
|
68
|
+
non-terminal stage through explicit resume and handoff operations.
|
|
64
69
|
|
|
65
70
|
Stages remain in progress until the user explicitly requests `/wc stage finish`.
|
|
66
71
|
Do not infer that request from completed work. Automatic completion is allowed
|
|
@@ -281,9 +286,19 @@ each direct commit or candidate fallback, the agent must read the effective mode
|
|
|
281
286
|
again and proceed only while it returns `per_item`. This is an agent-policy
|
|
282
287
|
preflight, not atomic Git enforcement. Before completing Current, the agent must
|
|
283
288
|
define an explicit patch boundary, run relevant verification, and create a safe
|
|
284
|
-
direct commit. Candidate publication remains separate.
|
|
285
|
-
`commited <SHA>`
|
|
286
|
-
|
|
289
|
+
direct commit. Candidate publication remains separate. After a direct commit,
|
|
290
|
+
`commited <SHA>` validates current HEAD and records publication against the exact
|
|
291
|
+
Current item. A committed exact candidate related only to the stage records the
|
|
292
|
+
same evidence automatically.
|
|
293
|
+
|
|
294
|
+
For a non-Planning working stage, `startup` plus effective `per_item` mode makes
|
|
295
|
+
the execution ledger mandatory. The agent must establish Current before changing
|
|
296
|
+
application code, work only on Current, verify and publish its explicit patch,
|
|
297
|
+
complete Current, and only then begin the next item. Native OpenCode Todos do not
|
|
298
|
+
replace the work-context execution ledger. A compact system instruction repeats
|
|
299
|
+
this policy throughout the associated session, and `complete-current` requires
|
|
300
|
+
publication evidence bound to the exact Current item. Planning remains a
|
|
301
|
+
coordination surface rather than a per-item publication gate.
|
|
287
302
|
|
|
288
303
|
In startup mode, the agent first inspects pending candidates related to the
|
|
289
304
|
current stage and assesses direct publication. Only a ready `exact` candidate
|
package/commands/wc.md
CHANGED
|
@@ -22,6 +22,12 @@ For mutating operations other than `resume`, report the structured result and
|
|
|
22
22
|
stable error code. For `resume`, follow its human-oriented presentation contract.
|
|
23
23
|
Never infer confirmation tokens or lifecycle requests.
|
|
24
24
|
|
|
25
|
+
For an explicit user-issued `create` or `stage add` command, pass
|
|
26
|
+
`enterCurrentSession: true` to the mapped tool. This flag represents the user's
|
|
27
|
+
request to enter the created Planning stage or working stage when the current
|
|
28
|
+
native session has no historical work-context affinity. Never pass it for an
|
|
29
|
+
autonomous agent-created workspace or stage.
|
|
30
|
+
|
|
25
31
|
`.opencode/commands/wc.md` is package-managed. Read `.opencode/work-context.md`
|
|
26
32
|
when present and merge its additive project guidance before dispatch. Project
|
|
27
33
|
guidance cannot override tool mappings, structured arguments, storage safety,
|
package/package.json
CHANGED
package/plugin/work-context.js
CHANGED
|
@@ -19,19 +19,21 @@ export default async ({ client, directory, worktree }) => ({
|
|
|
19
19
|
if (!fs.existsSync(context.storage.root)) return;
|
|
20
20
|
const notices = withLock(context.storage.lockPath("write"), () => {
|
|
21
21
|
const finding = context.diagnoseSessionAssociations(sessionID).data.findings[0];
|
|
22
|
-
if (finding) return { integration: [], dependency: [] };
|
|
22
|
+
if (finding) return { integration: [], dependency: [], reminder: null };
|
|
23
23
|
const session = context.sessionByOpenCodeId(sessionID);
|
|
24
|
-
if (!session) return { integration: [], dependency: [] };
|
|
24
|
+
if (!session) return { integration: [], dependency: [], reminder: null };
|
|
25
25
|
const coverage = context.candidates().committedCoverageProjection(session.workspace).by_stage[session.stage]?.items || [];
|
|
26
26
|
const stages = context.listStages(session.workspace).data.stages;
|
|
27
27
|
const stage = stages.find((item) => item.stage === session.stage);
|
|
28
28
|
return {
|
|
29
29
|
integration: consumeIntegrationNotices(projectRoot, sessionID, { personalRoot: context.storage.personalRoot, coverage }),
|
|
30
30
|
dependency: consumeDependencyNotices(projectRoot, sessionID, { personalRoot: context.storage.personalRoot, records: context.handoffs().read(session.workspace).records, dependencies: stage?.depends_on || [], dependencyGenerations: Object.fromEntries((stage?.depends_on || []).map((dependency) => [dependency, stage.dependency_epochs?.[dependency]?.generation || 1])) }),
|
|
31
|
+
reminder: context.mandatoryChecklistReminder(session.workspace, session.stage),
|
|
31
32
|
};
|
|
32
33
|
}, { owner: "work-context integration notice", session: sessionID });
|
|
33
34
|
appendIntegrationNotices(output.system, notices.integration);
|
|
34
35
|
appendDependencyNotices(output.system, notices.dependency);
|
|
36
|
+
if (notices.reminder) output.system.push(notices.reminder);
|
|
35
37
|
} catch {
|
|
36
38
|
// Local notice delivery is best effort and must not interrupt a model request.
|
|
37
39
|
}
|
package/src/candidates.js
CHANGED
|
@@ -17,7 +17,7 @@ const coverageStageLimit = 20;
|
|
|
17
17
|
const executionItemPattern = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|legacy-[0-9a-f]{24})$/;
|
|
18
18
|
const timestamp = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
19
19
|
const metadataKeys = ["schema", "candidate", "workspace", "title", "message", "base_head", "status", "created_at", "updated_at", "selected_paths", "patch_file"];
|
|
20
|
-
const optionalMetadataKeys = ["strategy", "related_stages", "coverage"];
|
|
20
|
+
const optionalMetadataKeys = ["strategy", "related_stages", "coverage", "publication"];
|
|
21
21
|
|
|
22
22
|
const validCoverage = (coverage) => coverage && typeof coverage === "object" && !Array.isArray(coverage)
|
|
23
23
|
&& Object.keys(coverage).every((key) => ["schema", "confirmed_at", "entries"].includes(key))
|
|
@@ -29,6 +29,11 @@ const validCoverage = (coverage) => coverage && typeof coverage === "object" &&
|
|
|
29
29
|
&& Number.isInteger(entry.execution_revision) && entry.execution_revision >= 0)
|
|
30
30
|
&& new Set(coverage.entries.map((entry) => entry.stage)).size === coverage.entries.length
|
|
31
31
|
&& coverage.entries.every((entry, index) => index === 0 || coverage.entries[index - 1].stage.localeCompare(entry.stage) < 0);
|
|
32
|
+
const validPublication = (publication) => publication && typeof publication === "object" && !Array.isArray(publication)
|
|
33
|
+
&& Object.keys(publication).every((key) => ["schema", "stage", "current_item_id", "execution_revision"].includes(key))
|
|
34
|
+
&& publication.schema === 1 && /^\d{2}$/.test(publication.stage) && publication.stage !== "00"
|
|
35
|
+
&& executionItemPattern.test(publication.current_item_id)
|
|
36
|
+
&& Number.isInteger(publication.execution_revision) && publication.execution_revision >= 0;
|
|
32
37
|
|
|
33
38
|
function validateCandidate(data, expectedId = null) {
|
|
34
39
|
const valid = data && typeof data === "object" && !Array.isArray(data)
|
|
@@ -47,6 +52,7 @@ function validateCandidate(data, expectedId = null) {
|
|
|
47
52
|
&& Array.isArray(data.related_stages) && data.related_stages.every((stage) => /^\d{2}$/.test(stage) && stage !== "00")
|
|
48
53
|
&& new Set(data.related_stages).size === data.related_stages.length))
|
|
49
54
|
&& (!Object.hasOwn(data, "coverage") || (data.strategy === "integration" && validCoverage(data.coverage)))
|
|
55
|
+
&& (!Object.hasOwn(data, "publication") || (data.strategy === "exact" && data.related_stages.length === 1 && validPublication(data.publication) && data.publication.stage === data.related_stages[0]))
|
|
50
56
|
&& (data.status === "committed"
|
|
51
57
|
? /^[0-9a-f]{40,64}$/.test(data.commit_hash) && timestamp(data.committed_at)
|
|
52
58
|
: !Object.hasOwn(data, "commit_hash") && !Object.hasOwn(data, "committed_at"));
|
|
@@ -289,6 +295,28 @@ export class CandidateStore {
|
|
|
289
295
|
return projection;
|
|
290
296
|
}
|
|
291
297
|
|
|
298
|
+
exactPublicationEntry(workspace, data) {
|
|
299
|
+
if (data.strategy !== "exact" || data.related_stages.length !== 1 || data.related_stages[0] === "01") return null;
|
|
300
|
+
const stage = data.related_stages[0];
|
|
301
|
+
const workspaceRecord = this.context.storage.readWorkspace(workspace).data;
|
|
302
|
+
const stageRecord = this.context.storage.readStage(workspace, stage).data;
|
|
303
|
+
if (this.effectiveCommitMode(workspaceRecord, stageRecord) !== "per_item") return null;
|
|
304
|
+
const execution = this.context.storage.readStageExecution(workspace, stage);
|
|
305
|
+
const current = execution ? this.context.readStageExecution(workspace, stage).data.current : null;
|
|
306
|
+
return current ? { schema: 1, stage, current_item_id: current.id, execution_revision: execution.revision } : null;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
publicationForCurrent(workspace, stage, currentItemId, executionRevision) {
|
|
310
|
+
const matches = this.projectionRecords(workspace).filter((candidate) => candidate.status === "committed").flatMap((candidate) => {
|
|
311
|
+
if (candidate.publication?.stage === stage && candidate.publication.current_item_id === currentItemId && candidate.publication.execution_revision === executionRevision) {
|
|
312
|
+
return [{ candidate: candidate.candidate, commit_hash: candidate.commit_hash, source: "exact_candidate" }];
|
|
313
|
+
}
|
|
314
|
+
const covered = candidate.coverage?.entries?.find((entry) => entry.stage === stage && entry.current_item_id === currentItemId && entry.execution_revision === executionRevision);
|
|
315
|
+
return covered ? [{ candidate: candidate.candidate, commit_hash: candidate.commit_hash, source: "integration_coverage" }] : [];
|
|
316
|
+
});
|
|
317
|
+
return matches.at(-1) || null;
|
|
318
|
+
}
|
|
319
|
+
|
|
292
320
|
capture(workspace, id, input, options = {}) {
|
|
293
321
|
workspace = options.allowStandard ? this.assertWorkspace(workspace) : this.assertStartup(workspace);
|
|
294
322
|
const data = this.read(id, workspace);
|
|
@@ -334,6 +362,8 @@ export class CandidateStore {
|
|
|
334
362
|
if (message !== undefined && (typeof message !== "string" || !message.trim())) fail(ERROR_CODES.INVALID_ARGUMENT, "Commit message must be a non-empty string");
|
|
335
363
|
const commitMessage = message === undefined ? data.message : message.trim();
|
|
336
364
|
this.validateCoverage(workspace, data);
|
|
365
|
+
const publication = this.exactPublicationEntry(workspace, data);
|
|
366
|
+
if (publication) data.publication = publication;
|
|
337
367
|
let metadata;
|
|
338
368
|
const published = commitPatch(this.context.storage.projectRoot, data.base_head, data.patch, commitMessage, {
|
|
339
369
|
expectedHead: options.expectedHead,
|
package/src/command-help.js
CHANGED
|
@@ -7,7 +7,7 @@ const COMMON_GUIDANCE = Object.freeze([
|
|
|
7
7
|
const TOPICS = Object.freeze({
|
|
8
8
|
basic: Object.freeze([
|
|
9
9
|
"Workspace list output includes workspace status and workflow mode, followed by every stage as: stage - status - title - description.",
|
|
10
|
-
"
|
|
10
|
+
"For an explicit user-issued /wc create operation, pass enterCurrentSession: true. It starts Planning only when the native OpenCode session has no active or historical work-context stage affinity. Autonomous agent creation must omit this flag and remain session-neutral.",
|
|
11
11
|
]),
|
|
12
12
|
commit_mode: Object.freeze([
|
|
13
13
|
"Workspace commit mode is manual or per_item; a stage override may be cleared to inherit the workspace value.",
|
|
@@ -35,7 +35,7 @@ const TOPICS = Object.freeze({
|
|
|
35
35
|
"Profiles setup asks interactively for scope, mode, and depth mappings, applies mode and mappings separately, then offers to refresh unfinished stages. Profiles reset asks for scope and requires the exact RESET_PROFILES confirmation token before removing mappings.",
|
|
36
36
|
]),
|
|
37
37
|
stage_creation: Object.freeze([
|
|
38
|
-
"
|
|
38
|
+
"For an explicit user-issued /wc stage add operation, pass enterCurrentSession: true. It enters the new stage only when the native OpenCode session has no historical affinity. Autonomous agent stage creation must omit this flag and remain planned and session-neutral. Infer missing execution capability and depth from complete context and pass classification inferred.",
|
|
39
39
|
"Stage delegate requires the active delegating working-stage session and atomically creates the delegated stage plus the dependency edge; failure leaves neither partial state.",
|
|
40
40
|
"Planning stage 01 is a coordination surface and must never be used as a dependency gate.",
|
|
41
41
|
]),
|
|
@@ -70,7 +70,7 @@ const TOPICS = Object.freeze({
|
|
|
70
70
|
"Force close is only for a stale active association after explicit diagnosis. It requires the exact FORCE_CLOSE token and must never close the presumed original affinity merely because split-brain diagnostics exist.",
|
|
71
71
|
]),
|
|
72
72
|
acknowledge: Object.freeze([
|
|
73
|
-
"The command is intentionally spelled commited with one t. It
|
|
73
|
+
"The command is intentionally spelled commited with one t. It validates a current-HEAD direct commit for the active stage, records exact Current publication in mandatory startup per-item mode, performs no Git operation, and returns its compact structured result without a second analysis response.",
|
|
74
74
|
]),
|
|
75
75
|
issues: Object.freeze([
|
|
76
76
|
"Issue links are explicit workspace or stage metadata. Do not infer a stage when the command supplies only a workspace.",
|
package/src/core.js
CHANGED
|
@@ -14,7 +14,7 @@ import { DeliveryStore } from "./delivery.js";
|
|
|
14
14
|
import { doctorDelivery as runDeliveryDoctor } from "./delivery-doctor.js";
|
|
15
15
|
import { applyExecutionItemPatch, applyExecutionTextPatchItems, assertExecutionSize, EXECUTION_SECTIONS, executionInputUsesItems, executionItems, executionItemsFromState, executionPatchUsesItems, executionReadModel, executionSchemaFor, normalizeExecutionItemState, normalizeExecutionState } from "./stage-execution.js";
|
|
16
16
|
import { CAPABILITY_CLASSIFICATIONS, CAPABILITY_DEPTHS, CAPABILITY_PROFILES, capabilityProfileMode, capabilityRecommendations, configureCapabilityMappings, readCapabilityMappings, resetCapabilityMappings, validateCapabilityMappings } from "./capability-profiles.js";
|
|
17
|
-
import { acknowledgeGitCommit, initializeGitCheckpoint } from "./git-acknowledgement.js";
|
|
17
|
+
import { acknowledgeGitCommit, gitPublicationReceipt, initializeGitCheckpoint } from "./git-acknowledgement.js";
|
|
18
18
|
import { isCommitAncestor, repositoryState, rollbackCommitRef } from "./git-candidates.js";
|
|
19
19
|
import { enqueueIntegrationNotice } from "./integration-notices.js";
|
|
20
20
|
import { DependencyHandoffStore } from "./dependency-handoffs.js";
|
|
@@ -114,7 +114,8 @@ const startupWorkflowPolicy = (commitMode = { mode: "manual" }) => ({
|
|
|
114
114
|
guidance: commitMode.mode === "per_item" ? [
|
|
115
115
|
"A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
|
|
116
116
|
"When changes appear mixed or overlapping, report only a bounded, explicitly uncertain list of likely affected stages supported by deterministic local evidence; never infer file or hunk ownership.",
|
|
117
|
-
"
|
|
117
|
+
"Work only on the authoritative Current execution item. Native OpenCode Todos never replace the work-context ledger or authorize Queued work.",
|
|
118
|
+
"Before each direct commit or candidate fallback, read the effective commit mode again. Proceed only while per_item remains effective.",
|
|
118
119
|
"Inspect pending candidates related to this stage, then assess direct publication of the explicit Current-item patch first.",
|
|
119
120
|
"Only a ready exact candidate explicitly related to this stage may ordinarily substitute when direct publication is unsafe but the patch is separable. Shared foundation and unconfirmed integration candidates do not satisfy Current completion.",
|
|
120
121
|
"A committed integration candidate satisfies publication only when explicit coverage still names this exact Current item. Do not republish or reconstruct provenance; perform remaining verification and complete Current separately.",
|
|
@@ -152,7 +153,13 @@ const executionInstruction = (record) => {
|
|
|
152
153
|
};
|
|
153
154
|
const commitModeInstruction = (commitMode) => {
|
|
154
155
|
if (commitMode.mode !== "per_item") return "";
|
|
155
|
-
return `\n\nChecklist commit policy: per_item (${commitMode.source}). This is persistent authorization to publish an explicit, coherent Current-item patch; it never authorizes unrelated changes. Immediately before each direct commit or candidate fallback, call work_context_read_effective_commit_mode and proceed only if it still returns per_item.
|
|
156
|
+
return `\n\nChecklist commit policy: per_item (${commitMode.source}). This is persistent authorization to publish an explicit, coherent Current-item patch; it never authorizes unrelated changes. Immediately before each direct commit or candidate fallback, call work_context_read_effective_commit_mode and proceed only if it still returns per_item. Before completing Current, define its explicit patch boundary and run relevant verification. When a direct commit is safe, create it, then call work_context_acknowledge_commit to bind publication to Current before complete-current. Candidate publication remains separate. A committed exact candidate related only to this stage records the same Current-bound evidence automatically. A committed integration candidate is a narrow substitute only when explicit durable coverage still names this exact Current item; do not publish it again. Ordinary integration relations are traceability-only. A true patch or merge conflict, failed verification, or incoherent boundary is a blocker: record it and do not complete Current.`;
|
|
157
|
+
};
|
|
158
|
+
const mandatoryChecklist = (workspaceRecord, stage, commitMode) => stage !== "01" && workspaceMode(workspaceRecord) === "startup" && commitMode.mode === "per_item";
|
|
159
|
+
const mandatoryChecklistInstruction = (execution) => {
|
|
160
|
+
const current = execution ? executionReadModel(execution).current : null;
|
|
161
|
+
if (!current) return `\n\nMandatory startup per-item checklist: no Current item exists. Do not inspect or modify application code. First create or repair the authoritative work-context execution ledger with one bounded Current item and ordered Queued items. Native OpenCode Todos do not replace this ledger.`;
|
|
162
|
+
return `\n\nMandatory startup per-item checklist: work only on Current (${current.text}). Do not begin a Queued item. After implementation, record verification, re-read effective commit mode, publish the exact Current patch, record publication when using a direct commit, then call complete-current before starting the next item. Native OpenCode Todos do not replace this ledger.`;
|
|
156
163
|
};
|
|
157
164
|
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.`;
|
|
158
165
|
const assertOpenCodeSessionAvailable = (events, opencodeSessionId, workspace, stage) => {
|
|
@@ -460,6 +467,16 @@ export class WorkContext {
|
|
|
460
467
|
return { ok: true, data: { workspace, stage, mode: effective.mode, source: effective.source } };
|
|
461
468
|
}
|
|
462
469
|
|
|
470
|
+
mandatoryChecklistReminder(workspace, stage) {
|
|
471
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
472
|
+
stage = normalizeStageId(stage);
|
|
473
|
+
const workspaceRecord = this.storage.readWorkspace(workspace).data;
|
|
474
|
+
const stageRecord = this.storage.readStage(workspace, stage).data;
|
|
475
|
+
const commitMode = effectiveCommitMode(workspaceRecord, stageRecord);
|
|
476
|
+
if (!mandatoryChecklist(workspaceRecord, stage, commitMode)) return null;
|
|
477
|
+
return mandatoryChecklistInstruction(this.storage.readStageExecution(workspace, stage)).trim();
|
|
478
|
+
}
|
|
479
|
+
|
|
463
480
|
candidates() { return new CandidateStore(this); }
|
|
464
481
|
deliveries() { return new DeliveryStore(this); }
|
|
465
482
|
handoffs() { return new DependencyHandoffStore(this.storage); }
|
|
@@ -629,8 +646,10 @@ export class WorkContext {
|
|
|
629
646
|
const committedCoverage = workflowPolicy ? this.candidates().committedCoverageProjection(workspace).by_stage[stage] || null : null;
|
|
630
647
|
const deliveryContext = stage === "01" ? this.deliveries().projection(workspace) : null;
|
|
631
648
|
const hasDeliveryContext = deliveryContext && (deliveryContext.committed.count || deliveryContext.environments.length || deliveryContext.unavailable);
|
|
632
|
-
|
|
633
|
-
|
|
649
|
+
const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
|
|
650
|
+
const execution = this.storage.readStageExecution(workspace, stage);
|
|
651
|
+
const checklistRequired = mandatoryChecklist(workspaceRecord, stage, commitMode);
|
|
652
|
+
const executionCurrent = execution ? executionReadModel(execution).current : null;
|
|
634
653
|
const dependencyContext = stageRecord.data.depends_on.length ? this.handoffs().context(workspace, stage, this.listStages(workspace).data.stages) : null;
|
|
635
654
|
const automaticFinish = automaticFinishAllowed(this.storage, workspace);
|
|
636
655
|
const recommendations = capabilityRecommendations(this.storage, stageRecord.data, readCapabilityMappings(this.storage, { homeDir: this.options.capabilityProfilesHome }));
|
|
@@ -675,10 +694,10 @@ export class WorkContext {
|
|
|
675
694
|
...(workflowPolicy ? { workflow_policy: workflowPolicy } : {}),
|
|
676
695
|
lifecycle: { automatic_finish_allowed: automaticFinish },
|
|
677
696
|
},
|
|
678
|
-
|
|
697
|
+
next_action: checklistRequired && !executionCurrent ? "initialize_execution" : hasPrompt ? confirmationRequired ? "await_confirmation" : "start_work" : "ask_questions",
|
|
679
698
|
instruction: `${hasPrompt
|
|
680
699
|
? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${executionInstruction(execution)}${startupWorkflowInstruction(workflowPolicy)}${stage === "01" ? deliveryPlanningInstruction : ""}`
|
|
681
|
-
|
|
700
|
+
: `This stage has no non-empty prompt. Give the user a concise plain-language summary of the stage title and goal, then ask focused questions needed to define the intended outcome and scope. Do not inspect or modify application code yet. Do not report raw operation metadata or identifiers.`}${commitModeInstruction(commitMode)}${checklistRequired ? mandatoryChecklistInstruction(execution) : ""}\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.`,
|
|
682
701
|
},
|
|
683
702
|
}, [workspace, stage]);
|
|
684
703
|
});
|
|
@@ -690,7 +709,16 @@ export class WorkContext {
|
|
|
690
709
|
this.storage.assertSafeRoots();
|
|
691
710
|
return withLock(this.storage.lockPath("git-acknowledgement"), () => {
|
|
692
711
|
assertActive(this.storage.readEvents(), workspace, stage, sessionId);
|
|
693
|
-
|
|
712
|
+
const workspaceRecord = this.storage.readWorkspace(workspace).data;
|
|
713
|
+
const stageRecord = this.storage.readStage(workspace, stage).data;
|
|
714
|
+
const commitMode = effectiveCommitMode(workspaceRecord, stageRecord);
|
|
715
|
+
const execution = this.storage.readStageExecution(workspace, stage);
|
|
716
|
+
const current = execution ? executionReadModel(execution).current : null;
|
|
717
|
+
if (mandatoryChecklist(workspaceRecord, stage, commitMode) && !current) fail(ERROR_CODES.EXECUTION_CURRENT_REQUIRED, "A Current execution item is required before recording per-item publication");
|
|
718
|
+
const publication = mandatoryChecklist(workspaceRecord, stage, commitMode)
|
|
719
|
+
? { schema: 1, workspace, stage, current_item_id: current.id, execution_revision: execution.revision }
|
|
720
|
+
: null;
|
|
721
|
+
return this.result(acknowledgeGitCommit(this.storage, { workspace, stage, sessionId, sha, publication }), ["local:git-checkpoint"]);
|
|
694
722
|
}, { session: sessionId, owner: actor(this.options) });
|
|
695
723
|
}
|
|
696
724
|
|
|
@@ -1130,6 +1158,20 @@ export class WorkContext {
|
|
|
1130
1158
|
const items = current && executionItems(current);
|
|
1131
1159
|
const currentItem = items?.remaining.shift();
|
|
1132
1160
|
if (!currentItem) fail(ERROR_CODES.INVALID_STATE, "No current execution item to complete");
|
|
1161
|
+
const workspaceRecord = this.storage.readWorkspace(workspace).data;
|
|
1162
|
+
const commitMode = effectiveCommitMode(workspaceRecord, stageRecord.data);
|
|
1163
|
+
if (mandatoryChecklist(workspaceRecord, stage, commitMode)) {
|
|
1164
|
+
const candidatePublication = this.candidates().publicationForCurrent(workspace, stage, currentItem.id, revision);
|
|
1165
|
+
const directPublication = gitPublicationReceipt(this.storage, sessionId);
|
|
1166
|
+
const matchingDirect = directPublication?.workspace === workspace && directPublication.stage === stage
|
|
1167
|
+
&& directPublication.current_item_id === currentItem.id && directPublication.execution_revision === revision
|
|
1168
|
+
? { commit_hash: directPublication.commit, source: "direct_commit" }
|
|
1169
|
+
: null;
|
|
1170
|
+
const publication = candidatePublication || matchingDirect;
|
|
1171
|
+
if (!publication) fail(ERROR_CODES.EXECUTION_PUBLICATION_REQUIRED, "Current must have publication evidence bound to its exact item and revision before completion", { current_item_id: currentItem.id, execution_revision: revision });
|
|
1172
|
+
const repository = repositoryState(this.storage.projectRoot);
|
|
1173
|
+
if (!isCommitAncestor(repository.root, publication.commit_hash, repository.head)) fail(ERROR_CODES.EXECUTION_PUBLICATION_REQUIRED, "Current publication commit is not reachable from HEAD", { commit: publication.commit_hash, current_head: repository.head });
|
|
1174
|
+
}
|
|
1133
1175
|
items.completed.push(currentItem);
|
|
1134
1176
|
const nextItems = normalizeExecutionItemState(items, current);
|
|
1135
1177
|
const timestamp = new Date().toISOString();
|
package/src/errors.js
CHANGED
|
@@ -22,6 +22,7 @@ export const ERROR_CODES = Object.freeze({
|
|
|
22
22
|
COMMIT_ALL_UNSAFE_STATE: "COMMIT_ALL_UNSAFE_STATE", COMMIT_ALL_INCOHERENT_BOUNDARY: "COMMIT_ALL_INCOHERENT_BOUNDARY",
|
|
23
23
|
COMMIT_ALL_STALE_PLAN: "COMMIT_ALL_STALE_PLAN", COMMIT_ALL_VERIFICATION_FAILED: "COMMIT_ALL_VERIFICATION_FAILED",
|
|
24
24
|
EXECUTION_REVISION_CONFLICT: "EXECUTION_REVISION_CONFLICT", EXECUTION_LIMIT_EXCEEDED: "EXECUTION_LIMIT_EXCEEDED",
|
|
25
|
+
EXECUTION_CURRENT_REQUIRED: "EXECUTION_CURRENT_REQUIRED", EXECUTION_PUBLICATION_REQUIRED: "EXECUTION_PUBLICATION_REQUIRED",
|
|
25
26
|
DELIVERY_INVALID_RANGE: "DELIVERY_INVALID_RANGE", DELIVERY_RANGE_TOO_LARGE: "DELIVERY_RANGE_TOO_LARGE",
|
|
26
27
|
DELIVERY_INVALID_FINDINGS: "DELIVERY_INVALID_FINDINGS", DELIVERY_DIAGNOSTIC_TOO_LARGE: "DELIVERY_DIAGNOSTIC_TOO_LARGE",
|
|
27
28
|
DELIVERY_COMMAND_PROTOCOL_MISMATCH: "DELIVERY_COMMAND_PROTOCOL_MISMATCH",
|
|
@@ -31,7 +31,14 @@ const checkpointFor = (personalRoot, sessionId) => {
|
|
|
31
31
|
const file = checkpointPath(personalRoot, sessionId);
|
|
32
32
|
try {
|
|
33
33
|
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
34
|
-
|
|
34
|
+
const publication = value?.publication;
|
|
35
|
+
const validPublication = publication === undefined || (publication && publication.schema === 1
|
|
36
|
+
&& typeof publication.workspace === "string" && /^\d{6}$/.test(publication.workspace)
|
|
37
|
+
&& typeof publication.stage === "string" && /^\d{2}$/.test(publication.stage)
|
|
38
|
+
&& typeof publication.current_item_id === "string" && publication.current_item_id.length <= 100
|
|
39
|
+
&& Number.isInteger(publication.execution_revision) && publication.execution_revision >= 0
|
|
40
|
+
&& typeof publication.commit === "string" && /^[0-9a-f]{40,64}$/.test(publication.commit));
|
|
41
|
+
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/") || !validPublication) {
|
|
35
42
|
fail(ERROR_CODES.STORAGE_ERROR, "Invalid Git acknowledgement checkpoint");
|
|
36
43
|
}
|
|
37
44
|
return { file, value };
|
|
@@ -78,7 +85,7 @@ export function initializeGitCheckpoint(storage, { workspace, stage, sessionId }
|
|
|
78
85
|
return value;
|
|
79
86
|
}
|
|
80
87
|
|
|
81
|
-
export function acknowledgeGitCommit(storage, { workspace, stage, sessionId, sha }) {
|
|
88
|
+
export function acknowledgeGitCommit(storage, { workspace, stage, sessionId, sha, publication = null }) {
|
|
82
89
|
const input = assertAcknowledgementHash(sha);
|
|
83
90
|
const checkpoint = checkpointFor(storage.personalRoot, sessionId);
|
|
84
91
|
if (!checkpoint.value) fail(ERROR_CODES.GIT_ACKNOWLEDGEMENT_CHECKPOINT_MISSING, "No Git checkpoint exists for this active session");
|
|
@@ -93,7 +100,11 @@ export function acknowledgeGitCommit(storage, { workspace, stage, sessionId, sha
|
|
|
93
100
|
if (verified.head !== state.head || verified.ref !== state.ref || gitOperationInProgress(verified.root)) {
|
|
94
101
|
fail(ERROR_CODES.GIT_ACKNOWLEDGEMENT_REF_CHANGED, "Git state changed while acknowledging the commit");
|
|
95
102
|
}
|
|
96
|
-
const value = { ...checkpoint.value, head: state.head, updated_at: new Date().toISOString() };
|
|
103
|
+
const value = { ...checkpoint.value, head: state.head, updated_at: new Date().toISOString(), ...(publication ? { publication: { ...publication, commit: state.head } } : {}) };
|
|
97
104
|
atomicWrite(checkpoint.file, `${JSON.stringify(value, null, 2)}\n`);
|
|
98
|
-
return { acknowledged: true, commit: state.head };
|
|
105
|
+
return { acknowledged: true, commit: state.head, ...(value.publication ? { publication: value.publication } : {}) };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function gitPublicationReceipt(storage, sessionId) {
|
|
109
|
+
return checkpointFor(storage.personalRoot, sessionId).value?.publication || null;
|
|
99
110
|
}
|
package/src/tool-definitions.js
CHANGED
|
@@ -84,9 +84,26 @@ const activeSessionFromContext = (ctx, workspace, stage) => {
|
|
|
84
84
|
return direct?.workspace === workspace && direct.stage === stage && direct.state === "active" ? direct : null;
|
|
85
85
|
};
|
|
86
86
|
const sessionFor = (ctx, oc, workspace, stage) => activeSessionFromContext(ctx, workspace, stage)?.session_id || oc.sessionID;
|
|
87
|
-
const addStageFromTool = (ctx, args) => {
|
|
87
|
+
const addStageFromTool = (ctx, args, oc) => {
|
|
88
88
|
const workspace = workspaceFromSession(ctx, args.workspace);
|
|
89
|
-
|
|
89
|
+
const created = ctx.addStage(workspace, args.title, { goal: args.goal, prompt: args.prompt, dependsOn: args.dependsOn, executionProfile: args.executionProfile, executionDepth: args.executionDepth, classification: args.classification, reviewProfile: args.reviewProfile });
|
|
90
|
+
if (!args.enterCurrentSession) return created;
|
|
91
|
+
if (ctx.sessionAffinityByOpenCodeId(oc.sessionID)) return {
|
|
92
|
+
...created,
|
|
93
|
+
data: { ...created.data, next_action: "start_new_opencode_session_and_resume" },
|
|
94
|
+
};
|
|
95
|
+
const started = ctx.startSession(workspace, created.data.stage, { sessionId: randomUUID(), opencodeSessionId: oc.sessionID });
|
|
96
|
+
return {
|
|
97
|
+
...started,
|
|
98
|
+
data: {
|
|
99
|
+
...started.data,
|
|
100
|
+
created: true,
|
|
101
|
+
status: "in_progress",
|
|
102
|
+
session_started: true,
|
|
103
|
+
resume_required: false,
|
|
104
|
+
},
|
|
105
|
+
changed: [...new Set([...(created.changed || []), ...(started.changed || [])])],
|
|
106
|
+
};
|
|
90
107
|
};
|
|
91
108
|
export const work_context_list_workspaces = tool({ description: "List work-context workspaces.", args: {}, execute: run((ctx) => ctx.listWorkspaces()) });
|
|
92
109
|
export const work_context_workspace_list = tool({ description: "List a workspace with stage descriptions and sessions.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.listStages(a.workspace)) });
|
|
@@ -118,18 +135,19 @@ export const work_context_doctor_delivery = createDoctorDeliveryTool();
|
|
|
118
135
|
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)) });
|
|
119
136
|
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)) });
|
|
120
137
|
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)) });
|
|
121
|
-
export const work_context_create_workspace = tool({ description: "Create a workspace
|
|
138
|
+
export const work_context_create_workspace = tool({ description: "Create a workspace. Pass enterCurrentSession only for an explicit user-issued /wc create operation; autonomous agent creation remains session-neutral.", args: { title: tool.schema.string(), mode: tool.schema.enum(["standard", "startup"]).optional(), enterCurrentSession: tool.schema.boolean().optional() }, execute: run((ctx, a, oc) => {
|
|
122
139
|
const currentSession = ctx.sessionAffinityByOpenCodeId(oc.sessionID);
|
|
123
|
-
|
|
140
|
+
const enterCurrentSession = a.enterCurrentSession === true && !currentSession;
|
|
141
|
+
return ctx.createWorkspace(a.title, { mode: a.mode, ...(enterCurrentSession ? { sessionId: randomUUID(), opencodeSessionId: oc.sessionID } : { startSession: false }) });
|
|
124
142
|
}) });
|
|
125
143
|
export const work_context_start_session = tool({ description: "Start a new active session for the stage permanently associated with this OpenCode session and return its human-oriented presentation, prompt, active workspace knowledge, and startup policy when applicable. A different stage requires a separate OpenCode session.", 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 })) });
|
|
126
|
-
export const work_context_acknowledge_commit = tool({ description: "
|
|
144
|
+
export const work_context_acknowledge_commit = tool({ description: "Validate and record a current-HEAD direct commit for the active session using a short or full commit hash. In mandatory startup per-item mode this binds publication to the exact Current item and revision.", args: { sha: tool.schema.string() }, execute: run((ctx, a) => {
|
|
127
145
|
const affinity = sessionFromContext(ctx);
|
|
128
146
|
const session = affinity && activeSessionFromContext(ctx, affinity.workspace, affinity.stage);
|
|
129
147
|
if (!session) fail(ERROR_CODES.STAGE_CONTEXT_REQUIRED, "An active work-context stage is required to acknowledge a commit");
|
|
130
148
|
return ctx.acknowledgeCommit(session.workspace, session.stage, session.session_id, a.sha);
|
|
131
149
|
}) });
|
|
132
|
-
export const work_context_add_stage = tool({ description: "Add a
|
|
150
|
+
export const work_context_add_stage = tool({ description: "Add a stage. Pass enterCurrentSession only for an explicit user-issued /wc stage add operation; autonomous agent creation remains planned and session-neutral. When the user did not specify execution capability and depth, 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(), enterCurrentSession: tool.schema.boolean().optional() }, execute: run(addStageFromTool) });
|
|
133
151
|
export const work_context_delegate_stage = tool({ description: "Atomically create a delegated working stage and add it as a dependency of the active delegating stage.", args: { ...contextualStage, title: tool.schema.string(), requestedOutcome: 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((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.delegateStage(workspace, stage, sessionFor(ctx, oc, workspace, stage), a.title, a.requestedOutcome, a); }) });
|
|
134
152
|
export const work_context_add_stage_dependency = tool({ description: "Add one explicit cycle-safe dependency edge to an actionable dependent stage.", args: { ...contextualStage, dependency: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.addStageDependency(workspace, stageFromSession(ctx, workspace, a.stage), a.dependency); }) });
|
|
135
153
|
export const work_context_remove_stage_dependency = tool({ description: "Remove one explicit dependency edge while retaining historical handoffs.", args: { ...contextualStage, dependency: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.removeStageDependency(workspace, stageFromSession(ctx, workspace, a.stage), a.dependency); }) });
|