@khoavu882/doflow 2.0.0-beta.4 → 2.0.0-beta.5

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 (101) hide show
  1. package/core/.antigravity-plugin/plugin.json +0 -1
  2. package/core/.claude-plugin/plugin.json +1 -1
  3. package/core/.codex-plugin/plugin.json +1 -1
  4. package/core/.plugin/plugin.json +1 -1
  5. package/core/harnesses/claude/hooks/mcp-tool-guard.sh +7 -17
  6. package/core/harnesses/claude/hooks/pre-bash-guard.sh +7 -17
  7. package/core/harnesses/claude/hooks/pre-implement-gate.sh +7 -18
  8. package/core/harnesses/claude/hooks/session-start.sh +5 -3
  9. package/core/harnesses/claude/hooks/stop-check.sh +5 -3
  10. package/core/harnesses/claude/hooks/subagent-audit.sh +5 -5
  11. package/core/harnesses/claude/hooks/user-prompt-submit.sh +5 -3
  12. package/core/harnesses/codex/hooks/mcp-tool-guard.sh +7 -15
  13. package/core/harnesses/codex/hooks/pre-bash-guard.sh +7 -15
  14. package/core/harnesses/codex/hooks/pre-implement-gate.sh +7 -16
  15. package/core/harnesses/codex/hooks/session-start.sh +5 -3
  16. package/core/harnesses/codex/hooks/stop-check.sh +6 -5
  17. package/core/harnesses/codex/hooks/subagent-audit.sh +17 -6
  18. package/core/harnesses/codex/hooks/user-prompt-submit.sh +5 -4
  19. package/core/harnesses/gemini/hooks/mcp-tool-guard.sh +7 -18
  20. package/core/harnesses/gemini/hooks/pre-bash-guard.sh +7 -18
  21. package/core/harnesses/gemini/hooks/pre-implement-gate.sh +7 -19
  22. package/core/harnesses/gemini/hooks/session-start.sh +5 -3
  23. package/core/harnesses/kiro/hooks/mcp-tool-guard.sh +20 -5
  24. package/core/harnesses/kiro/hooks/pre-bash-guard.sh +20 -5
  25. package/core/harnesses/kiro/hooks/pre-implement-gate.sh +20 -5
  26. package/core/harnesses/kiro/hooks/session-start.sh +11 -5
  27. package/core/harnesses/kiro/hooks/stop-check.sh +21 -30
  28. package/core/harnesses/pi/extensions/doflow-guard.js +159 -0
  29. package/core/harnesses/shared/hooks/ENVELOPE_MIGRATION.md +27 -11
  30. package/core/harnesses/shared/hooks/adapters/antigravity.js +14 -57
  31. package/core/harnesses/shared/hooks/bridge/bridge.sh +184 -0
  32. package/core/harnesses/shared/hooks/bridge/envelope.jq +60 -0
  33. package/core/harnesses/shared/hooks/bridge/respond.sh +62 -0
  34. package/core/harnesses/shared/hooks/policies/capture-failure.sh +4 -2
  35. package/core/harnesses/shared/hooks/policies/contract.sh +75 -0
  36. package/core/harnesses/shared/hooks/policies/deny-json.sh +39 -4
  37. package/core/harnesses/shared/hooks/policies/lib.sh +4 -2
  38. package/core/harnesses/shared/hooks/policies/mcp-tool-guard.sh +46 -34
  39. package/core/harnesses/shared/hooks/policies/pre-bash-guard.sh +75 -25
  40. package/core/harnesses/shared/hooks/policies/pre-implementation-gate.sh +67 -73
  41. package/core/harnesses/shared/hooks/policies/session-context.sh +37 -7
  42. package/core/harnesses/shared/hooks/policies/stop-check.sh +42 -15
  43. package/core/harnesses/shared/hooks/policies/subagent-audit.sh +35 -5
  44. package/core/harnesses/shared/hooks/policies/user-prompt-submit.sh +40 -7
  45. package/core/harnesses/shared/hooks/stream-hook-runner.js +69 -181
  46. package/core/registry/assets.json +19 -0
  47. package/core/registry/contracts.json +2 -2
  48. package/core/registry/harnesses.json +196 -10
  49. package/core/registry/lifecycle.json +2626 -7
  50. package/core/registry/storage.json +24 -1
  51. package/core/shared/scripts/doflow/bin/doflow-run +10 -6
  52. package/core/shared/skills/do-design/SKILL.md +6 -6
  53. package/core/shared/skills/do-execute-plan/SKILL.md +11 -10
  54. package/core/shared/skills/do-execute-plan/references/readiness_gate.md +2 -0
  55. package/core/shared/skills/do-implement/SKILL.md +3 -2
  56. package/core/shared/skills/do-plan/SKILL.md +7 -8
  57. package/package.json +1 -1
  58. package/src/adapters/antigravity/index.js +83 -47
  59. package/src/adapters/claude/index.js +15 -1
  60. package/src/adapters/codex/hooks.js +40 -5
  61. package/src/adapters/codex/index.js +52 -9
  62. package/src/adapters/copy-tree.js +4 -4
  63. package/src/adapters/gemini/hooks.js +57 -16
  64. package/src/adapters/gemini/index.js +57 -18
  65. package/src/adapters/kiro/index.js +15 -1
  66. package/src/adapters/pi/hooks.js +119 -0
  67. package/src/adapters/pi/index.js +34 -9
  68. package/src/cli/commands/install.js +1 -1
  69. package/src/cli/commands/update.js +1 -1
  70. package/src/cli/index.js +17 -5
  71. package/src/cli/runtime-commands.js +51 -12
  72. package/src/lifecycle/coverage.js +57 -0
  73. package/src/lifecycle/hook-step.js +61 -0
  74. package/src/lifecycle/index.js +28 -14
  75. package/src/registry/index.js +136 -7
  76. package/src/runtime/candidate.js +505 -0
  77. package/src/runtime/claims.js +14 -5
  78. package/src/runtime/cli-result.js +11 -4
  79. package/src/runtime/cli.js +35 -268
  80. package/src/runtime/context/budget.js +203 -0
  81. package/src/runtime/context/compose.js +1367 -0
  82. package/src/runtime/context/delivery-store.js +102 -0
  83. package/src/runtime/context/mandatory.js +594 -0
  84. package/src/runtime/context/pointer.js +142 -0
  85. package/src/runtime/context-pack.js +1029 -244
  86. package/src/runtime/evidence-fields.js +39 -0
  87. package/src/runtime/evidence-ledger.js +7 -0
  88. package/src/runtime/freshness.js +44 -7
  89. package/src/runtime/outcome.js +1 -1
  90. package/src/runtime/readiness.js +83 -13
  91. package/src/runtime/retrieval-plan.js +422 -73
  92. package/src/runtime/retrieval-record.js +223 -0
  93. package/src/runtime/scaffold/artifacts.js +3 -0
  94. package/src/runtime/source-version.js +289 -0
  95. package/src/runtime/task-attempts.js +1 -1
  96. package/src/runtime/task-scope.js +28 -3
  97. package/src/runtime/task-state.js +72 -7
  98. package/core/.antigravity-plugin/hooks.json +0 -39
  99. package/core/harnesses/shared/hooks/adapters/arg-fields.js +0 -19
  100. package/core/harnesses/shared/hooks/adapters/gemini.js +0 -114
  101. package/core/harnesses/shared/hooks/hooks.json +0 -47
