opencode-work-context 0.11.1 → 0.12.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 +83 -13
- package/bin/opencode-work-context.js +54 -2
- package/commands/wc.md +19 -7
- package/package.json +2 -1
- package/plugin/stages-tui.js +19 -9
- package/src/candidates.js +116 -9
- package/src/capability-profiles.js +75 -43
- package/src/core.js +94 -42
- package/src/errors.js +4 -0
- package/src/git-candidates.js +113 -1
- package/src/protocol.js +2 -2
- package/src/stage-execution.js +223 -16
- package/src/tool-definitions.js +13 -12
- package/tools/work_context_commit_all.js +3 -0
- package/tools/work_context_complete_current.js +1 -0
- package/tools/work_context_inspect_commit_all.js +3 -0
|
@@ -1,62 +1,67 @@
|
|
|
1
|
-
import fs from "node:fs";
|
|
2
1
|
import path from "node:path";
|
|
2
|
+
import {
|
|
3
|
+
CAPABILITY_DEPTHS,
|
|
4
|
+
CONFIG_FILE_NAME,
|
|
5
|
+
assertValidMappings,
|
|
6
|
+
configureGlobal,
|
|
7
|
+
configureProject,
|
|
8
|
+
globalConfigPath,
|
|
9
|
+
projectConfigPath,
|
|
10
|
+
readConfigFile,
|
|
11
|
+
readProfiles,
|
|
12
|
+
resetConfigFile,
|
|
13
|
+
resetGlobal,
|
|
14
|
+
resetProject,
|
|
15
|
+
resolveDepth,
|
|
16
|
+
writeConfigFile,
|
|
17
|
+
} from "opencode-capability-profiles";
|
|
3
18
|
|
|
4
19
|
export const CAPABILITY_PROFILES = Object.freeze(["routine", "implementation", "architecture", "security", "review"]);
|
|
5
|
-
export
|
|
20
|
+
export { CAPABILITY_DEPTHS };
|
|
6
21
|
export const CAPABILITY_CLASSIFICATIONS = Object.freeze(["inferred", "explicit"]);
|
|
7
22
|
export const CAPABILITY_PROFILE_MODES = Object.freeze(["advisory", "off"]);
|
|
8
|
-
export const CAPABILITY_MAPPINGS_FILE =
|
|
9
|
-
const MAX_MAPPING_BYTES = 16 * 1024;
|
|
10
|
-
const MAX_WARNINGS = 5;
|
|
23
|
+
export const CAPABILITY_MAPPINGS_FILE = CONFIG_FILE_NAME;
|
|
11
24
|
|
|
12
25
|
export const capabilityProfileMode = (storage) => storage.config.capability_profiles?.mode || "advisory";
|
|
13
26
|
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
&& !/[\u0000-\u001f\u007f]/.test(value);
|
|
27
|
+
const legacyWarning = (file) => ({
|
|
28
|
+
code: "LEGACY_CAPABILITY_MAPPING",
|
|
29
|
+
message: `Legacy capability mappings detected at ${file}; migrate them to the shared global or project configuration.`,
|
|
30
|
+
path: file,
|
|
31
|
+
});
|
|
20
32
|
|
|
21
|
-
export function readCapabilityMappings(storage) {
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
for (const [depth, target] of Object.entries(input.mappings)) {
|
|
40
|
-
const safeDepth = depth.replace(/[\u0000-\u001f\u007f]/g, "?").slice(0, 40);
|
|
41
|
-
if (!CAPABILITY_DEPTHS.includes(depth)) addWarning(`Ignoring unknown capability depth mapping: ${safeDepth}.`);
|
|
42
|
-
else if (!validTarget(target)) addWarning(`Ignoring invalid target for capability depth mapping: ${depth}.`);
|
|
43
|
-
else mappings[depth] = target;
|
|
44
|
-
}
|
|
45
|
-
return { mappings, warnings };
|
|
33
|
+
export function readCapabilityMappings(storage, options = {}) {
|
|
34
|
+
const profiles = readProfiles({
|
|
35
|
+
projectRoot: storage.projectRoot,
|
|
36
|
+
...(options.homeDir ? { homeDir: options.homeDir } : {}),
|
|
37
|
+
});
|
|
38
|
+
const legacyFile = path.join(storage.personalRoot, CAPABILITY_MAPPINGS_FILE);
|
|
39
|
+
const legacy = readConfigFile(legacyFile);
|
|
40
|
+
return {
|
|
41
|
+
mappings: { ...legacy.mappings, ...profiles.global.mappings, ...(profiles.project?.mappings || {}) },
|
|
42
|
+
warnings: [
|
|
43
|
+
...profiles.warnings,
|
|
44
|
+
...legacy.warnings,
|
|
45
|
+
...(legacy.exists && legacy.warnings.length === 0 ? [legacyWarning(legacyFile)] : []),
|
|
46
|
+
],
|
|
47
|
+
global: profiles.global,
|
|
48
|
+
project: profiles.project,
|
|
49
|
+
legacy,
|
|
50
|
+
};
|
|
46
51
|
}
|
|
47
52
|
|
|
48
53
|
export function capabilityRecommendations(storage, stage, localMappings) {
|
|
49
54
|
if (capabilityProfileMode(storage) === "off") return null;
|
|
50
55
|
if (!stage.execution_profile || !stage.execution_depth) return null;
|
|
51
|
-
const
|
|
52
|
-
const
|
|
56
|
+
const loaded = localMappings || readCapabilityMappings(storage);
|
|
57
|
+
const resolution = resolveDepth({ depth: stage.execution_depth, projectMappings: loaded.mappings });
|
|
53
58
|
return {
|
|
54
59
|
mode: "advisory",
|
|
55
|
-
execution: target
|
|
56
|
-
? { profile: stage.execution_profile, depth: stage.execution_depth, classification: stage.execution_classification || "explicit", source: "mapping", target }
|
|
60
|
+
execution: resolution.target
|
|
61
|
+
? { profile: stage.execution_profile, depth: stage.execution_depth, classification: stage.execution_classification || "explicit", source: "mapping", target: resolution.target }
|
|
57
62
|
: { profile: stage.execution_profile, depth: stage.execution_depth, classification: stage.execution_classification || "explicit", source: "current", message: "No mapping configured; continuing with the current model." },
|
|
58
63
|
...(stage.review_profile ? { review: { profile: stage.review_profile } } : {}),
|
|
59
|
-
...(warnings.length ? { warnings } : {}),
|
|
64
|
+
...(loaded.warnings.length ? { warnings: loaded.warnings } : {}),
|
|
60
65
|
};
|
|
61
66
|
}
|
|
62
67
|
|
|
@@ -73,6 +78,33 @@ export const stageCapabilityProfiles = (storage, stage, localMappings) => {
|
|
|
73
78
|
};
|
|
74
79
|
|
|
75
80
|
export function validateCapabilityMappings(mappings) {
|
|
76
|
-
|
|
77
|
-
|
|
81
|
+
try {
|
|
82
|
+
assertValidMappings(mappings);
|
|
83
|
+
return true;
|
|
84
|
+
} catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function configureCapabilityMappings(storage, mappings, options = {}) {
|
|
90
|
+
if (options.scope === "global") {
|
|
91
|
+
configureGlobal(mappings, options.homeDir ? { homeDir: options.homeDir } : {});
|
|
92
|
+
return globalConfigPath(options.homeDir);
|
|
93
|
+
}
|
|
94
|
+
if (options.scope === "project") {
|
|
95
|
+
configureProject(storage.projectRoot, mappings);
|
|
96
|
+
return projectConfigPath(storage.projectRoot);
|
|
97
|
+
}
|
|
98
|
+
const legacyFile = path.join(storage.personalRoot, CAPABILITY_MAPPINGS_FILE);
|
|
99
|
+
writeConfigFile(legacyFile, mappings, { mode: 0o600 });
|
|
100
|
+
return legacyFile;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function resetCapabilityMappings(storage, options = {}) {
|
|
104
|
+
if (options.scope === "global") {
|
|
105
|
+
return { removed: resetGlobal(options.homeDir ? { homeDir: options.homeDir } : {}), file: globalConfigPath(options.homeDir) };
|
|
106
|
+
}
|
|
107
|
+
if (options.scope === "project") return { removed: resetProject(storage.projectRoot), file: projectConfigPath(storage.projectRoot) };
|
|
108
|
+
const legacyFile = path.join(storage.personalRoot, CAPABILITY_MAPPINGS_FILE);
|
|
109
|
+
return { removed: resetConfigFile(legacyFile), file: legacyFile };
|
|
78
110
|
}
|
package/src/core.js
CHANGED
|
@@ -11,9 +11,10 @@ import { isDependencySatisfied } from "./stage-status.js";
|
|
|
11
11
|
import { CandidateStore } from "./candidates.js";
|
|
12
12
|
import { DeliveryStore } from "./delivery.js";
|
|
13
13
|
import { doctorDelivery as runDeliveryDoctor } from "./delivery-doctor.js";
|
|
14
|
-
import {
|
|
15
|
-
import { CAPABILITY_CLASSIFICATIONS, CAPABILITY_DEPTHS,
|
|
14
|
+
import { applyExecutionItemPatch, applyExecutionTextPatchItems, assertExecutionSize, EXECUTION_SECTIONS, executionInputUsesItems, executionItems, executionItemsFromState, executionPatchUsesItems, executionReadModel, normalizeExecutionItemState, normalizeExecutionState } from "./stage-execution.js";
|
|
15
|
+
import { CAPABILITY_CLASSIFICATIONS, CAPABILITY_DEPTHS, CAPABILITY_PROFILES, capabilityProfileMode, capabilityRecommendations, configureCapabilityMappings, readCapabilityMappings, resetCapabilityMappings, validateCapabilityMappings } from "./capability-profiles.js";
|
|
16
16
|
import { acknowledgeGitCommit, initializeGitCheckpoint } from "./git-acknowledgement.js";
|
|
17
|
+
import { rollbackCommitRef } from "./git-candidates.js";
|
|
17
18
|
|
|
18
19
|
const actor = (options) => options.actor || "OpenCode";
|
|
19
20
|
const workspaceMode = (data) => data.mode || "standard";
|
|
@@ -65,7 +66,15 @@ const resumePresentationInstruction = ({ confirmationRequired }) => `Before doin
|
|
|
65
66
|
- Mention previous progress only when presentation.previous_result or presentation.previous_session_summary contains useful information.
|
|
66
67
|
- State the immediate next action in one sentence.
|
|
67
68
|
${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."}`;
|
|
68
|
-
const executionInstruction = (record) =>
|
|
69
|
+
const executionInstruction = (record) => {
|
|
70
|
+
if (!record) return "";
|
|
71
|
+
const execution = executionReadModel(record);
|
|
72
|
+
const current = execution.current ? `\nCurrent checklist item: ${execution.current.text}` : "\nCurrent checklist item: none";
|
|
73
|
+
const queued = execution.queued.length
|
|
74
|
+
? `\nQueued checklist items: ${execution.queued.map((item) => item.text).join(" | ")}`
|
|
75
|
+
: "\nQueued checklist items: none";
|
|
76
|
+
return `\n\nCurrent stage execution state:${current}${queued}\n${JSON.stringify(execution, null, 2)}\nTreat this bounded stage-local ledger as the current operational checkpoint. Work only on the Current checklist item by default. Do not combine Queued items into the same change set unless the user explicitly asks. Update it after meaningful scope changes, decisions, substantial work, blockers, or verification changes, and before handoff; do not update it for trivial tool calls.`;
|
|
77
|
+
};
|
|
69
78
|
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.`;
|
|
70
79
|
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; } } };
|
|
71
80
|
|
|
@@ -240,7 +249,7 @@ export class WorkContext {
|
|
|
240
249
|
fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
|
|
241
250
|
this.storage.writeMarkdown(this.storage.workspaceFile(workspace), { schema: 1, workspace, title: title.trim(), status: "in_progress", mode, created_at: now, updated_at: now, tracker_links: [] }, body(title));
|
|
242
251
|
const planningGoal = "Clarify the work goal and constraints";
|
|
243
|
-
const planningPrompt = "Diagnose and plan the task without functional changes. Discuss possible solutions, record durable workspace-wide facts, decisions, constraints, important files, and risks through explicit knowledge operations, and decompose the work into the following stages. For each new implementation stage, write a separate detailed prompt with local context, concrete actions, constraints, completion criteria, and the expected result; do not duplicate shared knowledge that every stage receives in resume.context.workspace_knowledge. Ask clarifying questions only when genuinely blocked. Stages must remain in progress until the user explicitly requests stage finish. If the user explicitly agrees to automatic completion for this workspace, add the exact standalone line AUTO_STAGE_FINISH: allowed to this Planning-stage prompt.";
|
|
252
|
+
const planningPrompt = "Diagnose and plan the task without functional changes. Planning stage 01 is a continuously available coordination surface, never a prerequisite gate: do not make implementation, research, review, or other working stages depend on it. Discuss possible solutions, record durable workspace-wide facts, decisions, constraints, important files, and risks through explicit knowledge operations, and decompose the work into the following stages. For each new implementation stage, write a separate detailed prompt with local context, concrete actions, constraints, completion criteria, and the expected result; do not duplicate shared knowledge that every stage receives in resume.context.workspace_knowledge. Ask clarifying questions only when genuinely blocked. Stages must remain in progress until the user explicitly requests stage finish. If the user explicitly agrees to automatic completion for this workspace, add the exact standalone line AUTO_STAGE_FINISH: allowed to this Planning-stage prompt.";
|
|
244
253
|
this.storage.writeMarkdown(this.storage.stageFile(workspace, "01"), { schema: 1, workspace, stage: "01", title: "Planning", status: "in_progress", goal: planningGoal, prompt: planningPrompt, depends_on: [], owner: actor(this.options), created_at: now, updated_at: now, tracker_links: [] }, body("Planning", planningGoal, planningPrompt));
|
|
245
254
|
const sessionId = options.sessionId || randomUUID();
|
|
246
255
|
const workflowPolicy = mode === "startup" && options.opencodeSessionId ? startupWorkflowPolicy() : null;
|
|
@@ -342,6 +351,30 @@ export class WorkContext {
|
|
|
342
351
|
), { session: this.options.sessionId, owner: actor(this.options) });
|
|
343
352
|
}
|
|
344
353
|
|
|
354
|
+
inspectCommitAll(workspace, options = {}) { return { ok: true, data: this.candidates().inspectAll(workspace, options) }; }
|
|
355
|
+
|
|
356
|
+
commitAll(workspace, expectedFingerprint, confirmation, options = {}) {
|
|
357
|
+
this.storage.assertSafeRoots();
|
|
358
|
+
return withLock(this.storage.lockPath("candidate-git"), () => {
|
|
359
|
+
let publication;
|
|
360
|
+
try {
|
|
361
|
+
return this.transact("commit-all", () => this.result(this.candidates().commitAll(workspace, expectedFingerprint, confirmation, {
|
|
362
|
+
...options,
|
|
363
|
+
afterUpdateRef: (published) => { publication = published; options.afterUpdateRef?.(published); },
|
|
364
|
+
}), ["local:candidates"]));
|
|
365
|
+
} catch (error) {
|
|
366
|
+
if (publication) {
|
|
367
|
+
try { rollbackCommitRef(this.storage.projectRoot, publication); }
|
|
368
|
+
catch (rollbackError) {
|
|
369
|
+
this.candidates().write(publication.candidate_record, publication.patch);
|
|
370
|
+
throw rollbackError;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
throw error;
|
|
374
|
+
}
|
|
375
|
+
}, { session: this.options.sessionId, owner: actor(this.options) });
|
|
376
|
+
}
|
|
377
|
+
|
|
345
378
|
readDelivery(workspace, options = {}) { return { ok: true, data: this.deliveries().readContext(workspace, options) }; }
|
|
346
379
|
|
|
347
380
|
explainDelivery(workspace, from, to, findings = []) {
|
|
@@ -409,7 +442,7 @@ export class WorkContext {
|
|
|
409
442
|
const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
|
|
410
443
|
const execution = this.storage.readStageExecution(workspace, stage);
|
|
411
444
|
const automaticFinish = automaticFinishAllowed(this.storage, workspace);
|
|
412
|
-
|
|
445
|
+
const recommendations = capabilityRecommendations(this.storage, stageRecord.data, readCapabilityMappings(this.storage, { homeDir: this.options.capabilityProfilesHome }));
|
|
413
446
|
return this.result({
|
|
414
447
|
workspace,
|
|
415
448
|
stage,
|
|
@@ -431,7 +464,7 @@ export class WorkContext {
|
|
|
431
464
|
scope: stageRecord.data.prompt || null,
|
|
432
465
|
previous_result: previousResult,
|
|
433
466
|
previous_session_summary: previousSessionSummary,
|
|
434
|
-
|
|
467
|
+
...(execution ? { execution_state: executionReadModel(execution) } : {}),
|
|
435
468
|
...(recommendations ? { capability_profiles: recommendations } : {}),
|
|
436
469
|
},
|
|
437
470
|
context: {
|
|
@@ -439,7 +472,7 @@ export class WorkContext {
|
|
|
439
472
|
previous: previousSessionSummary || previousResult || "No previous progress was recorded.",
|
|
440
473
|
now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
|
|
441
474
|
workspace_knowledge: workspaceKnowledge,
|
|
442
|
-
|
|
475
|
+
...(execution ? { execution_state: executionReadModel(execution) } : {}),
|
|
443
476
|
...(recommendations ? { capability_profiles: recommendations } : {}),
|
|
444
477
|
...(pendingCandidates ? { pending_candidates: pendingCandidates } : {}),
|
|
445
478
|
...(hasDeliveryContext ? { delivery_context: deliveryContext } : {}),
|
|
@@ -471,6 +504,7 @@ export class WorkContext {
|
|
|
471
504
|
if (!Array.isArray(options.dependsOn || [])) fail(ERROR_CODES.INVALID_ARGUMENT, "dependsOn must contain unique stage IDs");
|
|
472
505
|
const dependsOn = (options.dependsOn || []).map(normalizeStageId);
|
|
473
506
|
if (new Set(dependsOn).size !== dependsOn.length) fail(ERROR_CODES.INVALID_ARGUMENT, "dependsOn must contain unique stage IDs");
|
|
507
|
+
if (dependsOn.includes("01")) fail(ERROR_CODES.PLANNING_DEPENDENCY_FORBIDDEN, "Working stages cannot depend on Planning stage 01");
|
|
474
508
|
assertCapabilityProfile(options.executionProfile, "executionProfile");
|
|
475
509
|
assertCapabilityDepth(options.executionDepth, "executionDepth");
|
|
476
510
|
assertCapabilityClassification(options.classification);
|
|
@@ -561,8 +595,8 @@ export class WorkContext {
|
|
|
561
595
|
}
|
|
562
596
|
|
|
563
597
|
showCapabilityProfiles() {
|
|
564
|
-
const local = readCapabilityMappings(this.storage);
|
|
565
|
-
return this.result({ mode: capabilityProfileMode(this.storage), mappings: local.mappings, warnings: local.warnings }, []);
|
|
598
|
+
const local = readCapabilityMappings(this.storage, { homeDir: this.options.capabilityProfilesHome });
|
|
599
|
+
return this.result({ mode: capabilityProfileMode(this.storage), mappings: local.mappings, global: local.global.mappings, project: local.project?.mappings || {}, legacy: local.legacy.mappings, warnings: local.warnings }, []);
|
|
566
600
|
}
|
|
567
601
|
|
|
568
602
|
configureCapabilityProfiles(options = {}) {
|
|
@@ -574,13 +608,7 @@ export class WorkContext {
|
|
|
574
608
|
this.storage.assertNoSymlinks();
|
|
575
609
|
const changed = [];
|
|
576
610
|
const configFile = path.join(this.storage.projectRoot, ".work-context", "config.yaml");
|
|
577
|
-
const mappingFile = path.join(this.storage.personalRoot, CAPABILITY_MAPPINGS_FILE);
|
|
578
611
|
const previousConfig = fs.readFileSync(configFile);
|
|
579
|
-
let previousMapping = null;
|
|
580
|
-
if (fs.existsSync(mappingFile)) {
|
|
581
|
-
if (!fs.lstatSync(mappingFile).isFile()) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${CAPABILITY_MAPPINGS_FILE} path`);
|
|
582
|
-
previousMapping = fs.readFileSync(mappingFile);
|
|
583
|
-
}
|
|
584
612
|
try {
|
|
585
613
|
if (options.mode !== undefined && options.mode !== capabilityProfileMode(this.storage)) {
|
|
586
614
|
const current = fs.readFileSync(configFile, "utf8");
|
|
@@ -592,30 +620,25 @@ export class WorkContext {
|
|
|
592
620
|
changed.push(configFile);
|
|
593
621
|
}
|
|
594
622
|
if (options.mappings !== undefined) {
|
|
595
|
-
|
|
623
|
+
const mappingFile = configureCapabilityMappings(this.storage, options.mappings, { scope: options.scope, homeDir: this.options.capabilityProfilesHome });
|
|
596
624
|
changed.push(mappingFile);
|
|
597
625
|
}
|
|
598
626
|
} catch (error) {
|
|
599
627
|
try { atomicWrite(configFile, previousConfig.toString("utf8")); } catch {}
|
|
600
|
-
try {
|
|
601
|
-
if (previousMapping) atomicWrite(mappingFile, previousMapping.toString("utf8"));
|
|
602
|
-
else fs.rmSync(mappingFile, { force: true });
|
|
603
|
-
} catch {}
|
|
604
628
|
throw error;
|
|
605
629
|
}
|
|
606
630
|
if (options.mode !== undefined) this.storage.config.capability_profiles.mode = options.mode;
|
|
607
|
-
const local = readCapabilityMappings(this.storage);
|
|
608
|
-
return this.result({ mode: capabilityProfileMode(this.storage), mappings: local.mappings, warnings: local.warnings }, changed);
|
|
631
|
+
const local = readCapabilityMappings(this.storage, { homeDir: this.options.capabilityProfilesHome });
|
|
632
|
+
return this.result({ mode: capabilityProfileMode(this.storage), mappings: local.mappings, global: local.global.mappings, project: local.project?.mappings || {}, legacy: local.legacy.mappings, warnings: local.warnings }, changed);
|
|
609
633
|
}, { owner: actor(this.options), session: this.options.sessionId || null });
|
|
610
634
|
}
|
|
611
635
|
|
|
612
|
-
resetCapabilityProfiles(confirmation) {
|
|
636
|
+
resetCapabilityProfiles(confirmation, options = {}) {
|
|
613
637
|
if (confirmation !== "RESET_PROFILES") fail(ERROR_CODES.CONFIRMATION_REQUIRED, "Reset requires RESET_PROFILES confirmation");
|
|
614
638
|
return this.transact("capability-profiles", () => {
|
|
615
|
-
const
|
|
616
|
-
const
|
|
617
|
-
|
|
618
|
-
return this.result({ mode: capabilityProfileMode(this.storage), mappings: {} }, existed ? [file] : []);
|
|
639
|
+
const reset = resetCapabilityMappings(this.storage, { scope: options.scope, homeDir: this.options.capabilityProfilesHome });
|
|
640
|
+
const local = readCapabilityMappings(this.storage, { homeDir: this.options.capabilityProfilesHome });
|
|
641
|
+
return this.result({ mode: capabilityProfileMode(this.storage), mappings: local.mappings, global: local.global.mappings, project: local.project?.mappings || {}, legacy: local.legacy.mappings, warnings: local.warnings }, reset.removed ? [reset.file] : []);
|
|
619
642
|
});
|
|
620
643
|
}
|
|
621
644
|
|
|
@@ -694,14 +717,13 @@ export class WorkContext {
|
|
|
694
717
|
this.storage.assertNoSymlinks();
|
|
695
718
|
this.storage.readStage(workspace, stage);
|
|
696
719
|
const record = this.storage.readStageExecution(workspace, stage);
|
|
697
|
-
return { ok: true, data: record
|
|
720
|
+
return { ok: true, data: record ? executionReadModel(record) : { schema: 1, workspace, stage, revision: 0, exists: false, ...normalizeExecutionState({}), items: Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, []])), current: null, queued: [] } };
|
|
698
721
|
}
|
|
699
722
|
|
|
700
723
|
replaceStageExecution(workspace, stage, sessionId, expectedRevision, input) {
|
|
701
724
|
workspace = normalizeWorkspaceId(workspace);
|
|
702
725
|
stage = normalizeStageId(stage);
|
|
703
726
|
if (!Number.isInteger(expectedRevision) || expectedRevision < 0) fail(ERROR_CODES.INVALID_ARGUMENT, "expectedRevision must be a non-negative integer");
|
|
704
|
-
const state = normalizeExecutionState(input);
|
|
705
727
|
return this.transact(`stage-execution-${workspace}-${stage}`, () => {
|
|
706
728
|
const stageRecord = this.storage.readStage(workspace, stage);
|
|
707
729
|
if (!["planned", "in_progress"].includes(stageRecord.data.status)) fail(ERROR_CODES.INVALID_STATE, "Execution state can only change for an actionable stage", { status: stageRecord.data.status });
|
|
@@ -709,12 +731,15 @@ export class WorkContext {
|
|
|
709
731
|
const current = this.storage.readStageExecution(workspace, stage);
|
|
710
732
|
const revision = current?.revision || 0;
|
|
711
733
|
if (revision !== expectedRevision) fail(ERROR_CODES.EXECUTION_REVISION_CONFLICT, "Stage execution state changed since it was read", { expectedRevision, actualRevision: revision });
|
|
712
|
-
|
|
734
|
+
const structured = executionInputUsesItems(input);
|
|
735
|
+
const state = structured ? null : normalizeExecutionState(input);
|
|
736
|
+
const items = structured ? normalizeExecutionItemState(input, current) : executionItemsFromState(state, current);
|
|
737
|
+
if (current && JSON.stringify(executionItems(current)) === JSON.stringify(items)) return this.result(executionReadModel(current), []);
|
|
713
738
|
const timestamp = new Date().toISOString();
|
|
714
|
-
const record = { schema:
|
|
739
|
+
const record = { schema: 2, workspace, stage, revision: revision + 1, created_at: current?.created_at || timestamp, updated_at: timestamp, updated_by: actor(this.options), items };
|
|
715
740
|
assertExecutionSize(record);
|
|
716
741
|
this.storage.writeStageExecution(workspace, stage, record);
|
|
717
|
-
return this.result(record, [this.storage.stageExecutionFile(workspace, stage)]);
|
|
742
|
+
return this.result(executionReadModel(record), [this.storage.stageExecutionFile(workspace, stage)]);
|
|
718
743
|
});
|
|
719
744
|
}
|
|
720
745
|
|
|
@@ -729,13 +754,39 @@ export class WorkContext {
|
|
|
729
754
|
const current = this.storage.readStageExecution(workspace, stage);
|
|
730
755
|
const revision = current?.revision || 0;
|
|
731
756
|
if (revision !== expectedRevision) fail(ERROR_CODES.EXECUTION_REVISION_CONFLICT, "Stage execution state changed since it was read", { expectedRevision, actualRevision: revision });
|
|
732
|
-
const
|
|
733
|
-
|
|
757
|
+
const structured = executionPatchUsesItems(patch);
|
|
758
|
+
const empty = { schema: 2, items: Object.fromEntries(EXECUTION_SECTIONS.map((section) => [section, []])) };
|
|
759
|
+
const items = structured ? applyExecutionItemPatch(current || empty, patch) : applyExecutionTextPatchItems(current || empty, patch);
|
|
760
|
+
if (current && JSON.stringify(executionItems(current)) === JSON.stringify(items)) return this.result(executionReadModel(current), []);
|
|
761
|
+
const timestamp = new Date().toISOString();
|
|
762
|
+
const record = { schema: 2, workspace, stage, revision: revision + 1, created_at: current?.created_at || timestamp, updated_at: timestamp, updated_by: actor(this.options), items };
|
|
763
|
+
assertExecutionSize(record);
|
|
764
|
+
this.storage.writeStageExecution(workspace, stage, record);
|
|
765
|
+
return this.result(executionReadModel(record), [this.storage.stageExecutionFile(workspace, stage)]);
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
completeCurrentExecution(workspace, stage, sessionId, expectedRevision) {
|
|
770
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
771
|
+
stage = normalizeStageId(stage);
|
|
772
|
+
if (!Number.isInteger(expectedRevision) || expectedRevision < 0) fail(ERROR_CODES.INVALID_ARGUMENT, "expectedRevision must be a non-negative integer");
|
|
773
|
+
return this.transact(`stage-execution-${workspace}-${stage}`, () => {
|
|
774
|
+
const stageRecord = this.storage.readStage(workspace, stage);
|
|
775
|
+
if (!["planned", "in_progress"].includes(stageRecord.data.status)) fail(ERROR_CODES.INVALID_STATE, "Execution state can only change for an actionable stage", { status: stageRecord.data.status });
|
|
776
|
+
assertActive(this.storage.readEvents(), workspace, stage, sessionId);
|
|
777
|
+
const current = this.storage.readStageExecution(workspace, stage);
|
|
778
|
+
const revision = current?.revision || 0;
|
|
779
|
+
if (revision !== expectedRevision) fail(ERROR_CODES.EXECUTION_REVISION_CONFLICT, "Stage execution state changed since it was read", { expectedRevision, actualRevision: revision });
|
|
780
|
+
const items = current && executionItems(current);
|
|
781
|
+
const currentItem = items?.remaining.shift();
|
|
782
|
+
if (!currentItem) fail(ERROR_CODES.INVALID_STATE, "No current execution item to complete");
|
|
783
|
+
items.completed.push(currentItem);
|
|
784
|
+
const nextItems = normalizeExecutionItemState(items, current);
|
|
734
785
|
const timestamp = new Date().toISOString();
|
|
735
|
-
const record = { schema:
|
|
786
|
+
const record = { schema: 2, workspace, stage, revision: revision + 1, created_at: current.created_at, updated_at: timestamp, updated_by: actor(this.options), items: nextItems };
|
|
736
787
|
assertExecutionSize(record);
|
|
737
788
|
this.storage.writeStageExecution(workspace, stage, record);
|
|
738
|
-
return this.result(record, [this.storage.stageExecutionFile(workspace, stage)]);
|
|
789
|
+
return this.result(executionReadModel(record), [this.storage.stageExecutionFile(workspace, stage)]);
|
|
739
790
|
});
|
|
740
791
|
}
|
|
741
792
|
|
|
@@ -967,10 +1018,11 @@ export class WorkContext {
|
|
|
967
1018
|
if (!['auto', 'added', 'none'].includes(knowledgeReview)) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge review must be 'auto', 'added' or 'none'");
|
|
968
1019
|
const knowledgeEntries = this.listKnowledge(workspace).data;
|
|
969
1020
|
const execution = this.storage.readStageExecution(workspace, stage);
|
|
970
|
-
const
|
|
971
|
-
|
|
972
|
-
...(
|
|
973
|
-
...(
|
|
1021
|
+
const executionData = execution ? executionReadModel(execution) : null;
|
|
1022
|
+
const executionWarnings = executionData ? [
|
|
1023
|
+
...(executionData.remaining.length ? [`${executionData.remaining.length} remaining item(s)`] : []),
|
|
1024
|
+
...(executionData.blockers.length ? [`${executionData.blockers.length} blocker(s) or open question(s)`] : []),
|
|
1025
|
+
...(executionData.verification.length ? [`${executionData.verification.length} pending verification item(s)`] : []),
|
|
974
1026
|
] : [];
|
|
975
1027
|
const active = activeSession(events, workspace, stage);
|
|
976
1028
|
if (!active || active.session_id !== sessionId) fail(active ? ERROR_CODES.ACTIVE_SESSION_EXISTS : ERROR_CODES.SESSION_NOT_ACTIVE, active ? "Another active session owns this stage" : "Session is not active");
|
|
@@ -982,7 +1034,7 @@ export class WorkContext {
|
|
|
982
1034
|
const promptReview = this.listStages(workspace).data.stages
|
|
983
1035
|
.filter((item) => Number(item.stage) > Number(stage) && !["completed", "archived"].includes(item.status))
|
|
984
1036
|
.map(({ stage: id, title, description, prompt, status }) => ({ stage: id, title, description, prompt: prompt || null, status }));
|
|
985
|
-
const data = { session_id: sessionId, workspace, stage, state: "closed", status: "completed", next_stage_started: false, knowledge_review: knowledgeReview, knowledge_entries: knowledgeEntries.length, active_knowledge_entries: activeKnowledge(knowledgeEntries).length, prompt_review: promptReview, ...(
|
|
1037
|
+
const data = { session_id: sessionId, workspace, stage, state: "closed", status: "completed", next_stage_started: false, knowledge_review: knowledgeReview, knowledge_entries: knowledgeEntries.length, active_knowledge_entries: activeKnowledge(knowledgeEntries).length, prompt_review: promptReview, ...(executionData ? { execution_state: executionData, execution_warnings: executionWarnings } : {}) };
|
|
986
1038
|
const incompleteStages = this.listStages(workspace).data.stages.filter((item) => !["completed", "archived"].includes(item.status));
|
|
987
1039
|
const next = incompleteStages.length ? null : {
|
|
988
1040
|
action: "workspace_finish",
|
|
@@ -997,7 +1049,7 @@ export class WorkContext {
|
|
|
997
1049
|
help(command = "") {
|
|
998
1050
|
return this.result({
|
|
999
1051
|
command,
|
|
1000
|
-
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 explain|delivery doctor|delivery mark|profiles show|profiles setup|profiles reset|workspace finish|workspace reopen|resume|stage add|stage profiles|stage profiles refresh|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage execution read|stage execution replace|stage execution update|stage 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]",
|
|
1052
|
+
syntax: "/wc [create|list|workspace list|workspace rename|workspace mode|candidate create|candidate capture|candidate preview|candidate show|candidate list|candidate ready|candidate commit|candidate discard|commit all|commit all confirm|delivery read|delivery explain|delivery doctor|delivery mark|profiles show|profiles setup|profiles reset|workspace finish|workspace reopen|resume|stage add|stage profiles|stage profiles refresh|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage execution read|stage execution replace|stage execution update|stage execution complete-current|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|unlink-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
|
|
1001
1053
|
note: "execution recommendations combine a vendor-neutral capability with light, standard, or deep depth; Planning agents infer missing values before stage creation, ordinary refresh updates missing/inferred classifications while preserving explicit assignments, and local depth mappings resolve only an advisory model label; profiles setup gathers mode and mappings through questions, off mode suppresses presentation and resolution, and no profile operation changes a model, agent, reviewer, or session; delivery context is workspace-level local operational state; exact Git range inspection runs only for explicit immutable hashes; stage execution state is a bounded stage-local operational checkpoint; associated startup sessions receive the shared-worktree candidate policy; stage finish requires an explicit user lifecycle request unless Planning contains AUTO_STAGE_FINISH: allowed; recovery operations preserve lifecycle history.",
|
|
1002
1054
|
}, []);
|
|
1003
1055
|
}
|
package/src/errors.js
CHANGED
|
@@ -13,10 +13,14 @@ export const ERROR_CODES = Object.freeze({
|
|
|
13
13
|
CANDIDATE_UNSUPPORTED: "CANDIDATE_UNSUPPORTED", CANDIDATE_STALE_BASE: "CANDIDATE_STALE_BASE",
|
|
14
14
|
CANDIDATE_CONFLICT: "CANDIDATE_CONFLICT", CANDIDATE_DETACHED_HEAD: "CANDIDATE_DETACHED_HEAD",
|
|
15
15
|
CANDIDATE_REF_RACE: "CANDIDATE_REF_RACE", CANDIDATE_COMMIT_FAILED: "CANDIDATE_COMMIT_FAILED",
|
|
16
|
+
COMMIT_ALL_CONFIRMATION_REQUIRED: "COMMIT_ALL_CONFIRMATION_REQUIRED", COMMIT_ALL_NO_CHANGES: "COMMIT_ALL_NO_CHANGES",
|
|
17
|
+
COMMIT_ALL_UNSAFE_STATE: "COMMIT_ALL_UNSAFE_STATE", COMMIT_ALL_INCOHERENT_BOUNDARY: "COMMIT_ALL_INCOHERENT_BOUNDARY",
|
|
18
|
+
COMMIT_ALL_STALE_PLAN: "COMMIT_ALL_STALE_PLAN", COMMIT_ALL_VERIFICATION_FAILED: "COMMIT_ALL_VERIFICATION_FAILED",
|
|
16
19
|
EXECUTION_REVISION_CONFLICT: "EXECUTION_REVISION_CONFLICT", EXECUTION_LIMIT_EXCEEDED: "EXECUTION_LIMIT_EXCEEDED",
|
|
17
20
|
DELIVERY_INVALID_RANGE: "DELIVERY_INVALID_RANGE", DELIVERY_RANGE_TOO_LARGE: "DELIVERY_RANGE_TOO_LARGE",
|
|
18
21
|
DELIVERY_INVALID_FINDINGS: "DELIVERY_INVALID_FINDINGS", DELIVERY_DIAGNOSTIC_TOO_LARGE: "DELIVERY_DIAGNOSTIC_TOO_LARGE",
|
|
19
22
|
DELIVERY_COMMAND_PROTOCOL_MISMATCH: "DELIVERY_COMMAND_PROTOCOL_MISMATCH",
|
|
23
|
+
PLANNING_DEPENDENCY_FORBIDDEN: "PLANNING_DEPENDENCY_FORBIDDEN",
|
|
20
24
|
});
|
|
21
25
|
|
|
22
26
|
export class WorkContextError extends Error {
|
package/src/git-candidates.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import os from "node:os";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
4
5
|
import { spawnSync } from "node:child_process";
|
|
5
6
|
import { ERROR_CODES, fail } from "./errors.js";
|
|
6
7
|
|
|
@@ -119,6 +120,104 @@ const patchFromIndex = (root, base, env) => {
|
|
|
119
120
|
return result.stdout;
|
|
120
121
|
};
|
|
121
122
|
|
|
123
|
+
const nulPaths = (value) => value.toString("utf8").split("\0").filter(Boolean);
|
|
124
|
+
const unsafeName = (relative) => {
|
|
125
|
+
const parts = relative.split("/");
|
|
126
|
+
const name = parts.at(-1).toLowerCase();
|
|
127
|
+
if (parts.some((part) => ["node_modules", "coverage", ".cache", ".next", ".nuxt", ".output", "vendor"].includes(part))
|
|
128
|
+
|| ["dist", "build", "tmp"].includes(parts[0]) || /\.(?:log|tmp|swp)$/.test(name)) return "generated_or_local";
|
|
129
|
+
if (relative === ".work-context/local" || relative.startsWith(".work-context/local/")) return "local_only";
|
|
130
|
+
if (name === ".env" || name.startsWith(".env.") || /(?:^|[._-])(secret|secrets|credential|credentials|private)(?:[._-]|$)/.test(name)
|
|
131
|
+
|| /\.(?:pem|key|p12|pfx)$/i.test(name) || ["id_rsa", "id_ed25519"].includes(name)) return "potential_secret";
|
|
132
|
+
return null;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
const secretContent = (root, relative) => {
|
|
136
|
+
const absolute = path.join(root, relative);
|
|
137
|
+
let stat;
|
|
138
|
+
try { stat = fs.statSync(absolute); } catch (error) { if (error.code === "ENOENT") return false; throw error; }
|
|
139
|
+
if (!stat.isFile() || stat.size > 1024 * 1024) return false;
|
|
140
|
+
const content = fs.readFileSync(absolute);
|
|
141
|
+
if (content.includes(0)) return false;
|
|
142
|
+
const text = content.toString("utf8");
|
|
143
|
+
return /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(text)
|
|
144
|
+
|| /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/.test(text)
|
|
145
|
+
|| /\b(?:ghp|github_pat|glpat)-?[A-Za-z0-9_]{20,}\b/.test(text)
|
|
146
|
+
|| /(?:api[_-]?key|access[_-]?token|client[_-]?secret|password)\s*[:=]\s*["']?(?!example|placeholder|changeme)[A-Za-z0-9_+/.=-]{12,}/i.test(text);
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
function nestedRepository(root, relative) {
|
|
150
|
+
let absolute = path.join(root, relative);
|
|
151
|
+
while (absolute !== root) {
|
|
152
|
+
if (fs.existsSync(absolute) && fs.statSync(absolute).isDirectory()) {
|
|
153
|
+
const result = git(absolute, ["rev-parse", "--show-toplevel"], { allowFailure: true });
|
|
154
|
+
if (result.status === 0 && fs.realpathSync(result.stdout.trim()) !== root) return true;
|
|
155
|
+
}
|
|
156
|
+
absolute = path.dirname(absolute);
|
|
157
|
+
}
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const gitOperation = (root) => {
|
|
162
|
+
const result = git(root, ["rev-parse", "--git-dir"], { allowFailure: true });
|
|
163
|
+
if (result.status !== 0) return "unknown";
|
|
164
|
+
const directory = path.resolve(root, result.stdout.trim());
|
|
165
|
+
return ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "BISECT_LOG", "rebase-apply", "rebase-merge", "sequencer"]
|
|
166
|
+
.find((entry) => fs.existsSync(path.join(directory, entry))) || null;
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
const explicitExclusion = (relative, exclusions) => exclusions.some((item) => relative === item || relative.startsWith(`${item}/`));
|
|
170
|
+
|
|
171
|
+
export function inspectCommitAll(root, personalRoot, options = {}) {
|
|
172
|
+
const repository = repositoryState(root);
|
|
173
|
+
const readOnlyEnv = { GIT_OPTIONAL_LOCKS: "0" };
|
|
174
|
+
const operation = gitOperation(repository.root);
|
|
175
|
+
if (operation) fail(ERROR_CODES.COMMIT_ALL_UNSAFE_STATE, "Commit all is unavailable while another Git operation is in progress", { operation });
|
|
176
|
+
const unmerged = git(repository.root, ["ls-files", "--unmerged", "-z"], { encoding: null, env: readOnlyEnv }).stdout;
|
|
177
|
+
if (unmerged.length) fail(ERROR_CODES.COMMIT_ALL_UNSAFE_STATE, "Commit all is unavailable while the Git index contains unresolved conflicts");
|
|
178
|
+
const explicitExclusions = options.excludePaths?.length ? normalizeCandidatePaths(repository.root, personalRoot, options.excludePaths) : [];
|
|
179
|
+
const changed = nulPaths(git(repository.root, ["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--name-only", "-z", "HEAD", "--"], { encoding: null, env: readOnlyEnv }).stdout);
|
|
180
|
+
const untracked = nulPaths(git(repository.root, ["ls-files", "--others", "--exclude-standard", "-z"], { encoding: null, env: readOnlyEnv }).stdout);
|
|
181
|
+
const gitlinks = new Set(nulPaths(git(repository.root, ["ls-files", "--stage", "-z"], { encoding: null, env: readOnlyEnv }).stdout)
|
|
182
|
+
.filter((entry) => entry.startsWith("160000 ")).map((entry) => entry.slice(entry.indexOf("\t") + 1)));
|
|
183
|
+
const included = [];
|
|
184
|
+
const excluded = [];
|
|
185
|
+
for (const relative of [...new Set([...changed, ...untracked])].sort()) {
|
|
186
|
+
if ([".work-context/.locks", ".work-context/.transactions"].some((item) => relative === item || relative.startsWith(`${item}/`))) continue;
|
|
187
|
+
if (relative === ".work-context/local" || relative.startsWith(".work-context/local/")) {
|
|
188
|
+
excluded.push({ path: relative, reason: "local_only" });
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
const normalized = normalizeCandidatePaths(repository.root, personalRoot, [relative])[0];
|
|
192
|
+
const reason = explicitExclusion(normalized, explicitExclusions) ? "user_excluded"
|
|
193
|
+
: normalized === ".gitmodules" && gitlinks.size ? "submodule_metadata"
|
|
194
|
+
: gitlinks.has(normalized) || [...gitlinks].some((gitlink) => normalized.startsWith(`${gitlink}/`))
|
|
195
|
+
? "submodule"
|
|
196
|
+
: nestedRepository(repository.root, normalized) ? "nested_repository" : unsafeName(normalized) || (secretContent(repository.root, normalized) ? "potential_secret" : null);
|
|
197
|
+
if (reason) excluded.push({ path: normalized, reason });
|
|
198
|
+
else included.push(normalized);
|
|
199
|
+
}
|
|
200
|
+
if (!included.length) return { repository_root: repository.root, base_head: repository.head, included_paths: [], excluded_paths: excluded, patch: "", patch_fingerprint: null, stat: "" };
|
|
201
|
+
let captured;
|
|
202
|
+
try { captured = capturePaths(repository.root, personalRoot, repository.head, included); }
|
|
203
|
+
catch (error) {
|
|
204
|
+
if (error.code === ERROR_CODES.CANDIDATE_UNSUPPORTED) fail(ERROR_CODES.COMMIT_ALL_INCOHERENT_BOUNDARY, "Commit-all changes cannot form one supported text patch", { cause: error.message });
|
|
205
|
+
throw error;
|
|
206
|
+
}
|
|
207
|
+
const preview = previewPatch(repository.root, repository.head, captured.patch);
|
|
208
|
+
if (preview.patch !== captured.patch) fail(ERROR_CODES.COMMIT_ALL_VERIFICATION_FAILED, "Commit-all preview did not reproduce the inspected patch");
|
|
209
|
+
return {
|
|
210
|
+
repository_root: repository.root,
|
|
211
|
+
base_head: repository.head,
|
|
212
|
+
included_paths: captured.paths,
|
|
213
|
+
excluded_paths: excluded,
|
|
214
|
+
patch: captured.patch,
|
|
215
|
+
patch_fingerprint: createHash("sha256").update(captured.patch).digest("hex"),
|
|
216
|
+
stat: preview.stat,
|
|
217
|
+
recent_subjects: git(repository.root, ["log", "-5", "--format=%s"], { env: readOnlyEnv }).stdout.trim().split("\n").filter(Boolean),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
122
221
|
export function normalizeCandidatePaths(root, personalRoot, values) {
|
|
123
222
|
if (!Array.isArray(values) || !values.length) fail(ERROR_CODES.INVALID_ARGUMENT, "At least one path is required");
|
|
124
223
|
const personal = fs.existsSync(personalRoot) ? fs.realpathSync(personalRoot) : path.resolve(personalRoot);
|
|
@@ -173,6 +272,7 @@ export function commitPatch(root, base, patchText, message, options = {}) {
|
|
|
173
272
|
rejectUnsupportedPatch(patchText);
|
|
174
273
|
if (typeof message !== "string" || !message.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Commit message is required");
|
|
175
274
|
const repository = repositoryState(root);
|
|
275
|
+
if (options.expectedHead && repository.head !== options.expectedHead) fail(ERROR_CODES.COMMIT_ALL_STALE_PLAN, "Git HEAD no longer matches the confirmed commit-all plan", { expected_head: options.expectedHead, actual_head: repository.head });
|
|
176
276
|
const branch = currentBranch(repository.root);
|
|
177
277
|
const baseCheck = git(repository.root, ["cat-file", "-e", `${base}^{commit}`], { allowFailure: true });
|
|
178
278
|
if (baseCheck.status !== 0) fail(ERROR_CODES.CANDIDATE_STALE_BASE, "Candidate base commit is unavailable", { base });
|
|
@@ -201,6 +301,18 @@ export function commitPatch(root, base, patchText, message, options = {}) {
|
|
|
201
301
|
expectedHead: repository.head,
|
|
202
302
|
stderr: updated.stderr.trim(),
|
|
203
303
|
});
|
|
204
|
-
|
|
304
|
+
const publication = { branch, previous_head: repository.head, commit, stale: repository.head !== base };
|
|
305
|
+
options.afterUpdateRef?.(publication);
|
|
306
|
+
return publication;
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export function rollbackCommitRef(root, publication) {
|
|
311
|
+
const repository = repositoryState(root);
|
|
312
|
+
const updated = git(repository.root, ["update-ref", publication.branch, publication.previous_head, publication.commit], { allowFailure: true });
|
|
313
|
+
if (updated.status !== 0) fail(ERROR_CODES.CANDIDATE_REF_RACE, "Cannot roll back a candidate commit after a storage failure", {
|
|
314
|
+
branch: publication.branch,
|
|
315
|
+
expectedHead: publication.commit,
|
|
316
|
+
stderr: updated.stderr.trim(),
|
|
205
317
|
});
|
|
206
318
|
}
|
package/src/protocol.js
CHANGED
|
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
|
|
|
3
3
|
export const WORK_CONTEXT_PROTOCOL = Object.freeze({
|
|
4
4
|
schema: 1,
|
|
5
5
|
major: 1,
|
|
6
|
-
minor:
|
|
6
|
+
minor: 3,
|
|
7
7
|
});
|
|
8
8
|
|
|
9
9
|
export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR = Object.freeze({
|
|
@@ -13,7 +13,7 @@ export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR = Object.freeze({
|
|
|
13
13
|
major: WORK_CONTEXT_PROTOCOL.major,
|
|
14
14
|
minor: WORK_CONTEXT_PROTOCOL.minor,
|
|
15
15
|
}),
|
|
16
|
-
operations: Object.freeze(["delivery.doctor", "commit.acknowledge"]),
|
|
16
|
+
operations: Object.freeze(["delivery.doctor", "commit.acknowledge", "commit.inspect_all", "commit.all", "execution.complete_current"]),
|
|
17
17
|
});
|
|
18
18
|
|
|
19
19
|
export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR_BYTES = JSON.stringify(WORK_CONTEXT_PROTOCOL_DESCRIPTOR);
|