harness-everything 0.50.0 → 0.52.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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.github/workflows/ci.yml +23 -0
- package/CHANGELOG.md +174 -115
- package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-a-evid-001.md +123 -0
- package/benchmarks/results/doc-evidence-e1/cycle-2026-11-11-b-route-001.md +130 -0
- package/ci/mechanism-2am-observations-session-import.test.js +4 -1
- package/ci/mechanism-34-observations.test.js +127 -23
- package/ci/mechanism-349-ci-change-scope.test.js +260 -0
- package/ci/mechanism-handoff-file.test.js +121 -0
- package/ci/mechanism-prb-outline-review.test.js +783 -107
- package/ci/mechanism-system-one-contract.test.js +9 -2
- package/ci/mechanism-system-one-curves.test.js +206 -0
- package/ci/mechanism-system-one-cycle.test.js +585 -0
- package/ci/mechanism-system-one-evaluation.test.js +32 -5
- package/ci/mechanism-system-one-handoff-input.test.js +208 -0
- package/ci/mechanism-system-one-install.test.js +202 -77
- package/ci/mechanism-system-one-live.test.js +361 -0
- package/ci/mechanism-system-one-relevance.test.js +11 -1
- package/ci/mechanism-system-one-train.test.js +136 -53
- package/ci/release-unreleased-heading.test.js +24 -0
- package/ci/system-one-adapter-test.py +331 -0
- package/ci/system-one-train-test.py +116 -24
- package/docs/adr/EVID-001.md +123 -0
- package/docs/adr/ROUTE-001-error-lesson-delivery.md +305 -0
- package/docs/doc-workflow-reconciliation.md +29 -16
- package/docs/governed-index.md +2 -0
- package/docs/platform-capabilities.md +2 -0
- package/docs/routing.md +2 -2
- package/docs/system-one-cycle.md +68 -0
- package/docs/system-one-observations.md +9 -8
- package/docs/system-one-routing.md +163 -115
- package/docs/system-one-suggestion-gates.md +6 -8
- package/docs/system-one-training.md +44 -7
- package/docs/workflow-runtime.md +19 -0
- package/harness-everything/SKILL.md +1 -1
- package/harness-everything/scripts/kernel-router.js +2 -1
- package/harness-everything/scripts/system-one/contract.js +19 -15
- package/harness-everything/scripts/system-one/cua_adapter.py +211 -17
- package/harness-everything/scripts/system-one/evaluate.js +4 -9
- package/harness-everything/scripts/system-one/handoff-input.js +76 -0
- package/harness-everything/scripts/system-one/install.js +281 -113
- package/harness-everything/scripts/system-one/manifest.js +58 -0
- package/harness-everything/scripts/system-one/provider.js +96 -2
- package/harness-everything/scripts/system-one/resident.js +47 -1
- package/harness-everything/scripts/system-one/router.js +80 -1
- package/harness-everything/scripts/tier-router.js +21 -6
- package/hooks/scripts/lib/doc-reconciliation-pilot.js +12 -0
- package/hooks/scripts/lib/doc-reconciliation-provider.js +575 -12
- package/hooks/scripts/lib/observations.js +43 -4
- package/hooks/scripts/lib/workflow-obligations.js +8 -4
- package/hooks/scripts/state-persist.js +26 -7
- package/hooks/scripts/w6-state-operations.js +239 -0
- package/opencode-plugin/plugin.json +1 -1
- package/package.json +2 -2
- package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-pilot.js +12 -0
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-provider.js +575 -12
- package/plugins/harness-everything/hooks/scripts/lib/observations.js +43 -4
- package/plugins/harness-everything/hooks/scripts/lib/workflow-obligations.js +8 -4
- package/plugins/harness-everything/hooks/scripts/state-persist.js +26 -7
- package/plugins/harness-everything/hooks/scripts/w6-state-operations.js +239 -0
- package/plugins/harness-everything/plugin.json +1 -1
- package/plugins/harness-everything/scripts/handoff-file.js +223 -0
- package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +2 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/contract.js +19 -15
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +211 -17
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/evaluate.js +4 -9
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/handoff-input.js +76 -0
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +281 -113
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +58 -0
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +96 -2
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/resident.js +47 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/router.js +80 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +21 -6
- package/sbom.cdx.json +7 -7
- package/scripts/ci-change-scope.js +59 -0
- package/scripts/handoff-file.js +223 -0
- package/scripts/sync-openai-plugin.js +4 -0
- package/scripts/system-one-calibrate.js +108 -41
- package/scripts/system-one-curves.js +332 -0
- package/scripts/system-one-cycle/adjudication-input.js +65 -0
- package/scripts/system-one-cycle/build.js +165 -0
- package/scripts/system-one-cycle/collect.js +50 -0
- package/scripts/system-one-cycle/common.js +137 -0
- package/scripts/system-one-cycle/engines.js +62 -0
- package/scripts/system-one-cycle/evaluate.js +70 -0
- package/scripts/system-one-cycle/judge.js +106 -0
- package/scripts/system-one-cycle/label.js +59 -0
- package/scripts/system-one-cycle/package.js +173 -0
- package/scripts/system-one-cycle/score.py +111 -0
- package/scripts/system-one-cycle/train.js +136 -0
- package/scripts/system-one-cycle.js +131 -0
- package/scripts/system-one-observations-export.js +29 -6
- package/scripts/system-one-observations-review.js +4 -5
- package/scripts/system-one-train.py +117 -61
|
@@ -58,7 +58,7 @@ function tailBytes(text, bytes) {
|
|
|
58
58
|
|
|
59
59
|
function validLabel(raw) {
|
|
60
60
|
if (!raw || typeof raw !== 'object' || raw.v !== 1) return false;
|
|
61
|
-
if (!VALIDITY.includes(raw.validity)
|
|
61
|
+
if (!VALIDITY.includes(raw.validity)) return false;
|
|
62
62
|
if (!(raw.tier === null || TIERS.includes(raw.tier))) return false;
|
|
63
63
|
if (!Array.isArray(raw.intents) || raw.intents.length > 6 || !raw.intents.every(i => typeof i === 'string')) return false;
|
|
64
64
|
const known = raw.intents.filter(i => INTENTS.includes(i));
|
|
@@ -79,7 +79,7 @@ function parseLabelLine(text) {
|
|
|
79
79
|
if (!validLabel(raw)) return { label: null, reason: 'label-invalid' };
|
|
80
80
|
// Unknown intent ids are dropped, not fatal: the rest of the label is still the agent's judgement.
|
|
81
81
|
const unknownIntents = raw.intents.filter(i => !INTENTS.includes(i));
|
|
82
|
-
const label = { v: 1, validity: raw.validity,
|
|
82
|
+
const label = { v: 1, validity: raw.validity, tier: raw.tier,
|
|
83
83
|
intents: raw.intents.filter(i => INTENTS.includes(i)), workflow: raw.workflow, skills: raw.skills.map(skillName) };
|
|
84
84
|
if (unknownIntents.length) label.unknownIntents = unknownIntents;
|
|
85
85
|
return { label, reason: null };
|
|
@@ -352,6 +352,44 @@ function detectHost(payload, hints) {
|
|
|
352
352
|
return 'unknown';
|
|
353
353
|
}
|
|
354
354
|
|
|
355
|
+
function normalizeSystemOne(value) {
|
|
356
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
357
|
+
const fields = ['version', 'sha256', 'mode', 'validity', 'intents', 'tier', 'decision'];
|
|
358
|
+
if (!fields.every(key => Object.hasOwn(value, key))
|
|
359
|
+
|| typeof value.version !== 'string' || !value.version.trim()
|
|
360
|
+
|| typeof value.sha256 !== 'string' || !/^[a-f\d]{16}$/i.test(value.sha256)
|
|
361
|
+
|| !['off', 'live'].includes(value.mode)) return null;
|
|
362
|
+
|
|
363
|
+
const invalid = Symbol('invalid-system-one');
|
|
364
|
+
const probabilities = (source, allowed, limit = 12) => {
|
|
365
|
+
if (source === null) return null;
|
|
366
|
+
if (!source || typeof source !== 'object' || Array.isArray(source)) return invalid;
|
|
367
|
+
const entries = Object.entries(source).filter(([key]) => !allowed || allowed.has(key)).slice(0, limit);
|
|
368
|
+
const bounded = [];
|
|
369
|
+
for (const [key, score] of entries) {
|
|
370
|
+
if (!key || !Number.isFinite(score)) return invalid;
|
|
371
|
+
bounded.push([key.slice(0, 64), Math.max(0, Math.min(1, score))]);
|
|
372
|
+
}
|
|
373
|
+
return Object.fromEntries(bounded);
|
|
374
|
+
};
|
|
375
|
+
const validity = probabilities(value.validity, new Set(['invalid']), 1);
|
|
376
|
+
const intents = probabilities(value.intents, null);
|
|
377
|
+
const tier = probabilities(value.tier, new Set(TIERS), TIERS.length);
|
|
378
|
+
const decision = value.decision;
|
|
379
|
+
if (validity === invalid || intents === invalid || tier === invalid
|
|
380
|
+
|| !decision || typeof decision !== 'object' || Array.isArray(decision)
|
|
381
|
+
|| !['actionable', 'invalid', 'abstain'].includes(decision.validity)
|
|
382
|
+
|| !Array.isArray(decision.intents)
|
|
383
|
+
|| !decision.intents.every(id => typeof id === 'string' && id.length > 0)
|
|
384
|
+
|| !(decision.tier === null || TIERS.includes(decision.tier))) return null;
|
|
385
|
+
|
|
386
|
+
return {
|
|
387
|
+
version: value.version.slice(0, 64), sha256: value.sha256.toLowerCase(), mode: value.mode,
|
|
388
|
+
validity, intents, tier,
|
|
389
|
+
decision: { validity: decision.validity, intents: decision.intents.slice(0, 12).map(id => id.slice(0, 64)), tier: decision.tier },
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
|
|
355
393
|
function routerState(payload) {
|
|
356
394
|
try {
|
|
357
395
|
const state = require('./harness-state');
|
|
@@ -364,7 +402,8 @@ function routerState(payload) {
|
|
|
364
402
|
const plan = run.workflowPlan && typeof run.workflowPlan === 'object' ? run.workflowPlan : run;
|
|
365
403
|
return { tier: plan.tier || run.tier || null, strategy: plan.strategy || run.strategy || null,
|
|
366
404
|
strategySelection: plan.strategySelection || run.strategySelection || null,
|
|
367
|
-
suggestedSkills: Array.isArray(plan.suggestedSkills) ? plan.suggestedSkills.slice(0, 12) : []
|
|
405
|
+
suggestedSkills: Array.isArray(plan.suggestedSkills) ? plan.suggestedSkills.slice(0, 12) : [],
|
|
406
|
+
systemOne: normalizeSystemOne(plan.systemOne) };
|
|
368
407
|
} catch (_) {
|
|
369
408
|
return null;
|
|
370
409
|
}
|
|
@@ -651,7 +690,7 @@ function handle(payload, env = process.env) {
|
|
|
651
690
|
}
|
|
652
691
|
|
|
653
692
|
module.exports = {
|
|
654
|
-
INTENTS, TIERS, STRATEGIES, RETENTION_MS, PREVIOUS_BYTES, enabled, storeRoot, redact, parseLabelLine, stripLabels, tailBytes, sha, classifyCommand, labelTier, contradictions,
|
|
693
|
+
INTENTS, TIERS, STRATEGIES, RETENTION_MS, PREVIOUS_BYTES, enabled, storeRoot, redact, parseLabelLine, stripLabels, tailBytes, sha, normalizeSystemOne, classifyCommand, labelTier, contradictions,
|
|
655
694
|
normalizeTerms, transcriptMessage, recordTool, emptyBehavior, mergeBehavior, toolFailed, handle, readJson, appendRecord, appendRecordDetailed, observationTurnMatch, findObservationTurnMatch, markSessionBackfillBehaviorUnobserved,
|
|
656
695
|
expired, recordText, sweep,
|
|
657
696
|
};
|
|
@@ -668,10 +668,14 @@ function updateStep(context, stepId, disposition, options = {}) {
|
|
|
668
668
|
throw new Error('resolve active-step bindings before passing the step: ' + ids.join(', '));
|
|
669
669
|
}
|
|
670
670
|
}
|
|
671
|
-
if (disposition === 'pass' && step.stepType === 'verification'
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
671
|
+
if (disposition === 'pass' && step.stepType === 'verification') {
|
|
672
|
+
const inFlightW6ToolUseId = require('./doc-reconciliation-provider').pendingW6VerificationInvocation(context);
|
|
673
|
+
const assessment = require('./doc-reconciliation-pilot').assess(context, loaded.set,
|
|
674
|
+
inFlightW6ToolUseId ? { allowInFlightW6ToolUseId: inFlightW6ToolUseId } : {});
|
|
675
|
+
if (assessment.withhold) {
|
|
676
|
+
withholdPilotVerification(context, loaded.set);
|
|
677
|
+
throw new Error('document verification pending: S1 grants no document credit');
|
|
678
|
+
}
|
|
675
679
|
}
|
|
676
680
|
// Review-mode refusal (pilot ON only): a self-authored or non-independent review PASS stays pending.
|
|
677
681
|
if (disposition === 'pass' && step.stepType === 'review') {
|
|
@@ -86,6 +86,8 @@ function processState(payload) {
|
|
|
86
86
|
const isSuccessEvent = hookEvent === 'PostToolUse';
|
|
87
87
|
const isFailed = hookEvent === 'PostToolUseFailure' || (exitCode !== undefined && exitCode !== 0) || (!isSuccessEvent && exitCode === undefined && stderrSignal);
|
|
88
88
|
const toolName = payload.tool_name || payload.tool || 'command';
|
|
89
|
+
let editAfterCapture = false;
|
|
90
|
+
let stateOnlyCandidate = false;
|
|
89
91
|
if (isFailed) {
|
|
90
92
|
let output = (stderrSignal ? stderr : stdout) || payload.output || '';
|
|
91
93
|
if (output.length > 500) output = '...' + output.slice(-500);
|
|
@@ -99,20 +101,26 @@ function processState(payload) {
|
|
|
99
101
|
const command = (payload.tool_input && payload.tool_input.command) || '';
|
|
100
102
|
if (isShell) {
|
|
101
103
|
const commandClass = classifyShell(command);
|
|
102
|
-
const
|
|
104
|
+
const pilotEnabled = process.env.HARNESS_DOC_RECONCILIATION_PILOT === '1';
|
|
105
|
+
const docCheck = pilotEnabled ? require('./lib/doc-reconciliation-provider') : null;
|
|
106
|
+
stateOnlyCandidate = Boolean(docCheck && typeof payload.cwd === 'string' && payload.cwd
|
|
107
|
+
&& docCheck.isW6StateCommand(command, payload.cwd, root,
|
|
108
|
+
{ toolName, sessionId, agentId: payload.agent_id }));
|
|
109
|
+
const metadataStep = !stateOnlyCandidate && !isFailed && (isSuccessEvent || exitCode === 0)
|
|
103
110
|
&& isSuccessfulMetadataStep(command, cwdOf(payload, root));
|
|
104
|
-
if (!metadataStep && commandClass !== 'read-only' && commandClass !== 'worktree-setup')
|
|
111
|
+
if (!metadataStep && commandClass !== 'read-only' && commandClass !== 'worktree-setup') {
|
|
112
|
+
if (stateOnlyCandidate) editAfterCapture = true;
|
|
113
|
+
else state.lastEditAt = Date.now();
|
|
114
|
+
}
|
|
105
115
|
// Verification evidence needs a confirmed success: a PostToolUse event or an explicit zero exit.
|
|
106
116
|
// Pilot ON only: a registered, argv-validated doc-check that resolves to this install's own runtime is the document
|
|
107
117
|
// verification evidence, and only at the shipped pin (R3-02). Any other path earns no verification evidence. OFF stays legacy.
|
|
108
|
-
const pilotEnabled = process.env.HARNESS_DOC_RECONCILIATION_PILOT === '1';
|
|
109
|
-
const docCheck = pilotEnabled ? require('./lib/doc-reconciliation-provider') : null;
|
|
110
118
|
const installedCheck = docCheck && docCheck.registeredInstalledCheck(command, cwdOf(payload, root));
|
|
111
119
|
const docCheckCandidate = installedCheck && installedCheck.kind !== 'not-candidate';
|
|
112
120
|
const pinCheckable = installedCheck && installedCheck.installed
|
|
113
121
|
&& (installedCheck.kind === 'accepted' || installedCheck.reason === 'implementation-pin-mismatch');
|
|
114
122
|
// A non-candidate that is compound or names the checker is not generic verification (trustRisk); the scanner miss does not clear it.
|
|
115
|
-
const verifies = docCheckCandidate
|
|
123
|
+
const verifies = stateOnlyCandidate ? false : docCheckCandidate
|
|
116
124
|
? Boolean(pinCheckable) && docCheck.fileDigest(installedCheck.installed) === docCheck.SHIPPED_DOC_CHECK_DIGEST
|
|
117
125
|
: !(pilotEnabled && docCheck.trustRisk(command)) && isVerificationShell(command, { cwd: cwdOf(payload, root), root });
|
|
118
126
|
if (!isFailed && (isSuccessEvent || exitCode === 0) && verifies) {
|
|
@@ -130,6 +138,17 @@ function processState(payload) {
|
|
|
130
138
|
fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), 'utf8');
|
|
131
139
|
observeTool(payload);
|
|
132
140
|
persistPilotCapture(payload, captureEventName, sessionId, root);
|
|
141
|
+
if (editAfterCapture) {
|
|
142
|
+
const pilotEnabled = process.env.HARNESS_DOC_RECONCILIATION_PILOT === '1';
|
|
143
|
+
const docCheck = pilotEnabled ? require('./lib/doc-reconciliation-provider') : null;
|
|
144
|
+
const captures = docCheck && docCheck.readCaptureView(getSessionDir(root, sessionId));
|
|
145
|
+
const verifiedStateOnly = stateOnlyCandidate && docCheck && captures && !captures.tampered
|
|
146
|
+
&& docCheck.isVerifiedW6StateOperation(captures.records, getSessionDir(root, sessionId), payload.tool_use_id);
|
|
147
|
+
if (!verifiedStateOnly) {
|
|
148
|
+
state.lastEditAt = Date.now();
|
|
149
|
+
fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), 'utf8');
|
|
150
|
+
}
|
|
151
|
+
}
|
|
133
152
|
} catch (_) {}
|
|
134
153
|
process.exit(0);
|
|
135
154
|
}
|
|
@@ -142,9 +161,9 @@ function persistPilotCapture(payload, eventName, sessionId, root) {
|
|
|
142
161
|
if (!payload || process.env.HARNESS_DOC_RECONCILIATION_PILOT !== '1') return;
|
|
143
162
|
if (PILOT_CAPTURE_EVENT_NAMES.indexOf(eventName) === -1) return;
|
|
144
163
|
const provider = require('./lib/doc-reconciliation-provider');
|
|
145
|
-
const entry = provider.buildCaptureRecord(payload, eventName, root);
|
|
146
|
-
if (!entry) return;
|
|
147
164
|
const sessionDir = getSessionDir(root, sessionId);
|
|
165
|
+
const entry = provider.buildCaptureRecord(payload, eventName, root, { sessionDir });
|
|
166
|
+
if (!entry) return;
|
|
148
167
|
// Observation-time identity: the workflow and pin in force when the host event was captured.
|
|
149
168
|
const observed = provider.observedIdentityFor(sessionDir);
|
|
150
169
|
if (observed) entry.observedIdentity = observed;
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const crypto = require('crypto');
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const { getWorkspaceRoot, getSessionDir } = require('./lib/harness-state');
|
|
8
|
+
const { canonical } = require('./lib/workflow-isolation');
|
|
9
|
+
|
|
10
|
+
const INVENTORY_FILE = 'doc-reconciliation/outline-confirmation/inventory';
|
|
11
|
+
const APPROVED_INVENTORY = 'benchmarks/results/live-host/claude-341-outline-dispatch-2026-10-28/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md';
|
|
12
|
+
|
|
13
|
+
function git(root, args, buffer = false) {
|
|
14
|
+
const { execFileSync } = require('child_process');
|
|
15
|
+
return execFileSync('git', ['-C', root, ...args], { encoding: buffer ? null : 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function readJson(file) { return JSON.parse(fs.readFileSync(file, 'utf8')); }
|
|
19
|
+
function sha(bytes) { return crypto.createHash('sha256').update(bytes).digest('hex'); }
|
|
20
|
+
function jsonBytes(value) { return Buffer.from(JSON.stringify(value, null, 2) + '\n'); }
|
|
21
|
+
function same(left, right) { return JSON.stringify(left) === JSON.stringify(right); }
|
|
22
|
+
|
|
23
|
+
function safeStatePath(sessionDir, relative, allowMissing = false) {
|
|
24
|
+
const sessionRoot = fs.realpathSync.native(sessionDir);
|
|
25
|
+
if (path.isAbsolute(relative) || relative.split(/[\\/]/).some(part => !part || part === '.' || part === '..')) {
|
|
26
|
+
throw new Error('invalid-state-destination');
|
|
27
|
+
}
|
|
28
|
+
const destination = path.resolve(sessionRoot, relative);
|
|
29
|
+
const within = path.relative(sessionRoot, destination);
|
|
30
|
+
if (!within || within.startsWith('..' + path.sep) || within === '..' || path.isAbsolute(within)) throw new Error('state-destination-escape');
|
|
31
|
+
let cursor = sessionRoot;
|
|
32
|
+
const parts = relative.split(/[\\/]/);
|
|
33
|
+
for (let index = 0; index < parts.length; index += 1) {
|
|
34
|
+
cursor = path.join(cursor, parts[index]);
|
|
35
|
+
try {
|
|
36
|
+
const stat = fs.lstatSync(cursor);
|
|
37
|
+
if (stat.isSymbolicLink() || (index < parts.length - 1 && !stat.isDirectory())
|
|
38
|
+
|| (index === parts.length - 1 && !stat.isFile())) throw new Error('state-destination-not-regular');
|
|
39
|
+
} catch (error) {
|
|
40
|
+
if (error.code !== 'ENOENT') throw error;
|
|
41
|
+
if (!allowMissing) throw error;
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const parent = path.dirname(destination);
|
|
46
|
+
if (fs.existsSync(parent) && fs.realpathSync.native(parent) !== path.resolve(sessionRoot, path.dirname(relative))) {
|
|
47
|
+
throw new Error('state-destination-parent-alias');
|
|
48
|
+
}
|
|
49
|
+
return destination;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function writeNewStateFile(sessionDir, relative, bytes) {
|
|
53
|
+
const file = safeStatePath(sessionDir, relative, true);
|
|
54
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
55
|
+
safeStatePath(sessionDir, relative, true);
|
|
56
|
+
fs.writeFileSync(file, bytes, { flag: 'wx' });
|
|
57
|
+
if (fs.realpathSync.native(path.dirname(file)) !== path.resolve(fs.realpathSync.native(sessionDir), path.dirname(relative))) {
|
|
58
|
+
throw new Error('state-destination-parent-alias');
|
|
59
|
+
}
|
|
60
|
+
return file;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function loadProvider() { return require('./lib/doc-reconciliation-provider'); }
|
|
64
|
+
|
|
65
|
+
function hostInvocation(sessionId, operation) {
|
|
66
|
+
const root = canonical(getWorkspaceRoot());
|
|
67
|
+
const sessionDir = getSessionDir(root, sessionId);
|
|
68
|
+
const provider = loadProvider();
|
|
69
|
+
const captures = provider.readCaptureView(sessionDir);
|
|
70
|
+
if (captures.tampered) throw new Error('capture-view-tampered');
|
|
71
|
+
const script = fs.realpathSync.native(__filename);
|
|
72
|
+
const matched = captures.records.filter(record => {
|
|
73
|
+
if (!record || record.event !== 'PreToolUse' || record.tool_name !== 'Bash'
|
|
74
|
+
|| record.session_id !== sessionId || record.agent_id !== undefined || !record.tool_use_id) return false;
|
|
75
|
+
let cwd;
|
|
76
|
+
try { cwd = canonical(record.cwd); } catch { return false; }
|
|
77
|
+
if (cwd !== root) return false;
|
|
78
|
+
const parsed = provider._internals.safeTokenize(record.command);
|
|
79
|
+
if (!parsed.ok || parsed.tokens.length !== 5 || !['node', 'nodejs'].includes(parsed.tokens[0])) return false;
|
|
80
|
+
let invoked;
|
|
81
|
+
try { invoked = fs.realpathSync.native(path.resolve(cwd, parsed.tokens[1])); } catch { return false; }
|
|
82
|
+
return invoked === script && parsed.tokens[2] === operation
|
|
83
|
+
&& parsed.tokens[3] === '--session-id' && parsed.tokens[4] === sessionId;
|
|
84
|
+
});
|
|
85
|
+
if (matched.length !== 1) throw new Error('unique-correlated-pre-invocation-required');
|
|
86
|
+
const pre = matched[0];
|
|
87
|
+
if (captures.records.some(record => record && record.ref !== pre.ref && record.session_id === sessionId
|
|
88
|
+
&& record.tool_use_id === pre.tool_use_id && ['PostToolUse', 'PostToolUseFailure'].includes(record.event))) {
|
|
89
|
+
throw new Error('operation-already-completed');
|
|
90
|
+
}
|
|
91
|
+
return { root, sessionDir, provider, captures: captures.records, pre };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function loadRow17State(root, sessionDir) {
|
|
95
|
+
const workflow = readJson(path.join(sessionDir, 'workflow-run.json'));
|
|
96
|
+
const task = workflow.docReconciliationTask;
|
|
97
|
+
const baseline = workflow.docReconciliationBaseline;
|
|
98
|
+
if (workflow.strategy !== 'iterative-single' || workflow.state !== 'running' || !Number.isInteger(workflow.revision)
|
|
99
|
+
|| !task || task.schema !== 'harness.doc-reconciliation-task-pin.v1'
|
|
100
|
+
|| !same(task.requirementIds, ['adr-evid', 'verify-row17']) || task.taskId !== 'task-adr-evid+verify-row17'
|
|
101
|
+
|| task.sessionId !== workflow.sessionId || task.workflowId !== workflow.workflowId
|
|
102
|
+
|| !baseline || canonical(baseline.root) !== root || task.baselineRoot !== baseline.root
|
|
103
|
+
|| task.baselineCommit !== baseline.commit) throw new Error('row17-task-pin-invalid');
|
|
104
|
+
return { workflow, task, baseline };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function inventoryBytes(provider) {
|
|
108
|
+
const source = path.resolve(__dirname, '..', '..', APPROVED_INVENTORY);
|
|
109
|
+
if (fs.existsSync(source)) return fs.readFileSync(source);
|
|
110
|
+
const capture = path.join(__dirname, 'lib/doc-reconciliation-outline-capture.sanitized.jsonl');
|
|
111
|
+
for (const line of fs.readFileSync(capture, 'utf8').split(/\r?\n/)) {
|
|
112
|
+
if (!line) continue;
|
|
113
|
+
const record = JSON.parse(line);
|
|
114
|
+
const candidates = [record.tool_response?.content?.[0]?.text, record.tool_response?.file?.content, record.tool_response?.stdout];
|
|
115
|
+
for (const value of candidates) {
|
|
116
|
+
if (typeof value === 'string' && sha(Buffer.from(value)) === provider._internals.OUTLINE_INVENTORY_PIN.sha256) {
|
|
117
|
+
return Buffer.from(value);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
throw new Error('pinned-inventory-bytes-unavailable');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function inventory({ sessionId }) {
|
|
125
|
+
const context = hostInvocation(sessionId, 'inventory');
|
|
126
|
+
const { root, sessionDir, provider } = context;
|
|
127
|
+
const { workflow, task, baseline } = loadRow17State(root, sessionDir);
|
|
128
|
+
const head = git(root, ['rev-parse', '--verify', 'HEAD^{commit}']).trim();
|
|
129
|
+
const tree = git(root, ['rev-parse', '--verify', 'HEAD^{tree}']).trim();
|
|
130
|
+
if (head !== baseline.commit || tree !== baseline.tree || git(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all'], true).length) {
|
|
131
|
+
throw new Error('inventory-must-run-on-clean-baseline');
|
|
132
|
+
}
|
|
133
|
+
const expectedPin = provider._internals.OUTLINE_INVENTORY_PIN;
|
|
134
|
+
const bytes = inventoryBytes(provider);
|
|
135
|
+
const validated = provider._internals.validateOutlineInventoryPin({ bytes, pin: expectedPin, expectedPin });
|
|
136
|
+
const row = provider._internals.resolveInventoryRow({ parsed: validated.parsed, pin: expectedPin }, '17');
|
|
137
|
+
if (sha(bytes) !== expectedPin.sha256 || validated.state !== 'accepted' || row.state !== 'accepted' || row.row.domain !== 'EVID'
|
|
138
|
+
|| expectedPin.rowDomainMappings[0].approvalRef !== 'https://github.com/dyphn1/Harness-everything/issues/325#issuecomment-6706805112') {
|
|
139
|
+
throw new Error('pinned-row17-inventory-invalid');
|
|
140
|
+
}
|
|
141
|
+
const inventoryRelative = `${INVENTORY_FILE}/${path.posix.basename(expectedPin.retainedArtifactPath)}`;
|
|
142
|
+
const pinRelative = `${INVENTORY_FILE}/inventory-pin.json`;
|
|
143
|
+
writeNewStateFile(sessionDir, inventoryRelative, bytes);
|
|
144
|
+
writeNewStateFile(sessionDir, pinRelative, jsonBytes(expectedPin));
|
|
145
|
+
return { operation: 'inventory', workflowId: workflow.workflowId, revision: workflow.revision, taskId: task.taskId,
|
|
146
|
+
destinations: [inventoryRelative, pinRelative], sha256: expectedPin.sha256 };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function seal({ sessionId }) {
|
|
150
|
+
const context = hostInvocation(sessionId, 'seal');
|
|
151
|
+
const { root, sessionDir, provider, captures } = context;
|
|
152
|
+
const { workflow, task, baseline } = loadRow17State(root, sessionDir);
|
|
153
|
+
const head = git(root, ['rev-parse', '--verify', 'HEAD^{commit}']).trim();
|
|
154
|
+
const tree = git(root, ['rev-parse', '--verify', 'HEAD^{tree}']).trim();
|
|
155
|
+
if (head === baseline.commit || git(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all'], true).length
|
|
156
|
+
|| git(root, ['merge-base', '--is-ancestor', baseline.commit, head]) !== '') throw new Error('seal-requires-clean-b-to-o-outline');
|
|
157
|
+
const expectedPin = provider._internals.OUTLINE_INVENTORY_PIN;
|
|
158
|
+
const inventoryRoot = path.join(sessionDir, INVENTORY_FILE);
|
|
159
|
+
const pinFile = path.join(inventoryRoot, 'inventory-pin.json');
|
|
160
|
+
const pinBytes = fs.readFileSync(pinFile);
|
|
161
|
+
const pin = JSON.parse(pinBytes.toString('utf8'));
|
|
162
|
+
const bytes = fs.readFileSync(path.join(inventoryRoot, path.posix.basename(expectedPin.retainedArtifactPath)));
|
|
163
|
+
const inventory = provider._internals.validateOutlineInventoryPin({ bytes, pin, expectedPin });
|
|
164
|
+
if (inventory.state !== 'accepted' || sha(pinBytes) !== sha(jsonBytes(expectedPin))) throw new Error('pinned-inventory-not-installed');
|
|
165
|
+
const inventoryPath = `doc-reconciliation/outline-confirmation/inventory/${path.posix.basename(expectedPin.retainedArtifactPath)}`;
|
|
166
|
+
const reviewEvents = captures.filter(record => record && record.event === 'SubagentStop' && record.agent_type === 'reviewer'
|
|
167
|
+
&& record.reviewVerdict === 'approve' && record.reviewSummary);
|
|
168
|
+
const candidates = reviewEvents.filter(review => {
|
|
169
|
+
const targets = Object.keys(review.reviewedArtifactDigests || {}).filter(relative => relative !== inventoryPath);
|
|
170
|
+
return targets.length === 1 && review.reviewedArtifactDigests[inventoryPath] === sha(bytes);
|
|
171
|
+
});
|
|
172
|
+
if (candidates.length !== 1) throw new Error('unique-approved-outline-review-required');
|
|
173
|
+
const review = candidates[0];
|
|
174
|
+
const targetPaths = Object.keys(review.reviewedArtifactDigests).filter(relative => relative !== inventoryPath);
|
|
175
|
+
const target = targetPaths[0];
|
|
176
|
+
const targetBytes = git(root, ['show', `${head}:${target}`], true);
|
|
177
|
+
const citation = provider._internals.parseOutlineCitation(targetBytes, target);
|
|
178
|
+
const row = provider._internals.resolveInventoryRow(inventory, citation.rowId);
|
|
179
|
+
const targetBlob = git(root, ['rev-parse', `${head}:${target}`]).trim();
|
|
180
|
+
if (citation.state !== 'accepted' || citation.rowId !== '17' || citation.domain !== 'EVID'
|
|
181
|
+
|| row.state !== 'accepted' || row.row.domain !== 'EVID'
|
|
182
|
+
|| review.reviewedArtifactDigests[target] !== sha(targetBytes)) throw new Error('approved-outline-does-not-match-pinned-row17');
|
|
183
|
+
const start = captures.filter(record => record && record.event === 'SubagentStart' && record.agent_id === review.agent_id);
|
|
184
|
+
const launch = captures.filter(record => record && record.event === 'PostToolUse' && ['Task', 'Agent'].includes(record.tool_name)
|
|
185
|
+
&& record.agent_id === review.agent_id);
|
|
186
|
+
if (start.length !== 1 || launch.length !== 1 || captures.indexOf(start[0]) >= captures.indexOf(review)
|
|
187
|
+
|| captures.indexOf(launch[0]) >= captures.indexOf(review)
|
|
188
|
+
|| start[0].outlineIdentity?.state !== 'accepted'
|
|
189
|
+
|| start[0].outlineIdentity.identity.outlineCommit !== head || start[0].outlineIdentity.identity.outlineTree !== tree
|
|
190
|
+
|| !provider.reviewRecordIndependent(review, captures, { author: sessionId,
|
|
191
|
+
executors: provider.journalExecutors(captures, sessionId) })) throw new Error('outline-review-lifecycle-or-identity-invalid');
|
|
192
|
+
const outlineDigests = { [target]: sha(targetBytes) };
|
|
193
|
+
const attemptId = 'attempt-' + sha(review.ref).slice(0, 16);
|
|
194
|
+
const attemptRelative = `doc-reconciliation/outline-confirmation/${task.taskId}/attempts/${attemptId}`;
|
|
195
|
+
const attemptDir = path.join(sessionDir, attemptRelative);
|
|
196
|
+
const lease = { schema: 'harness.outline-writer-lease.v1', id: 'lease-' + sha(review.ref).slice(0, 16),
|
|
197
|
+
taskId: task.taskId, attemptId, principalId: sessionId, root, exclusive: true, active: true };
|
|
198
|
+
const leaseRelative = `${attemptRelative}/writer-lease.json`;
|
|
199
|
+
const leaseBytes = jsonBytes(lease);
|
|
200
|
+
const leaseDigest = sha(leaseBytes);
|
|
201
|
+
const reviewDigest = provider._internals.captureDigest(review);
|
|
202
|
+
const handoff = {
|
|
203
|
+
schema: 'harness.outline-handoff.v1', handoffId: 'handoff-' + sha(review.ref).slice(0, 16),
|
|
204
|
+
taskId: task.taskId, attemptId, supersedesAttemptId: null, workspaceId: task.workspaceId,
|
|
205
|
+
workflowId: workflow.workflowId, workflowRevision: workflow.revision, sessionId, hostId: 'claude-code',
|
|
206
|
+
baseline: { root: baseline.root, commit: baseline.commit, tree: baseline.tree, configDigest: task.configDigest },
|
|
207
|
+
configDigest: task.configDigest, targetPaths, draftWorktreeRoot: root,
|
|
208
|
+
outline: { commit: head, tree, targetBlobs: { [target]: { blobOid: targetBlob, storedBytesSha256: sha(targetBytes) } } },
|
|
209
|
+
inventory: { ...expectedPin, rowId: '17', domain: 'EVID', targetPaths },
|
|
210
|
+
reviewCaptureRef: review.ref, reviewCaptureDigest: reviewDigest, reviewDigest: review.reviewDigest,
|
|
211
|
+
coordinatorPrincipal: sessionId, writerLeaseId: lease.id, writerLeaseDigest: leaseDigest,
|
|
212
|
+
draftDispatchToken: crypto.randomBytes(24).toString('hex'),
|
|
213
|
+
};
|
|
214
|
+
const validatedReview = provider._internals.validateOutlineReview({ handoff, attemptDir, captures, targetPaths,
|
|
215
|
+
outlineDigests, inventory, sessionId });
|
|
216
|
+
if (validatedReview.state !== 'accepted') throw new Error(validatedReview.reason || 'outline-review-invalid');
|
|
217
|
+
const handoffRelative = `${attemptRelative}/handoff.json`;
|
|
218
|
+
fs.mkdirSync(attemptDir, { recursive: true });
|
|
219
|
+
writeNewStateFile(sessionDir, leaseRelative, leaseBytes);
|
|
220
|
+
writeNewStateFile(sessionDir, handoffRelative, jsonBytes(handoff));
|
|
221
|
+
return { operation: 'seal', workflowId: workflow.workflowId, revision: workflow.revision, taskId: task.taskId,
|
|
222
|
+
attemptId, destinations: [leaseRelative, handoffRelative], handoff };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function main(argv) {
|
|
226
|
+
const [operation, flag, sessionId, extra] = argv;
|
|
227
|
+
if (!['inventory', 'seal'].includes(operation) || flag !== '--session-id' || !sessionId || extra !== undefined) {
|
|
228
|
+
throw new Error('Usage: w6-state-operations.js <inventory|seal> --session-id <id>');
|
|
229
|
+
}
|
|
230
|
+
const result = operation === 'inventory' ? inventory({ sessionId }) : seal({ sessionId });
|
|
231
|
+
process.stdout.write(JSON.stringify(result) + '\n');
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (require.main === module) {
|
|
235
|
+
try { main(process.argv.slice(2)); }
|
|
236
|
+
catch (error) { console.error('[W6 State Operation] ' + error.message); process.exitCode = 2; }
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
module.exports = { main };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
|
|
3
3
|
"name": "harness-everything",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.52.0",
|
|
5
5
|
"description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Miya Daniel",
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
// Agents hand each other Markdown work orders, and script-generating them keeps
|
|
5
|
+
// the format from drifting. The file begins with a tiny YAML front matter
|
|
6
|
+
// header; System One reads only that header as input (#409 L0). The YAML subset
|
|
7
|
+
// is flat scalars and flat lists, emitted and parsed here with no dependency.
|
|
8
|
+
|
|
9
|
+
const fs = require('fs');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
|
|
12
|
+
const HEADER_LIMIT = 2048;
|
|
13
|
+
const KINDS = ['implement', 'test', 'review', 'design', 'question', 'answer'];
|
|
14
|
+
const KEY_ORDER = ['harness-handoff', 'kind', 'title', 'summary', 'writes', 'gate', 'report'];
|
|
15
|
+
const RESERVED = new Set(['true', 'false', 'null', 'yes', 'no', 'on', 'off', '~', 'nan', 'inf']);
|
|
16
|
+
|
|
17
|
+
const BODY = [
|
|
18
|
+
'## Scope anchor',
|
|
19
|
+
'',
|
|
20
|
+
'## Task',
|
|
21
|
+
'',
|
|
22
|
+
'## Write-set',
|
|
23
|
+
'',
|
|
24
|
+
'## Verification',
|
|
25
|
+
'',
|
|
26
|
+
'## Report',
|
|
27
|
+
'',
|
|
28
|
+
'<!-- STATUS: <pending> -->',
|
|
29
|
+
'',
|
|
30
|
+
].join('\n');
|
|
31
|
+
|
|
32
|
+
function fail(message) {
|
|
33
|
+
throw new Error(message);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function usage() {
|
|
37
|
+
const error = new Error([
|
|
38
|
+
'Usage:',
|
|
39
|
+
' handoff-file.js new --kind <implement|test|review|design|question|answer>',
|
|
40
|
+
' --title "<text>" --summary "<text>" --out <file.md>',
|
|
41
|
+
' [--writes a,b] [--gate "<text>"] [--report <path>]',
|
|
42
|
+
' handoff-file.js header <file.md>',
|
|
43
|
+
' handoff-file.js check <file.md>',
|
|
44
|
+
'',
|
|
45
|
+
].join('\n'));
|
|
46
|
+
error.code = 'HANDOFF_USAGE';
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function plainSafe(value) {
|
|
51
|
+
if (!value || value !== value.trim()) return false;
|
|
52
|
+
if (RESERVED.has(value.toLowerCase())) return false;
|
|
53
|
+
return /^[A-Za-z0-9_/][A-Za-z0-9 _.@/()+-]*$/.test(value);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function yamlScalar(value) {
|
|
57
|
+
const s = String(value);
|
|
58
|
+
if (plainSafe(s)) return s;
|
|
59
|
+
return `"${s
|
|
60
|
+
.replace(/\\/g, '\\\\')
|
|
61
|
+
.replace(/"/g, '\\"')
|
|
62
|
+
.replace(/\n/g, '\\n')
|
|
63
|
+
.replace(/\r/g, '\\r')
|
|
64
|
+
.replace(/\t/g, '\\t')}"`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function unquote(raw) {
|
|
68
|
+
const s = raw.trim();
|
|
69
|
+
if (s.length < 2 || s[0] !== '"' || s[s.length - 1] !== '"') return s;
|
|
70
|
+
let out = '';
|
|
71
|
+
for (let i = 1; i < s.length - 1; i += 1) {
|
|
72
|
+
if (s[i] !== '\\') {
|
|
73
|
+
out += s[i];
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const next = s[i + 1];
|
|
77
|
+
if (next === 'n') out += '\n';
|
|
78
|
+
else if (next === 'r') out += '\r';
|
|
79
|
+
else if (next === 't') out += '\t';
|
|
80
|
+
else out += next === undefined ? '\\' : next;
|
|
81
|
+
i += 1;
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function parseValue(raw) {
|
|
87
|
+
if (raw === undefined) return '';
|
|
88
|
+
const s = raw.trim();
|
|
89
|
+
if (s.startsWith('[') && s.endsWith(']')) {
|
|
90
|
+
const inner = s.slice(1, -1).trim();
|
|
91
|
+
return inner === '' ? [] : inner.split(',').map(unquote);
|
|
92
|
+
}
|
|
93
|
+
return unquote(s);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function renderHeader(header) {
|
|
97
|
+
const lines = ['---'];
|
|
98
|
+
for (const key of KEY_ORDER) {
|
|
99
|
+
if (!(key in header)) continue;
|
|
100
|
+
const value = header[key];
|
|
101
|
+
const rendered = key === 'writes' ? `[${value.map(yamlScalar).join(', ')}]` : yamlScalar(value);
|
|
102
|
+
lines.push(`${key}: ${rendered}`);
|
|
103
|
+
}
|
|
104
|
+
lines.push('---');
|
|
105
|
+
return lines.join('\n');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function parseHeader(file) {
|
|
109
|
+
let text;
|
|
110
|
+
try {
|
|
111
|
+
const fd = fs.openSync(file, 'r');
|
|
112
|
+
const buf = Buffer.alloc(HEADER_LIMIT);
|
|
113
|
+
const read = fs.readSync(fd, buf, 0, HEADER_LIMIT, 0);
|
|
114
|
+
fs.closeSync(fd);
|
|
115
|
+
text = buf.subarray(0, read).toString('utf8');
|
|
116
|
+
} catch (err) {
|
|
117
|
+
fail(`cannot read ${file}: ${err.message}`);
|
|
118
|
+
}
|
|
119
|
+
if (!/^---(\r?\n|$)/.test(text)) fail(`${file}: no handoff header (file must start with '---')`);
|
|
120
|
+
const block = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
|
|
121
|
+
if (!block) fail(`${file}: header exceeds ${HEADER_LIMIT} bytes or is unterminated`);
|
|
122
|
+
if (Buffer.byteLength(block[0], 'utf8') > HEADER_LIMIT) {
|
|
123
|
+
fail(`${file}: header exceeds ${HEADER_LIMIT} bytes`);
|
|
124
|
+
}
|
|
125
|
+
const header = {};
|
|
126
|
+
for (const line of block[1].split(/\r?\n/)) {
|
|
127
|
+
if (line === '') continue;
|
|
128
|
+
const kv = /^([A-Za-z][A-Za-z0-9-]*):(?:[ ](.*))?$/.exec(line);
|
|
129
|
+
if (!kv) fail(`${file}: malformed header line ${JSON.stringify(line)}`);
|
|
130
|
+
if (kv[1] in header) fail(`${file}: duplicate header key ${kv[1]}`);
|
|
131
|
+
header[kv[1]] = parseValue(kv[2]);
|
|
132
|
+
}
|
|
133
|
+
return header;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function normalize(header) {
|
|
137
|
+
const out = {};
|
|
138
|
+
for (const key of KEY_ORDER) {
|
|
139
|
+
if (key in header) out[key] = key === 'harness-handoff' ? Number(header[key]) : header[key];
|
|
140
|
+
}
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function validate(file, header) {
|
|
145
|
+
const unknown = Object.keys(header).filter((key) => !KEY_ORDER.includes(key));
|
|
146
|
+
if (unknown.length) fail(`${file}: unknown header key(s): ${unknown.join(', ')}`);
|
|
147
|
+
if (Number(header['harness-handoff']) !== 1) fail(`${file}: harness-handoff must be 1`);
|
|
148
|
+
if (!KINDS.includes(header.kind)) fail(`${file}: kind must be one of ${KINDS.join('|')}`);
|
|
149
|
+
if (typeof header.title !== 'string' || header.title === '') fail(`${file}: title is required`);
|
|
150
|
+
if (typeof header.summary !== 'string' || header.summary === '') fail(`${file}: summary is required`);
|
|
151
|
+
if ([...header.summary].length > 200) fail(`${file}: summary must be at most 200 characters`);
|
|
152
|
+
if ('writes' in header && !Array.isArray(header.writes)) fail(`${file}: writes must be a list`);
|
|
153
|
+
for (const key of ['gate', 'report']) {
|
|
154
|
+
if (key in header && typeof header[key] !== 'string') fail(`${file}: ${key} must be a string`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function loadHeader(file) {
|
|
159
|
+
const header = parseHeader(file);
|
|
160
|
+
validate(file, header);
|
|
161
|
+
return normalize(header);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function parseFlags(args, allowed) {
|
|
165
|
+
const opts = {};
|
|
166
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
167
|
+
const flag = args[i];
|
|
168
|
+
if (!flag.startsWith('--')) fail(`unexpected argument ${JSON.stringify(flag)}`);
|
|
169
|
+
const name = flag.slice(2);
|
|
170
|
+
if (!allowed.includes(name)) fail(`unknown flag ${flag}`);
|
|
171
|
+
const value = args[i + 1];
|
|
172
|
+
if (value === undefined || value.startsWith('--')) fail(`${flag} requires a value`);
|
|
173
|
+
opts[name] = value;
|
|
174
|
+
i += 1;
|
|
175
|
+
}
|
|
176
|
+
return opts;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function createHandoff(args) {
|
|
180
|
+
const opts = parseFlags(args, ['kind', 'title', 'summary', 'out', 'writes', 'gate', 'report']);
|
|
181
|
+
for (const key of ['kind', 'title', 'summary', 'out']) {
|
|
182
|
+
if (!opts[key]) fail(`new requires --${key}`);
|
|
183
|
+
}
|
|
184
|
+
const header = { 'harness-handoff': 1, kind: opts.kind, title: opts.title, summary: opts.summary };
|
|
185
|
+
if (opts.writes !== undefined) {
|
|
186
|
+
// shortcut: a comma inside one write path splits it into two items, upgrade if a path may hold one
|
|
187
|
+
header.writes = opts.writes.split(',').map((item) => item.trim()).filter((item) => item !== '');
|
|
188
|
+
}
|
|
189
|
+
if (opts.gate !== undefined) header.gate = opts.gate;
|
|
190
|
+
if (opts.report !== undefined) header.report = opts.report;
|
|
191
|
+
validate(opts.out, header);
|
|
192
|
+
const rendered = renderHeader(header);
|
|
193
|
+
if (Buffer.byteLength(rendered, 'utf8') > HEADER_LIMIT) fail(`${opts.out}: header exceeds ${HEADER_LIMIT} bytes`);
|
|
194
|
+
const target = path.resolve(opts.out);
|
|
195
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
196
|
+
fs.writeFileSync(target, `${rendered}\n${BODY}`, 'utf8');
|
|
197
|
+
process.stdout.write(`${target}\n`);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function main() {
|
|
201
|
+
try {
|
|
202
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
203
|
+
if (command === 'new') {
|
|
204
|
+
createHandoff(rest);
|
|
205
|
+
} else if (command === 'header' || command === 'check') {
|
|
206
|
+
const file = rest[0];
|
|
207
|
+
if (!file) fail(`${command} requires <file.md>`);
|
|
208
|
+
const header = loadHeader(file);
|
|
209
|
+
process.stdout.write(
|
|
210
|
+
command === 'header' ? `${JSON.stringify(header, null, 2)}\n` : `${file}: ok (kind=${header.kind})\n`,
|
|
211
|
+
);
|
|
212
|
+
} else {
|
|
213
|
+
usage();
|
|
214
|
+
}
|
|
215
|
+
} catch (error) {
|
|
216
|
+
process.stderr.write(error.code === 'HANDOFF_USAGE' ? error.message : `handoff-file: ${error.message}\n`);
|
|
217
|
+
process.exitCode = 1;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (require.main === module) main();
|
|
222
|
+
|
|
223
|
+
module.exports = { loadHeader };
|