harness-everything 0.31.3 → 0.32.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.
Files changed (26) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +11 -0
  4. package/ci/mechanism-2az-step-type-registry.test.js +837 -0
  5. package/ci/mechanism-2ba-step-type-docs.test.js +166 -0
  6. package/harness-everything/SKILL.md +1 -1
  7. package/harness-everything/references/router-workflow-plan.md +18 -0
  8. package/harness-everything/scripts/kernel-router.js +37 -5
  9. package/hooks/scripts/codex-user-prompt.js +5 -2
  10. package/hooks/scripts/lib/step-types.json +37 -0
  11. package/hooks/scripts/lib/workflow-obligations.js +117 -14
  12. package/hooks/scripts/workflow-disposition.js +16 -9
  13. package/hooks/scripts/workflow-stop-gate.js +31 -8
  14. package/opencode-plugin/plugin.json +1 -1
  15. package/package.json +1 -1
  16. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  17. package/plugins/harness-everything/hooks/scripts/codex-user-prompt.js +5 -2
  18. package/plugins/harness-everything/hooks/scripts/lib/step-types.json +37 -0
  19. package/plugins/harness-everything/hooks/scripts/lib/workflow-obligations.js +117 -14
  20. package/plugins/harness-everything/hooks/scripts/workflow-disposition.js +16 -9
  21. package/plugins/harness-everything/hooks/scripts/workflow-stop-gate.js +31 -8
  22. package/plugins/harness-everything/plugin.json +1 -1
  23. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  24. package/plugins/harness-everything/skills/harness-everything/references/router-workflow-plan.md +18 -0
  25. package/plugins/harness-everything/skills/harness-everything/scripts/kernel-router.js +37 -5
  26. package/sbom.cdx.json +7 -7