@@ -5,12 +5,12 @@
5
5
  const crypto = require('node:crypto');
6
6
  const fs = require('node:fs');
7
7
  const path = require('node:path');
8
- const { execFileSync } = require('node:child_process');
9
8
  const { CapabilityRouter } = require('./capability-router.js');
10
- const { EvidenceLedger, VALID_EVIDENCE_KINDS, VALID_PROVENANCE } = require('./evidence-ledger.js');
11
- const { resolveLocator, describeResolution } = require('./locator-resolve.js');
9
+ const { EvidenceLedger } = require('./evidence-ledger.js');
12
10
  const { ClaimsManager } = require('./claims.js');
13
- const { measureFreshness } = require('./freshness.js');
11
+ const { measureTreeState } = require('./source-version.js');
12
+ const { toEvidence, validateEvidenceItem, EVIDENCE_REFUSED_FIELDS } = require('./candidate.js');
13
+ const { sourceModeLookup } = require('./retrieval-plan.js');
14
14
  const { evaluateTaskReadiness } = require('./readiness.js');
15
15
  const { writeReadinessRecord } = require('./readiness-record.js');
16
16
  const { parseDeclaredScope } = require('./verification/scope-bound.js');
@@ -90,7 +90,7 @@ function handleCapabilitiesCommand({ json = false, check = false, repoRoot }
90
90
  * @returns {number} exit code: 0 once the evaluation is recorded, whatever its state
91
91
  */
92
92
  function handleReadinessCommand({
93
- taskClass = 'feature', taskId = 'default', json = false, repoRoot, stateRoot,
93
+ taskClass = 'feature', taskId = 'default', json = false, repoRoot, stateRoot, sourceRoot,
94
94
  verificationPlan, scopeClear, invariants, userDecisionPending = false, mode = 'workflow', now, slug = null,
95
95
  } = {}) {
96
96
  // Two different roots, previously conflated into one. `root` locates the *registry* (the
@@ -111,7 +111,7 @@ function handleReadinessCommand({
111
111
 
112
112
  let report;
113
113
  try {
114
- report = evaluateTaskReadiness({ taskProfile: profile, repoRoot: root, projectRoot: state, mode });
114
+ report = evaluateTaskReadiness({ taskProfile: profile, repoRoot: root, projectRoot: state, treeRoot: sourceRoot || state, mode });
115
115
  } catch (error ) {
116
116
  return usageError('readiness', error.message, json, error);
117
117
  }
@@ -196,263 +196,23 @@ function handleReadinessCommand({
196
196
  // every key it does not recognise, so a field this boundary forwards blindly is a field the caller
197
197
  // watches vanish while the command reports success. Nothing reaches the ledger unnamed.
198
198
 
199
- /** Every field an evidence item may carry here. Anything else is refused, never dropped. */
200
- const EVIDENCE_ITEM_FIELDS = ['kind', 'provenance', 'source', 'locator', 'content', 'taskId', 'establishes', 'observation'];
201
- const EVIDENCE_SOURCE_FIELDS = ['provider', 'capability'];
202
- const EVIDENCE_LOCATOR_FIELDS = ['file', 'line', 'symbol', 'uri'];
203
- const EVIDENCE_OBSERVATION_FIELDS = ['command', 'exitCode'];
204
-
205
- /** Kinds that record an execution and may carry a typed observation. */
206
- const OBSERVATION_KINDS = new Set(['test-result', 'runtime-observation']);
207
-
208
- /** Kinds that are by definition not a direct read of the repository. FR-007's second sentence. */
209
- const NON_REPOSITORY_KINDS = new Set(['generated-analysis', 'user-statement']);
210
-
211
- /** Fields a caller might plausibly send that this boundary refuses by name, with the reason.
212
- * A named refusal beats the generic unknown-field error: each of these would otherwise be
213
- * silently discarded by `addEvidence`, and a silent discard reads as a successful write. */
214
- const EVIDENCE_REFUSED_FIELDS = new Map([
215
- ['id', 'evidence ids are minted by the ledger — a caller-chosen id can overwrite an unrelated record'],
216
- ['freshness', 'freshness is measured here from the working tree at write time, never asserted by the writer'],
217
- ['supports', 'link evidence to a claim with `claim --action link`, which updates both sides; a list written here would leave the claim unaware of it'],
218
- ['contradicts', 'link evidence to a claim with `claim --action link`, which updates both sides; a list written here would leave the claim unaware of it'],
219
- ['stage', 'the evidence record has no stage field — the batch *is* the stage boundary, so a stage name recorded here would be dropped'],
220
- ['status', "lifecycle status starts 'active' and changes only through `evidence --action supersede` — asserting it here would let a caller declare an item superseded without naming what replaces it"],
221
- ]);
222
-
223
- /** The names a retrieval score arrives under, in camelCase (`--relevance-score` normalises here).
224
- * Exported because `bin/doflow.js` refuses the same names on the command line, and because
225
- * `retrieval-plan.ts` and `outcome.ts` refuse them on the option object a declared plan and a
226
- * terminal record are built from: one definition, three input surfaces (argv, a `--batch` JSON
227
- * file, and a verb's own options), each with exactly one enforcement point. A second copy of
228
- * this list is how one of them drifts. */
229
- const EVIDENCE_SCORE_FIELDS = new Set([
230
- 'confidence', 'score', 'relevance', 'relevanceScore', 'similarity',
231
- 'certainty', 'probability', 'rank', 'distance', 'weight',
232
- ]);
233
-
234
- /** The one refusal message for a score offered as a property of a fact. */
235
- function scoreFieldRefusal(name ) {
236
- return `'${name}' is a retrieval score and this boundary records none (FR-007). Relevance is a `
237
- + 'property of a search, not of a fact: stored beside the fact it is read as confidence by the '
238
- + 'next worker, which is the specific interpretation the requirement forbids. Record the '
239
- + 'locator and the content instead — a reader who can see where a fact came from does not need '
240
- + 'to be told how sure to be.';
241
- }
242
-
243
- /** Refuses a score-shaped key anywhere in an item, including nested under source or locator. */
244
- function assertNoScoreFields(value , prefix ) {
245
- if (!value || typeof value !== 'object' || Array.isArray(value)) return;
246
- for (const [key, inner] of Object.entries(value)) {
247
- const dotted = prefix ? `${prefix}.${key}` : key;
248
- if (EVIDENCE_SCORE_FIELDS.has(key)) throw new Error(scoreFieldRefusal(dotted));
249
- assertNoScoreFields(inner, dotted);
250
- }
251
- }
252
-
253
- /**
254
- * Normalises a locator given either as an object or as a `file[:line]` / URI string.
255
- * @param {Object|string} raw
256
- * @returns {Object}
257
- */
258
- function parseLocator(raw ) {
259
- if (typeof raw === 'string') {
260
- const text = raw.trim();
261
- if (text === '') throw new Error('locator is empty');
262
- if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text)) return { uri: text };
263
- const withLine = text.match(/^(.+):(\d+)$/);
264
- if (withLine) return { file: withLine[1], line: Number(withLine[2]) };
265
- return { file: text };
266
- }
267
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
268
- throw new Error("locator must be an object, or a 'path/to/file[:line]' or URI string");
269
- }
270
- const locator = {};
271
- for (const [key, value] of Object.entries(raw)) {
272
- if (!EVIDENCE_LOCATOR_FIELDS.includes(key)) {
273
- throw new Error(`unknown locator field '${key}'. Accepted: ${EVIDENCE_LOCATOR_FIELDS.join(', ')}`);
274
- }
275
- locator[key] = value;
276
- }
277
- if (locator.line !== undefined && (!Number.isInteger(locator.line) || locator.line < 1)) {
278
- throw new Error(`locator.line must be a positive integer, got '${locator.line}'`);
279
- }
280
- for (const key of ['file', 'symbol', 'uri']) {
281
- if (locator[key] !== undefined && (typeof locator[key] !== 'string' || locator[key].trim() === '')) {
282
- throw new Error(`locator.${key} must be a non-empty string`);
283
- }
284
- }
285
- if (!locator.file && !locator.uri) throw new Error('a locator needs at least a file or a uri');
286
- return locator;
287
- }
288
-
289
- /**
290
- * Validates one raw evidence item and returns the record fields the ledger will store.
291
- *
292
- * Throws on anything it cannot account for. Every rule here traces to FR-007 or to the
293
- * vacuous-record family: a record with no statement and no locator asserts nothing, and storing it
294
- * inflates the evidence count that the readiness gate then reads.
295
- *
296
- * @param {Object} raw
297
- * @param {string} taskId the task the batch is being written to
298
- * @param {string} [repoRoot] root a relative locator resolves against; defaults to cwd
299
- * @returns {{kind:string, provenance:string, source:Object, locator:Object, content:(string|null)}}
300
- */
301
- function validateEvidenceItem(raw , taskId , repoRoot ) {
302
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('an evidence item must be a JSON object');
303
- assertNoScoreFields(raw, '');
304
-
305
- for (const key of Object.keys(raw)) {
306
- if (EVIDENCE_REFUSED_FIELDS.has(key)) throw new Error(`'${key}' is not accepted here: ${EVIDENCE_REFUSED_FIELDS.get(key)}`);
307
- if (!EVIDENCE_ITEM_FIELDS.includes(key)) {
308
- throw new Error(`unknown evidence field '${key}'. Accepted: ${EVIDENCE_ITEM_FIELDS.join(', ')}`);
309
- }
310
- }
311
-
312
- if (raw.taskId !== undefined && raw.taskId !== taskId) {
313
- throw new Error(`item names task '${raw.taskId}' but this write targets '${taskId}' — one write, one task`);
314
- }
315
-
316
- const kinds = [...VALID_EVIDENCE_KINDS].sort().join(', ');
317
- if (typeof raw.kind !== 'string' || raw.kind.trim() === '') throw new Error(`kind is required. Valid: ${kinds}`);
318
- if (!VALID_EVIDENCE_KINDS.has(raw.kind)) throw new Error(`unknown evidence kind '${raw.kind}'. Valid: ${kinds}`);
319
-
320
- const provenances = [...VALID_PROVENANCE].sort().join(', ');
321
- if (typeof raw.provenance !== 'string' || raw.provenance.trim() === '') {
322
- throw new Error('provenance is required and has no default here — defaulting it would file model '
323
- + `analysis as repository fact, the one distinction FR-007 makes binding. Valid: ${provenances}`);
324
- }
325
- if (!VALID_PROVENANCE.has(raw.provenance)) throw new Error(`unknown provenance '${raw.provenance}'. Valid: ${provenances}`);
326
- if (NON_REPOSITORY_KINDS.has(raw.kind) && raw.provenance === 'extracted') {
327
- throw new Error(`kind '${raw.kind}' cannot carry provenance 'extracted': it is not a read of the `
328
- + "repository, and labelling it as one is exactly how model analysis stops being distinguishable "
329
- + "from fact. Use 'inferred' (derived by analysis) or 'asserted' (stated by a person).");
330
- }
331
-
332
- if (raw.source === undefined) {
333
- throw new Error('source is required: which provider answered, under which capability. '
334
- + "It has no default — 'unknown/general' is a plausible-looking answer to a question nobody asked.");
335
- }
336
- if (!raw.source || typeof raw.source !== 'object' || Array.isArray(raw.source)) {
337
- throw new Error('source must be an object with provider and capability');
338
- }
339
- for (const key of Object.keys(raw.source)) {
340
- if (!EVIDENCE_SOURCE_FIELDS.includes(key)) {
341
- throw new Error(`unknown source field '${key}'. Accepted: ${EVIDENCE_SOURCE_FIELDS.join(', ')}`);
342
- }
343
- }
344
- for (const key of EVIDENCE_SOURCE_FIELDS) {
345
- if (typeof raw.source[key] !== 'string' || raw.source[key].trim() === '') {
346
- throw new Error(`source.${key} is required and must be a non-empty string`);
347
- }
348
- }
349
-
350
- const locator = raw.locator === undefined ? null : parseLocator(raw.locator);
351
- // An item carrying an observation is anchored by the command it records — that command is what
352
- // the next worker re-runs to check it — so the locator becomes optional there and only there.
353
- if (raw.provenance === 'extracted' && !locator && raw.observation === undefined) {
354
- throw new Error("provenance 'extracted' requires a locator — a fact read from the repository "
355
- + 'must name where it was read, or the next worker cannot check it and cannot tell when it goes stale');
356
- }
357
-
358
- // A locator that parses is not a locator that resolves (FR-004). Shape validation alone let an
359
- // item naming line 799 of a 28-line file be recorded as support and counted by the readiness
360
- // gate. The refusal names what the file actually offers, so the writer can correct it here rather
361
- // than discover it at the gate.
362
- if (raw.provenance === 'extracted' && locator) {
363
- const resolution = resolveLocator({ locator, repoRoot });
364
- if (!resolution.resolved) {
365
- throw new Error(`the locator does not resolve: ${describeResolution(locator, resolution)}. `
366
- + "An 'extracted' item asserts a read of the repository, so a locator that points at nothing "
367
- + 'records a fact nobody can check');
368
- }
369
- }
370
-
371
- if (raw.content !== undefined && typeof raw.content !== 'string') throw new Error('content must be a string');
372
- const content = typeof raw.content === 'string' && raw.content.trim() !== '' ? raw.content : null;
373
- if (raw.provenance !== 'extracted' && !content) {
374
- throw new Error(`provenance '${raw.provenance}' requires content — an inferred or asserted item `
375
- + 'is the statement itself, so a record without one records nothing while still counting as evidence');
376
- }
377
-
378
- // Requirement bindings: which readiness-template requirements this item claims to establish.
379
- // Declared by the writer, judged by the gate — the gate counts an item toward a requirement only
380
- // when it is named here, so a structural item can no longer satisfy `architecture_mapped` and
381
- // `blast_radius` at once by category alone (review R1).
382
- let establishes = [];
383
- if (raw.establishes !== undefined) {
384
- const list = typeof raw.establishes === 'string' ? raw.establishes.split(',').map((s ) => s.trim()) : raw.establishes;
385
- if (!Array.isArray(list) || list.length === 0 || list.some((r) => typeof r !== 'string' || r.trim() === '')) {
386
- throw new Error("'establishes' must be a requirement id, a comma-separated list of them, or a non-empty array of non-empty strings");
387
- }
388
- establishes = list.map((s) => s.trim());
389
- }
390
-
391
- // Typed observation: the execution behind a test-result or runtime-observation. Command and exit
392
- // status are the two facts the gate can actually grade; tree identity and observation time are
393
- // measured into freshness at this same write. Only an 'extracted' item may carry one — an
394
- // observation asserts an execution happened, and an inferred item is by definition not one.
395
- let observation = null;
396
- if (raw.observation !== undefined) {
397
- if (!raw.observation || typeof raw.observation !== 'object' || Array.isArray(raw.observation)) {
398
- throw new Error('observation must be an object with command and exitCode');
399
- }
400
- for (const key of Object.keys(raw.observation)) {
401
- if (!EVIDENCE_OBSERVATION_FIELDS.includes(key)) {
402
- throw new Error(`unknown observation field '${key}'. Accepted: ${EVIDENCE_OBSERVATION_FIELDS.join(', ')}`);
403
- }
404
- }
405
- if (typeof raw.observation.command !== 'string' || raw.observation.command.trim() === '') {
406
- throw new Error('observation.command is required: the exact command whose exit status is being recorded');
407
- }
408
- if (!Number.isInteger(raw.observation.exitCode) || raw.observation.exitCode < 0) {
409
- throw new Error(`observation.exitCode must be a non-negative integer, got '${raw.observation.exitCode}'`);
410
- }
411
- if (!OBSERVATION_KINDS.has(raw.kind)) {
412
- throw new Error(`kind '${raw.kind}' cannot carry an observation — only ${[...OBSERVATION_KINDS].join(', ')} record an execution`);
413
- }
414
- if (raw.provenance !== 'extracted') {
415
- throw new Error(`provenance '${raw.provenance}' cannot carry an observation: an observation asserts a command `
416
- + 'was actually run, which is a read of the world, not an inference or an assertion. '
417
- + "Either record the execution as 'extracted', or drop the observation.");
418
- }
419
- observation = { command: raw.observation.command.trim(), exitCode: raw.observation.exitCode };
420
- }
421
- if (raw.kind === 'test-result' && raw.provenance === 'extracted' && !observation) {
422
- throw new Error("an 'extracted' test-result requires an observation ({command, exitCode}) — a test result "
423
- + 'without the command and exit status behind it is a claim about an execution nobody can check, '
424
- + 'and it is exactly how a failed baseline was once accepted as a passing one');
425
- }
426
-
427
- return {
428
- kind: raw.kind,
429
- provenance: raw.provenance,
430
- source: { provider: raw.source.provider, capability: raw.source.capability },
431
- locator: locator || {},
432
- content,
433
- establishes,
434
- observation,
435
- };
436
- }
199
+ const {
200
+ EVIDENCE_SCORE_FIELDS,
201
+ scoreFieldRefusal,
202
+ assertNoScoreFields,
203
+ } = require('./evidence-fields.js');
437
204
 
438
- /** HEAD of the tree the evidence was observed in, or null outside a repo. Measured, not asserted. */
439
- function headCommit(root ) {
440
- try {
441
- return execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], {
442
- encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'],
443
- }).trim() || null;
444
- } catch {
445
- return null;
446
- }
447
- }
448
205
 
449
206
 
450
207
  /**
451
208
  * Reads a stage's evidence batch: a JSON array, or `{ "evidence": [...] }`.
452
209
  * @param {string} batchPath a file path, or `-` for stdin
210
+ * @param {string} taskId
211
+ * @param {string} root
212
+ * @param {string|null} [slug]
453
213
  * @returns {Array<Object>}
454
214
  */
455
- function readEvidenceBatch(batchPath ) {
215
+ function readEvidenceBatch(batchPath , taskId , root , slug = null) {
456
216
  let text;
457
217
  try {
458
218
  text = batchPath === '-' ? fs.readFileSync(0, 'utf8') : fs.readFileSync(path.resolve(batchPath), 'utf8');
@@ -469,7 +229,9 @@ function readEvidenceBatch(batchPath ) {
469
229
  if (data && typeof data === 'object') {
470
230
  for (const key of Object.keys(data)) {
471
231
  if (key === 'evidence') continue;
472
- const named = EVIDENCE_REFUSED_FIELDS.has(key) ? ` — ${EVIDENCE_REFUSED_FIELDS.get(key)}` : '';
232
+ const refusedVal = EVIDENCE_REFUSED_FIELDS.get(key);
233
+ const reason = typeof refusedVal === 'function' ? refusedVal(taskId, root, slug) : refusedVal;
234
+ const named = reason ? ` — ${reason.endsWith('.') ? reason.slice(0, -1) : reason}` : '';
473
235
  throw new Error(`unknown batch field '${key}'${named}. A batch is a JSON array of items, `
474
236
  + "or an object whose only key is 'evidence'");
475
237
  }
@@ -483,7 +245,7 @@ function readEvidenceBatch(batchPath ) {
483
245
  * The `--action add` arm: validate the whole batch, then write it.
484
246
  * @returns {number} exit code
485
247
  */
486
- function addEvidence({ ledger, root, taskId, item, batchPath, json } ) {
248
+ function addEvidence({ ledger, root, sourceRoot = root, attemptRoot, taskId, item, batchPath, json, slug = null } ) {
487
249
  const flagged = item && Object.keys(item).length > 0;
488
250
  if (flagged && batchPath) {
489
251
  return usageError('evidence', '--batch and the single-item flags are two spellings of the same write; use one', json);
@@ -495,7 +257,7 @@ function addEvidence({ ledger, root, taskId, item, batchPath, json } ) {
495
257
 
496
258
  let raws;
497
259
  try {
498
- raws = batchPath ? readEvidenceBatch(batchPath) : [item];
260
+ raws = batchPath ? readEvidenceBatch(batchPath, taskId, root, slug) : [item];
499
261
  } catch (error ) {
500
262
  return usageError('evidence', error.message, json, error);
501
263
  }
@@ -506,26 +268,30 @@ function addEvidence({ ledger, root, taskId, item, batchPath, json } ) {
506
268
 
507
269
  // The whole batch is validated before any of it is written. A half-written stage batch is worse
508
270
  // than a rejected one: the half that landed looks complete to every later reader.
271
+ const treeState = measureTreeState(root);
272
+ const hasAbsence = raws.some((raw ) => raw?.absence === true);
273
+ const absenceTreeState = hasAbsence && path.resolve(sourceRoot) !== path.resolve(root)
274
+ ? measureTreeState(sourceRoot) : null;
275
+ const providerFreshness = new Map();
276
+ let sourceModeOf = null;
509
277
  const validated = [];
510
278
  for (const [index, raw] of raws.entries()) {
511
279
  try {
512
- validated.push(validateEvidenceItem(raw, taskId, root));
280
+ if (raw && raw.absence && !sourceModeOf) {
281
+ sourceModeOf = sourceModeLookup(new CapabilityRouter({ repoRoot: REPO_ROOT }).capabilities);
282
+ }
283
+ validated.push(toEvidence({ item: raw }, { taskId, root, treeState, absenceTreeState, probeRoot: sourceRoot, attemptRoot, slug, providerFreshness, sourceModeOf }));
513
284
  } catch (error ) {
514
285
  const where = raws.length > 1 ? `batch item ${index + 1} of ${raws.length}: ` : '';
515
286
  return usageError('evidence', `${where}${error.message}`, json, error);
516
287
  }
517
288
  }
518
289
 
519
- const gitCommit = headCommit(root);
520
290
  const written = [];
521
291
  let stateFile;
522
292
  try {
523
293
  for (const record of validated) {
524
- const id = ledger.addEvidence({
525
- ...record,
526
- taskId,
527
- freshness: measureFreshness(root, record.locator, gitCommit),
528
- });
294
+ const id = ledger.addEvidence(record);
529
295
  written.push(ledger.getEvidence(id));
530
296
  }
531
297
  stateFile = ledger.save(taskId);
@@ -552,7 +318,8 @@ function addEvidence({ ledger, root, taskId, item, batchPath, json } ) {
552
318
  }
553
319
  console.log('─'.repeat(78));
554
320
  console.log(`Wrote ${written.length} item(s) to ${stateFile}`);
555
- console.log(`Commit at observation: ${gitCommit || 'not a git worktree — freshness cannot expire by diff'}`);
321
+ const observedTree = absenceTreeState || treeState;
322
+ console.log(`Commit at observation: ${observedTree.gitCommit || (observedTree.prefix !== null ? 'not measured' : 'not a git worktree — freshness cannot expire by diff')}`);
556
323
  console.log('═'.repeat(78) + '\n');
557
324
  return finish(0);
558
325
  }
@@ -610,7 +377,7 @@ function supersedeEvidence({ ledger, taskId, evidenceId, replacedBy, json }
610
377
  * @param {string} [options.stateRoot]
611
378
  * @returns {number} exit code
612
379
  */
613
- function handleEvidenceCommand({ taskId = 'default', action = 'list', item = null, batchPath = null, evidenceId = null, replacedBy = null, json = false, repoRoot, stateRoot } = {}) {
380
+ function handleEvidenceCommand({ taskId = 'default', action = 'list', item = null, batchPath = null, evidenceId = null, replacedBy = null, json = false, repoRoot, stateRoot, sourceRoot, attemptRoot, slug = null } = {}) {
614
381
  // See handleReadinessCommand: evidence is the caller's project state, not DoFlow package state.
615
382
  const root = stateRoot || repoRoot || process.cwd();
616
383
  const isQuery = action === 'list' || action === 'status';
@@ -630,7 +397,7 @@ function handleEvidenceCommand({ taskId = 'default', action = 'list', item = nul
630
397
  return usageError('evidence', error.message, json, error);
631
398
  }
632
399
 
633
- if (action === 'add') return addEvidence({ ledger, root, taskId, item, batchPath, json });
400
+ if (action === 'add') return addEvidence({ ledger, root, sourceRoot: sourceRoot || root, attemptRoot, taskId, item, batchPath, json, slug });
634
401
  if (action === 'supersede') return supersedeEvidence({ ledger, taskId, evidenceId, replacedBy, json });
635
402
 
636
403
  const items = ledger.queryEvidence({ taskId });
@@ -0,0 +1,203 @@
1
+ 'use strict';
2
+
3
+ // TypeScript migration (agent-docs/BRIEF_GOAL_DOFLOW.md): run directly by Node native type-stripping.
4
+
5
+ const path = require('node:path');
6
+ const fs = require('node:fs');
7
+ const { loadRegistry } = require('../../registry/index.js');
8
+
9
+ const TASK_CLASS_BUDGETS = Object.freeze({
10
+ feature: 225000,
11
+ 'dependency-change': 85000,
12
+ bug: 71000,
13
+ refactor: 71000,
14
+ documentation: 57000,
15
+ operations: 45000,
16
+ review: 42000,
17
+ research: 35302,
18
+ 'trivial-edit': 30000,
19
+ });
20
+
21
+ let cachedHarnesses = null;
22
+ let cachedHarnessIds = null;
23
+ let registryLoadCount = 0;
24
+
25
+ function clearRegistryCache() {
26
+ cachedHarnesses = null;
27
+ cachedHarnessIds = null;
28
+ cachedBudgetsJson = null;
29
+ }
30
+
31
+ function getRegistryLoadCount() {
32
+ return registryLoadCount;
33
+ }
34
+
35
+ function getRegisteredHarnesses() {
36
+ if (cachedHarnesses) return cachedHarnesses;
37
+ registryLoadCount++;
38
+ const repoRoot = path.resolve(__dirname, '../../../');
39
+ const harnessesPath = path.join(repoRoot, 'core', 'registry', 'harnesses.json');
40
+ try {
41
+ const raw = JSON.parse(fs.readFileSync(harnessesPath, 'utf8'));
42
+ if (Array.isArray(raw?.harnesses)) {
43
+ cachedHarnesses = raw.harnesses;
44
+ return cachedHarnesses;
45
+ }
46
+ } catch {
47
+ // fallback if unreadable
48
+ }
49
+ cachedHarnesses = loadRegistry({ repoRoot }).harnesses;
50
+ return cachedHarnesses;
51
+ }
52
+
53
+ function getRegisteredHarnessIds() {
54
+ if (cachedHarnessIds && cachedHarnesses) return cachedHarnessIds;
55
+ const ids = getRegisteredHarnesses().map((h ) => h.id);
56
+ cachedHarnessIds = ids;
57
+ return ids;
58
+ }
59
+
60
+ let cachedBudgetsJson = null;
61
+
62
+ function getBudgetsJson() {
63
+ if (cachedBudgetsJson) return cachedBudgetsJson;
64
+ try {
65
+ const budgetsPath = path.resolve(__dirname, '../../../bench/perf/budgets.json');
66
+ if (fs.existsSync(budgetsPath)) {
67
+ cachedBudgetsJson = JSON.parse(fs.readFileSync(budgetsPath, 'utf8'));
68
+ return cachedBudgetsJson;
69
+ }
70
+ } catch {
71
+ // fallback if unreadable
72
+ }
73
+ return null;
74
+ }
75
+
76
+ /**
77
+ * Resolves budget and harness identity per IC-012.
78
+ * Precedence:
79
+ * 1. Harness identity: flag -> env (DOFLOW_AGENT) -> unstated
80
+ * 2. Cap: override (--max-bytes) -> profile -> task-class
81
+ * 3. Capacity: declared -> unknown
82
+ */
83
+ function resolveBudget({
84
+ taskClass = 'feature',
85
+ maxBytes,
86
+ harnessFlag = null,
87
+ env = process.env,
88
+ profiles = null,
89
+ budgetsJson = null,
90
+ } = {}) {
91
+ const harnesses = profiles || getRegisteredHarnesses();
92
+ const validIds = harnesses.map((h ) => h.id);
93
+
94
+ // 1. Harness identity
95
+ let harness ;
96
+
97
+ if (harnessFlag !== null && harnessFlag !== undefined && harnessFlag !== '') {
98
+ if (!validIds.includes(harnessFlag)) {
99
+ const err = new Error(`Unknown harness '${harnessFlag}'. Valid harnesses: ${validIds.join(', ')}`);
100
+ err.code = 'USAGE_ERROR';
101
+ err.validIds = validIds;
102
+ throw err;
103
+ }
104
+ harness = { id: harnessFlag, source: 'flag' };
105
+ } else if (env && env.DOFLOW_AGENT) {
106
+ const agentEnv = env.DOFLOW_AGENT;
107
+ if (validIds.includes(agentEnv)) {
108
+ harness = { id: agentEnv, source: 'env' };
109
+ } else {
110
+ harness = { id: null, source: 'unstated', basis: 'env-unregistered' };
111
+ }
112
+ } else {
113
+ harness = { id: null, source: 'unstated' };
114
+ }
115
+
116
+ // Find harness declaration for profile lookup
117
+ const harnessObj = harness.id ? harnesses.find((h ) => h.id === harness.id) : null;
118
+ const contextProfile = harnessObj?.contextProfile;
119
+
120
+ // Capacity & Tool Limit
121
+ let capacity ;
122
+ let toolResultLimitBytes = null;
123
+
124
+ if (!harness.id) {
125
+ capacity = { value: null, basis: 'unknown:harness-unstated' };
126
+ } else if (contextProfile?.capacityTokens && typeof contextProfile.capacityTokens.value === 'number') {
127
+ capacity = {
128
+ value: contextProfile.capacityTokens.value,
129
+ basis: `declared:${contextProfile.capacityTokens.source || 'profile'}`,
130
+ };
131
+ } else if (contextProfile?.capacityTokens?.unverified) {
132
+ capacity = {
133
+ value: null,
134
+ basis: `unknown:${contextProfile.capacityTokens.unverified}`,
135
+ };
136
+ } else {
137
+ capacity = {
138
+ value: null,
139
+ basis: 'unknown:profile-value-unavailable',
140
+ };
141
+ }
142
+
143
+ if (contextProfile?.toolResultLimitBytes && typeof contextProfile.toolResultLimitBytes.value === 'number') {
144
+ toolResultLimitBytes = contextProfile.toolResultLimitBytes.value;
145
+ }
146
+
147
+ // 2. Cap resolution
148
+ let resolvedMaxBytes ;
149
+ let source ;
150
+ let startupTokens = null;
151
+
152
+ if (Number.isInteger(maxBytes) && maxBytes > 0) {
153
+ resolvedMaxBytes = maxBytes;
154
+ source = 'override';
155
+ } else if (
156
+ contextProfile?.capacityTokens &&
157
+ typeof contextProfile.capacityTokens.value === 'number' &&
158
+ contextProfile?.reserveTokens &&
159
+ typeof contextProfile.reserveTokens.value === 'number'
160
+ ) {
161
+ // Profile available calculation: (capacity - startup - reserve) * 4
162
+ const effectiveBudgets = budgetsJson !== null && budgetsJson !== undefined ? budgetsJson : getBudgetsJson();
163
+ let startupTokensEstimate = 0;
164
+ let startupTokensBasis = 'unmeasured:no-entry';
165
+ if (effectiveBudgets?.startupContext && Array.isArray(effectiveBudgets.startupContext)) {
166
+ const entry = effectiveBudgets.startupContext.find((s ) => s.harness === harness.id);
167
+ if (typeof entry?.tokensEst === 'number') {
168
+ startupTokensEstimate = entry.tokensEst;
169
+ startupTokensBasis = entry.tokensBasis || 'estimated:bytes/4';
170
+ } else if (entry?.sessionStartStdoutBytes?.unmeasured) {
171
+ startupTokensBasis = `unmeasured:${entry.sessionStartStdoutBytes.unmeasured}`;
172
+ }
173
+ }
174
+ startupTokens = {
175
+ value: startupTokensEstimate,
176
+ basis: startupTokensBasis,
177
+ };
178
+ const available = (contextProfile.capacityTokens.value - startupTokensEstimate - contextProfile.reserveTokens.value) * 4;
179
+ resolvedMaxBytes = Math.max(0, available);
180
+ source = 'profile';
181
+ } else {
182
+ resolvedMaxBytes = TASK_CLASS_BUDGETS[taskClass] || 225000;
183
+ source = 'task-class';
184
+ }
185
+
186
+ return {
187
+ maxBytes: resolvedMaxBytes,
188
+ source,
189
+ harness,
190
+ capacity,
191
+ toolResultLimitBytes,
192
+ ...(startupTokens ? { startupTokens } : {}),
193
+ };
194
+ }
195
+
196
+ module.exports = {
197
+ TASK_CLASS_BUDGETS,
198
+ resolveBudget,
199
+ getRegisteredHarnessIds,
200
+ getRegisteredHarnesses,
201
+ clearRegistryCache,
202
+ getRegistryLoadCount,
203
+ };