@@ -0,0 +1,166 @@
1
+ const fs = require('fs');
2
+ const os = require('os');
3
+ const path = require('path');
4
+ const { spawnSync } = require('child_process');
5
+
6
+ const ROOT = path.resolve(__dirname, '..');
7
+ const registryFile = path.join(ROOT, 'hooks', 'scripts', 'lib', 'step-types.json');
8
+ const routerFile = path.join(ROOT, 'harness-everything', 'scripts', 'kernel-router.js');
9
+ const AUTHORITATIVE_DOC = 'harness-everything/references/router-workflow-plan.md';
10
+ const ALLOWED_LIST_DOCS = [
11
+ 'docs/routing.md',
12
+ 'harness-everything/references/router-workflow-plan.md',
13
+ 'harness-everything/references/triage-and-tiers.md',
14
+ 'docs/workflows/harness-everything.md',
15
+ ];
16
+ const START = '<!-- step-types:start -->';
17
+ const END = '<!-- step-types:end -->';
18
+ const FIX_PROMPT = 'Fix this checkout bug and add a regression test.';
19
+ const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-step-type-docs-'));
20
+ let failed = 0;
21
+
22
+ process.on('exit', () => fs.rmSync(tempRoot, { recursive: true, force: true }));
23
+
24
+ console.log('\n[2ba] step-type registry documentation and router drift...');
25
+
26
+ function check(name, ok, detail) {
27
+ if (ok) console.log(`✅ ${name}`);
28
+ else {
29
+ failed++;
30
+ console.log(`❌ ${name}`);
31
+ if (detail) console.log(` ${detail}`);
32
+ }
33
+ }
34
+
35
+ function checkCase(name, run) {
36
+ try {
37
+ run();
38
+ check(name, true);
39
+ } catch (error) {
40
+ check(name, false, error && error.message ? error.message : String(error));
41
+ }
42
+ }
43
+
44
+ // Independent oracle: renders the registry directly from the JSON file, not through the runtime loader.
45
+ function renderRegistry(entries) {
46
+ const byId = (left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
47
+ const list = bindings => bindings.map(binding => `\`${binding}\``).join(', ') || 'none';
48
+ return entries.slice().sort(byId).map(entry =>
49
+ `- \`${entry.id}\` — required bindings: ${list(entry.requiredBindings)} — forbidden bindings: ${list(entry.forbiddenBindings)}`,
50
+ );
51
+ }
52
+
53
+ function markerBlocks(text, label) {
54
+ const lines = text.split('\n');
55
+ const blocks = [];
56
+ let openAt = null;
57
+ lines.forEach((line, index) => {
58
+ const marker = line.trim();
59
+ if (marker === START) {
60
+ if (openAt !== null) throw new Error(`${label}: nested step-types:start at line ${index + 1}`);
61
+ openAt = index;
62
+ } else if (marker === END) {
63
+ if (openAt === null) throw new Error(`${label}: step-types:end without start at line ${index + 1}`);
64
+ blocks.push(lines.slice(openAt + 1, index).map(item => item.trim()).filter(Boolean));
65
+ openAt = null;
66
+ }
67
+ });
68
+ if (openAt !== null) throw new Error(`${label}: step-types:start is never closed`);
69
+ return blocks;
70
+ }
71
+
72
+ function routeFixPrompt(runtimeRoot, workspace) {
73
+ const home = path.join(tempRoot, `home-${Math.random().toString(36).slice(2)}`);
74
+ fs.mkdirSync(home, { recursive: true });
75
+ const payload = { session_id: `2ba-${Math.random().toString(36).slice(2)}`, cwd: workspace, prompt: FIX_PROMPT };
76
+ return spawnSync(process.execPath, [path.join(runtimeRoot, 'harness-everything', 'scripts', 'kernel-router.js')], {
77
+ cwd: workspace,
78
+ encoding: 'utf8',
79
+ input: JSON.stringify(payload),
80
+ env: {
81
+ ...process.env,
82
+ HARNESS_STATE_HOME: path.join(tempRoot, 'state'),
83
+ HARNESS_WORKSPACE_ROOT: workspace,
84
+ HOME: home,
85
+ USERPROFILE: home,
86
+ },
87
+ });
88
+ }
89
+
90
+ const registry = JSON.parse(fs.readFileSync(registryFile, 'utf8'));
91
+ const registryIds = registry.map(entry => entry.id).sort();
92
+ const expectedLines = renderRegistry(registry);
93
+
94
+ checkCase('2ba. every step-types marker block in the allowed-list docs equals the registry rendering', () => {
95
+ let total = 0;
96
+ for (const doc of ALLOWED_LIST_DOCS) {
97
+ const blocks = markerBlocks(fs.readFileSync(path.join(ROOT, doc), 'utf8'), doc);
98
+ for (const block of blocks) {
99
+ total++;
100
+ if (JSON.stringify(block) !== JSON.stringify(expectedLines)) {
101
+ throw new Error(`${doc} marker block drifted from the registry:\n${block.join('\n')}\nexpected:\n${expectedLines.join('\n')}`);
102
+ }
103
+ }
104
+ }
105
+ if (total === 0) throw new Error('no step-types marker block found in any allowed-list doc');
106
+ const authoritative = markerBlocks(fs.readFileSync(path.join(ROOT, AUTHORITATIVE_DOC), 'utf8'), AUTHORITATIVE_DOC);
107
+ if (authoritative.length !== 1) throw new Error(`${AUTHORITATIVE_DOC} must carry exactly one step-types marker block; found ${authoritative.length}`);
108
+ });
109
+
110
+ checkCase('2ba. router lists exactly the registry step-type ids', () => {
111
+ const routed = routeFixPrompt(ROOT, ROOT);
112
+ if (routed.status !== 0) throw new Error(`router exited ${routed.status}: ${routed.stderr}`);
113
+ const match = routed.stdout.match(/Record ordered step types \(([^)]*)\) and their bindings/);
114
+ if (!match) throw new Error('router did not print the ordered step-type list');
115
+ const listed = match[1].split(',').map(item => item.trim());
116
+ if (JSON.stringify(listed) !== JSON.stringify(registryIds)) {
117
+ throw new Error(`router listed [${listed.join(', ')}]; registry ids are [${registryIds.join(', ')}]`);
118
+ }
119
+ });
120
+
121
+ checkCase('2ba. router example plan does not steer step authoring toward behavior-change', () => {
122
+ const routed = routeFixPrompt(ROOT, ROOT);
123
+ const recordPlan = routed.stdout.split('\n').find(line => line.includes('Record plan:')) || '';
124
+ if (!recordPlan) throw new Error('router did not print a Record plan example');
125
+ if (recordPlan.includes('behavior-change')) throw new Error(`example still hard-codes behavior-change: ${recordPlan}`);
126
+ });
127
+
128
+ checkCase('2ba. router prints the explicit-choice guidance line exactly once in fresh tier2 output', () => {
129
+ const guidance = '- Replace <step-type-id> with a registered type you choose explicitly; mixed docs+code work uses separate doc-change and behavior-change steps; keep the verification step.';
130
+ const routed = routeFixPrompt(ROOT, ROOT);
131
+ if (routed.status !== 0) throw new Error(`router exited ${routed.status}: ${routed.stderr}`);
132
+ const matches = routed.stdout.split('\n').filter(line => line.trim() === guidance);
133
+ if (matches.length !== 1) throw new Error(`expected the guidance line exactly once; found ${matches.length}`);
134
+ });
135
+
136
+ checkCase('2ba. router record-plan guidance keeps the space after "node" in fresh tier2 output', () => {
137
+ const routed = routeFixPrompt(ROOT, ROOT);
138
+ if (routed.status !== 0) throw new Error(`router exited ${routed.status}: ${routed.stderr}`);
139
+ if (!routed.stdout.includes(' - Record plan: node "')) {
140
+ throw new Error(`router record-plan line lacks "Record plan: node"; got: ${routed.stdout.split('\n').find(line => line.includes('Record plan')) || '(none)'}`);
141
+ }
142
+ });
143
+
144
+ checkCase('2ba. router never crashes or prints a stale step-type list when the registry is missing', () => {
145
+ const copy = path.join(tempRoot, 'runtime-without-registry');
146
+ fs.cpSync(ROOT, copy, {
147
+ recursive: true,
148
+ filter: source => !/[\\/](node_modules|\.git|benchmarks|plugins)([\\/]|$)/.test(source),
149
+ });
150
+ fs.rmSync(path.join(copy, 'hooks', 'scripts', 'lib', 'step-types.json'));
151
+ const routed = routeFixPrompt(copy, copy);
152
+ if (routed.status !== 0) throw new Error(`router exited ${routed.status} without the registry: ${routed.stderr}`);
153
+ if (/Record ordered step types \(/.test(routed.stdout)) throw new Error('router printed a step-type list without a registry');
154
+ if (!routed.stderr.includes('cannot load step-type registry')) {
155
+ throw new Error(`router did not surface the missing registry visibly; stderr: ${routed.stderr}`);
156
+ }
157
+ });
158
+
159
+ checkCase('2ba. router-workflow-plan documents old-runtime rejection of persisted doc-change plans', () => {
160
+ const text = fs.readFileSync(path.join(ROOT, AUTHORITATIVE_DOC), 'utf8');
161
+ for (const required of ['doc-change', 'declared-only', 'planning:steps-invalid']) {
162
+ if (!text.includes(required)) throw new Error(`${AUTHORITATIVE_DOC} must mention ${required}`);
163
+ }
164
+ });
165
+
166
+ process.exitCode = failed ? 1 : 0;
@@ -4,7 +4,7 @@ description: "Route software/project work through Harness: classify tier/topolog
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.31.0
7
+ version: 0.32.0
8
8
  ---
9
9
 
10
10
  # Harness Everything
@@ -118,6 +118,24 @@ Examples:
118
118
 
119
119
  There is no universal `TODO → TDD → verification` pipeline.
120
120
 
121
+ ## Step types
122
+
123
+ The allowed step types are the entries of `hooks/scripts/lib/step-types.json`. The list below is rendered from that registry and checked against it by `ci/mechanism-2ba-step-type-docs.test.js`; examples elsewhere may name a subset.
124
+
125
+ <!-- step-types:start -->
126
+ - `behavior-change` — required bindings: `tdd` — forbidden bindings: none
127
+ - `commit` — required bindings: `git-commit` — forbidden bindings: none
128
+ - `doc-change` — required bindings: none — forbidden bindings: none
129
+ - `review` — required bindings: none — forbidden bindings: `tdd`
130
+ - `verification` — required bindings: `verification-loop` — forbidden bindings: none
131
+ <!-- step-types:end -->
132
+
133
+ `doc-change` is declared-only: a plan author chooses it explicitly, and router classification, keyword routing and System One never infer or insert it. It has no default bindings, and an explicitly declared `tdd` binding stays legal. Mixed documentation and code work is written as ordered `doc-change` and `behavior-change` steps, and one shared verification step may verify both.
134
+
135
+ Old runtimes reject a persisted non-Fable `doc-change` plan visibly at the controller and Stop boundaries (`planning:steps-invalid`). The old retained router does not show that rejection: it shows no active step. Persisted bytes are not renamed or reset. Inert Fable planning metadata is not rejected by old runtimes, because step bindings are disabled there.
136
+
137
+ Registry revisions: binding defaults and required/forbidden binding policy are materialized when a plan is recorded and are not reapplied on ordinary load. Existing typed plans must still reference currently registered step types; removing a type can invalidate a plan rather than migrate or waive its stored bindings. A policy fingerprint or migration path is future work and is not implemented today.
138
+
121
139
  ## Binding and disclosure rule
122
140
 
123
141
  Each ordered requirement or Fable stage may declare `requiredBindings` and `optionalBindings` by stable id and concrete repository-relative path. Only the active requirement or dependency-ready stage exposes its paths. Required bindings must resolve before that step/stage passes; unknown required bindings remain visible and unresolved. Future-step paths and keyword-matched documents are never preloaded.
@@ -33,6 +33,14 @@ function issueMemoryCapability(workflow) {
33
33
  return token;
34
34
  }
35
35
 
36
+ function needsStepTypeRegistry(plan) {
37
+ return Boolean(
38
+ plan && plan.strategySelection === 'selected' &&
39
+ ['tier2', 'tier3'].includes(plan.tier) && plan.strategy &&
40
+ !String(plan.strategy).startsWith('fable-')
41
+ );
42
+ }
43
+
36
44
  // Host-generated background-task notifications arrive as UserPromptSubmit
37
45
  // hook payloads but are not user input (#168). Routing them like prompts
38
46
  // replaces the workflow contract mid-turn (e.g. deferred -> a new Tier-2).
@@ -44,11 +52,28 @@ function isHostNotificationPrompt(prompt) {
44
52
  return /^<task-notification[\s>][\s\S]*<\/task-notification>\s*$/i.test(text);
45
53
  }
46
54
 
55
+ function stepTypeIdsFor(hooksRoot) {
56
+ try {
57
+ return require(path.join(hooksRoot, 'lib/workflow-obligations')).stepTypeIds();
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
47
63
  function persistWorkflow(contract, payload, prompt) {
48
64
  const plan = contract && contract.workflowPlan;
49
65
  if (!payload || !(payload.session_id || payload.sessionId)) return null;
50
66
  const { runtime, hooksRoot } = loadRuntime();
51
67
  const context = runtime.loadWorkflow(payload);
68
+ const hasRetainedWorkflow = Boolean(context.workflow && runtime.OPEN_STATES.has(context.workflow.state));
69
+ const activePlan = hasRetainedWorkflow ? context.workflow.workflowPlan : plan;
70
+ if (needsStepTypeRegistry(activePlan)) {
71
+ try { require(path.join(hooksRoot, 'lib/workflow-obligations')).loadStepTypeRegistry(); }
72
+ catch (error) {
73
+ if (hasRetainedWorkflow) return { ...context, hooksRoot, retained: true, registryError: error };
74
+ throw error;
75
+ }
76
+ }
52
77
  const { writeCurrentSession } = require(path.join(hooksRoot, 'lib/harness-state'));
53
78
  writeCurrentSession(context.root, context.sessionId);
54
79
  if (isHostNotificationPrompt(prompt)) {
@@ -121,8 +146,8 @@ function activeExecutionFor(persisted, plan) {
121
146
  const obligations = require(path.join(persisted.hooksRoot, 'lib/workflow-obligations'));
122
147
  const loaded = obligations.loadObligationSet(persisted, plan);
123
148
  return { activeStep: loaded.set ? obligations.activeStepSnapshot(loaded.set) : null };
124
- } catch (_) {
125
- return null;
149
+ } catch (error) {
150
+ return { error: error && error.message ? error.message : String(error) };
126
151
  }
127
152
  }
128
153
 
@@ -163,10 +188,15 @@ function run(raw) {
163
188
  if (persisted?.retained && persisted.workflow) {
164
189
  if (persisted.hostNotification) console.log('\n=> Host notification: routing unchanged; keeping the active execution contract.');
165
190
  else console.log('\n=> Retaining unresolved workflow; showing its compact active contract.');
166
- const activeExecution = activeExecutionFor(persisted, plan) || {};
191
+ const activeExecution = persisted.registryError
192
+ ? { error: persisted.registryError.message || String(persisted.registryError) }
193
+ : activeExecutionFor(persisted, plan) || {};
167
194
  const activeStep = activeExecution.activeStep || null;
168
195
  const activeStages = activeExecution.activeStages || [];
169
196
  core.printRetainedWorkflow(plan, persisted.workflow, activeStep, activeStages);
197
+ if (activeExecution.error) {
198
+ console.log(' - [Workflow Reminder] Active-step context unavailable: ' + activeExecution.error);
199
+ }
170
200
  if (activeStep) {
171
201
  const controller = path.join(persisted.hooksRoot, 'workflow-disposition.js');
172
202
  console.log(' - Resolve only bindings for this active step, then pass this step with evidence.');
@@ -205,8 +235,10 @@ function run(raw) {
205
235
  if (plan.strategySelection === 'selected' && ['tier2', 'tier3'].includes(plan.tier)) {
206
236
  console.log(' - Planning contract: ' + path.join(persisted.sessionDir, 'workflow-obligations.json'));
207
237
  console.log(' - Requirements first: decompose intent into requirement fragments, then confirm the smallest sufficient workflow.');
208
- console.log(' - Record ordered step types (review, behavior-change, verification, commit) and their bindings before execution.');
209
- console.log(' - Record plan: node "' + controller + '" plan --session-id "' + persisted.sessionId + '" --requirements-json "[{\\"id\\":\\"req-1\\",\\"stepType\\":\\"behavior-change\\",\\"summary\\":\\"...\\",\\"acceptance\\":\\"...\\"},{\\"id\\":\\"req-verify\\",\\"stepType\\":\\"verification\\",\\"summary\\":\\"...\\",\\"acceptance\\":\\"...\\"}]" --strategy "' + plan.strategy + '" --evidence "<why this workflow fits>"');
238
+ const stepTypeIds = stepTypeIdsFor(persisted.hooksRoot);
239
+ console.log(' - Record ordered step types' + (stepTypeIds ? ' (' + stepTypeIds.join(', ') + ')' : '') + ' and their bindings before execution.');
240
+ console.log(' - Replace <step-type-id> with a registered type you choose explicitly; mixed docs+code work uses separate doc-change and behavior-change steps; keep the verification step.');
241
+ console.log(' - Record plan: node "' + controller + '" plan --session-id "' + persisted.sessionId + '" --requirements-json "[{\\"id\\":\\"req-1\\",\\"stepType\\":\\"<step-type-id>\\",\\"summary\\":\\"...\\",\\"acceptance\\":\\"...\\"},{\\"id\\":\\"req-verify\\",\\"stepType\\":\\"verification\\",\\"summary\\":\\"...\\",\\"acceptance\\":\\"...\\"}]" --strategy "' + plan.strategy + '" --evidence "<why this workflow fits>"');
210
242
  }
211
243
  console.log(' - Enter selected workflow after planning: node "' + controller + '" start --session-id "' + persisted.sessionId + '"');
212
244
  console.log(' - Escape one declared stage: node "' + controller + '" escape --session-id "' + persisted.sessionId + '" --stage-id "<id>" --reason-code workflow-uncovered-scope --scope "<uncovered scope>" --evidence "<evidence>"');
@@ -24,8 +24,11 @@ function finish() {
24
24
  clearTimeout(timer);
25
25
  if (!ROUTER) process.exit(0);
26
26
  const result = spawnSync(process.execPath, [ROUTER], { input, encoding: 'utf8', env: process.env, timeout: 25000 });
27
- if (result.stderr) process.stderr.write(result.stderr);
28
- const context = String(result.stdout || '').trim();
27
+ const stderr = String(result.stderr || '');
28
+ if (stderr) process.stderr.write(stderr);
29
+ const registryDiagnostics = stderr.split(/\r?\n/)
30
+ .filter(line => line.includes('cannot load step-type registry') && /(repair|restore|plugin:sync)/i.test(line));
31
+ const context = [String(result.stdout || '').trim(), ...registryDiagnostics].filter(Boolean).join('\n').trim();
29
32
  if (context) {
30
33
  process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: context } }));
31
34
  }
@@ -0,0 +1,37 @@
1
+ [
2
+ {
3
+ "id": "behavior-change",
4
+ "requiredBindings": ["tdd"],
5
+ "optionalBindings": [],
6
+ "forbiddenBindings": [],
7
+ "evidenceHint": "Evidence should show the requested behavior changed."
8
+ },
9
+ {
10
+ "id": "commit",
11
+ "requiredBindings": ["git-commit"],
12
+ "optionalBindings": [],
13
+ "forbiddenBindings": [],
14
+ "evidenceHint": "Evidence should identify the authorized commit."
15
+ },
16
+ {
17
+ "id": "doc-change",
18
+ "requiredBindings": [],
19
+ "optionalBindings": [],
20
+ "forbiddenBindings": [],
21
+ "evidenceHint": "Evidence should show the requested document update."
22
+ },
23
+ {
24
+ "id": "review",
25
+ "requiredBindings": [],
26
+ "optionalBindings": [],
27
+ "forbiddenBindings": ["tdd"],
28
+ "evidenceHint": "Evidence should identify the reviewed scope and findings."
29
+ },
30
+ {
31
+ "id": "verification",
32
+ "requiredBindings": ["verification-loop"],
33
+ "optionalBindings": [],
34
+ "forbiddenBindings": [],
35
+ "evidenceHint": "Evidence should record objective checks appropriate to the change."
36
+ }
37
+ ]
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const fs = require('fs');
3
4
  const path = require('path');
4
5
  const { atomicWriteJson, readJson } = require('./fable-contracts');
5
6
  const { resolveBinding, PACKAGED_BINDING_PATHS: BINDING_PATHS } = require('./binding-resolver');
@@ -8,13 +9,102 @@ const OBLIGATION_SCHEMA_VERSION = 1;
8
9
  const OBLIGATION_FILE = 'workflow-obligations.json';
9
10
  const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
10
11
  const ALLOWED_ESCAPE_REASONS = new Set(['workflow-uncovered-scope', 'host-capability-unavailable']);
11
- const STEP_TYPES = new Set(['review', 'behavior-change', 'verification', 'commit']);
12
- const REQUIRED_BINDINGS_BY_STEP = {
13
- review: [],
14
- 'behavior-change': ['tdd'],
15
- verification: ['verification-loop'],
16
- commit: ['git-commit'],
17
- };
12
+ const STEP_TYPE_REGISTRY_FILE = path.join(__dirname, 'step-types.json');
13
+
14
+ function validateStepTypeRegistry(registry) {
15
+ const errors = [];
16
+ if (!Array.isArray(registry) || registry.length === 0) {
17
+ throw new Error('invalid step-type registry: expected a non-empty array');
18
+ }
19
+ const idCounts = new Map();
20
+ const bindingFields = ['requiredBindings', 'optionalBindings', 'forbiddenBindings'];
21
+ for (const entry of registry) {
22
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
23
+ errors.push('entry must be an object');
24
+ continue;
25
+ }
26
+ const id = typeof entry.id === 'string' ? entry.id : '';
27
+ const validId = SAFE_ID.test(id) && id === id.trim();
28
+ const label = validId ? `step type ${id}` : 'step type with invalid id';
29
+ if (!validId) errors.push(`${label} must declare a stable id`);
30
+ else idCounts.set(id, (idCounts.get(id) || 0) + 1);
31
+ if (typeof entry.evidenceHint !== 'string' || !entry.evidenceHint.trim()) {
32
+ errors.push(`${label} evidenceHint must be a non-empty string`);
33
+ }
34
+ const valuesByField = new Map();
35
+ for (const field of bindingFields) {
36
+ if (!Array.isArray(entry[field])) {
37
+ errors.push(`${label} ${field} must be an array`);
38
+ valuesByField.set(field, []);
39
+ continue;
40
+ }
41
+ const values = [];
42
+ for (const binding of entry[field]) {
43
+ if (typeof binding !== 'string' || !SAFE_ID.test(binding) || binding !== binding.trim()) {
44
+ errors.push(`${label} ${field} entries must be stable binding ids`);
45
+ continue;
46
+ }
47
+ values.push(binding);
48
+ }
49
+ const unique = [...new Set(values)].sort();
50
+ if (unique.length !== values.length) errors.push(`${label} ${field} contains duplicate binding ids`);
51
+ valuesByField.set(field, unique);
52
+ }
53
+ for (const [left, right] of [
54
+ ['requiredBindings', 'optionalBindings'],
55
+ ['requiredBindings', 'forbiddenBindings'],
56
+ ['optionalBindings', 'forbiddenBindings'],
57
+ ]) {
58
+ const rightValues = new Set(valuesByField.get(right) || []);
59
+ for (const binding of valuesByField.get(left) || []) {
60
+ if (rightValues.has(binding)) errors.push(`${label} has conflicting ${left} and ${right} default for ${binding}`);
61
+ }
62
+ }
63
+ }
64
+ for (const id of [...idCounts.keys()].sort()) {
65
+ if (idCounts.get(id) > 1) errors.push(`duplicate step type id ${id}`);
66
+ }
67
+ if (errors.length) throw new Error('invalid step-type registry: ' + [...new Set(errors)].sort().join('; '));
68
+ return registry.map(entry => ({
69
+ id: entry.id,
70
+ requiredBindings: [...entry.requiredBindings],
71
+ optionalBindings: [...entry.optionalBindings],
72
+ forbiddenBindings: [...entry.forbiddenBindings],
73
+ evidenceHint: entry.evidenceHint.trim(),
74
+ })).sort((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
75
+ }
76
+
77
+ const STEP_TYPE_REGISTRY_UNAVAILABLE = 'STEP_TYPE_REGISTRY_UNAVAILABLE';
78
+
79
+ function readStepTypeRegistry(registryFile = STEP_TYPE_REGISTRY_FILE) {
80
+ const resolvedRegistryFile = path.resolve(registryFile);
81
+ try {
82
+ const parsed = JSON.parse(fs.readFileSync(resolvedRegistryFile, 'utf8'));
83
+ return validateStepTypeRegistry(parsed);
84
+ } catch (error) {
85
+ const unavailable = new Error(
86
+ `cannot load step-type registry ${resolvedRegistryFile}: ${error.message}. ` +
87
+ `Repair action: reinstall or update the Harness plugin so this file is restored; in a Harness source checkout, restore it and run npm run plugin:sync.`,
88
+ );
89
+ unavailable.code = STEP_TYPE_REGISTRY_UNAVAILABLE;
90
+ throw unavailable;
91
+ }
92
+ }
93
+
94
+ // Loaded on first typed use only, so registry-independent planning and execution never read it.
95
+ let stepTypeRegistry = null;
96
+ function loadStepTypeRegistry() {
97
+ if (!stepTypeRegistry) stepTypeRegistry = readStepTypeRegistry();
98
+ return stepTypeRegistry;
99
+ }
100
+
101
+ function stepTypeIds() {
102
+ return loadStepTypeRegistry().map(entry => entry.id).sort();
103
+ }
104
+
105
+ function stepTypeIndex() {
106
+ return new Map(loadStepTypeRegistry().map(entry => [entry.id, entry]));
107
+ }
18
108
 
19
109
  function obligationPath(sessionDir) {
20
110
  return path.join(sessionDir, OBLIGATION_FILE);
@@ -125,6 +215,14 @@ function initializePlanningContract(context, plan) {
125
215
  return set;
126
216
  }
127
217
 
218
+ function typedStepType(rawStepType) {
219
+ const registered = stepTypeIndex();
220
+ if (!registered.has(rawStepType)) {
221
+ throw new Error(`unsupported requirement stepType: ${rawStepType}; registered step types: ${stepTypeIds().join(', ')}`);
222
+ }
223
+ return registered.get(rawStepType);
224
+ }
225
+
128
226
  function parseRequirements(requirementsJson, workspaceRoot) {
129
227
  let parsed;
130
228
  try { parsed = JSON.parse(String(requirementsJson || '')); }
@@ -145,7 +243,7 @@ function parseRequirements(requirementsJson, workspaceRoot) {
145
243
  ? [...new Set(item.suggestedSkills.filter(value => typeof value === 'string' && value.trim()).map(value => value.trim()))]
146
244
  : [];
147
245
  const rawStepType = item.stepType === undefined ? '' : String(item.stepType).trim();
148
- if (rawStepType && !STEP_TYPES.has(rawStepType)) throw new Error(`unsupported requirement stepType: ${rawStepType}`);
246
+ const stepType = rawStepType ? typedStepType(rawStepType) : null;
149
247
  for (const field of ['requiredBindings', 'optionalBindings']) {
150
248
  if (Object.prototype.hasOwnProperty.call(item, field) && !Array.isArray(item[field])) {
151
249
  throw new Error(`${id}.${field} must be an array`);
@@ -155,17 +253,18 @@ function parseRequirements(requirementsJson, workspaceRoot) {
155
253
  if (!rawStepType) return requirement;
156
254
 
157
255
  const requiredBindings = normalizeBindingDeclarations([
158
- ...(REQUIRED_BINDINGS_BY_STEP[rawStepType] || []),
256
+ ...(stepType.requiredBindings || []),
159
257
  ...(item.requiredBindings || []),
160
258
  ]);
161
259
  const requiredIds = new Set(requiredBindings.map(binding => binding.id));
162
260
  const optionalBindings = normalizeBindingDeclarations([
261
+ ...(stepType.optionalBindings || []),
163
262
  ...(item.optionalBindings || []),
164
263
  ...suggestedSkills,
165
264
  ]).filter(binding => !requiredIds.has(binding.id));
166
- if (rawStepType === 'review' && [...requiredBindings, ...optionalBindings].some(binding => binding.id === 'tdd')) {
167
- throw new Error('review steps cannot bind tdd');
168
- }
265
+ const forbiddenBinding = [...requiredBindings, ...optionalBindings]
266
+ .find(binding => stepType.forbiddenBindings.includes(binding.id));
267
+ if (forbiddenBinding) throw new Error(`${rawStepType} steps cannot bind ${forbiddenBinding.id}`);
169
268
  requirement.stepType = rawStepType;
170
269
  requirement.status = 'pending';
171
270
  requirement.evidence = null;
@@ -268,7 +367,7 @@ function recordPlanning(context, requirementsJson, selectedPlan, requestedStrate
268
367
  }
269
368
  const isFable = String(selectedPlan.strategy || '').startsWith('fable-');
270
369
  if (!isFable && !hasTypedSteps) {
271
- throw new Error('selected single-agent workflows require ordered stepType values: review, behavior-change, verification, or commit');
370
+ throw new Error(`selected single-agent workflows require ordered stepType values: ${stepTypeIds().join(', ')}`);
272
371
  }
273
372
  if (!isFable && !requirements.some(item => item.stepType === 'verification')) {
274
373
  throw new Error('step-bound workflows require an explicit verification step');
@@ -360,7 +459,8 @@ function validateObligationSet(context, set, plan = context.workflow?.pendingPla
360
459
  if (!['pending', 'pass', 'escaped', 'blocked'].includes(obligation.status)) return 'obligation-status-invalid';
361
460
  }
362
461
  if (set.stepBindingsEnabled === true) {
363
- if (set.requirements.some(item => !item || !STEP_TYPES.has(item.stepType) ||
462
+ const registered = stepTypeIndex();
463
+ if (set.requirements.some(item => !item || !registered.has(item.stepType) ||
364
464
  !['pending', 'pass', 'blocked'].includes(item.status) || !Array.isArray(item.requiredBindings) ||
365
465
  !Array.isArray(item.optionalBindings))) return 'steps-invalid';
366
466
  for (const step of set.requirements) {
@@ -585,6 +685,9 @@ function unresolvedObligations(context) {
585
685
  module.exports = {
586
686
  OBLIGATION_FILE,
587
687
  ALLOWED_ESCAPE_REASONS,
688
+ loadStepTypeRegistry,
689
+ stepTypeIds,
690
+ validateStepTypeRegistry,
588
691
  obligationPath,
589
692
  needsPlanningContract,
590
693
  needsGenericExecutionObligations,
@@ -7,15 +7,20 @@ const { loadWorkflow, saveWorkflow, matchingRun, OPEN_STATES, WORKFLOW_CONTROLLE
7
7
  const { getWorkspaceRoot, readCurrentSession } = require('./lib/harness-state');
8
8
  const { atomicWriteJson, readJson } = require('./lib/fable-contracts');
9
9
  const { resolveBinding } = require('./lib/binding-resolver');
10
- const {
11
- planningUnresolved,
12
- recordPlanning,
13
- materializeExecutionObligations,
14
- updateObligation,
15
- updateBinding,
16
- updateStep,
17
- activeStepSnapshot,
18
- } = require('./lib/workflow-obligations');
10
+
11
+ let obligationApi;
12
+ function workflowObligations() {
13
+ if (!obligationApi) obligationApi = require('./lib/workflow-obligations');
14
+ return obligationApi;
15
+ }
16
+
17
+ const planningUnresolved = (...args) => workflowObligations().planningUnresolved(...args);
18
+ const recordPlanning = (...args) => workflowObligations().recordPlanning(...args);
19
+ const materializeExecutionObligations = (...args) => workflowObligations().materializeExecutionObligations(...args);
20
+ const updateObligation = (...args) => workflowObligations().updateObligation(...args);
21
+ const updateBinding = (...args) => workflowObligations().updateBinding(...args);
22
+ const updateStep = (...args) => workflowObligations().updateStep(...args);
23
+ const activeStepSnapshot = (...args) => workflowObligations().activeStepSnapshot(...args);
19
24
 
20
25
  const ALLOWED_ESCAPE_REASONS = new Set(['workflow-uncovered-scope', 'host-capability-unavailable']);
21
26
 
@@ -149,6 +154,8 @@ function activatePlan(workflow, plan) {
149
154
  }
150
155
 
151
156
  function main() {
157
+ // The step-type registry loads lazily through the wrappers above, only for commands that
158
+ // consume typed obligations; the top-level handler turns a load failure into one semantic line.
152
159
  if (process.argv[2] === '--help' || process.argv[2] === '-h') {
153
160
  process.stdout.write(usage() + '\n');
154
161
  return;
@@ -3,35 +3,58 @@
3
3
  const path = require('path');
4
4
  const { readJson } = require('./lib/fable-contracts');
5
5
  const { loadWorkflow, saveWorkflow, matchingRun, unresolvedStages, readHookInput } = require('./lib/workflow-runtime');
6
- const { planningUnresolved, unresolvedObligations } = require('./lib/workflow-obligations');
6
+
7
+ const REGISTRY_UNAVAILABLE = 'step-type-registry-unavailable';
8
+ const STEP_TYPE_REGISTRY_UNAVAILABLE = 'STEP_TYPE_REGISTRY_UNAVAILABLE';
7
9
 
8
10
  function warn(message) { console.error('[Workflow Reminder] ' + message); }
9
11
 
10
12
  function decide(payload) {
11
13
  if (!payload) return;
12
14
  try {
15
+ const { planningUnresolved, unresolvedObligations } = require('./lib/workflow-obligations');
13
16
  const context = loadWorkflow(payload);
14
17
  const { workflow, sessionDir } = context;
15
18
  if (!workflow || workflow.state === 'deferred') return;
16
19
  const handoff = readJson(path.join(sessionDir, 'handoff-state.json'));
17
- let unresolved = planningUnresolved(context);
20
+ const unresolved = [];
21
+ const diagnostics = [];
22
+ let requiredFault = false;
23
+
24
+ // Only a validation that actually reads the registry can fail here. It records the
25
+ // semantic diagnostic and the unresolved token itself; other checks keep running.
26
+ const required = check => {
27
+ try {
28
+ unresolved.push(...check());
29
+ } catch (error) {
30
+ if (error.code !== STEP_TYPE_REGISTRY_UNAVAILABLE) throw error;
31
+ diagnostics.push(error.message);
32
+ unresolved.push(REGISTRY_UNAVAILABLE);
33
+ requiredFault = true;
34
+ }
35
+ };
18
36
 
37
+ required(() => planningUnresolved(context));
19
38
  if (String(workflow.strategy || '').startsWith('fable-')) {
20
39
  const match = matchingRun(context);
21
40
  unresolved.push(...(match ? unresolvedStages(match, workflow, handoff?.lastEditAt || 0) : ['correlated-run-missing']));
22
41
  } else {
23
- unresolved.push(...unresolvedObligations(context));
42
+ required(() => unresolvedObligations(context));
24
43
  const lastEdit = Math.max(workflow.lastMutationAt || 0, handoff?.lastEditAt || 0);
25
44
  if (lastEdit && (handoff?.lastVerifyAt || 0) < lastEdit) unresolved.push('verification-after-edit-missing');
26
45
  }
27
46
 
28
- unresolved = [...new Set(unresolved)];
47
+ const pending = [...new Set(unresolved)];
29
48
  const wasBlocked = workflow.state === 'blocked';
30
49
  if (wasBlocked) warn('Workflow is marked BLOCKED; report or revisit the recorded blocker, but Harness will not trap the session.');
31
- if (unresolved.length) {
32
- workflow.unresolved = unresolved;
33
- saveWorkflow(context);
34
- warn('Unresolved workflow evidence: ' + unresolved.join(', ') + '. Resolve/verify before claiming completion.');
50
+ [...new Set(diagnostics)].forEach(message => warn(message));
51
+ if (pending.length) {
52
+ // A failed required validation leaves the workflow file as recorded; it is never marked satisfied.
53
+ if (!requiredFault) {
54
+ workflow.unresolved = pending;
55
+ saveWorkflow(context);
56
+ }
57
+ warn('Unresolved workflow evidence: ' + pending.join(', ') + '. Resolve/verify before claiming completion.');
35
58
  return;
36
59
  }
37
60
  if (wasBlocked) return;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "harness-enforcement",
3
3
  "description": "Repository inventory for the opencode enforcement plugin and its standalone helper",
4
- "version": "0.31.3",
4
+ "version": "0.32.0",
5
5
  "runtime": "index.mjs",
6
6
  "hooks": {
7
7
  "verify": "hooks/verify.js"