harnessed 4.32.22 → 4.37.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 (99) hide show
  1. package/README.md +6 -6
  2. package/bin/harnessed-inject-state.mjs +16 -0
  3. package/dist/cli.mjs +1471 -302
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/index.mjs +1 -1
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/schemas/index.mjs.map +1 -1
  8. package/manifests/optional/doc-discipline-gate.yaml +54 -0
  9. package/messages/en.json +8 -0
  10. package/messages/zh-Hans.json +8 -0
  11. package/package.json +1 -1
  12. package/routing/decision_rules.yaml +1 -1
  13. package/workflows/README.md +1 -1
  14. package/workflows/auto/SKILL.md +13 -9
  15. package/workflows/auto/SKILL.zh-Hans.md +13 -9
  16. package/workflows/capabilities.yaml +100 -40
  17. package/workflows/defaults.yaml +8 -2
  18. package/workflows/disciplines/karpathy.yaml +29 -0
  19. package/workflows/disciplines/karpathy.zh-Hans.yaml +27 -0
  20. package/workflows/disciplines/language.yaml +15 -10
  21. package/workflows/disciplines/operational.yaml +1 -1
  22. package/workflows/disciplines/operational.zh-Hans.yaml +1 -1
  23. package/workflows/disciplines/output-style.yaml +10 -2
  24. package/workflows/disciplines/output-style.zh-Hans.yaml +10 -2
  25. package/workflows/disciplines/priority.yaml +15 -2
  26. package/workflows/disciplines/priority.zh-Hans.yaml +15 -2
  27. package/workflows/discuss/auto/SKILL.md +4 -4
  28. package/workflows/discuss/auto/SKILL.zh-Hans.md +4 -4
  29. package/workflows/discuss/auto/workflow.yaml +16 -3
  30. package/workflows/discuss/phase/SKILL.md +1 -1
  31. package/workflows/discuss/phase/SKILL.zh-Hans.md +1 -1
  32. package/workflows/discuss/strategic/SKILL.md +1 -1
  33. package/workflows/discuss/strategic/SKILL.zh-Hans.md +1 -1
  34. package/workflows/discuss/subtask/SKILL.md +1 -1
  35. package/workflows/discuss/subtask/SKILL.zh-Hans.md +1 -1
  36. package/workflows/judgments/parallelism-gate.yaml +11 -6
  37. package/workflows/judgments/phase-gate.yaml +5 -1
  38. package/workflows/judgments/stage-routing.yaml +21 -26
  39. package/workflows/judgments/strategic-gate.yaml +30 -0
  40. package/workflows/judgments/user-overrides.yaml +7 -3
  41. package/workflows/judgments/web-testing-routing.yaml +33 -12
  42. package/workflows/plan/architecture/SKILL.md +7 -3
  43. package/workflows/plan/architecture/SKILL.zh-Hans.md +7 -3
  44. package/workflows/plan/auto/SKILL.md +11 -7
  45. package/workflows/plan/auto/SKILL.zh-Hans.md +11 -7
  46. package/workflows/plan/phase/SKILL.md +7 -3
  47. package/workflows/plan/phase/SKILL.zh-Hans.md +7 -3
  48. package/workflows/research/SKILL.md +24 -9
  49. package/workflows/research/SKILL.zh-Hans.md +23 -9
  50. package/workflows/research/workflow.yaml +43 -3
  51. package/workflows/retro/SKILL.md +7 -3
  52. package/workflows/retro/SKILL.zh-Hans.md +7 -3
  53. package/workflows/role-prompts.yaml +28 -21
  54. package/workflows/role-prompts.zh-Hans.yaml +22 -17
  55. package/workflows/ship/auto/SKILL.md +11 -7
  56. package/workflows/ship/auto/SKILL.zh-Hans.md +11 -7
  57. package/workflows/ship/preflight/SKILL.md +7 -3
  58. package/workflows/ship/preflight/SKILL.zh-Hans.md +7 -3
  59. package/workflows/task/auto/SKILL.md +26 -16
  60. package/workflows/task/auto/SKILL.zh-Hans.md +26 -16
  61. package/workflows/task/auto/workflow.yaml +11 -4
  62. package/workflows/task/clarify/SKILL.md +1 -1
  63. package/workflows/task/clarify/SKILL.zh-Hans.md +1 -1
  64. package/workflows/task/code/SKILL.md +7 -3
  65. package/workflows/task/code/SKILL.zh-Hans.md +7 -3
  66. package/workflows/task/deliver/SKILL.md +53 -35
  67. package/workflows/task/deliver/SKILL.zh-Hans.md +54 -36
  68. package/workflows/task/deliver/workflow.yaml +32 -24
  69. package/workflows/task/test/SKILL.md +37 -3
  70. package/workflows/task/test/SKILL.zh-Hans.md +33 -3
  71. package/workflows/task/test/workflow.yaml +13 -0
  72. package/workflows/verify/auto/SKILL.md +12 -8
  73. package/workflows/verify/auto/SKILL.zh-Hans.md +12 -8
  74. package/workflows/verify/auto/workflow.yaml +3 -1
  75. package/workflows/verify/code-review/SKILL.md +7 -3
  76. package/workflows/verify/code-review/SKILL.zh-Hans.md +7 -3
  77. package/workflows/verify/design/SKILL.md +24 -10
  78. package/workflows/verify/design/SKILL.zh-Hans.md +24 -10
  79. package/workflows/verify/design/workflow.yaml +36 -7
  80. package/workflows/verify/eval-review/SKILL.md +7 -3
  81. package/workflows/verify/eval-review/SKILL.zh-Hans.md +7 -3
  82. package/workflows/verify/multispec/SKILL.md +17 -10
  83. package/workflows/verify/multispec/SKILL.zh-Hans.md +16 -10
  84. package/workflows/verify/multispec/workflow.yaml +7 -5
  85. package/workflows/verify/paranoid/SKILL.md +7 -3
  86. package/workflows/verify/paranoid/SKILL.zh-Hans.md +7 -3
  87. package/workflows/verify/progress/SKILL.md +7 -3
  88. package/workflows/verify/progress/SKILL.zh-Hans.md +7 -3
  89. package/workflows/verify/qa/SKILL.md +44 -14
  90. package/workflows/verify/qa/SKILL.zh-Hans.md +44 -14
  91. package/workflows/verify/qa/workflow.yaml +61 -2
  92. package/workflows/verify/security/SKILL.md +7 -3
  93. package/workflows/verify/security/SKILL.zh-Hans.md +7 -3
  94. package/workflows/verify/simplify/SKILL.md +7 -3
  95. package/workflows/verify/simplify/SKILL.zh-Hans.md +7 -3
  96. package/workflows/verify/validate-phase/SKILL.md +7 -3
  97. package/workflows/verify/validate-phase/SKILL.zh-Hans.md +7 -3
  98. package/manifests/skill-packs/karpathy-skills.yaml +0 -65
  99. package/manifests/tools/ralph-loop.yaml +0 -46
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync, mkdirSync, renameSync, writeFileSync, readFileSync, readdirSync, realpathSync, mkdtempSync, utimesSync, rmSync, statSync } from 'fs';
2
+ import { existsSync, mkdirSync, renameSync, writeFileSync, readFileSync, readdirSync, realpathSync, mkdtempSync, utimesSync, rmSync, statSync, appendFileSync } from 'fs';
3
3
  import { homedir, tmpdir } from 'os';
4
4
  import { join, resolve, dirname, basename, sep, isAbsolute, win32, posix, relative } from 'path';
5
5
  import { Type } from '@sinclair/typebox';
@@ -9,7 +9,7 @@ import lockfile from 'proper-lockfile';
9
9
  import { LineCounter, parseDocument, parse, isSeq, isScalar, stringify } from 'yaml';
10
10
  import { Ajv } from 'ajv';
11
11
  import * as ajvFormatsNs from 'ajv-formats';
12
- import { execFileSync, spawnSync, spawn, execSync, exec, execFile } from 'child_process';
12
+ import { execFileSync, spawnSync, spawn, execSync, execFile, exec } from 'child_process';
13
13
  import { pathToFileURL, fileURLToPath } from 'url';
14
14
  import { createHash, verify, createPublicKey } from 'crypto';
15
15
  import { promisify } from 'util';
@@ -38,7 +38,7 @@ var init_package = __esm({
38
38
  "package.json"() {
39
39
  package_default = {
40
40
  name: "harnessed",
41
- version: "4.32.22",
41
+ version: "4.37.0",
42
42
  description: "AI coding harness package manager + composition orchestrator",
43
43
  type: "module",
44
44
  license: "Apache-2.0",
@@ -470,7 +470,39 @@ var init_currentWorkflow_v1 = __esm({
470
470
  // envelopes lack them, and the guard no-ops on entries without `mode`
471
471
  // (back-compat fail-soft; comet 0.3.9 phase-skip lesson).
472
472
  mode: Type.Optional(Type.Union([Type.Literal("serial"), Type.Literal("parallel")])),
473
- order: Type.Optional(Type.Integer())
473
+ order: Type.Optional(Type.Integer()),
474
+ // ── T2.7 (loop internalization) — three additive-optional fields that move the
475
+ // completion GUARANTEE from the dead `harnessed run` path onto the ledger. Old
476
+ // envelopes without them still Value.Check-pass → NO schemaVersion bump.
477
+ //
478
+ // completion_claim — verdict of the `<promise>COMPLETE</promise>` predicate
479
+ // (src/workflow/lib/ralphLoop.ts isComplete) at `checkpoint complete`.
480
+ // 'not_provided' = the caller passed no claim, so the gate was unarmed.
481
+ completion_claim: Type.Optional(
482
+ Type.Union([
483
+ Type.Literal("complete"),
484
+ Type.Literal("incomplete"),
485
+ Type.Literal("not_provided")
486
+ ])
487
+ ),
488
+ // progress — no-progress damping state (src/checkpoint/progress.ts). `stale_count`
489
+ // is consecutive attempts with no improvement under `metric`; PLATEAU_THRESHOLD
490
+ // consecutive ones mean the loop is spinning in place.
491
+ progress: Type.Optional(
492
+ Type.Object(
493
+ {
494
+ metric: Type.Union([Type.Literal("failing_tests"), Type.Literal("evidence_digest")]),
495
+ failing_tests: Type.Optional(Type.Integer({ minimum: 0 })),
496
+ evidence_digest: Type.Optional(Type.String()),
497
+ stale_count: Type.Integer({ minimum: 0 })
498
+ },
499
+ { additionalProperties: false }
500
+ )
501
+ ),
502
+ // attempt_budget — the sub's resolved `ralph_max_iterations` ceiling, persisted at
503
+ // the first failure so the PURE per-turn injector can compare it against
504
+ // fail_count without reading yaml (src/checkpoint/budget.ts resolves it).
505
+ attempt_budget: Type.Optional(Type.Integer({ minimum: 1 }))
474
506
  },
475
507
  { additionalProperties: false }
476
508
  );
@@ -889,6 +921,9 @@ function markSub(entries, sub, status, opts) {
889
921
  if (status === "failed") updated.fail_count = (current.fail_count ?? 0) + 1;
890
922
  if (opts?.evidence !== void 0) updated.evidence = opts.evidence;
891
923
  if (opts?.evidence_status !== void 0) updated.evidence_status = opts.evidence_status;
924
+ if (opts?.completion_claim !== void 0) updated.completion_claim = opts.completion_claim;
925
+ if (opts?.progress !== void 0) updated.progress = opts.progress;
926
+ if (opts?.attempt_budget !== void 0) updated.attempt_budget = opts.attempt_budget;
892
927
  const next = entries.slice();
893
928
  next[idx] = updated;
894
929
  return next;
@@ -1884,6 +1919,13 @@ var init_en = __esm({
1884
1919
  "doctor.summary.fail": "\nsome checks failed (see fix hints above)",
1885
1920
  "doctor.summary.warn": "\nall checks ok (with warnings \u2014 see hints above)",
1886
1921
  "doctor.summary.pass": "\nall checks passed",
1922
+ "check_docs.clean": "documentation discipline: no violations",
1923
+ "check_docs.state_line_limit": "STATE.md is {{lines}} lines > the {{limit}}-line digest limit \u2014 archive older phase narrative to RETROSPECTIVE.md (override for one run: HARNESSED_ALLOW_LONG_STATE=1)",
1924
+ "check_docs.state_key_decisions": "{{count}} '\u5173\u952E\u51B3\u8BAE ship \u603B\u7ED3' section(s) > {{limit}} \u2014 keep only the current one; move the rest to RETROSPECTIVE.md",
1925
+ "check_docs.state_errata": "historical commentary '{{excerpt}}' belongs in RETROSPECTIVE.md, not in the STATE digest",
1926
+ "check_docs.roadmap_narrative": "closing narrative inlined in an overview doc ({{signals}}) \u2014 ROADMAP carries one line + a pointer per phase; narrative goes to SUMMARY / VERIFICATION",
1927
+ "check_docs.summary_halt": "\ndocumentation discipline: {{halt}} blocking + {{warn}} advisory violation(s)",
1928
+ "check_docs.summary_warn": "\ndocumentation discipline: {{warn}} advisory violation(s) (non-blocking)",
1887
1929
  "backup.no_backups": "no backups found ({{root}} absent)",
1888
1930
  "backup.no_backups_empty": "no backups found ({{root}} empty)",
1889
1931
  "backup.total_snapshots": "\n{{count}} snapshot(s) total",
@@ -2902,6 +2944,240 @@ var init_assetsRoot = __esm({
2902
2944
  }
2903
2945
  });
2904
2946
 
2947
+ // src/checkpoint/tddBoundary.ts
2948
+ var tddBoundary_exports = {};
2949
+ __export(tddBoundary_exports, {
2950
+ TDD_EVIDENCE_ARTIFACT: () => TDD_EVIDENCE_ARTIFACT,
2951
+ assertionDelta: () => assertionDelta,
2952
+ checkTddBoundary: () => checkTddBoundary,
2953
+ isTddEvidencePath: () => isTddEvidencePath
2954
+ });
2955
+ function isTddEvidencePath(path) {
2956
+ return path.split(/[\\/]/).pop() === TDD_EVIDENCE_ARTIFACT;
2957
+ }
2958
+ function isTestPath(p7) {
2959
+ const s = p7.replace(/\\/g, "/");
2960
+ return /(^|\/)tests?\//.test(s) || /\.(test|spec)\.[cm]?[jt]sx?$/.test(s) || /(^|\/)test_[^/]+\.py$/.test(s) || /_test\.(py|go|rb)$/.test(s);
2961
+ }
2962
+ function substantiveBody(text) {
2963
+ return text.split("\n").filter((l) => l.trim() !== "" && !/^\s*#{1,6}\s/.test(l)).join("\n").trim();
2964
+ }
2965
+ async function checkTddBoundary(cwd, evidencePath) {
2966
+ const findings = [];
2967
+ const exists = await stat(evidencePath).then((s) => s.isFile()).catch(() => false);
2968
+ if (!exists) return findings;
2969
+ const text = await readFile(evidencePath, "utf8").catch(() => "");
2970
+ const body = substantiveBody(text);
2971
+ if (body.length === 0) {
2972
+ findings.push({
2973
+ id: "evidence-empty",
2974
+ kind: "block",
2975
+ message: `${TDD_EVIDENCE_ARTIFACT} has no content beyond headings \u2014 an empty artifact satisfies the file-exists criterion but records nothing. Write the red\u2192green record, or an explicit \`SKIPPED \u2014 <reason>\`.`
2976
+ });
2977
+ } else if (!SKIP_DECLARATION.test(body) && !(RED_MARKER.test(body) && GREEN_MARKER.test(body))) {
2978
+ findings.push({
2979
+ id: "evidence-one-sided",
2980
+ kind: "block",
2981
+ message: `${TDD_EVIDENCE_ARTIFACT} records neither a red\u2192green cycle (a failing run AND the subsequent pass) nor a reasoned \`SKIPPED \u2014 <reason>\` declaration.`
2982
+ });
2983
+ }
2984
+ findings.push(...await gitBoundaries(cwd));
2985
+ return findings;
2986
+ }
2987
+ async function diffBase(cwd) {
2988
+ try {
2989
+ const { stdout: stdout2 } = await execFileP("git", ["merge-base", "HEAD", "origin/main"], { cwd });
2990
+ const ref = stdout2.trim();
2991
+ if (ref) return ref;
2992
+ } catch {
2993
+ }
2994
+ try {
2995
+ await execFileP("git", ["rev-parse", "--verify", "HEAD"], { cwd });
2996
+ return "HEAD";
2997
+ } catch {
2998
+ return null;
2999
+ }
3000
+ }
3001
+ async function gitBoundaries(cwd) {
3002
+ const base = await diffBase(cwd);
3003
+ if (!base) return [];
3004
+ const findings = [];
3005
+ try {
3006
+ const { stdout: stdout2 } = await execFileP(
3007
+ "git",
3008
+ ["diff", "--name-only", "--diff-filter=D", base, ...SCOPE],
3009
+ {
3010
+ cwd
3011
+ }
3012
+ );
3013
+ const deleted = stdout2.split("\n").map((l) => l.trim()).filter((l) => l !== "" && isTestPath(l));
3014
+ if (deleted.length > 0) {
3015
+ findings.push({
3016
+ id: "test-file-deleted",
3017
+ kind: "block",
3018
+ message: `${deleted.length} test file(s) deleted since ${base} \u2014 a done-criterion that only asks for evidence is satisfiable by removing the tests it describes: ${deleted.join(", ")}. Restore them, or re-run with --force to record a deliberate override.`
3019
+ });
3020
+ }
3021
+ } catch {
3022
+ }
3023
+ try {
3024
+ const { stdout: stdout2 } = await execFileP("git", ["diff", "-U0", base, ...SCOPE], {
3025
+ cwd,
3026
+ maxBuffer: 32 * 1024 * 1024
3027
+ });
3028
+ const delta = assertionDelta(stdout2);
3029
+ if (delta.removed > delta.added) {
3030
+ findings.push({
3031
+ id: "assertions-weakened",
3032
+ kind: "warn",
3033
+ message: `assertion count in test files dropped (-${delta.removed} / +${delta.added}) \u2014 verify this is a refactor, not a weakened suite. Heuristic (parametrized cases legitimately reduce the count), so this warns and does not block.`
3034
+ });
3035
+ }
3036
+ } catch {
3037
+ }
3038
+ return findings;
3039
+ }
3040
+ function assertionDelta(diff) {
3041
+ let inTest = false;
3042
+ let added = 0;
3043
+ let removed = 0;
3044
+ for (const line of diff.split("\n")) {
3045
+ if (line.startsWith("+++ ")) {
3046
+ const p7 = line.slice(4).trim().replace(/^b\//, "");
3047
+ inTest = p7 !== "/dev/null" && isTestPath(p7);
3048
+ continue;
3049
+ }
3050
+ if (line.startsWith("--- ") || line.startsWith("diff --git") || line.startsWith("@@")) continue;
3051
+ if (!inTest) continue;
3052
+ if (line.startsWith("+") && ASSERTION_TOKEN.test(line)) added++;
3053
+ else if (line.startsWith("-") && ASSERTION_TOKEN.test(line)) removed++;
3054
+ }
3055
+ return { added, removed };
3056
+ }
3057
+ var execFileP, TDD_EVIDENCE_ARTIFACT, RED_MARKER, GREEN_MARKER, SKIP_DECLARATION, SCOPE, ASSERTION_TOKEN;
3058
+ var init_tddBoundary = __esm({
3059
+ "src/checkpoint/tddBoundary.ts"() {
3060
+ execFileP = promisify(execFile);
3061
+ TDD_EVIDENCE_ARTIFACT = "tdd-evidence.md";
3062
+ RED_MARKER = /\b(red|fail(?:s|ed|ing|ure)?)\b/i;
3063
+ GREEN_MARKER = /\b(green|pass(?:es|ed|ing)?)\b/i;
3064
+ SKIP_DECLARATION = /\bSKIPPED\b\s*[—–:-]\s*\S+/i;
3065
+ SCOPE = ["--", "."];
3066
+ ASSERTION_TOKEN = /\b(expect|assert\w*|should|toBe\w*|toEqual|toThrow|toMatch)\b|\.to\./;
3067
+ }
3068
+ });
3069
+
3070
+ // src/workflow/lib/promiseExtract.ts
3071
+ function extractPromise(text) {
3072
+ const match = text.match(PROMISE_PATTERN);
3073
+ return match ? match[1] : null;
3074
+ }
3075
+ var PROMISE_PATTERN;
3076
+ var init_promiseExtract = __esm({
3077
+ "src/workflow/lib/promiseExtract.ts"() {
3078
+ PROMISE_PATTERN = /<promise>([^<]+)<\/promise>/;
3079
+ }
3080
+ });
3081
+
3082
+ // src/workflow/lib/fallbackHandlers.ts
3083
+ function handleMaxIterationsExceeded(err2, fallback, ctx) {
3084
+ const yamlShort = fallback.message.replace(
3085
+ /\{\{\s*args\.max_iterations\s*\}\}/g,
3086
+ String(ctx.maxIterations)
3087
+ );
3088
+ const truncated = (ctx.lastMessage ?? "<empty>").slice(0, 500);
3089
+ const uxText = `\u274C ralph-loop max-iterations exceeded (${err2.iterations}/${ctx.maxIterations}).
3090
+ Sub-task: ${ctx.subtaskSummary}
3091
+ Workflow: ${ctx.workflowName} / phase ${ctx.phaseId}
3092
+ Last subagent output (truncated): ${truncated}
3093
+ The subagent attempted ${err2.iterations} iterations without emitting verbatim "<promise>COMPLETE</promise>".
3094
+ This indicates one of:
3095
+ 1. Sub-task is genuinely incomplete (escalate to user / re-scope)
3096
+ 2. Subagent is stuck in a loop (review prompt / system instructions)
3097
+ 3. max-iterations too low (override via --max-iterations <N>, hard upper limit 100)
3098
+ Manual options:
3099
+ A) Continue with current state: \`harnessed workflow resume --skip-completion-gate\`
3100
+ B) Re-run from last checkpoint: \`harnessed workflow resume --from-checkpoint\`
3101
+ C) Abort cleanly: exit 1
3102
+ Exit code: ${fallback.exit_code}
3103
+ ${yamlShort}`;
3104
+ console.error(uxText);
3105
+ process.exit(fallback.exit_code);
3106
+ throw new Error("unreachable");
3107
+ }
3108
+ var init_fallbackHandlers = __esm({
3109
+ "src/workflow/lib/fallbackHandlers.ts"() {
3110
+ }
3111
+ });
3112
+
3113
+ // src/workflow/lib/ralphLoop.ts
3114
+ function isComplete(output) {
3115
+ let env;
3116
+ try {
3117
+ env = JSON.parse(output);
3118
+ } catch {
3119
+ return extractPromise(output) === "COMPLETE";
3120
+ }
3121
+ const succeeded = env.subtype === "success";
3122
+ const status = env.structured_output?.status;
3123
+ if (status === "COMPLETE") return succeeded;
3124
+ if (status === "PARTIAL" || status === "BLOCKED") return false;
3125
+ if (succeeded) return true;
3126
+ return extractPromise(env.text ?? env.result ?? "") === "COMPLETE";
3127
+ }
3128
+ async function ralphLoopWrap(spawn7, maxIter) {
3129
+ let last = "";
3130
+ let sessionId;
3131
+ for (let i = 0; i < maxIter; i++) {
3132
+ last = await spawn7(sessionId, (id) => {
3133
+ sessionId = id;
3134
+ });
3135
+ if (isComplete(last)) return last;
3136
+ }
3137
+ throw new MaxIterationsExceededError(maxIter);
3138
+ }
3139
+ var MaxIterationsExceededError;
3140
+ var init_ralphLoop = __esm({
3141
+ "src/workflow/lib/ralphLoop.ts"() {
3142
+ init_promiseExtract();
3143
+ init_fallbackHandlers();
3144
+ MaxIterationsExceededError = class extends Error {
3145
+ constructor(iterations) {
3146
+ super(`ralph-loop max-iterations exceeded after ${iterations} attempts`);
3147
+ this.iterations = iterations;
3148
+ this.name = "MaxIterationsExceededError";
3149
+ }
3150
+ iterations;
3151
+ };
3152
+ }
3153
+ });
3154
+
3155
+ // src/checkpoint/completionClaim.ts
3156
+ var completionClaim_exports = {};
3157
+ __export(completionClaim_exports, {
3158
+ verifyCompletionClaim: () => verifyCompletionClaim
3159
+ });
3160
+ async function verifyCompletionClaim(input) {
3161
+ if (input.resultFile) {
3162
+ let text;
3163
+ try {
3164
+ text = await readFile(input.resultFile, "utf8");
3165
+ } catch {
3166
+ return { verdict: "incomplete", source: input.resultFile };
3167
+ }
3168
+ return { verdict: isComplete(text) ? "complete" : "incomplete", source: input.resultFile };
3169
+ }
3170
+ if (typeof input.result === "string" && input.result.trim() !== "") {
3171
+ return { verdict: isComplete(input.result) ? "complete" : "incomplete", source: "--result" };
3172
+ }
3173
+ return { verdict: "not_provided", source: null };
3174
+ }
3175
+ var init_completionClaim = __esm({
3176
+ "src/checkpoint/completionClaim.ts"() {
3177
+ init_ralphLoop();
3178
+ }
3179
+ });
3180
+
2905
3181
  // src/checkpoint/scale.ts
2906
3182
  var scale_exports = {};
2907
3183
  __export(scale_exports, {
@@ -2944,6 +3220,164 @@ var init_scale = __esm({
2944
3220
  execp = promisify(exec);
2945
3221
  }
2946
3222
  });
3223
+ function extractVerifyBinary(verifyCmd, fallback) {
3224
+ const token = verifyCmd?.trim().split(/\s+/)[0];
3225
+ if (token && BARE_BIN_RE.test(token) && !NON_COMPONENT_TOKENS.has(token)) return token;
3226
+ if (BARE_BIN_RE.test(fallback) && !NON_COMPONENT_TOKENS.has(fallback)) return fallback;
3227
+ return null;
3228
+ }
3229
+ function realRun(finder, bin) {
3230
+ try {
3231
+ if (typeof spawnSync !== "function") return null;
3232
+ const r = spawnSync(finder, [bin], { encoding: "utf8" });
3233
+ if (!r || r.error) return null;
3234
+ return { status: r.status, stdout: r.stdout ?? "" };
3235
+ } catch {
3236
+ return null;
3237
+ }
3238
+ }
3239
+ function binaryOnPath(bin, deps) {
3240
+ const platform = process.platform;
3241
+ const run = realRun;
3242
+ const finder = platform === "win32" ? "where" : "which";
3243
+ const r = run(finder, bin);
3244
+ if (!r || r.status !== 0) return false;
3245
+ return r.stdout.trim().length > 0;
3246
+ }
3247
+ var NON_COMPONENT_TOKENS, BARE_BIN_RE;
3248
+ var init_binaryProbe = __esm({
3249
+ "src/installers/lib/binaryProbe.ts"() {
3250
+ NON_COMPONENT_TOKENS = /* @__PURE__ */ new Set([
3251
+ "test",
3252
+ "grep",
3253
+ "ls",
3254
+ "cat",
3255
+ "echo",
3256
+ "command",
3257
+ "sh",
3258
+ "bash",
3259
+ "[",
3260
+ "npx",
3261
+ "npm",
3262
+ "node",
3263
+ "corepack",
3264
+ "pnpm",
3265
+ "yarn",
3266
+ "bun",
3267
+ "git",
3268
+ "claude",
3269
+ "codex"
3270
+ ]);
3271
+ BARE_BIN_RE = /^[A-Za-z0-9][\w.@-]*$/;
3272
+ }
3273
+ });
3274
+
3275
+ // src/checkpoint/codegraphInit.ts
3276
+ var codegraphInit_exports = {};
3277
+ __export(codegraphInit_exports, {
3278
+ ensureCodegraphIgnored: () => ensureCodegraphIgnored,
3279
+ maybeInitCodeGraph: () => maybeInitCodeGraph
3280
+ });
3281
+ function claimPath(cwd) {
3282
+ const key = createHash("sha1").update(resolve(cwd)).digest("hex").slice(0, 16);
3283
+ return join(harnessedSubdir("codegraph-init"), `${key}.claim`);
3284
+ }
3285
+ function realClaim(cwd) {
3286
+ const path = claimPath(cwd);
3287
+ const stamp = (/* @__PURE__ */ new Date()).toISOString();
3288
+ try {
3289
+ mkdirSync(dirname(path), { recursive: true });
3290
+ } catch {
3291
+ return false;
3292
+ }
3293
+ try {
3294
+ writeFileSync(path, stamp, { flag: "wx" });
3295
+ return true;
3296
+ } catch {
3297
+ try {
3298
+ if (Date.now() - statSync(path).mtimeMs < STALE_CLAIM_MS) return false;
3299
+ writeFileSync(path, stamp);
3300
+ return true;
3301
+ } catch {
3302
+ return false;
3303
+ }
3304
+ }
3305
+ }
3306
+ function realLaunch(cwd) {
3307
+ if (typeof spawn !== "function") return;
3308
+ const win = process.platform === "win32";
3309
+ const child = win ? spawn("cmd.exe", ["/d", "/s", "/c", "codegraph", "init"], {
3310
+ cwd,
3311
+ stdio: "ignore",
3312
+ windowsHide: true
3313
+ }) : spawn("codegraph", ["init"], { cwd, stdio: "ignore", detached: true });
3314
+ child.on("error", () => {
3315
+ });
3316
+ child.unref();
3317
+ }
3318
+ function ignoresCodegraph(body) {
3319
+ for (const raw of body.split(/\r?\n/)) {
3320
+ const line = raw.trim();
3321
+ if (line === "" || line.startsWith("#") || line.startsWith("!")) continue;
3322
+ if (line.replace(/^\//, "").replace(/\/$/, "") === ".codegraph") return true;
3323
+ }
3324
+ return false;
3325
+ }
3326
+ function ensureCodegraphIgnored(cwd) {
3327
+ const path = join(cwd, ".gitignore");
3328
+ try {
3329
+ if (!existsSync(path)) {
3330
+ writeFileSync(path, `${IGNORE_LINE}
3331
+ `);
3332
+ return "created";
3333
+ }
3334
+ const body = readFileSync(path, "utf8");
3335
+ if (ignoresCodegraph(body)) return "already";
3336
+ appendFileSync(path, `${body.endsWith("\n") || body === "" ? "" : "\n"}${IGNORE_LINE}
3337
+ `);
3338
+ return "appended";
3339
+ } catch {
3340
+ return "error";
3341
+ }
3342
+ }
3343
+ function maybeInitCodeGraph(overrides = {}) {
3344
+ const cwd = overrides.cwd ?? process.cwd();
3345
+ const hasIndex = overrides.hasIndex ?? ((c) => existsSync(join(c, ".codegraph")));
3346
+ const hasBinary = overrides.hasBinary ?? (() => binaryOnPath("codegraph"));
3347
+ const claim = overrides.claim ?? realClaim;
3348
+ const launch = overrides.launch ?? realLaunch;
3349
+ const note2 = overrides.note ?? ((m) => {
3350
+ console.error(m);
3351
+ });
3352
+ if (hasIndex(cwd)) return "index-present";
3353
+ if (!hasBinary()) return "no-binary";
3354
+ if (!claim(cwd)) return "already-claimed";
3355
+ try {
3356
+ launch(cwd);
3357
+ } catch (e) {
3358
+ note2(`[harnessed] codegraph init could not be started (ignored): ${e.message}`);
3359
+ return "launch-failed";
3360
+ }
3361
+ note2(
3362
+ `[harnessed] codegraph init started in the background for ${cwd} \u2014 the next task gets a semantic index (first-time only; upstream's watcher keeps it fresh).`
3363
+ );
3364
+ const ignored = ensureCodegraphIgnored(cwd);
3365
+ if (ignored === "appended" || ignored === "created") {
3366
+ note2(
3367
+ `[harnessed] appended \`${IGNORE_LINE}\` to ${join(cwd, ".gitignore")} \u2014 the index is a SQLite DB, and an unignored one gets swept into the next \`git add -A\`.`
3368
+ );
3369
+ }
3370
+ return "launched";
3371
+ }
3372
+ var STALE_CLAIM_MS, IGNORE_LINE;
3373
+ var init_codegraphInit = __esm({
3374
+ "src/checkpoint/codegraphInit.ts"() {
3375
+ init_binaryProbe();
3376
+ init_harnessedRoot();
3377
+ STALE_CLAIM_MS = 30 * 6e4;
3378
+ IGNORE_LINE = ".codegraph/";
3379
+ }
3380
+ });
2947
3381
 
2948
3382
  // src/checkpoint/learnings.ts
2949
3383
  var learnings_exports = {};
@@ -3175,6 +3609,99 @@ var init_retroMeta = __esm({
3175
3609
  }
3176
3610
  });
3177
3611
 
3612
+ // src/checkpoint/progress.ts
3613
+ var progress_exports = {};
3614
+ __export(progress_exports, {
3615
+ PLATEAU_THRESHOLD: () => PLATEAU_THRESHOLD,
3616
+ evidenceDigest: () => evidenceDigest,
3617
+ isPlateaued: () => isPlateaued,
3618
+ sampleProgress: () => sampleProgress
3619
+ });
3620
+ function evidenceDigest(refs) {
3621
+ if (refs.length === 0) return "";
3622
+ return refs.map((r) => r.sha256.slice(0, 12)).sort().join(",");
3623
+ }
3624
+ function sampleProgress(prev, sample) {
3625
+ const count = sample.failing_tests;
3626
+ if (usableCount(count)) {
3627
+ const before = prev?.metric === "failing_tests" ? prev.failing_tests : void 0;
3628
+ const stalled = usableCount(before) && count >= before;
3629
+ return {
3630
+ metric: "failing_tests",
3631
+ failing_tests: count,
3632
+ stale_count: stalled ? (prev?.stale_count ?? 0) + 1 : 0
3633
+ };
3634
+ }
3635
+ const digest = sample.evidence_digest;
3636
+ if (typeof digest === "string" && digest !== "") {
3637
+ const before = prev?.metric === "evidence_digest" ? prev.evidence_digest : void 0;
3638
+ const stalled = !!before && digest === before;
3639
+ return {
3640
+ metric: "evidence_digest",
3641
+ evidence_digest: digest,
3642
+ stale_count: stalled ? (prev?.stale_count ?? 0) + 1 : 0
3643
+ };
3644
+ }
3645
+ return null;
3646
+ }
3647
+ function isPlateaued(mark) {
3648
+ return (mark?.stale_count ?? 0) >= PLATEAU_THRESHOLD;
3649
+ }
3650
+ var PLATEAU_THRESHOLD, usableCount;
3651
+ var init_progress = __esm({
3652
+ "src/checkpoint/progress.ts"() {
3653
+ PLATEAU_THRESHOLD = 2;
3654
+ usableCount = (n) => typeof n === "number" && Number.isInteger(n) && n >= 0;
3655
+ }
3656
+ });
3657
+
3658
+ // src/checkpoint/budget.ts
3659
+ var budget_exports = {};
3660
+ __export(budget_exports, {
3661
+ DEFAULT_ATTEMPT_BUDGET: () => DEFAULT_ATTEMPT_BUDGET,
3662
+ FALLBACK_HARD_UPPER_LIMIT: () => FALLBACK_HARD_UPPER_LIMIT,
3663
+ isBudgetExhausted: () => isBudgetExhausted,
3664
+ resolveAttemptBudget: () => resolveAttemptBudget
3665
+ });
3666
+ function entryValues(entry) {
3667
+ if (typeof entry === "number" && Number.isFinite(entry)) return [entry];
3668
+ if (entry && typeof entry === "object") {
3669
+ return Object.values(entry).filter(
3670
+ (v) => typeof v === "number" && Number.isFinite(v)
3671
+ );
3672
+ }
3673
+ return [];
3674
+ }
3675
+ function tableValues(table, sub) {
3676
+ const exact = entryValues(table[sub]);
3677
+ if (exact.length > 0) return exact;
3678
+ const suffix = `-${sub}`;
3679
+ return Object.keys(table).filter((k) => k.endsWith(suffix)).flatMap((k) => entryValues(table[k]));
3680
+ }
3681
+ async function resolveAttemptBudget(sub, packageRoot) {
3682
+ try {
3683
+ const doc = parse(
3684
+ await readFile(resolve(packageRoot, "workflows", "defaults.yaml"), "utf8")
3685
+ );
3686
+ const cap = typeof doc?.hard_upper_limit === "number" && Number.isFinite(doc.hard_upper_limit) ? doc.hard_upper_limit : FALLBACK_HARD_UPPER_LIMIT;
3687
+ const values = tableValues(doc?.ralph_max_iterations ?? {}, sub);
3688
+ if (values.length > 0) return Math.min(Math.max(...values), cap);
3689
+ return DEFAULT_ATTEMPT_BUDGET;
3690
+ } catch {
3691
+ return DEFAULT_ATTEMPT_BUDGET;
3692
+ }
3693
+ }
3694
+ function isBudgetExhausted(attempts, budget) {
3695
+ return attempts >= budget;
3696
+ }
3697
+ var DEFAULT_ATTEMPT_BUDGET, FALLBACK_HARD_UPPER_LIMIT;
3698
+ var init_budget = __esm({
3699
+ "src/checkpoint/budget.ts"() {
3700
+ DEFAULT_ATTEMPT_BUDGET = 20;
3701
+ FALLBACK_HARD_UPPER_LIMIT = 100;
3702
+ }
3703
+ });
3704
+
3178
3705
  // src/checkpoint/breakLoop.ts
3179
3706
  var breakLoop_exports = {};
3180
3707
  __export(breakLoop_exports, {
@@ -3259,14 +3786,13 @@ async function absorbIntentFor(sub) {
3259
3786
  } catch {
3260
3787
  }
3261
3788
  }
3262
- async function serialOrderBlockers(sub, deps = defaultRunDeps) {
3789
+ async function readLedgerSafe(deps = defaultRunDeps) {
3263
3790
  try {
3264
3791
  const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
3265
- const { findSerialBlockers: findSerialBlockers2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
3266
3792
  const wf = await readCurrentWorkflow2();
3267
- return findSerialBlockers2(wf?.sub_progress ?? [], sub);
3793
+ return wf?.sub_progress ?? [];
3268
3794
  } catch (e) {
3269
- deps.warn(`[harnessed] serial-order guard skipped (fail-soft): ${e.message}`);
3795
+ deps.warn(`[harnessed] ledger read skipped (fail-soft): ${e.message}`);
3270
3796
  return [];
3271
3797
  }
3272
3798
  }
@@ -3362,7 +3888,8 @@ async function runCheckpointStart(sub, opts, deps = defaultRunDeps) {
3362
3888
  }
3363
3889
  async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
3364
3890
  const { completePhase: completePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
3365
- if (!enforceSerialOrder("complete", sub, await serialOrderBlockers(sub, deps), opts.force, deps)) {
3891
+ const preLedger = await readLedgerSafe(deps);
3892
+ if (!enforceSerialOrder("complete", sub, findSerialBlockers(preLedger, sub), opts.force, deps)) {
3366
3893
  deps.exit(1);
3367
3894
  return;
3368
3895
  }
@@ -3372,7 +3899,32 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
3372
3899
  const result = await checkArtifacts2(sub, getAssetsRoot2());
3373
3900
  const { checkPlanningSync: checkPlanningSync2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
3374
3901
  const syncResult = await checkPlanningSync2(process.cwd(), null);
3375
- const allMissing = [...result.missing, ...syncResult.missing];
3902
+ const boundaryBlocks = [];
3903
+ try {
3904
+ const { checkTddBoundary: checkTddBoundary2, isTddEvidencePath: isTddEvidencePath2 } = await Promise.resolve().then(() => (init_tddBoundary(), tddBoundary_exports));
3905
+ const evidenceArtifact = result.found.find((f) => isTddEvidencePath2(f.path));
3906
+ if (evidenceArtifact) {
3907
+ for (const f of await checkTddBoundary2(process.cwd(), evidenceArtifact.path)) {
3908
+ if (f.kind === "block") boundaryBlocks.push(`boundary(${f.id}): ${f.message}`);
3909
+ else deps.warn(`\u26A0\uFE0F [harnessed] boundary warning (${f.id}): ${f.message}`);
3910
+ }
3911
+ }
3912
+ } catch {
3913
+ }
3914
+ const { verifyCompletionClaim: verifyCompletionClaim2 } = await Promise.resolve().then(() => (init_completionClaim(), completionClaim_exports));
3915
+ const claim = await verifyCompletionClaim2({
3916
+ ...opts.result !== void 0 ? { result: opts.result } : {},
3917
+ ...opts.resultFile !== void 0 ? { resultFile: opts.resultFile } : {}
3918
+ });
3919
+ const claimBlocks = claim.verdict === "incomplete" ? [
3920
+ `completion promise not met (${claim.source}): the subagent output carries no verbatim <promise>COMPLETE</promise> and no structured COMPLETE status on a successful run`
3921
+ ] : [];
3922
+ if (claim.verdict === "not_provided") {
3923
+ deps.warn(
3924
+ `\u26A0\uFE0F [harnessed] completion promise unverified for ${sub} \u2014 no --result/--result-file supplied, so the promise gate is unarmed for this completion (artifact + boundary gates still applied).`
3925
+ );
3926
+ }
3927
+ const allMissing = [...result.missing, ...syncResult.missing, ...boundaryBlocks, ...claimBlocks];
3376
3928
  if (allMissing.length > 0 && !opts.force) {
3377
3929
  deps.error(
3378
3930
  `[harnessed] checkpoint complete BLOCKED: ${sub} \u2014 ${allMissing.length} item(s) missing (evidence guard + .planning/ sync, fail-closed):`
@@ -3386,7 +3938,11 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
3386
3938
  if (allMissing.length > 0 && opts.force) evidenceStatus = "overridden";
3387
3939
  else if (result.status === "verified") evidenceStatus = "verified";
3388
3940
  else evidenceStatus = "none_declared";
3389
- const markOpts = evidenceStatus === "none_declared" ? { evidence_status: evidenceStatus } : { evidence: result.found, evidence_status: evidenceStatus };
3941
+ const markOpts = evidenceStatus === "none_declared" ? { evidence_status: evidenceStatus, completion_claim: claim.verdict } : {
3942
+ evidence: result.found,
3943
+ evidence_status: evidenceStatus,
3944
+ completion_claim: claim.verdict
3945
+ };
3390
3946
  await mutateSubProgress2((e) => markIfSeeded(e, sub, "done", markOpts));
3391
3947
  await absorbIntentFor(sub);
3392
3948
  const { collectScaleMetrics: collectScaleMetrics2, assessScale: assessScale2 } = await Promise.resolve().then(() => (init_scale(), scale_exports));
@@ -3404,6 +3960,13 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
3404
3960
  lastTask: opts.summary ?? `phase ${sub} complete`,
3405
3961
  transitionWorkflowComplete: allResolved
3406
3962
  });
3963
+ if (allResolved && afterMark?.phase === "task") {
3964
+ try {
3965
+ const { maybeInitCodeGraph: maybeInitCodeGraph2 } = await Promise.resolve().then(() => (init_codegraphInit(), codegraphInit_exports));
3966
+ maybeInitCodeGraph2({ note: (m) => deps.error(m) });
3967
+ } catch {
3968
+ }
3969
+ }
3407
3970
  if (allResolved && afterMark) {
3408
3971
  const { captureWorkflowLearnings: captureWorkflowLearnings2 } = await Promise.resolve().then(() => (init_learnings(), learnings_exports));
3409
3972
  const captured = await captureWorkflowLearnings2(afterMark.sub_progress ?? [], sub);
@@ -3455,12 +4018,35 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
3455
4018
  }
3456
4019
  async function runCheckpointFail(sub, opts, deps = defaultRunDeps) {
3457
4020
  const { completePhase: completePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
3458
- if (!enforceSerialOrder("fail", sub, await serialOrderBlockers(sub, deps), opts.force, deps)) {
4021
+ const preLedger = await readLedgerSafe(deps);
4022
+ if (!enforceSerialOrder("fail", sub, findSerialBlockers(preLedger, sub), opts.force, deps)) {
3459
4023
  deps.exit(1);
3460
4024
  return;
3461
4025
  }
4026
+ const { sampleProgress: sampleProgress2, isPlateaued: isPlateaued2, evidenceDigest: evidenceDigest2, PLATEAU_THRESHOLD: PLATEAU_THRESHOLD2 } = await Promise.resolve().then(() => (init_progress(), progress_exports));
4027
+ const { getAssetsRoot: getAssetsRoot2 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
4028
+ const assetsRoot = getAssetsRoot2();
4029
+ const failingTests = opts.failingTests !== void 0 ? Number(opts.failingTests) : void 0;
4030
+ let digest = "";
4031
+ try {
4032
+ const { checkArtifacts: checkArtifacts2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
4033
+ digest = evidenceDigest2((await checkArtifacts2(sub, assetsRoot)).found);
4034
+ } catch {
4035
+ }
4036
+ const prev = preLedger.find((e) => e.sub === sub)?.progress;
4037
+ const nextProgress = sampleProgress2(prev, {
4038
+ ...failingTests !== void 0 && Number.isFinite(failingTests) ? { failing_tests: failingTests } : {},
4039
+ evidence_digest: digest
4040
+ });
4041
+ const { resolveAttemptBudget: resolveAttemptBudget2, isBudgetExhausted: isBudgetExhausted2 } = await Promise.resolve().then(() => (init_budget(), budget_exports));
4042
+ const budget = await resolveAttemptBudget2(sub, assetsRoot);
3462
4043
  const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
3463
- await mutateSubProgress2((e) => markIfSeeded(e, sub, "failed"));
4044
+ await mutateSubProgress2(
4045
+ (e) => markIfSeeded(e, sub, "failed", {
4046
+ attempt_budget: budget,
4047
+ ...nextProgress ? { progress: nextProgress } : {}
4048
+ })
4049
+ );
3464
4050
  await absorbIntentFor(sub);
3465
4051
  await completePhase2({
3466
4052
  phaseId: sub,
@@ -3478,6 +4064,17 @@ async function runCheckpointFail(sub, opts, deps = defaultRunDeps) {
3478
4064
  `[harnessed] BREAK-LOOP: sub '${sub}' failed ${looped.count}x (>= ${LOOP_THRESHOLD2}). Stop retrying \u2014 run the break-loop skill for root-cause analysis and capture the lesson to .planning/.`
3479
4065
  );
3480
4066
  }
4067
+ const attempts = latest?.sub_progress?.find((e) => e.sub === sub)?.fail_count ?? 0;
4068
+ if (isBudgetExhausted2(attempts, budget)) {
4069
+ deps.error(
4070
+ `[harnessed] BUDGET-EXHAUSTED: sub '${sub}' has spent ${attempts}/${budget} attempts (workflows/defaults.yaml ralph_max_iterations). Do not spawn it again \u2014 re-scope the subtask, fix the blocker, or escalate to the user.`
4071
+ );
4072
+ }
4073
+ if (isPlateaued2(nextProgress)) {
4074
+ deps.error(
4075
+ `[harnessed] NO-PROGRESS: sub '${sub}' has produced no improvement for ${nextProgress?.stale_count} consecutive attempts (metric: ${nextProgress?.metric}, threshold ${PLATEAU_THRESHOLD2}). Stop respawning \u2014 a loop with no damping just spins in place. Change the approach or escalate.`
4076
+ );
4077
+ }
3481
4078
  deps.error(
3482
4079
  `[harnessed] checkpoint FAILED recorded: ${sub}${opts.summary ? ` \u2014 ${opts.summary}` : ""}`
3483
4080
  );
@@ -3493,6 +4090,15 @@ function registerCheckpoint(program2) {
3493
4090
  ).option(
3494
4091
  "--tokens <n>",
3495
4092
  "complete only \u2014 conversation token count; auto-compacts the ledger when >= the shouldCompact threshold (Phase 14)"
4093
+ ).option(
4094
+ "--result <text>",
4095
+ "complete only \u2014 the subagent's final output (or SDK result envelope JSON); blocked unless it carries a verbatim <promise>COMPLETE</promise> or a structured COMPLETE status"
4096
+ ).option(
4097
+ "--result-file <path>",
4098
+ "complete only \u2014 same as --result but read from a file (quoting-safe on Windows); wins over --result"
4099
+ ).option(
4100
+ "--failing-tests <n>",
4101
+ "fail only \u2014 number of tests still failing after this attempt; drives the no-progress circuit breaker (falls back to the evidence-artifact digest when omitted)"
3496
4102
  ).action(
3497
4103
  async (action, sub, opts) => {
3498
4104
  if (!isAction(action)) {
@@ -3612,8 +4218,8 @@ function compute(d) {
3612
4218
  }
3613
4219
  const gitFirst = d.where("git")[0];
3614
4220
  if (gitFirst && /git\.exe$/i.test(gitFirst)) {
3615
- const root = dirname8(dirname8(gitFirst));
3616
- for (const cand of [join18(root, "bin", "bash.exe"), join18(root, "usr", "bin", "bash.exe")]) {
4221
+ const root = dirname9(dirname9(gitFirst));
4222
+ for (const cand of [join20(root, "bin", "bash.exe"), join20(root, "usr", "bin", "bash.exe")]) {
3617
4223
  if (d.exists(cand) && usable(cand)) return { path: cand, source: "git-derived", wslOnPath };
3618
4224
  }
3619
4225
  }
@@ -3621,13 +4227,13 @@ function compute(d) {
3621
4227
  d.env.ProgramFiles,
3622
4228
  d.env.ProgramW6432,
3623
4229
  d.env["ProgramFiles(x86)"],
3624
- d.env.LOCALAPPDATA ? join18(d.env.LOCALAPPDATA, "Programs") : void 0
4230
+ d.env.LOCALAPPDATA ? join20(d.env.LOCALAPPDATA, "Programs") : void 0
3625
4231
  ];
3626
4232
  for (const base of bases) {
3627
4233
  if (!base) continue;
3628
4234
  for (const cand of [
3629
- join18(base, "Git", "bin", "bash.exe"),
3630
- join18(base, "Git", "usr", "bin", "bash.exe")
4235
+ join20(base, "Git", "bin", "bash.exe"),
4236
+ join20(base, "Git", "usr", "bin", "bash.exe")
3631
4237
  ]) {
3632
4238
  if (d.exists(cand) && usable(cand))
3633
4239
  return { path: cand, source: "standard-location", wslOnPath };
@@ -3640,10 +4246,10 @@ function compute(d) {
3640
4246
  }
3641
4247
  return { path: "bash", source: "path-fallback" };
3642
4248
  }
3643
- var dirname8, join18, WSL_STUB_RE, cache2;
4249
+ var dirname9, join20, WSL_STUB_RE, cache2;
3644
4250
  var init_resolveBash = __esm({
3645
4251
  "src/installers/lib/resolveBash.ts"() {
3646
- ({ dirname: dirname8, join: join18 } = win32);
4252
+ ({ dirname: dirname9, join: join20 } = win32);
3647
4253
  WSL_STUB_RE = /[\\/](windows[\\/](system32|sysnative|syswow64)|microsoft[\\/]windowsapps)[\\/]bash\.exe$/i;
3648
4254
  cache2 = null;
3649
4255
  }
@@ -3741,7 +4347,7 @@ function checkJq() {
3741
4347
  return {
3742
4348
  name: "jq present",
3743
4349
  status: "warn",
3744
- message: "jq not found in PATH (optional \u2014 needed by `harnessed audit-log --filter` and the ralph-loop plugin on Windows)",
4350
+ message: "jq not found in PATH (optional \u2014 needed by `harnessed audit-log --filter`)",
3745
4351
  fix,
3746
4352
  install_commands: [installCmd]
3747
4353
  };
@@ -3774,7 +4380,7 @@ function checkWinBash() {
3774
4380
  return {
3775
4381
  name: "bash flavor (win)",
3776
4382
  status: "warn",
3777
- message: `PATH-first bash is the WSL stub (${sanitizeToolOutput(r.wslOnPath)}); harnessed resolved Git Bash at ${r.path} \u2014 but OTHER tools (e.g. ralph-loop plugin forks) may still hit WSL`,
4383
+ message: `PATH-first bash is the WSL stub (${sanitizeToolOutput(r.wslOnPath)}); harnessed resolved Git Bash at ${r.path} \u2014 but OTHER tools (e.g. third-party plugin forks) may still hit WSL`,
3778
4384
  fix: "reorder PATH so Git Bash precedes WSL bash.exe (Settings \u2192 System \u2192 Environment Variables)"
3779
4385
  };
3780
4386
  }
@@ -4361,7 +4967,7 @@ var check_bun_exports = {};
4361
4967
  __export(check_bun_exports, {
4362
4968
  checkBun: () => checkBun
4363
4969
  });
4364
- function realRun(finder) {
4970
+ function realRun2(finder) {
4365
4971
  try {
4366
4972
  if (typeof spawnSync !== "function") return null;
4367
4973
  const r = spawnSync(finder, ["bun"], { encoding: "utf8" });
@@ -4373,7 +4979,7 @@ function realRun(finder) {
4373
4979
  }
4374
4980
  function checkBun(deps) {
4375
4981
  const platform = deps?.platform ?? process.platform;
4376
- const run = deps?.run ?? realRun;
4982
+ const run = deps?.run ?? realRun2;
4377
4983
  const finder = platform === "win32" ? "where" : "which";
4378
4984
  const r = run(finder);
4379
4985
  if (r && r.status === 0 && r.stdout.trim().length > 0) {
@@ -4948,14 +5554,38 @@ function stripQuotes(token) {
4948
5554
  if (m?.[1] !== void 0) return { bare: m[1], quoted: true };
4949
5555
  return { bare: token, quoted: false };
4950
5556
  }
5557
+ function splitTokens(raw) {
5558
+ return raw.split(/\s+/).filter((t2) => t2.length > 0);
5559
+ }
5560
+ function hookMarkerAt(raw) {
5561
+ const tokens = splitTokens(raw);
5562
+ for (const [i, token] of tokens.entries()) {
5563
+ const { bare: bare2 } = stripQuotes(token);
5564
+ if (!isRelativeFileToken(bare2)) continue;
5565
+ const seg = bare2.split(/[\\/]/);
5566
+ const base = seg[seg.length - 1];
5567
+ if (base === void 0) return null;
5568
+ const id = COMPILED_HOOK_IDENTITIES.find((k) => base.includes(k));
5569
+ return { marker: id ?? base, index: i };
5570
+ }
5571
+ for (const [i, token] of tokens.entries()) {
5572
+ const { bare: bare2 } = stripQuotes(token);
5573
+ if (COMPILED_HOOK_IDENTITIES.includes(bare2))
5574
+ return { marker: bare2, index: i };
5575
+ }
5576
+ return null;
5577
+ }
4951
5578
  function resolveHookCommand(raw, deps) {
4952
- const marker = deps.compiledExecPath ? hookScriptMarker(raw) : null;
4953
- if (deps.compiledExecPath && marker && COMPILED_HOOK_IDENTITIES.includes(marker)) {
5579
+ const at = deps.compiledExecPath ? hookMarkerAt(raw) : null;
5580
+ if (deps.compiledExecPath && at && COMPILED_HOOK_IDENTITIES.includes(at.marker)) {
4954
5581
  const exe = deps.compiledExecPath();
4955
- if (exe) return `"${exe.replace(/\\/g, "/")}" ${marker}`;
5582
+ if (exe) {
5583
+ const tail = splitTokens(raw).slice(at.index + 1);
5584
+ return [`"${exe.replace(/\\/g, "/")}"`, at.marker, ...tail].join(" ");
5585
+ }
4956
5586
  }
4957
5587
  let root = null;
4958
- const tokens = raw.split(/\s+/).filter((t2) => t2.length > 0);
5588
+ const tokens = splitTokens(raw);
4959
5589
  const out = tokens.map((token) => {
4960
5590
  const { bare: bare2 } = stripQuotes(token);
4961
5591
  if (!isRelativeFileToken(bare2)) return token;
@@ -4967,21 +5597,8 @@ function resolveHookCommand(raw, deps) {
4967
5597
  return out.join(" ");
4968
5598
  }
4969
5599
  function hookScriptMarker(raw) {
4970
- for (const token of raw.split(/\s+/)) {
4971
- const { bare: bare2 } = stripQuotes(token);
4972
- if (isRelativeFileToken(bare2)) {
4973
- const seg = bare2.split(/[\\/]/);
4974
- const base = seg[seg.length - 1] ?? null;
4975
- const id = COMPILED_HOOK_IDENTITIES.find((k) => base?.includes(k));
4976
- if (id) return id;
4977
- return base;
4978
- }
4979
- }
4980
- for (const token of raw.split(/\s+/)) {
4981
- const { bare: bare2 } = stripQuotes(token);
4982
- if (COMPILED_HOOK_IDENTITIES.includes(bare2)) return bare2;
4983
- }
4984
- return null;
5600
+ const at = hookMarkerAt(raw);
5601
+ return at === null ? null : at.marker;
4985
5602
  }
4986
5603
  function entryCommands(entry) {
4987
5604
  if (!entry || typeof entry !== "object") return [];
@@ -5031,7 +5648,7 @@ function detectCcHookInstalled(settingsRaw, ev, raw, matcher, deps) {
5031
5648
  var COMPILED_HOOK_IDENTITIES, ABSOLUTE_RE;
5032
5649
  var init_hookEntry = __esm({
5033
5650
  "src/installers/lib/hookEntry.ts"() {
5034
- COMPILED_HOOK_IDENTITIES = ["inject-state", "stop-hook"];
5651
+ COMPILED_HOOK_IDENTITIES = ["inject-state", "stop-hook", "check-docs"];
5035
5652
  ABSOLUTE_RE = /^([A-Za-z]:[\\/]|[\\/])/;
5036
5653
  }
5037
5654
  });
@@ -5178,6 +5795,62 @@ var init_check_stale_hooks = __esm({
5178
5795
  }
5179
5796
  });
5180
5797
 
5798
+ // src/cli/lib/probe-chrome-devtools.ts
5799
+ async function probeOne2(fn, onFault) {
5800
+ try {
5801
+ return await fn();
5802
+ } catch {
5803
+ onFault();
5804
+ return false;
5805
+ }
5806
+ }
5807
+ async function probeChromeDevtools(deps = {}) {
5808
+ const d = { ...DEFAULT_DEPS, ...deps };
5809
+ let unknown = false;
5810
+ const fault = () => {
5811
+ unknown = true;
5812
+ };
5813
+ const ecc = await probeOne2(() => d.pluginRegistered(ECC_PLUGIN_NAME), fault);
5814
+ const standalonePlugin = await probeOne2(() => d.pluginRegistered(CHROME_DEVTOOLS_MCP_NAME), fault);
5815
+ const standaloneStdio = await probeOne2(
5816
+ () => d.mcpServerRegistered(CHROME_DEVTOOLS_MCP_NAME),
5817
+ fault
5818
+ );
5819
+ const providers = [];
5820
+ if (ecc) providers.push("ecc plugin");
5821
+ if (standalonePlugin) providers.push(`${CHROME_DEVTOOLS_MCP_NAME}@claude-plugins-official plugin`);
5822
+ if (standaloneStdio) providers.push(`${CHROME_DEVTOOLS_MCP_NAME} stdio MCP server`);
5823
+ return { ecc, standalonePlugin, standaloneStdio, unknown, providers };
5824
+ }
5825
+ function chromeDevtoolsAvailable(p7) {
5826
+ return p7.providers.length > 0 || p7.unknown;
5827
+ }
5828
+ async function isChromeDevtoolsAvailable(deps) {
5829
+ return chromeDevtoolsAvailable(await probeChromeDevtools(deps));
5830
+ }
5831
+ function chromeDevtoolsFactSource(p7) {
5832
+ if (p7.providers.length > 0) {
5833
+ return `chrome-devtools provider registered: ${p7.providers.join(" + ")}`;
5834
+ }
5835
+ if (p7.unknown) {
5836
+ return `chrome-devtools provider probe FAULTED (unreadable plugin registry / MCP config) \u2014 availability unknown, reported true so the perf / a11y / memory diagnostic lane is never silently deleted (ADR-0029 fail-soft). To make it definite, ${CHROME_DEVTOOLS_ENABLE_PATHS}`;
5837
+ }
5838
+ return `NO chrome-devtools provider registered \u2014 the verify-qa \`05-perf-a11y-diagnostic\` lane (perf / a11y / memory, judgments.web-testing-routing.chrome-devtools-mcp-diagnostic.fires) will NOT run. To turn it on, ${CHROME_DEVTOOLS_ENABLE_PATHS}`;
5839
+ }
5840
+ var CHROME_DEVTOOLS_MCP_NAME, ECC_PLUGIN_NAME, CHROME_DEVTOOLS_ENABLE_PATHS, DEFAULT_DEPS;
5841
+ var init_probe_chrome_devtools = __esm({
5842
+ "src/cli/lib/probe-chrome-devtools.ts"() {
5843
+ init_readClaudeConfig();
5844
+ CHROME_DEVTOOLS_MCP_NAME = "chrome-devtools-mcp";
5845
+ ECC_PLUGIN_NAME = "ecc";
5846
+ CHROME_DEVTOOLS_ENABLE_PATHS = "enable EITHER provider: (1) install the ecc plugin (`harnessed install ecc` \u2014 chrome-devtools is its only default MCP connector), OR (2) self-install the standalone server (`claude mcp add chrome-devtools-mcp`, manifests/optional/chrome-devtools-mcp.yaml). Install exactly ONE \u2014 both at once creates same-name dual-prefix tool-call ambiguity (the doctor `ecc` check warns on the leftover).";
5847
+ DEFAULT_DEPS = {
5848
+ pluginRegistered: isPluginRegistered,
5849
+ mcpServerRegistered: isMcpServerRegistered
5850
+ };
5851
+ }
5852
+ });
5853
+
5181
5854
  // src/cli/lib/check-ecc.ts
5182
5855
  var check_ecc_exports = {};
5183
5856
  __export(check_ecc_exports, {
@@ -5192,7 +5865,8 @@ async function pathExists(p7) {
5192
5865
  }
5193
5866
  }
5194
5867
  async function checkEcc() {
5195
- const ccInstalled = await isPluginRegistered("ecc");
5868
+ const cdt = await probeChromeDevtools();
5869
+ const ccInstalled = cdt.ecc;
5196
5870
  const codexHome = join(homedir(), ".codex");
5197
5871
  const codexPresent = await pathExists(join(codexHome, "config.toml"));
5198
5872
  const codexInstalled = codexPresent && await pathExists(join(codexHome, ".cache", "ecc", ".git"));
@@ -5201,11 +5875,11 @@ async function checkEcc() {
5201
5875
  if (ccInstalled) {
5202
5876
  const leftovers = [];
5203
5877
  const fixes = [];
5204
- if (await isPluginRegistered("chrome-devtools-mcp")) {
5878
+ if (cdt.standalonePlugin) {
5205
5879
  leftovers.push("official chrome-devtools-mcp@claude-plugins-official plugin still enabled");
5206
5880
  fixes.push("`claude plugin uninstall chrome-devtools-mcp@claude-plugins-official`");
5207
5881
  }
5208
- if (await isMcpServerRegistered("chrome-devtools-mcp")) {
5882
+ if (cdt.standaloneStdio) {
5209
5883
  leftovers.push("chrome-devtools-mcp stdio entry still registered in mcpServers");
5210
5884
  fixes.push("`claude mcp remove chrome-devtools-mcp`");
5211
5885
  }
@@ -5219,10 +5893,11 @@ async function checkEcc() {
5219
5893
  }
5220
5894
  }
5221
5895
  if (!ccInstalled && !codexInstalled) {
5896
+ const cdtPart = cdt.unknown ? " Separately, the chrome-devtools provider probe FAULTED (unreadable plugin registry / MCP config) \u2014 availability unknown, so the perf / a11y / memory diagnostic lane is left ON (fail-soft)." : cdt.providers.length > 0 ? ` chrome-devtools is still covered by the standalone provider (${cdt.providers.join(" + ")}).` : ` NOTE: chrome-devtools now has ZERO providers, so the perf / a11y / memory diagnostic lane (verify-qa \`05-perf-a11y-diagnostic\`) will not run \u2014 ${CHROME_DEVTOOLS_ENABLE_PATHS}`;
5222
5897
  return {
5223
5898
  name: NAME2,
5224
5899
  status: "pass",
5225
- message: `not installed (${ccPart}; ${codexPart}) \u2014 optional enhancement: \`harnessed install ecc\` unlocks finer-grained orchestration (per-language review/build expert routing etc.) at a ~20k+ tokens/session static-listing cost (ECC-side scale, not harnessed)`
5900
+ message: `not installed (${ccPart}; ${codexPart}) \u2014 optional enhancement: \`harnessed install ecc\` unlocks finer-grained orchestration (per-language review/build expert routing etc.) at a ~20k+ tokens/session static-listing cost (ECC-side scale, not harnessed).${cdtPart}`
5226
5901
  };
5227
5902
  }
5228
5903
  return {
@@ -5234,7 +5909,7 @@ async function checkEcc() {
5234
5909
  var NAME2;
5235
5910
  var init_check_ecc = __esm({
5236
5911
  "src/cli/lib/check-ecc.ts"() {
5237
- init_readClaudeConfig();
5912
+ init_probe_chrome_devtools();
5238
5913
  NAME2 = "ecc";
5239
5914
  }
5240
5915
  });
@@ -5415,6 +6090,7 @@ var judgmentResolver_exports = {};
5415
6090
  __export(judgmentResolver_exports, {
5416
6091
  TriggerNotFoundError: () => TriggerNotFoundError,
5417
6092
  _clearJudgmentCache: () => _clearJudgmentCache,
6093
+ resolveJudgmentExpression: () => resolveJudgmentExpression,
5418
6094
  resolveJudgmentGate: () => resolveJudgmentGate
5419
6095
  });
5420
6096
  async function resolveJudgmentGate(gateRef, context, packageRoot) {
@@ -5422,6 +6098,9 @@ async function resolveJudgmentGate(gateRef, context, packageRoot) {
5422
6098
  if (Array.isArray(userOverrides) && userOverrides.includes(gateRef)) {
5423
6099
  return true;
5424
6100
  }
6101
+ return evalGate(await resolveJudgmentExpression(gateRef, packageRoot), context);
6102
+ }
6103
+ async function resolveJudgmentExpression(gateRef, packageRoot) {
5425
6104
  const parts = gateRef.split(".");
5426
6105
  if (parts.length !== 4 || parts[0] !== "judgments") {
5427
6106
  throw new Error(`Invalid gate ref: ${gateRef}`);
@@ -5451,7 +6130,7 @@ async function resolveJudgmentGate(gateRef, context, packageRoot) {
5451
6130
  `Field '${fieldName}' has no expression in trigger '${triggerName}' of ${fileName}.yaml`
5452
6131
  );
5453
6132
  }
5454
- return evalGate(expr, context);
6133
+ return expr;
5455
6134
  }
5456
6135
  function _clearJudgmentCache() {
5457
6136
  _fileCache.clear();
@@ -5475,13 +6154,32 @@ var init_judgmentResolver = __esm({
5475
6154
  }
5476
6155
  });
5477
6156
 
6157
+ // src/workflow/skipGate.ts
6158
+ async function resolveSkipVeto(skipGateRef, context, packageRoot) {
6159
+ if (!skipGateRef) return null;
6160
+ try {
6161
+ const expr = await resolveJudgmentExpression(skipGateRef, packageRoot);
6162
+ if (!evalGate(expr, context)) return null;
6163
+ return `skip_gate ${skipGateRef} = true (skip condition met \u2014 sub vetoed despite its gate firing)`;
6164
+ } catch {
6165
+ return null;
6166
+ }
6167
+ }
6168
+ var init_skipGate = __esm({
6169
+ "src/workflow/skipGate.ts"() {
6170
+ init_exprBuilder();
6171
+ init_judgmentResolver();
6172
+ }
6173
+ });
6174
+
5478
6175
  // src/workflow/skipSubs.ts
5479
6176
  function matchSkipSub(requested, sub, master) {
5480
6177
  if (requested.has(sub)) return sub;
5481
6178
  const alias = `${master}-${sub}`;
5482
6179
  if (requested.has(alias)) return alias;
5483
- for (const [syn, canonical] of Object.entries(SKIP_SYNONYMS)) {
5484
- if (canonical === sub && requested.has(syn)) return syn;
6180
+ for (const [a, b] of Object.entries(SKIP_SYNONYMS)) {
6181
+ if (b === sub && requested.has(a)) return a;
6182
+ if (a === sub && requested.has(b)) return b;
5485
6183
  }
5486
6184
  return null;
5487
6185
  }
@@ -5527,16 +6225,44 @@ function buildDefaultGateContext(task, stage) {
5527
6225
  // extraction → eval threw undefined-variable → ADR 0029 fail-soft fired the
5528
6226
  // 4-specialist multispec team on EVERY verify. Opt-in via --context.
5529
6227
  is_critical_release: false,
6228
+ // chrome-devtools MCP provider availability — the BARE identifier read by
6229
+ // judgments.web-testing-routing.chrome-devtools-mcp-diagnostic.fires, so it
6230
+ // MUST be declared here (an absent bare variable throws → ADR-0038
6231
+ // fail-closed would delete the lane on a machine that HAS a provider).
6232
+ //
6233
+ // Seeded TRUE = "unknown", not "measured". This builder is synchronous and
6234
+ // the real answer needs async fs probes (~/.claude/plugins/installed_plugins.json
6235
+ // + the harness mcpServers config), so the honest default is the fail-soft
6236
+ // direction documented in src/cli/lib/probe-chrome-devtools.ts: a value we
6237
+ // could not measure must never silently REMOVE a declared capability
6238
+ // (src/workflow/skipGate.ts invariant). The measured value arrives through
6239
+ // `harnessed facts <master>` (deterministically derived, auto-filled) →
6240
+ // `harnessed gates --context-file`, and through `harnessed run`'s awaited
6241
+ // probe overlay.
6242
+ chrome_devtools_available: true,
5530
6243
  phase: {
5531
6244
  stage,
5532
- is_critical_module: true,
6245
+ // T2.1 OQ2(c) — withdrawn: gated stage-routing.verify-paranoid-critical,
6246
+ // which meant the paranoid staff-engineer review fired on EVERY verify.
6247
+ is_critical_module: false,
5533
6248
  is_final_step: true,
5534
6249
  is_major_release: false,
5535
6250
  has_auth_or_secrets: false,
5536
6251
  has_design_changes: false,
5537
6252
  has_ui_changes: false,
6253
+ // T2.1 gap-close — stage-routing verify-eval-review-aiphase /
6254
+ // verify-validate-phase-coverage read these; neither was declared here nor
6255
+ // in PhaseShape, so the member was absent and both gates evaluated to a
6256
+ // silent false forever. Default FALSE (the non-firing side) on purpose:
6257
+ // both subs are expensive retroactive audits that should be requested by a
6258
+ // filled fact, not defaulted on. `harnessed facts verify` lists them as
6259
+ // nulls with hints so the model supplies the real answer.
6260
+ has_ai_phase: false,
6261
+ requires_coverage_audit: false,
5538
6262
  requires_creative_polish: false,
5539
- is_complex_architecture: true,
6263
+ // T2.1 OQ2(c) — withdrawn: gated stage-routing.plan-architecture-delegate,
6264
+ // which meant /plan always spawned the eng-review architecture sub.
6265
+ is_complex_architecture: false,
5540
6266
  has_cross_phase_data_flow: true,
5541
6267
  open_decisions: 2,
5542
6268
  scope_days: 2,
@@ -5546,9 +6272,11 @@ function buildDefaultGateContext(task, stage) {
5546
6272
  },
5547
6273
  subtask: {
5548
6274
  approaches: 2,
5549
- core_algorithm: true,
6275
+ // T2.1 OQ2(c) — withdrawn (both are subtask-gate.brainstorming OR-arms;
6276
+ // `approaches: 2` / `has_api_contract: true` stay as the safety net).
6277
+ core_algorithm: false,
5550
6278
  has_api_contract: true,
5551
- error_cost: "high",
6279
+ error_cost: "low",
5552
6280
  lines: 50,
5553
6281
  type: "general",
5554
6282
  is_core_business_logic: true,
@@ -5558,9 +6286,23 @@ function buildDefaultGateContext(task, stage) {
5558
6286
  reliability_required: true,
5559
6287
  communication_needed: false,
5560
6288
  needs_lib_docs: false,
5561
- needs_web_search: false,
6289
+ // T2.3 — web-search-routing.yaml declares Tavily/keyword THE default route,
6290
+ // and workflows/research/workflow.yaml now gates its 5 source lanes on those
6291
+ // triggers. Leaving needs_web_search=false + search_type='general' (not even
6292
+ // a member of the SearchType union in schema/phaseFactContext.ts) would make
6293
+ // every lane evaluate false → the research workflow would degrade to zero
6294
+ // sources, a regression vs the previously-unconditional fan-out step. The
6295
+ // non-default lanes (descriptive/academic → exa, site-crawl, lib-docs →
6296
+ // ctx7, single-url → WebFetch) stay opt-in via --context.
6297
+ needs_web_search: true,
6298
+ search_type: "keyword",
6299
+ // T2.3 — `browse` capability + web-testing-routing browse-probe fact. Default
6300
+ // FALSE (opt-in): it is an OR-arm of the browser-probe route, and defaulting
6301
+ // it true would route a browser lane on every eval — the same "most expensive
6302
+ // sub became the default path" defect 4.23.2 fixed. Reachable via --context
6303
+ // or a facts-extraction chain.
6304
+ needs_browser_automation: false,
5562
6305
  parallel_count: 1,
5563
- search_type: "general",
5564
6306
  test_type: "general"
5565
6307
  }
5566
6308
  };
@@ -5568,8 +6310,12 @@ function buildDefaultGateContext(task, stage) {
5568
6310
  function mergeGateContext(base, extra) {
5569
6311
  const merged = { ...base };
5570
6312
  for (const [k, v] of Object.entries(extra)) {
6313
+ if (v === null) continue;
5571
6314
  if ((k === "phase" || k === "subtask") && v && typeof v === "object" && !Array.isArray(v)) {
5572
- merged[k] = { ...base[k], ...v };
6315
+ const overrides = Object.fromEntries(
6316
+ Object.entries(v).filter(([, val]) => val !== null)
6317
+ );
6318
+ merged[k] = { ...base[k], ...overrides };
5573
6319
  } else {
5574
6320
  merged[k] = v;
5575
6321
  }
@@ -5584,7 +6330,9 @@ var init_gateContext = __esm({
5584
6330
  // src/cli/gates.ts
5585
6331
  var gates_exports = {};
5586
6332
  __export(gates_exports, {
6333
+ GATE_MASTERS: () => GATE_MASTERS,
5587
6334
  registerGates: () => registerGates,
6335
+ resolveMasterYamlPath: () => resolveMasterYamlPath,
5588
6336
  runGatesPlan: () => runGatesPlan
5589
6337
  });
5590
6338
  function resolveMasterYamlPath(master, packageRoot) {
@@ -5635,6 +6383,28 @@ async function runGatesPlan(master, raw, deps = defaultRunDeps) {
5635
6383
  const task = typeof raw.task === "string" ? raw.task : "";
5636
6384
  const stage = master;
5637
6385
  let ctx = buildDefaultGateContext(task, stage);
6386
+ if (typeof raw.contextFile === "string" && raw.contextFile.length > 0) {
6387
+ let rawJson;
6388
+ try {
6389
+ rawJson = await readFile(raw.contextFile, "utf8");
6390
+ } catch (err2) {
6391
+ deps.error(
6392
+ `error: failed to read --context-file at ${raw.contextFile} \u2014 ${err2.message}`
6393
+ );
6394
+ deps.exit(1);
6395
+ return;
6396
+ }
6397
+ let extra;
6398
+ try {
6399
+ extra = JSON.parse(rawJson);
6400
+ } catch (err2) {
6401
+ deps.error(`error: --context-file is not valid JSON \u2014 ${err2.message}`);
6402
+ deps.exit(1);
6403
+ return;
6404
+ }
6405
+ const unwrapped = unwrapFactsEnvelope(extra);
6406
+ if (unwrapped) ctx = mergeGateContext(ctx, unwrapped);
6407
+ }
5638
6408
  if (typeof raw.context === "string" && raw.context.length > 0) {
5639
6409
  let extra;
5640
6410
  try {
@@ -5671,11 +6441,13 @@ async function runGatesPlan(master, raw, deps = defaultRunDeps) {
5671
6441
  }
5672
6442
  try {
5673
6443
  const passes = await resolveJudgmentGate(clause.gate, ctx, packageRoot);
5674
- if (passes) {
5675
- fire.push(fireEntry(clause, master));
5676
- } else {
6444
+ if (!passes) {
5677
6445
  skip.push({ sub: clause.sub, reason: `gate ${clause.gate} = false` });
6446
+ continue;
5678
6447
  }
6448
+ const veto = await resolveSkipVeto(clause.skip_gate, ctx, packageRoot);
6449
+ if (veto) skip.push({ sub: clause.sub, reason: veto });
6450
+ else fire.push(fireEntry(clause, master));
5679
6451
  } catch (e) {
5680
6452
  if (isUndefinedVariableError(e)) {
5681
6453
  deps.warn(
@@ -5728,10 +6500,22 @@ function registerGates(program2) {
5728
6500
  "sub names to skip without gate eval (repeatable and/or comma-separated)",
5729
6501
  (v, prev) => [...prev, v],
5730
6502
  []
5731
- ).option("--context <json>", "JSON object merged over the default gate context").action(async (master, raw) => {
6503
+ ).option("--context <json>", "JSON object merged over the default gate context").option(
6504
+ "--context-file <path>",
6505
+ 'path to a JSON gate context (bare object OR a `harnessed facts` envelope). Merged BEFORE --context, so an inline --context wins on conflict. A null fact means "not provided" and keeps the default.'
6506
+ ).action(async (master, raw) => {
5732
6507
  await runGatesPlan(master, raw);
5733
6508
  });
5734
6509
  }
6510
+ function unwrapFactsEnvelope(parsed) {
6511
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
6512
+ const obj = parsed;
6513
+ const facts = obj.facts;
6514
+ if (facts && typeof facts === "object" && !Array.isArray(facts)) {
6515
+ return facts;
6516
+ }
6517
+ return obj;
6518
+ }
5735
6519
  function fireEntry(clause, master) {
5736
6520
  const isMaster = STAGE_MASTERS.has(clause.sub);
5737
6521
  const sub = master !== "auto" && !isMaster ? `${master}-${clause.sub}` : clause.sub;
@@ -5742,7 +6526,7 @@ function fireEntry(clause, master) {
5742
6526
  if (isMaster) entry.is_master = true;
5743
6527
  return entry;
5744
6528
  }
5745
- var VALID_MASTERS, STAGE_MASTERS, PARALLELISM_GATE;
6529
+ var GATE_MASTERS, VALID_MASTERS, STAGE_MASTERS, PARALLELISM_GATE;
5746
6530
  var init_gates = __esm({
5747
6531
  "src/cli/gates.ts"() {
5748
6532
  init_path_guard();
@@ -5750,10 +6534,12 @@ var init_gates = __esm({
5750
6534
  init_runDeps();
5751
6535
  init_exprBuilder();
5752
6536
  init_judgmentResolver();
6537
+ init_skipGate();
5753
6538
  init_skipSubs();
5754
6539
  init_detectHeadless();
5755
6540
  init_gateContext();
5756
- VALID_MASTERS = /* @__PURE__ */ new Set(["auto", "discuss", "plan", "task", "verify", "ship"]);
6541
+ GATE_MASTERS = ["auto", "discuss", "plan", "task", "verify", "ship"];
6542
+ VALID_MASTERS = new Set(GATE_MASTERS);
5757
6543
  STAGE_MASTERS = /* @__PURE__ */ new Set(["discuss", "plan", "task", "verify"]);
5758
6544
  PARALLELISM_GATE = "judgments.parallelism-gate.agent-teams-upgrade.fires";
5759
6545
  }
@@ -6241,64 +7027,13 @@ var init_ccHookAdd2 = __esm({
6241
7027
  ctx,
6242
7028
  "/spec/install/hook_command",
6243
7029
  `hook '${resolvedCmd.slice(0, 80)}' missing in hooks.${ev}[] after write`,
6244
- "verify-failed"
6245
- )
6246
- };
6247
- }
6248
- await updateInstalled(ctx.cwd, ctx.manifest.metadata.name, "", "");
6249
- return { ok: true, backupId: bk.backupId, appliedFiles: [settingsPath] };
6250
- };
6251
- }
6252
- });
6253
- function extractVerifyBinary(verifyCmd, fallback) {
6254
- const token = verifyCmd?.trim().split(/\s+/)[0];
6255
- if (token && BARE_BIN_RE.test(token) && !NON_COMPONENT_TOKENS.has(token)) return token;
6256
- if (BARE_BIN_RE.test(fallback) && !NON_COMPONENT_TOKENS.has(fallback)) return fallback;
6257
- return null;
6258
- }
6259
- function realRun2(finder, bin) {
6260
- try {
6261
- if (typeof spawnSync !== "function") return null;
6262
- const r = spawnSync(finder, [bin], { encoding: "utf8" });
6263
- if (!r || r.error) return null;
6264
- return { status: r.status, stdout: r.stdout ?? "" };
6265
- } catch {
6266
- return null;
6267
- }
6268
- }
6269
- function binaryOnPath(bin, deps) {
6270
- const platform = process.platform;
6271
- const run = realRun2;
6272
- const finder = platform === "win32" ? "where" : "which";
6273
- const r = run(finder, bin);
6274
- if (!r || r.status !== 0) return false;
6275
- return r.stdout.trim().length > 0;
6276
- }
6277
- var NON_COMPONENT_TOKENS, BARE_BIN_RE;
6278
- var init_binaryProbe = __esm({
6279
- "src/installers/lib/binaryProbe.ts"() {
6280
- NON_COMPONENT_TOKENS = /* @__PURE__ */ new Set([
6281
- "test",
6282
- "grep",
6283
- "ls",
6284
- "cat",
6285
- "echo",
6286
- "command",
6287
- "sh",
6288
- "bash",
6289
- "[",
6290
- "npx",
6291
- "npm",
6292
- "node",
6293
- "corepack",
6294
- "pnpm",
6295
- "yarn",
6296
- "bun",
6297
- "git",
6298
- "claude",
6299
- "codex"
6300
- ]);
6301
- BARE_BIN_RE = /^[A-Za-z0-9][\w.@-]*$/;
7030
+ "verify-failed"
7031
+ )
7032
+ };
7033
+ }
7034
+ await updateInstalled(ctx.cwd, ctx.manifest.metadata.name, "", "");
7035
+ return { ok: true, backupId: bk.backupId, appliedFiles: [settingsPath] };
7036
+ };
6302
7037
  }
6303
7038
  });
6304
7039
  function evalClause(clause, home) {
@@ -6451,10 +7186,10 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
6451
7186
  child.stderr?.setEncoding("utf8").on("data", (chunk) => {
6452
7187
  stderr += chunk;
6453
7188
  });
6454
- return await new Promise((resolve21) => {
7189
+ return await new Promise((resolve24) => {
6455
7190
  const timer = setTimeout(() => {
6456
7191
  child.kill("SIGKILL");
6457
- resolve21({
7192
+ resolve24({
6458
7193
  ok: false,
6459
7194
  phase: "spawn",
6460
7195
  error: {
@@ -6475,7 +7210,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
6475
7210
  child.on("error", (err2) => {
6476
7211
  clearTimeout(timer);
6477
7212
  const bashMissing = triedBash && err2.code === "ENOENT";
6478
- resolve21({
7213
+ resolve24({
6479
7214
  ok: false,
6480
7215
  phase: "spawn",
6481
7216
  error: {
@@ -6490,7 +7225,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
6490
7225
  });
6491
7226
  child.on("close", (code) => {
6492
7227
  clearTimeout(timer);
6493
- resolve21({ ok: true, exitCode: code ?? -1, stdout: stdout2, stderr });
7228
+ resolve24({ ok: true, exitCode: code ?? -1, stdout: stdout2, stderr });
6494
7229
  });
6495
7230
  });
6496
7231
  }
@@ -6691,7 +7426,7 @@ var init_idempotent = __esm({
6691
7426
  }
6692
7427
  });
6693
7428
  function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3) {
6694
- return new Promise((resolve21) => {
7429
+ return new Promise((resolve24) => {
6695
7430
  const isWin = process.platform === "win32";
6696
7431
  const stdio = ["ignore", "pipe", "pipe"];
6697
7432
  const child = isWin ? spawn("cmd.exe", ["/c", bin, ...args], { cwd, windowsHide: true, stdio }) : spawn(bin, args, { cwd, shell: false, stdio });
@@ -6705,17 +7440,17 @@ function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3) {
6705
7440
  });
6706
7441
  const timer = setTimeout(() => {
6707
7442
  child.kill("SIGKILL");
6708
- resolve21({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
7443
+ resolve24({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
6709
7444
  }, timeoutMs);
6710
7445
  child.on("error", (e) => {
6711
7446
  clearTimeout(timer);
6712
7447
  const enoent = e.code === "ENOENT";
6713
7448
  const msg = enoent && bin === "codex" ? "codex CLI not found on PATH \u2014 install Codex CLI or re-run setup on the claude platform" : e.message;
6714
- resolve21({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
7449
+ resolve24({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
6715
7450
  });
6716
7451
  child.on("close", (code) => {
6717
7452
  clearTimeout(timer);
6718
- resolve21({ exitCode: code ?? -1, stdout: stdout2, stderr });
7453
+ resolve24({ exitCode: code ?? -1, stdout: stdout2, stderr });
6719
7454
  });
6720
7455
  });
6721
7456
  }
@@ -6798,7 +7533,7 @@ var init_ccPluginMarketplace2 = __esm({
6798
7533
  `cc-plugin-marketplace cmd must contain \`plugin install <plugin>@<marketplace>\` (parsed from: '${install.cmd.slice(0, 100)}')`,
6799
7534
  "cc-plugin-shape"
6800
7535
  ),
6801
- suggest: "see manifests/tools/ralph-loop.yaml or manifests/tools/superpowers.yaml for shape"
7536
+ suggest: "see manifests/tools/superpowers.yaml for shape"
6802
7537
  }
6803
7538
  };
6804
7539
  }
@@ -6971,7 +7706,7 @@ var init_packSkillAudit = __esm({
6971
7706
  }
6972
7707
  });
6973
7708
  function gitRevParseHead(cwd, timeoutMs = 1e4) {
6974
- return new Promise((resolve21) => {
7709
+ return new Promise((resolve24) => {
6975
7710
  const isWin = process.platform === "win32";
6976
7711
  const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
6977
7712
  let stdout2 = "";
@@ -6980,15 +7715,15 @@ function gitRevParseHead(cwd, timeoutMs = 1e4) {
6980
7715
  });
6981
7716
  const timer = setTimeout(() => {
6982
7717
  child.kill("SIGKILL");
6983
- resolve21({ sha: "", exit: -1 });
7718
+ resolve24({ sha: "", exit: -1 });
6984
7719
  }, timeoutMs);
6985
7720
  child.on("error", () => {
6986
7721
  clearTimeout(timer);
6987
- resolve21({ sha: "", exit: -1 });
7722
+ resolve24({ sha: "", exit: -1 });
6988
7723
  });
6989
7724
  child.on("close", (code) => {
6990
7725
  clearTimeout(timer);
6991
- resolve21({ sha: stdout2.trim(), exit: code ?? -1 });
7726
+ resolve24({ sha: stdout2.trim(), exit: code ?? -1 });
6992
7727
  });
6993
7728
  });
6994
7729
  }
@@ -8143,6 +8878,19 @@ function buildWorkflowStateBlock(wf, forward, ledgerAgeMs) {
8143
8878
  `BREAK-LOOP: sub '${l.sub}' failed ${l.count}x \u2014 stop retrying, run break-loop skill`
8144
8879
  );
8145
8880
  }
8881
+ for (const e of ledger) {
8882
+ const attempts = e.fail_count ?? 0;
8883
+ if (e.attempt_budget !== void 0 && attempts >= e.attempt_budget) {
8884
+ lines.push(
8885
+ `BUDGET-EXHAUSTED: sub '${e.sub}' spent ${attempts}/${e.attempt_budget} attempts \u2014 do NOT spawn it again; re-scope, fix the blocker, or escalate`
8886
+ );
8887
+ }
8888
+ if ((e.progress?.stale_count ?? 0) >= PLATEAU_THRESHOLD) {
8889
+ lines.push(
8890
+ `NO-PROGRESS: sub '${e.sub}' made no improvement for ${e.progress?.stale_count} consecutive attempts (metric: ${e.progress?.metric}) \u2014 stop respawning, change the approach`
8891
+ );
8892
+ }
8893
+ }
8146
8894
  if (wf.ship_ready) {
8147
8895
  lines.push(
8148
8896
  `SHIP-READY: ${wf.ship_commits ?? 0} commit(s) since the last release tag \u2014 consider shipping (harnessed release-preflight, then /ship)`
@@ -8258,6 +9006,7 @@ var init_injectState = __esm({
8258
9006
  init_forwardStep();
8259
9007
  init_ledger();
8260
9008
  init_planningScan();
9009
+ init_progress();
8261
9010
  INTENT_TTL_MS = 24 * 60 * 60 * 1e3;
8262
9011
  STALE_LEDGER_MS = 24 * 60 * 60 * 1e3;
8263
9012
  DEFAULT_INJECT_BUDGET = 1500;
@@ -9183,9 +9932,9 @@ function realSelfUpdateDeps() {
9183
9932
  return res.text();
9184
9933
  },
9185
9934
  smoke: async (bin) => {
9186
- const { execFile: execFile2 } = await import('child_process');
9187
- const { promisify: promisify3 } = await import('util');
9188
- const { stdout: stdout2 } = await promisify3(execFile2)(bin, ["--version"], {
9935
+ const { execFile: execFile3 } = await import('child_process');
9936
+ const { promisify: promisify4 } = await import('util');
9937
+ const { stdout: stdout2 } = await promisify4(execFile3)(bin, ["--version"], {
9189
9938
  timeout: 3e4,
9190
9939
  windowsHide: true
9191
9940
  });
@@ -9482,7 +10231,7 @@ function renderHumanTable(records) {
9482
10231
  }
9483
10232
  }
9484
10233
  function pipeToJq(filterExpr, lines) {
9485
- return new Promise((resolve21, reject) => {
10234
+ return new Promise((resolve24, reject) => {
9486
10235
  const child = spawn("jq", [filterExpr], {
9487
10236
  stdio: ["pipe", "inherit", "inherit"],
9488
10237
  windowsHide: true
@@ -9491,12 +10240,12 @@ function pipeToJq(filterExpr, lines) {
9491
10240
  const e = err2;
9492
10241
  if (e.code === "ENOENT") {
9493
10242
  console.error(t("audit_log.jq_missing"));
9494
- resolve21(1);
10243
+ resolve24(1);
9495
10244
  } else {
9496
10245
  reject(err2);
9497
10246
  }
9498
10247
  });
9499
- child.on("close", (code) => resolve21(code ?? 0));
10248
+ child.on("close", (code) => resolve24(code ?? 0));
9500
10249
  child.stdin.write(lines.join("\n"));
9501
10250
  child.stdin.end();
9502
10251
  });
@@ -9592,6 +10341,157 @@ function registerBackupList(program2) {
9592
10341
  });
9593
10342
  }
9594
10343
 
10344
+ // src/cli/checkDocs.ts
10345
+ init_i18n();
10346
+ var DEFAULT_MAX_STATE_LINES = 100;
10347
+ var KEY_DECISIONS_SECTION_RE = /^##\s+.*关键决议\s*ship\s*总结/gm;
10348
+ var KEY_DECISIONS_SECTION_LIMIT = 1;
10349
+ var HISTORICAL_ERRATA_RE = /W-[1-9]\s+errata|sister\s+review\s+M[1-9]\s+修正/;
10350
+ var ROADMAP_NARRATIVE_SIGNALS = [
10351
+ { id: "commit-hash", test: hasCommitHash },
10352
+ { id: "test-tally", test: (l) => /\b\d{2,}\s*\/\s*0\b/.test(l) },
10353
+ { id: "ci-verdict", test: (l) => /\bCI\s+(green|red|绿|红)/i.test(l) },
10354
+ { id: "lesson", test: (l) => /(教训|lesson\s*[::]|lessons?\s+learned)/i.test(l) }
10355
+ ];
10356
+ function hasCommitHash(line) {
10357
+ for (const m of line.matchAll(/\b[0-9a-f]{7,40}\b/g)) {
10358
+ if (/\d/.test(m[0]) && /[a-f]/.test(m[0])) return true;
10359
+ }
10360
+ return false;
10361
+ }
10362
+ function read(cwd, rel) {
10363
+ const p7 = join(cwd, rel);
10364
+ if (!existsSync(p7)) return null;
10365
+ try {
10366
+ return readFileSync(p7, "utf8");
10367
+ } catch {
10368
+ return null;
10369
+ }
10370
+ }
10371
+ function contentLines(content) {
10372
+ const lines = content.split(/\r?\n/);
10373
+ if (lines[lines.length - 1] === "") lines.pop();
10374
+ return lines;
10375
+ }
10376
+ function collectDocViolations(opts) {
10377
+ const limit = opts.maxStateLines ?? DEFAULT_MAX_STATE_LINES;
10378
+ const out = [];
10379
+ const state = read(opts.cwd, join(".planning", "STATE.md"));
10380
+ if (state !== null) {
10381
+ const lines = contentLines(state);
10382
+ if (lines.length > limit && !opts.allowLongState) {
10383
+ out.push({
10384
+ rule: "state-digest-line-limit",
10385
+ tier: "halt",
10386
+ file: ".planning/STATE.md",
10387
+ message: t("check_docs.state_line_limit", { lines: lines.length, limit })
10388
+ });
10389
+ }
10390
+ const sections = state.match(KEY_DECISIONS_SECTION_RE) ?? [];
10391
+ if (sections.length > KEY_DECISIONS_SECTION_LIMIT) {
10392
+ out.push({
10393
+ rule: "state-key-decisions-section-limit",
10394
+ tier: "warn",
10395
+ file: ".planning/STATE.md",
10396
+ message: t("check_docs.state_key_decisions", {
10397
+ count: sections.length,
10398
+ limit: KEY_DECISIONS_SECTION_LIMIT
10399
+ })
10400
+ });
10401
+ }
10402
+ for (let i = 0; i < lines.length; i++) {
10403
+ const line = lines[i] ?? "";
10404
+ if (HISTORICAL_ERRATA_RE.test(line)) {
10405
+ out.push({
10406
+ rule: "state-historical-errata",
10407
+ tier: "warn",
10408
+ file: ".planning/STATE.md",
10409
+ line: i + 1,
10410
+ message: t("check_docs.state_errata", { excerpt: line.trim().slice(0, 80) })
10411
+ });
10412
+ }
10413
+ }
10414
+ }
10415
+ const roadmap = read(opts.cwd, join(".planning", "ROADMAP.md"));
10416
+ if (roadmap !== null) {
10417
+ const lines = contentLines(roadmap);
10418
+ for (let i = 0; i < lines.length; i++) {
10419
+ const line = lines[i] ?? "";
10420
+ const hits = ROADMAP_NARRATIVE_SIGNALS.filter((s) => s.test(line)).map((s) => s.id);
10421
+ if (hits.length > 0) {
10422
+ out.push({
10423
+ rule: "roadmap-no-inline-narrative",
10424
+ tier: "warn",
10425
+ file: ".planning/ROADMAP.md",
10426
+ line: i + 1,
10427
+ message: t("check_docs.roadmap_narrative", { signals: hits.join(", ") })
10428
+ });
10429
+ }
10430
+ }
10431
+ }
10432
+ return out;
10433
+ }
10434
+ function exitCodeFor(violations) {
10435
+ if (violations.some((v) => v.tier === "halt")) return 2;
10436
+ return violations.length > 0 ? 1 : 0;
10437
+ }
10438
+ function shouldGateForHookPayload(raw) {
10439
+ if (!raw.trim()) return false;
10440
+ let payload;
10441
+ try {
10442
+ payload = JSON.parse(raw);
10443
+ } catch {
10444
+ return false;
10445
+ }
10446
+ if (payload?.tool_name !== "Bash") return false;
10447
+ const cmd = payload.tool_input?.command;
10448
+ return typeof cmd === "string" && /\bgit\s+(?:-\S+\s+)*commit\b/.test(cmd);
10449
+ }
10450
+ async function readStdin() {
10451
+ if (process.stdin.isTTY) return "";
10452
+ try {
10453
+ const chunks = [];
10454
+ for await (const c of process.stdin) chunks.push(c);
10455
+ return Buffer.concat(chunks).toString("utf8");
10456
+ } catch {
10457
+ return "";
10458
+ }
10459
+ }
10460
+ function registerCheckDocs(program2) {
10461
+ program2.command("check-docs").description(
10462
+ "Documentation-discipline gate over .planning/ (STATE digest limit + archive cadence + ROADMAP pointer-not-narrative). Exits 2 on a blocking violation, 1 on advisory-only."
10463
+ ).option("--json", "output JSON instead of human-readable").option("--cwd <dir>", "repo root holding .planning/ (default: current directory)").option("--max-state-lines <n>", `STATE.md digest ceiling (default ${DEFAULT_MAX_STATE_LINES})`).option("--hook", "PreToolUse mode: read the tool payload on stdin, gate only git commit").action(
10464
+ async (opts) => {
10465
+ if (opts.hook && !shouldGateForHookPayload(await readStdin())) process.exit(0);
10466
+ const parsed = Number(opts.maxStateLines);
10467
+ const violations = collectDocViolations({
10468
+ cwd: opts.cwd ?? process.cwd(),
10469
+ ...Number.isFinite(parsed) && parsed > 0 ? { maxStateLines: parsed } : {},
10470
+ allowLongState: !!process.env.HARNESSED_ALLOW_LONG_STATE
10471
+ });
10472
+ const code = exitCodeFor(violations);
10473
+ const summary = code === 2 ? "halt" : code === 1 ? "warn" : "pass";
10474
+ if (opts.json) {
10475
+ console.log(JSON.stringify({ violations, summary, exit_code: code }, null, 2));
10476
+ } else if (violations.length === 0) {
10477
+ console.log(t("check_docs.clean"));
10478
+ } else {
10479
+ for (const v of violations) {
10480
+ const where = v.line === void 0 ? v.file : `${v.file}:${v.line}`;
10481
+ console.error(`${v.tier === "halt" ? "\u2717" : "\u26A0"} ${where} [${v.rule}] ${v.message}`);
10482
+ }
10483
+ console.error(
10484
+ code === 2 ? t("check_docs.summary_halt", {
10485
+ halt: violations.filter((v) => v.tier === "halt").length,
10486
+ warn: violations.filter((v) => v.tier === "warn").length
10487
+ }) : t("check_docs.summary_warn", { warn: violations.length })
10488
+ );
10489
+ }
10490
+ process.exit(code);
10491
+ }
10492
+ );
10493
+ }
10494
+
9595
10495
  // src/cli.ts
9596
10496
  init_checkpoint();
9597
10497
 
@@ -9621,7 +10521,15 @@ function registerDoctor(program2) {
9621
10521
  program2.command("doctor").description(
9622
10522
  "Preflight checks (Node / MCP scope / jq / Win bash / origin URL / gstack prefix / deprecations / token budget / Agent Teams / planning-with-files / mattpocock-skills / MCP availability / ECC)"
9623
10523
  ).option("--json", "output JSON instead of human-readable").action(async (opts) => {
9624
- const results = await Promise.all(CHECKS.map((c) => c()));
10524
+ const settled = await Promise.allSettled(CHECKS.map((c) => c()));
10525
+ const results = settled.map(
10526
+ (s, i) => s.status === "fulfilled" ? s.value : {
10527
+ name: `check #${i + 1}`,
10528
+ status: "warn",
10529
+ message: `check crashed: ${s.reason instanceof Error ? s.reason.message : String(s.reason)}`,
10530
+ fix: "this check was skipped; the other checks above are unaffected"
10531
+ }
10532
+ );
9625
10533
  const hasFail = results.some((r) => r.status === "fail");
9626
10534
  const hasWarn = results.some((r) => r.status === "warn");
9627
10535
  if (opts.json) {
@@ -10284,6 +11192,233 @@ function registerExemptGateguard(program2) {
10284
11192
  });
10285
11193
  }
10286
11194
 
11195
+ // src/cli/facts.ts
11196
+ init_path_guard();
11197
+ init_assetsRoot();
11198
+ init_runDeps();
11199
+ init_exprBuilder();
11200
+ init_judgmentResolver();
11201
+ init_gates();
11202
+ init_probe_chrome_devtools();
11203
+ var VALID_MASTERS2 = new Set(GATE_MASTERS);
11204
+ function deriveGitFacts(run) {
11205
+ let lines = 0;
11206
+ let sawNumstat = false;
11207
+ for (const args of [
11208
+ ["diff", "--numstat"],
11209
+ ["diff", "--cached", "--numstat"]
11210
+ ]) {
11211
+ const out = run(args);
11212
+ if (out === null) continue;
11213
+ sawNumstat = true;
11214
+ for (const row of out.split(/\r?\n/)) {
11215
+ const m = /^(\d+)\t(\d+)\t/.exec(row);
11216
+ if (m) lines += Number(m[1]) + Number(m[2]);
11217
+ }
11218
+ }
11219
+ const files = /* @__PURE__ */ new Set();
11220
+ let sawNames = false;
11221
+ for (const args of [
11222
+ ["diff", "--name-only"],
11223
+ ["diff", "--cached", "--name-only"]
11224
+ ]) {
11225
+ const out = run(args);
11226
+ if (out === null) continue;
11227
+ sawNames = true;
11228
+ for (const row of out.split(/\r?\n/)) {
11229
+ const p7 = row.trim();
11230
+ if (p7) files.add(p7);
11231
+ }
11232
+ }
11233
+ return {
11234
+ lines: sawNumstat && lines > 0 ? lines : null,
11235
+ files_touched: sawNames && files.size > 0 ? files.size : null
11236
+ };
11237
+ }
11238
+ function defaultGitRun(args) {
11239
+ try {
11240
+ return execFileSync("git", args, {
11241
+ cwd: process.cwd(),
11242
+ encoding: "utf8",
11243
+ stdio: ["ignore", "pipe", "ignore"]
11244
+ });
11245
+ } catch {
11246
+ return null;
11247
+ }
11248
+ }
11249
+ function factNamesOf(expression) {
11250
+ return _parserSingleton.parse(expression).variables({ withMembers: true });
11251
+ }
11252
+ async function readDelegates(master, packageRoot) {
11253
+ const yamlPath = resolveMasterYamlPath(master, packageRoot);
11254
+ const parsed = parse(await readFile(yamlPath, "utf8"));
11255
+ const delegates = parsed?.delegates_to;
11256
+ return Array.isArray(delegates) ? delegates : [];
11257
+ }
11258
+ async function collectGatedFactNames(master, packageRoot) {
11259
+ const names = /* @__PURE__ */ new Set();
11260
+ for (const clause of await readDelegates(master, packageRoot)) {
11261
+ for (const ref of [clause.gate, clause.skip_gate]) {
11262
+ if (!ref) continue;
11263
+ let expr;
11264
+ try {
11265
+ expr = await resolveJudgmentExpression(ref, packageRoot);
11266
+ } catch {
11267
+ continue;
11268
+ }
11269
+ try {
11270
+ for (const n of factNamesOf(expr)) names.add(n);
11271
+ } catch {
11272
+ }
11273
+ }
11274
+ }
11275
+ return [...names].sort();
11276
+ }
11277
+ var FACT_HINTS = {
11278
+ // phase tier
11279
+ "phase.type": "Phase kind: 'new_project' | 'new_milestone' | 'new_feature' | 'bug_fix' | 'tech_debt' | 'continuing_phase'. Only the first three open the strategic (office-hours / CEO-review) tier.",
11280
+ "phase.stage": "Current stage name (derived from the invocation; do not edit).",
11281
+ "phase.open_decisions": "How many implementation decisions are still genuinely open for this phase (>=2 opens the phase-tier discussion).",
11282
+ "phase.scope_days": "Estimated phase size in days (>1 opens the phase-tier discussion).",
11283
+ "phase.single_task": "true if the phase is one self-contained task with no sub-structure.",
11284
+ "phase.scope_locked_in_history": "true if the scope was already decided in an earlier session / design doc, so re-litigating it is waste.",
11285
+ "phase.files_touched": "How many files this phase changes (derived from git when a diff exists; estimate it if the tree is still clean).",
11286
+ "phase.has_cross_phase_data_flow": "true if this phase shares a data flow, API contract or dependency with another phase.",
11287
+ "phase.is_complex_architecture": "true if the design has non-obvious structural choices (new layer / new seam / cross-cutting change), not just new code inside an existing pattern.",
11288
+ "phase.is_critical_module": "true if this touches a module where a regression is expensive (auth, payments, data migration, the release path).",
11289
+ "phase.is_major_release": "true if this phase ships a major version / externally visible launch.",
11290
+ "phase.is_final_step": "true if this is the last step of the phase (enables the simplify pass).",
11291
+ "phase.has_ui_changes": "true if user-visible UI changed (opens the QA lane).",
11292
+ "phase.has_design_changes": "true if visual design / design-system tokens changed (opens the design-review lane).",
11293
+ "phase.has_auth_or_secrets": "true if auth, credentials, tokens or secret handling changed (opens the security lane).",
11294
+ "phase.has_ai_phase": "true if this phase ships LLM/AI behaviour needing an eval-coverage audit.",
11295
+ "phase.requires_coverage_audit": "true if the phase needs a requirements-coverage audit rather than ordinary verification.",
11296
+ // subtask tier
11297
+ "subtask.type": "Subtask kind: 'crud' | 'core_logic' | 'algorithm' | 'ui_polish' | 'docs_only' | 'single_command_query' | 'standard_lib_call'. The first, last and 'ui_polish'/'docs_only' are what legitimately skip brainstorming / TDD.",
11298
+ "subtask.lines": "Rough size of the change in lines (derived from git when a diff exists; estimate it if nothing is written yet). <20 is the trivial-change skip.",
11299
+ "subtask.approaches": "How many genuinely different implementations you are choosing between (>=2 means the choice deserves a decision, not a coin flip).",
11300
+ "subtask.core_algorithm": "true if this designs an algorithm or data structure rather than wiring existing pieces together.",
11301
+ "subtask.has_api_contract": "true if this defines or changes an interface other code must conform to.",
11302
+ "subtask.error_cost": "Cost of getting this wrong: 'low' | 'medium' | 'high'. 'high' = data migration, concurrency, a performance-critical path, anything not cheaply reversible.",
11303
+ "subtask.is_core_business_logic": "true if this is core domain logic rather than glue or config.",
11304
+ "subtask.is_algorithm": "true if correctness depends on an algorithm you could get subtly wrong.",
11305
+ "subtask.is_data_processing": "true if this transforms, parses or migrates data.",
11306
+ "subtask.regression_risk": "How likely a silent regression is here: 'low' | 'medium' | 'high'.",
11307
+ "subtask.reliability_required": "true if this must keep working unattended (hooks, CI gates, release path).",
11308
+ // root-flat
11309
+ is_critical_release: "true if this verification guards a critical release (escalates to the multi-specialist review team).",
11310
+ user_understanding_unclear: "true if YOU do not yet understand the request well enough to plan it (opens the research stage)."
11311
+ };
11312
+ function hintFor(name) {
11313
+ return FACT_HINTS[name] ?? `Judgement call consumed by a gate expression in workflows/judgments/ \u2014 read the trigger that references '${name}' before filling it.`;
11314
+ }
11315
+ function setNested(target, dotted, value) {
11316
+ const parts = dotted.split(".");
11317
+ if (parts.length === 1) {
11318
+ target[dotted] = value;
11319
+ return;
11320
+ }
11321
+ const [group, key] = parts;
11322
+ let bucket = target[group];
11323
+ if (!bucket) {
11324
+ bucket = {};
11325
+ target[group] = bucket;
11326
+ }
11327
+ bucket[key] = value;
11328
+ }
11329
+ function buildFactsEnvelope(master, gatedNames, derived) {
11330
+ const facts = {};
11331
+ const hints = {};
11332
+ const all = [.../* @__PURE__ */ new Set([...gatedNames, ...Object.keys(derived)])].sort();
11333
+ for (const name of all) {
11334
+ const value = derived[name]?.value ?? null;
11335
+ setNested(facts, name, value);
11336
+ if (value === null) hints[name] = hintFor(name);
11337
+ }
11338
+ return {
11339
+ master,
11340
+ facts,
11341
+ hints,
11342
+ derived,
11343
+ usage: `Fill every null in \`facts\` with your honest judgement (leave a fact null to accept harnessed's default), write that object to a file, then run: harnessed gates ${master} --task "<locked spec>" --context-file <path>. The output of this command can be passed back verbatim \u2014 the envelope is unwrapped automatically.`
11344
+ };
11345
+ }
11346
+ async function runFactsPlan(master, raw, deps = defaultRunDeps, gitRun = defaultGitRun, probeCdt = () => probeChromeDevtools()) {
11347
+ if (!VALID_MASTERS2.has(master)) {
11348
+ deps.error(
11349
+ `error: unknown master '${master}'. Expected one of: ${[...GATE_MASTERS].join(", ")}.`
11350
+ );
11351
+ deps.exit(1);
11352
+ return;
11353
+ }
11354
+ try {
11355
+ checkPathSafe(master);
11356
+ } catch {
11357
+ deps.error("error: invalid master name (path traversal rejected)");
11358
+ deps.exit(1);
11359
+ return;
11360
+ }
11361
+ const packageRoot = getAssetsRoot();
11362
+ let gated;
11363
+ try {
11364
+ gated = await collectGatedFactNames(master, packageRoot);
11365
+ } catch (err2) {
11366
+ deps.error(
11367
+ `error: failed to read master workflow.yaml at ${resolveMasterYamlPath(master, packageRoot)} \u2014 ${err2.message}`
11368
+ );
11369
+ deps.exit(1);
11370
+ return;
11371
+ }
11372
+ const git = deriveGitFacts(gitRun);
11373
+ const cdt = await probeCdt();
11374
+ const derived = {
11375
+ // `harnessed gates` seeds phase.stage from the master argument, so facts MUST
11376
+ // report the same thing: deriving a stage from the ledger instead could hand
11377
+ // back a STALE stage that then overrides the real one through --context-file
11378
+ // and turn every `phase.stage == '<x>'` gate false.
11379
+ "phase.stage": {
11380
+ value: master,
11381
+ source: `master argument (mirrors \`harnessed gates ${master}\`)`
11382
+ },
11383
+ "subtask.lines": {
11384
+ value: git.lines,
11385
+ source: "git diff --numstat + --cached --numstat (added+deleted; null when no repo / clean tree)"
11386
+ },
11387
+ "phase.files_touched": {
11388
+ value: git.files_touched,
11389
+ source: "git diff --name-only + --cached --name-only (unique paths; null when no repo / clean tree)"
11390
+ },
11391
+ // Root-flat (bare identifier), sister src/workflow/schema/phaseFactContext.ts.
11392
+ // `source` doubles as the SKIP REASON: when no provider is registered it
11393
+ // names BOTH enable paths, so losing the diagnostic lane is never silent.
11394
+ chrome_devtools_available: {
11395
+ value: chromeDevtoolsAvailable(cdt),
11396
+ source: chromeDevtoolsFactSource(cdt)
11397
+ }
11398
+ };
11399
+ const envelope = buildFactsEnvelope(master, gated, derived);
11400
+ const json = JSON.stringify(envelope, null, 2);
11401
+ if (raw.out) {
11402
+ try {
11403
+ await writeFile(raw.out, json, "utf8");
11404
+ } catch (err2) {
11405
+ deps.error(`error: failed to write --out ${raw.out} \u2014 ${err2.message}`);
11406
+ deps.exit(1);
11407
+ return;
11408
+ }
11409
+ }
11410
+ deps.log(json);
11411
+ deps.exit(0);
11412
+ return;
11413
+ }
11414
+ function registerFacts(program2) {
11415
+ program2.command("facts").description(
11416
+ "List the gate facts a master actually consumes: deterministic ones filled in, judgement calls left null with a one-line hint. Feed the filled file to `harnessed gates --context-file`."
11417
+ ).argument("<master>", "master name: auto | discuss | plan | task | verify | ship").option("--out <path>", "also write the JSON envelope to this file").action(async (master, raw) => {
11418
+ await runFactsPlan(master, raw);
11419
+ });
11420
+ }
11421
+
10287
11422
  // src/cli.ts
10288
11423
  init_gates();
10289
11424
  init_gc();
@@ -10848,29 +11983,7 @@ async function loadAllApplied(disciplines_applied, packageRoot) {
10848
11983
  return out;
10849
11984
  }
10850
11985
 
10851
- // src/discipline/enforcement/after-output.ts
10852
- var EM_DASH_RE = /——|—/;
10853
- var EMOJI_RE = new RegExp("\\p{Emoji_Presentation}", "u");
10854
- var SYCOPHANTIC_RE = /(好问题|太棒了|完美|希望对你有帮助|还需要别的吗|要不要我帮你)/;
10855
- var END_RECAP_RE = /## 总结|## Summary|综上所述|In summary/;
10856
- async function runAfterOutputHook(ctx) {
10857
- const warns = [];
10858
- await Promise.all([
10859
- loadDiscipline("output-style", ctx.packageRoot),
10860
- loadDiscipline("language", ctx.packageRoot)
10861
- ]);
10862
- const firstSentence = ctx.responseText.split(/[。.!?\n]/)[0] ?? "";
10863
- if (firstSentence.length > 100) warns.push("BLUF missing: first sentence > 100 char");
10864
- if (EM_DASH_RE.test(ctx.responseText)) warns.push("em-dash detected (auto-fix recommended)");
10865
- if (EMOJI_RE.test(ctx.responseText)) {
10866
- warns.push("emoji used without explicit user request");
10867
- }
10868
- if (SYCOPHANTIC_RE.test(ctx.responseText)) warns.push("sycophantic phrase detected");
10869
- const lastChunk = ctx.responseText.slice(-200);
10870
- if (END_RECAP_RE.test(lastChunk)) warns.push("redundant end recap detected");
10871
- for (const w of warns) console.warn(`\u26A0\uFE0F output-style: ${w}`);
10872
- return warns;
10873
- }
11986
+ // src/discipline/enforcement/before-commit.ts
10874
11987
  var TS_JS_RE = /\.(ts|tsx|js|mjs)$/;
10875
11988
  async function runBeforeCommitHook(ctx) {
10876
11989
  const d = await loadDiscipline("operational", ctx.packageRoot);
@@ -10912,17 +12025,58 @@ async function runBeforeCommitHook(ctx) {
10912
12025
  async function loadDisciplinesForPhase(disciplines_applied, packageRoot) {
10913
12026
  return loadAllApplied(disciplines_applied, packageRoot);
10914
12027
  }
10915
-
10916
- // src/discipline/enforcement/before-spawn.ts
12028
+ var IMPL_TIER = {
12029
+ gstack: "gstack",
12030
+ gsd: "gsd",
12031
+ superpowers: "superpowers",
12032
+ "mattpocock-skills": "mattpocock",
12033
+ // agent-teams-create / -send-message / -shutdown — 子任务并行机制 (Agent Teams).
12034
+ "claude-platform": "parallel"
12035
+ };
12036
+ var NAME_TIER = {
12037
+ "planning-with-files": "planning-with-files",
12038
+ "karpathy-guidelines": "karpathy"
12039
+ };
12040
+ var _implCache = /* @__PURE__ */ new Map();
12041
+ async function loadCapabilityImpls(packageRoot) {
12042
+ const cached = _implCache.get(packageRoot);
12043
+ if (cached) return cached;
12044
+ const out = /* @__PURE__ */ new Map();
12045
+ try {
12046
+ const raw = await readFile(resolve(packageRoot, "workflows", "capabilities.yaml"), "utf8");
12047
+ const parsed = parse(raw);
12048
+ for (const [name, entry] of Object.entries(parsed?.capabilities ?? {})) {
12049
+ if (entry && typeof entry.impl === "string") out.set(name, entry.impl);
12050
+ }
12051
+ } catch (err2) {
12052
+ console.warn(
12053
+ `\u26A0\uFE0F before-spawn: capabilities.yaml unreadable (${err2.message}); arbitrating without capability\u2192tier resolution (ADR 0029 fail-soft \u2014 fired order preserved).`
12054
+ );
12055
+ return out;
12056
+ }
12057
+ _implCache.set(packageRoot, out);
12058
+ return out;
12059
+ }
12060
+ function resolveTier(cap, impls) {
12061
+ if (cap.tier !== void 0) return cap.tier;
12062
+ const byName = NAME_TIER[cap.name];
12063
+ if (byName) return byName;
12064
+ const impl = impls.get(cap.name);
12065
+ return impl ? IMPL_TIER[impl] : void 0;
12066
+ }
10917
12067
  async function arbitrateBeforeSpawn(fired, packageRoot) {
10918
12068
  if (fired.length <= 1) return fired;
10919
12069
  const d = await loadDiscipline("priority", packageRoot);
10920
12070
  const hierarchy = d.priority_hierarchy ?? [];
10921
- const rank = (tier) => {
10922
- const i = hierarchy.indexOf(tier);
10923
- return i === -1 ? Number.MAX_SAFE_INTEGER : i;
10924
- };
10925
- return [...fired].sort((a, b) => rank(a.tier) - rank(b.tier));
12071
+ const impls = await loadCapabilityImpls(packageRoot);
12072
+ return fired.map((cap) => {
12073
+ const tier = resolveTier(cap, impls);
12074
+ const i = tier === void 0 ? -1 : hierarchy.indexOf(tier);
12075
+ return {
12076
+ cap: tier === void 0 ? cap : { ...cap, tier },
12077
+ rank: i === -1 ? Number.MAX_SAFE_INTEGER : i
12078
+ };
12079
+ }).sort((a, b) => a.rank - b.rank).map((e) => e.cap);
10926
12080
  }
10927
12081
 
10928
12082
  // src/workflow/run.ts
@@ -10985,75 +12139,7 @@ async function isVetoed() {
10985
12139
 
10986
12140
  // src/workflow/run.ts
10987
12141
  init_judgmentResolver();
10988
-
10989
- // src/workflow/lib/promiseExtract.ts
10990
- var PROMISE_PATTERN = /<promise>([^<]+)<\/promise>/;
10991
- function extractPromise(text) {
10992
- const match = text.match(PROMISE_PATTERN);
10993
- return match ? match[1] : null;
10994
- }
10995
-
10996
- // src/workflow/lib/fallbackHandlers.ts
10997
- function handleMaxIterationsExceeded(err2, fallback, ctx) {
10998
- const yamlShort = fallback.message.replace(
10999
- /\{\{\s*args\.max_iterations\s*\}\}/g,
11000
- String(ctx.maxIterations)
11001
- );
11002
- const truncated = (ctx.lastMessage ?? "<empty>").slice(0, 500);
11003
- const uxText = `\u274C ralph-loop max-iterations exceeded (${err2.iterations}/${ctx.maxIterations}).
11004
- Sub-task: ${ctx.subtaskSummary}
11005
- Workflow: ${ctx.workflowName} / phase ${ctx.phaseId}
11006
- Last subagent output (truncated): ${truncated}
11007
- The subagent attempted ${err2.iterations} iterations without emitting verbatim "<promise>COMPLETE</promise>".
11008
- This indicates one of:
11009
- 1. Sub-task is genuinely incomplete (escalate to user / re-scope)
11010
- 2. Subagent is stuck in a loop (review prompt / system instructions)
11011
- 3. max-iterations too low (override via --max-iterations <N>, hard upper limit 100)
11012
- Manual options:
11013
- A) Continue with current state: \`harnessed workflow resume --skip-completion-gate\`
11014
- B) Re-run from last checkpoint: \`harnessed workflow resume --from-checkpoint\`
11015
- C) Abort cleanly: exit 1
11016
- Exit code: ${fallback.exit_code}
11017
- ${yamlShort}`;
11018
- console.error(uxText);
11019
- process.exit(fallback.exit_code);
11020
- throw new Error("unreachable");
11021
- }
11022
-
11023
- // src/workflow/lib/ralphLoop.ts
11024
- function isComplete(output) {
11025
- let env;
11026
- try {
11027
- env = JSON.parse(output);
11028
- } catch {
11029
- return extractPromise(output) === "COMPLETE";
11030
- }
11031
- const succeeded = env.subtype === "success";
11032
- const status = env.structured_output?.status;
11033
- if (status === "COMPLETE") return succeeded;
11034
- if (status === "PARTIAL" || status === "BLOCKED") return false;
11035
- if (succeeded) return true;
11036
- return extractPromise(env.text ?? env.result ?? "") === "COMPLETE";
11037
- }
11038
- var MaxIterationsExceededError = class extends Error {
11039
- constructor(iterations) {
11040
- super(`ralph-loop max-iterations exceeded after ${iterations} attempts`);
11041
- this.iterations = iterations;
11042
- this.name = "MaxIterationsExceededError";
11043
- }
11044
- iterations;
11045
- };
11046
- async function ralphLoopWrap(spawn6, maxIter) {
11047
- let last = "";
11048
- let sessionId;
11049
- for (let i = 0; i < maxIter; i++) {
11050
- last = await spawn6(sessionId, (id) => {
11051
- sessionId = id;
11052
- });
11053
- if (isComplete(last)) return last;
11054
- }
11055
- throw new MaxIterationsExceededError(maxIter);
11056
- }
12142
+ init_ralphLoop();
11057
12143
 
11058
12144
  // src/workflow/lib/completionSchema.ts
11059
12145
  var COMPLETION_SCHEMA = {
@@ -11066,8 +12152,11 @@ var COMPLETION_SCHEMA = {
11066
12152
  // v3.5.0 Phase 2 — Option 1-Lite signal-driven Agent Teams escalation.
11067
12153
  // spawned subagent SHOULD set this when any of parallelism-gate.yaml 5
11068
12154
  // upgrade triggers fire. harnessed runtime propagates to stderr hint;
11069
- // user opens team in main Claude Code session (TeamCreate not exposed to
11070
- // spawned subagents via SDK v0.3.142 — see PHASE-2-SPEC.md § Why).
12155
+ // user opens the team in the main Claude Code session — a spawned subagent
12156
+ // cannot form one itself (originally because the SDK never exposed the create
12157
+ // tool; since CC v2.1.178 there IS no create tool at all — teams form
12158
+ // implicitly on the lead's first background teammate spawn, and teammates
12159
+ // cannot nest teammates. See PHASE-2-SPEC.md § Why for the original rationale).
11071
12160
  needs_teams_escalation: { type: "boolean" },
11072
12161
  escalation_reason: { type: "string" }
11073
12162
  },
@@ -11303,6 +12392,11 @@ var DelegationClause = Type.Object(
11303
12392
  // sub-stage workflow name e.g. 'strategic' / 'phase' / 'subtask'
11304
12393
  gate: Type.Optional(Type.String()),
11305
12394
  // judgments.<file>.<trigger>.fires 4-level ref
12395
+ // T2.1 D-5 NEW — judgments.<file>.<trigger>.skips 4-level ref. Evaluated ONLY
12396
+ // when `gate` fired; true ⇒ veto the sub. Any fault (undefined variable /
12397
+ // missing trigger / no skips_when) ⇒ no veto, so a broken skip expression can
12398
+ // never silently delete a governance step (src/workflow/skipGate.ts).
12399
+ skip_gate: Type.Optional(Type.String()),
11306
12400
  mode: Type.Optional(Type.Union([Type.Literal("parallel"), Type.Literal("serial")])),
11307
12401
  order: Type.Optional(Type.Number())
11308
12402
  // serial-only: explicit ordering (K9 mitigation enforced in check-workflow-schema)
@@ -11330,7 +12424,7 @@ var WorkflowPhaseV3 = Type.Object(
11330
12424
  name: Type.Optional(Type.String()),
11331
12425
  upstream: Type.Optional(Type.String()),
11332
12426
  capability: Type.Optional(Type.String()),
11333
- // '{{ capabilities.ralph-loop.cmd }}'
12427
+ // '{{ capabilities.completion-gate.cmd }}'
11334
12428
  model: Type.Optional(ModelTier3),
11335
12429
  invokes: Type.Optional(Type.String()),
11336
12430
  // legacy slash-cmd OR JINJA template
@@ -11414,6 +12508,7 @@ function loadPhases(yamlPath, vars) {
11414
12508
  init_subAnchor();
11415
12509
  init_exprBuilder();
11416
12510
  init_judgmentResolver();
12511
+ init_skipGate();
11417
12512
  init_skipSubs();
11418
12513
  function resolveMasterYamlPath2(masterName, packageRoot) {
11419
12514
  return masterName === "auto" ? resolve(packageRoot, "workflows", "auto", "workflow.yaml") : resolve(packageRoot, "workflows", masterName, "auto", "workflow.yaml");
@@ -11566,11 +12661,12 @@ async function runMasterOrchestrator(masterName, context, packageRoot, spawnDriv
11566
12661
  }
11567
12662
  try {
11568
12663
  const passes = await resolveJudgmentGate(clause.gate, context, packageRoot);
11569
- gateEvalled.push({
11570
- clause,
11571
- passes,
11572
- reason: passes ? void 0 : `gate ${clause.gate} = false`
11573
- });
12664
+ if (!passes) {
12665
+ gateEvalled.push({ clause, passes: false, reason: `gate ${clause.gate} = false` });
12666
+ continue;
12667
+ }
12668
+ const veto = await resolveSkipVeto(clause.skip_gate, context, packageRoot);
12669
+ gateEvalled.push(veto ? { clause, passes: false, reason: veto } : { clause, passes: true });
11574
12670
  } catch (e) {
11575
12671
  if (isUndefinedVariableError(e)) {
11576
12672
  console.warn(
@@ -11652,7 +12748,7 @@ async function runMasterOrchestrator(masterName, context, packageRoot, spawnDriv
11652
12748
  var MASTER_NAMES = ["discuss", "plan", "task", "verify", "auto"];
11653
12749
  var RALPH_DEFAULT_MAX_ITER = 20;
11654
12750
  var RALPH_HARD_UPPER_LIMIT = 100;
11655
- var ESCALATION_RULES = `If during this task you detect ANY of the following 5 conditions, set \`needs_teams_escalation: true\` in your structured output and fill \`escalation_reason\` with the trigger name + one-sentence specifics. These are signals to the human user in the main Claude Code session \u2014 do NOT attempt to call TeamCreate/SendMessage/TeamDelete yourself (those tools are not available to you).
12751
+ var ESCALATION_RULES = `If during this task you detect ANY of the following 5 conditions, set \`needs_teams_escalation: true\` in your structured output and fill \`escalation_reason\` with the trigger name + one-sentence specifics. These are signals to the human user in the main Claude Code session \u2014 do NOT attempt to spawn teammates or call SendMessage yourself (the Agent Teams surface is not available to you, and upstream forbids nested teams: only the lead session can manage a team).
11656
12752
 
11657
12753
  Five triggers (any one suffices):
11658
12754
 
@@ -11673,11 +12769,11 @@ var TRANSPARENT_SKIP_RULES = `When you encounter a phase gate or routing decisio
11673
12769
  (\u4E2D\u6587: "\u8FD9\u6B21\u8DF3\u8FC7\u4E86 <phase>, \u56E0\u4E3A <reason>. \u5982\u679C\u4F60\u8BA4\u4E3A\u9700\u8981\u8BF7\u660E\u8BF4.")
11674
12770
 
11675
12771
  This applies to: strategic-layer review skip / phase-layer clarification skip / subtask-brainstorming skip / TDD enforcement skip / Agent Teams escalation skip. Chain-isolation rule: skipping one layer does NOT mandate skipping subsequent layers \u2014 each layer is independently evaluated.`;
11676
- var AGENT_TEAMS_PREVENTION_RULES = `If you signal needs_teams_escalation=true, ALSO advise the user on these 4 Agent Teams prevention rules in your escalation_reason or summary (the user will be the one calling TeamCreate / SendMessage / TeamDelete; remind them upfront):
12772
+ var AGENT_TEAMS_PREVENTION_RULES = `If you signal needs_teams_escalation=true, ALSO advise the user on these 4 Agent Teams prevention rules in your escalation_reason or summary (the user will be the one spawning teammates and calling SendMessage; remind them upfront):
11677
12773
 
11678
- 1. **Session-scoped**: Teams live only in the current Claude Code session. \`/resume\` loses all teammates. Do not treat teams as persistent state \u2014 finish team work within one session.
12774
+ 1. **Session-scoped**: Teams live only in the current Claude Code session. \`/resume\` loses all teammates. Do not treat teams as persistent state \u2014 finish team work within one session. A team forms implicitly on the first background \`Agent(...)\` teammate spawn; there is no create step (CC 2.1.178+ removed the create/delete tools).
11679
12775
 
11680
- 2. **Cleanup mandatory**: Before session ends, send \`SendMessage(to=<teammate>, content="shutdown_request")\` to each teammate, then call \`TeamDelete\`. Orphan teammates consume resources. This is a hard rule, not advisory.
12776
+ 2. **Stop every teammate before finishing**: ask each teammate to shut down BY NAME (e.g. "ask the researcher teammate to shut down") \u2014 it is a request, so the teammate finishes its current tool call first and may reject with a reason; confirm it actually stopped. The team's shared directories are cleaned up automatically at session exit, so there is no separate teardown step, but a teammate left running keeps consuming tokens. This is a hard rule, not advisory.
11681
12777
 
11682
12778
  3. **Token cost estimation**: Before creating a team, estimate \`team_cost \u2248 N_teammates \xD7 N_rounds \xD7 avg_tokens_per_round + N_teammates \xD7 initial_brief_tokens\`. Compare to subagent fan-out cost (\`\u2248 N_subagents \xD7 (initial_brief + summary_tokens)\`). Only open a team when \`team_cost < 2 \xD7 subagent_cost\` \u2014 otherwise prefer fan-out.
11683
12779
 
@@ -11848,8 +12944,11 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
11848
12944
  const invokesTools = "invokes_tools" in ph && Array.isArray(ph.invokes_tools) ? ph.invokes_tools : void 0;
11849
12945
  if (invokesTools && invokesTools.length > 1) {
11850
12946
  try {
11851
- const firedCaps = invokesTools.map((c) => ({ name: c.tool, tier: c.tool }));
11852
- await arbitrateBeforeSpawn(firedCaps, packageRoot);
12947
+ const firedCaps = invokesTools.map((c) => ({ name: c.tool }));
12948
+ const arbitrated = await arbitrateBeforeSpawn(firedCaps, packageRoot);
12949
+ console.warn(
12950
+ `\u26A0\uFE0F phase ${ph.id} fires ${arbitrated.length} tools \u2014 priority-arbitrated order: ${arbitrated.map((c) => c.tier ? `${c.name} (${c.tier})` : c.name).join(" > ")} (highest priority.yaml tier first; untiered capabilities keep declared order at the tail; K14 warn-not-halt).`
12951
+ );
11853
12952
  } catch (err2) {
11854
12953
  console.warn(
11855
12954
  `\u26A0\uFE0F phase ${ph.id} before-spawn arbitrate failed (${err2.message}); proceeding default tool order (K14 warn-not-halt).`
@@ -11901,23 +13000,9 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
11901
13000
  if (r.needsTeamsEscalation === true) {
11902
13001
  const reason = r.escalationReason ?? "unspecified trigger";
11903
13002
  console.error(
11904
- `\u26A0\uFE0F phase ${ph.id} suggests Agent Teams escalation \u2014 ${reason}. Consider opening a team in your main Claude Code session (TeamCreate) if continuing this work benefits from teammate coordination. See workflows/judgments/parallelism-gate.yaml for the 5 upgrade triggers.`
13003
+ `\u26A0\uFE0F phase ${ph.id} suggests Agent Teams escalation \u2014 ${reason}. Consider forming a team in your main Claude Code session (spawn background teammates with the Agent tool) if continuing this work benefits from teammate coordination. See workflows/judgments/parallelism-gate.yaml for the 5 upgrade triggers.`
11905
13004
  );
11906
13005
  }
11907
- if (r.target === "chat") {
11908
- try {
11909
- await runAfterOutputHook({
11910
- responseText: r.output,
11911
- responseTarget: "chat",
11912
- userRequestedEmoji: false,
11913
- packageRoot
11914
- });
11915
- } catch (err2) {
11916
- console.warn(
11917
- `\u26A0\uFE0F phase ${ph.id} after-output hook failed (${err2.message}); proceeding (ADR 0029 fail-soft).`
11918
- );
11919
- }
11920
- }
11921
13006
  if (r.triggers_commit === true) {
11922
13007
  try {
11923
13008
  await runBeforeCommitHook({
@@ -11976,6 +13061,13 @@ async function buildToolsSection(sub, packageRoot) {
11976
13061
  const cmd = caps[tool]?.cmd;
11977
13062
  const impl = caps[tool]?.impl;
11978
13063
  lines.push(cmd ? `- Invoke \`${cmd}\` (${tool}${impl ? `, ${impl}` : ""})` : `- ${tool}`);
13064
+ const aliases = (caps[tool]?.aliases ?? []).filter((a) => typeof a.cmd === "string");
13065
+ if (cmd && aliases.length > 0) {
13066
+ const rendered = aliases.map((a) => `\`${a.cmd}\`${a.impl ? ` (${a.impl})` : ""}`).join(", ");
13067
+ lines.push(
13068
+ ` - specialist alternatives: ${rendered} \u2014 pick at most ONE whose provider is installed AND whose language/stack matches the change; run it INSTEAD of the base cmd above (never both). Provider not installed or no match \u2192 just use \`${cmd}\`.`
13069
+ );
13070
+ }
11979
13071
  }
11980
13072
  if (lines.length === 0) return "";
11981
13073
  return `
@@ -11987,6 +13079,12 @@ ${lines.join("\n")}
11987
13079
  return "";
11988
13080
  }
11989
13081
  }
13082
+ var CHAT_TRIGGER_RE = /response\.target\s*==\s*['"]chat['"]/;
13083
+ var CHAT_SCOPE_NOTE = "scope \u2014 chat replies ONLY: the rules nested below govern how you talk to the user and do NOT constrain the files you write (README / CHANGELOG / PLAN.md / SUMMARY.md / docs / code comments follow their own conventions, and may use emoji, em-dashes, headings and summary sections):";
13084
+ function isChatScoped(trigger) {
13085
+ const s = Array.isArray(trigger) ? trigger.join(" ") : typeof trigger === "string" ? trigger : "";
13086
+ return CHAT_TRIGGER_RE.test(s);
13087
+ }
11990
13088
  async function buildDisciplinesSection(sub, packageRoot, locale = getLocale()) {
11991
13089
  try {
11992
13090
  const workflowsDir = resolve(packageRoot, "workflows");
@@ -12000,9 +13098,20 @@ async function buildDisciplinesSection(sub, packageRoot, locale = getLocale()) {
12000
13098
  const dRaw = await readFile(resolveLocaleYaml(disciplinesDir, name, locale), "utf8");
12001
13099
  const dDoc = parse(dRaw);
12002
13100
  const rules = Array.isArray(dDoc?.rules) ? dDoc.rules : [];
12003
- const descs = rules.map((r) => typeof r.description === "string" ? r.description.trim() : "").filter((s) => s.length > 0).map((s) => ` - ${s.replace(/\s+/g, " ")}`);
12004
- if (descs.length > 0) blocks.push(`- **${name}**:
12005
- ${descs.join("\n")}`);
13101
+ const always = [];
13102
+ const chat = [];
13103
+ for (const r of rules) {
13104
+ const desc = typeof r.description === "string" ? r.description.trim().replace(/\s+/g, " ") : "";
13105
+ if (desc.length === 0) continue;
13106
+ (isChatScoped(r.trigger) ? chat : always).push(desc);
13107
+ }
13108
+ const lines = always.map((d) => ` - ${d}`);
13109
+ if (chat.length > 0) {
13110
+ lines.push(` - ${CHAT_SCOPE_NOTE}`);
13111
+ lines.push(...chat.map((d) => ` - ${d}`));
13112
+ }
13113
+ if (lines.length > 0) blocks.push(`- **${name}**:
13114
+ ${lines.join("\n")}`);
12006
13115
  } catch {
12007
13116
  }
12008
13117
  }
@@ -12016,13 +13125,31 @@ ${blocks.join("\n")}
12016
13125
  return "";
12017
13126
  }
12018
13127
  }
12019
- function buildLanguageSection() {
13128
+ var PRESERVE_FALLBACK = "Keep code, commands, file/identifier/API names, error messages, stack traces, URLs, commit hashes, and version numbers in their original form (do not translate or transliterate them).";
13129
+ async function loadPreserveCategories(packageRoot) {
13130
+ try {
13131
+ const path = resolve(packageRoot, "workflows", "disciplines", "language.yaml");
13132
+ const doc = parse(await readFile(path, "utf8"));
13133
+ const rule = (Array.isArray(doc?.rules) ? doc.rules : []).find(
13134
+ (r) => r?.id === "preserve-english-categories"
13135
+ );
13136
+ const desc = typeof rule?.description === "string" ? rule.description : "";
13137
+ return desc.split("\n").map((l) => l.trim()).filter((l) => /^\d+\.\s+\S/.test(l));
13138
+ } catch {
13139
+ return [];
13140
+ }
13141
+ }
13142
+ async function buildLanguageSection(packageRoot) {
12020
13143
  const code = process.env.HARNESSED_USER_LANG;
12021
13144
  if (!code) return "";
12022
13145
  const name = LANG_NAMES[code] ?? code;
13146
+ const categories = await loadPreserveCategories(packageRoot);
13147
+ const preserve = categories.length > 0 ? `The following always stay in their original English form (do not translate, transliterate, or rewrite them):
13148
+ ${categories.join("\n")}` : PRESERVE_FALLBACK;
12023
13149
  return `
12024
13150
  ## Language
12025
- Respond in ${name}. Keep code, commands, file/identifier/API names, error messages, stack traces, URLs, commit hashes, and version numbers in their original form (do not translate or transliterate them).
13151
+ Respond in ${name}.
13152
+ ${preserve}
12026
13153
  `;
12027
13154
  }
12028
13155
  var PROTOCOLS = `
@@ -12072,8 +13199,9 @@ ${raw.task}
12072
13199
  ` : "";
12073
13200
  const toolsSection = await buildToolsSection(sub, packageRoot);
12074
13201
  const disciplinesSection = await buildDisciplinesSection(sub, packageRoot);
13202
+ const languageSection = await buildLanguageSection(packageRoot);
12075
13203
  const fullPrompt = `${taskSection}${body}
12076
- ${toolsSection}${disciplinesSection}${PROTOCOLS}${buildLanguageSection()}`;
13204
+ ${toolsSection}${disciplinesSection}${PROTOCOLS}${languageSection}`;
12077
13205
  if (raw.json) {
12078
13206
  const maxIterations = await resolveMaxIterations2(sub, packageRoot);
12079
13207
  const rp = rolePrompts[sub];
@@ -12372,6 +13500,7 @@ function extractMatchedTriggers(userText, overrides) {
12372
13500
 
12373
13501
  // src/cli/run.ts
12374
13502
  init_gateContext();
13503
+ init_probe_chrome_devtools();
12375
13504
  var PACKAGE_ROOT2 = getAssetsRoot();
12376
13505
  var WORKFLOWS_DIR2 = join(PACKAGE_ROOT2, "workflows");
12377
13506
  var _autoChainCache = null;
@@ -12381,7 +13510,7 @@ function registerRun(program2) {
12381
13510
  "Run a harnessed workflow via in-process SDK spawn (CI/headless mode \u2014 blocks, no Agent Teams, no clarification round-trip). Slash commands use CC-native spawn via gates/prompt/checkpoint instead."
12382
13511
  ).argument("[name]", "workflow name (e.g. discuss, verify-paranoid, research, auto)").option("--task <text>", "task description (passed as workflow gateContext.task)").option("--task-stdin", "read task description from stdin until EOF (avoids shell-escape)").option(
12383
13512
  "--max-iterations <n>",
12384
- "ralph-loop max iter (default 20; honored Phase 3 onward)",
13513
+ "SDK-path retry-loop max iter (default 20; honored Phase 3 onward)",
12385
13514
  (v) => parseInt(v, 10)
12386
13515
  ).option("--model <model>", "subagent model: 'haiku' | 'sonnet' | 'opus'").option(
12387
13516
  "--dry-run",
@@ -12429,6 +13558,12 @@ function registerRun(program2) {
12429
13558
  const stage = name.includes("-") ? name.split("-")[0] ?? "" : name;
12430
13559
  const gateContext = {
12431
13560
  ...buildDefaultGateContext(task, stage),
13561
+ // buildDefaultGateContext is synchronous and can only seed the fail-soft
13562
+ // "unknown = available" default for chrome_devtools_available. This is the
13563
+ // runtime path that actually evaluates the verify/qa phase-05 gate, so
13564
+ // overlay the MEASURED value (never throws; unknown still resolves true —
13565
+ // see src/cli/lib/probe-chrome-devtools.ts).
13566
+ chrome_devtools_available: await isChromeDevtoolsAvailable(),
12432
13567
  ...raw.model ? { modelOverride: raw.model } : {},
12433
13568
  ...raw.maxIterations ? { maxIterations: raw.maxIterations } : {},
12434
13569
  ...raw.staged ? { staged: true } : {},
@@ -12744,13 +13879,12 @@ function spawnLoopSteps(indent) {
12744
13879
  const i = indent;
12745
13880
  return [
12746
13881
  `${i}a. Bash: \`harnessed prompt <sub> --task "<spec>" --json\` \u2192 parse \`{prompt, max_iterations, model}\`.`,
12747
- `${i}b. Spawn a CC-native subagent (Task / Agent tool) with that \`prompt\` and \`model\`. Wrap in the ralph-loop plugin for completion-promise enforcement:`,
12748
- `${i} \`/ralph-loop "<prompt>" --max-iterations <max_iterations> --completion-promise "COMPLETE"\``,
12749
- // v4.15.0 (ADR 0036) — 3-tier preference chain: plugin → native /goal → self-loop.
12750
- `${i} If the ralph-loop plugin is not installed, use the native goal gate instead (Claude Code 2.1.139+ / Codex): \`/goal "this subtask is delivered: the subagent's final output contains verbatim <promise>COMPLETE</promise>; or stop after <max_iterations> turns"\` then spawn the subagent and let the goal evaluator drive re-spawns until it clears. Set the goal only at the leaf subtask level (\`/goal\` is single-slot per session).`,
12751
- `${i} If \`/goal\` is unavailable too, self-loop: spawn \u2192 check output for \`<promise>COMPLETE</promise>\` \u2192 if absent, re-spawn with the prior output appended (up to max_iterations).`,
13882
+ `${i}b. Spawn a CC-native subagent (Task / Agent tool) with that \`prompt\` and \`model\`, then drive delivery with harnessed's own completion gate:`,
13883
+ `${i} - on return, write the subagent's final output to a file and run \`harnessed checkpoint complete <sub> --result-file <path>\` \u2014 it is fail-closed on the declared artifacts, the TDD boundary, and the verbatim \`<promise>COMPLETE</promise>\`.`,
13884
+ `${i} - if it blocks, run \`harnessed checkpoint fail <sub> --failing-tests <n>\` to record the attempt; it prints BUDGET-EXHAUSTED / NO-PROGRESS / BREAK-LOOP when a stop condition is reached.`,
13885
+ `${i} - respawn ONLY while none of those three has fired. Any one of them means stop: re-scope the subtask, fix the blocker, or escalate to the user. Never respawn past a stop directive.`,
12752
13886
  `${i}c. If the subagent output contains \`STATUS: NEEDS_CLARIFICATION\` + a question list: STOP. Use AskUserQuestion to relay those exact questions to the user. Append the user's answers to the spec, then re-spawn the same sub. (This is the round-trip headless spawn cannot do.)`,
12753
- `${i}d. On \`<promise>COMPLETE</promise>\`: Bash \`harnessed checkpoint complete <sub> --summary "<one-line>"\`.`
13887
+ `${i}d. On \`<promise>COMPLETE</promise>\`: Bash \`harnessed checkpoint complete <sub> --result-file <path> --summary "<one-line>"\`.`
12754
13888
  ];
12755
13889
  }
12756
13890
  function buildInteractiveBody(name, prompt) {
@@ -12796,8 +13930,8 @@ function buildOrchestratorBody(name, prompt) {
12796
13930
  const leafIndent = " ";
12797
13931
  const leafSpawnLoop = [
12798
13932
  ...spawnLoopSteps(leafIndent).slice(0, 6),
12799
- `${leafIndent}d. On \`<promise>COMPLETE</promise>\`: Bash \`harnessed checkpoint complete <sub> --summary "<one-line>"\`. The evidence guard runs here (fail-CLOSED): if it exits non-zero because a declared \`artifacts_expected\` file is missing, the sub is NOT done \u2014 re-spawn to produce the artifact, or pass \`--force\` only to deliberately override (records \`evidence_status: overridden\`).`,
12800
- `${leafIndent}e. If the sub cannot reach COMPLETE (max_iterations exhausted, unrecoverable error): Bash \`harnessed checkpoint fail <sub> --summary "<why>"\` to flip the ledger entry to \`failed\`, then STOP and report to the user.`
13933
+ `${leafIndent}d. On \`<promise>COMPLETE</promise>\`: write the subagent's final output to a file, then Bash \`harnessed checkpoint complete <sub> --result-file <path> --summary "<one-line>"\`. The evidence guard runs here (fail-CLOSED) and blocks unless ALL hold: every declared \`artifacts_expected\` file exists, the TDD boundary passes (non-empty evidence / both the red and green sides present / the test file was not deleted), and the result carries a verbatim \`<promise>COMPLETE</promise>\` (or a structured COMPLETE status). \`--result <text>\` is the inline variant; \`--result-file\` wins and is quoting-safe on Windows. If it exits non-zero the sub is NOT done \u2014 re-spawn to fix the gap, or pass \`--force\` only to deliberately override (records \`evidence_status: overridden\` \u2014 an audited override, not a silent pass).`,
13934
+ `${leafIndent}e. If the complete gate blocked: Bash \`harnessed checkpoint fail <sub> --failing-tests <n>\` to record the attempt (omit the flag when the sub has no tests \u2014 the evidence-artifact digest is the fallback progress metric). It prints \`BUDGET-EXHAUSTED\` (attempts spent vs \`workflows/defaults.yaml ralph_max_iterations\`), \`NO-PROGRESS\` (no improvement for N consecutive attempts) or \`BREAK-LOOP\` (this sub failed >= the threshold) when a stop condition is reached. Respawn ONLY while none of those three has fired; any one of them means STOP \u2014 re-scope the subtask, fix the blocker, or escalate to the user, and report it. Never respawn past a stop directive.`
12801
13935
  ];
12802
13936
  return [
12803
13937
  `# /${name}`,
@@ -12822,11 +13956,26 @@ function buildOrchestratorBody(name, prompt) {
12822
13956
  `Drive this exact sequence (it is the state machine \u2014 follow the file, don't improvise from memory):`,
12823
13957
  ``,
12824
13958
  ...autoDiscussStep,
12825
- `2. Bash: \`harnessed gates ${name} --task "<locked spec>" --skip-sub discuss\` \u2192 parse the JSON \`{fire: [{sub, order, mode, is_master}], skip: [{sub, reason}], parallelism: {escalate_to_teams}}\`. This is the plan SoT (no spawn). Keep the verbatim JSON for the next step.${name === "auto" ? " For a small self-contained task (single-file / single-page class), the sanctioned lite path is adding `--skip-sub verify --skip-sub retro` (repeatable / comma-separated) \u2014 skipped subs are still recorded in the ledger with reasons; lite \u2260 freestyle (the ledger/evidence IS the difference)." : ""}`,
13959
+ // T2.1 — MUST stay in lockstep with `factsStepEn` in
13960
+ // scripts/rewrite-skill-invoke-sections.mjs (copied verbatim; the SKILL is
13961
+ // the sister rendering of this same sequence). Without this step the gates
13962
+ // below evaluate against generic defaults, which is the audit-S2 defect
13963
+ // itself: every judgement-call fact pinned to its firing side and no caller
13964
+ // ever passing context, i.e. criteria with zero discriminating power.
13965
+ `1b. Bash: \`harnessed facts ${name} --out .harnessed-facts.json\` \u2192 it lists ONLY the facts this stage\u2019s gates actually read: deterministic ones already filled (change size / files touched / stage, from git), judgement calls left \`null\` with a one-line hint of what to judge. Edit the file and replace each \`null\` in \`facts\` with your honest answer from the locked spec \u2014 leave one null only if you genuinely cannot judge it (it then falls back to the built-in default). Do NOT skip this step and do NOT invent facts the command did not ask for.`,
13966
+ `2. Bash: \`harnessed gates ${name} --task "<locked spec>" --context-file .harnessed-facts.json --skip-sub discuss\` \u2192 parse the JSON \`{fire: [{sub, order, mode, is_master}], skip: [{sub, reason}], parallelism: {escalate_to_teams}}\`. This is the plan SoT (no spawn). Keep the verbatim JSON for the next step.${name === "auto" ? " For a small self-contained task (single-file / single-page class), the sanctioned lite path is adding `--skip-sub verify --skip-sub retro` (repeatable / comma-separated) \u2014 skipped subs are still recorded in the ledger with reasons; lite \u2260 freestyle (the ledger/evidence IS the difference)." : ""}`,
12826
13967
  `3. Bash: \`harnessed checkpoint start ${name} --plan '<the verbatim gates JSON from step 2>'\` \u2192 seeds the sub-progress ledger in \`current-workflow.json\` (fired subs \u2192 \`pending\`, skipped subs \u2192 \`skipped\` + reason). This makes \`harnessed status --recover\` able to tell you where you are after compaction.`,
12827
- `4. If \`parallelism.escalate_to_teams === true\`: this stage needs multiple subagents to coordinate (SendMessage / shared contract). Read \`~/.claude/rules/agent-teams.md\`, then \`TeamCreate\` \u2192 \`Agent(name, team_name, ...)\` per fired sub (prompt from \`harnessed prompt <sub>\`) \u2192 coordinate via SendMessage \u2192 \`SendMessage shutdown_request\` + \`TeamDelete\`. Still checkpoint each sub (\`complete\` / \`fail\`) as below.`,
13968
+ // 4.34.0 — MUST stay in lockstep with the Agent Teams step 4 in
13969
+ // workflows/*/SKILL.md (see scripts/rewrite-skill-invoke-sections.mjs). CC
13970
+ // v2.1.178+ removed the two team lifecycle tools: the team forms implicitly on
13971
+ // the first background teammate spawn, `team_name` is accepted but ignored,
13972
+ // shutdown is a BY-NAME request rather than a tool call, and the team directory
13973
+ // is removed at session exit. Deliberately not naming the removed tools here —
13974
+ // tests/workflow/agentTeamsApiMigration.test.ts fails on those literals anywhere
13975
+ // in the live instruction surface, and this generator IS that surface.
13976
+ `4. If \`parallelism.escalate_to_teams === true\`: this stage needs multiple subagents to coordinate (SendMessage / shared contract). Read \`~/.claude/rules/agent-teams.md\`, then drive the fired subs as an Agent Team. There is NO create step and no create tool \u2014 spawn one background teammate per fired sub with \`Agent(name: <sub>, run_in_background: true, prompt: <that sub's \`harnessed prompt <sub>\` prompt>)\`; the team forms implicitly on the FIRST spawn with this session as lead (\`team_name\` is accepted but ignored \u2014 the name is session-derived). Coordinate via \`SendMessage\`; when a sub is finished, ask that teammate to shut down BY NAME (e.g. "ask the verify-qa teammate to shut down") \u2014 shutdown is a REQUEST, so re-ask rather than assume, and shut every teammate down before you finish (a teammate you never stopped keeps burning tokens and can hang the host). The team directory is removed automatically at session exit; there is no teardown tool. Still checkpoint each sub (\`complete\` / \`fail\`) as below.`,
12828
13977
  `5. Otherwise, for each fired sub in \`order\` (serial subs sequentially, parallel subs concurrently via parallel Task calls):`,
12829
- ` - **If the fired entry has \`is_master: true\`** (it is itself a stage master, e.g. \`/auto\` firing \`plan\`/\`task\`/\`verify\`): do NOT prompt+spawn it directly \u2014 that would yield a vague dispatcher. RECURSE: run that master's orchestration \u2014 \`harnessed gates <sub> --task "<spec>" --skip-sub discuss\` \u2192 \`harnessed checkpoint start <sub> --plan '<that JSON>'\` \u2192 repeat this whole loop for ITS fired subs. Only leaf subs (no \`is_master\`) reach the spawn loop below.`,
13978
+ ` - **If the fired entry has \`is_master: true\`** (it is itself a stage master, e.g. \`/auto\` firing \`plan\`/\`task\`/\`verify\`): do NOT prompt+spawn it directly \u2014 that would yield a vague dispatcher. RECURSE: run that master's orchestration \u2014 \`harnessed facts <sub> --out .harnessed-facts.json\` (fill the nulls) \u2192 \`harnessed gates <sub> --task "<spec>" --context-file .harnessed-facts.json --skip-sub discuss\` \u2192 \`harnessed checkpoint start <sub> --plan '<that JSON>'\` \u2192 repeat this whole loop for ITS fired subs. Only leaf subs (no \`is_master\`) reach the spawn loop below.`,
12830
13979
  ` - **Else (leaf sub)** \u2014 spawn it, then checkpoint the outcome:`,
12831
13980
  ...leafSpawnLoop,
12832
13981
  `6. After all fired subs are \`done\` (or recorded \`failed\`), Bash \`harnessed status --recover\` to confirm the ledger position (what's done, what's still pending, any evidence drift). Report a per-sub fired/skipped/done/failed summary to the user. ${name === "auto" ? "Then run the `retro` stage to capture lessons." : ""}`,
@@ -12916,7 +14065,7 @@ var V3_4_3_SIGNATURE_MASTER_RX = /\*\*Preferred path\*\*[\s\S]*dispatch to the p
12916
14065
  function shouldOverwriteFile(content) {
12917
14066
  return HARNESSED_MARKER_RX2.test(content) || V3_4_3_SIGNATURE_SUB_RX.test(content) || V3_4_3_SIGNATURE_MASTER_RX.test(content);
12918
14067
  }
12919
- async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync20 = (p7) => readFileSync(p7, "utf8")) {
14068
+ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync22 = (p7) => readFileSync(p7, "utf8")) {
12920
14069
  const results = [];
12921
14070
  const aggregatedWarnings = /* @__PURE__ */ new Set();
12922
14071
  for (const name of slashNames) {
@@ -12935,7 +14084,7 @@ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabiliti
12935
14084
  if (fileExists2(path)) {
12936
14085
  let existing = "";
12937
14086
  try {
12938
- existing = readFileSync20(path);
14087
+ existing = readFileSync22(path);
12939
14088
  } catch {
12940
14089
  existing = "";
12941
14090
  }
@@ -13185,8 +14334,8 @@ async function runStepBInstall(manifestPaths, runOpts = {}) {
13185
14334
  return emit({ status: "failed", name, reason: String(e) });
13186
14335
  }
13187
14336
  };
13188
- const mcp = valid.filter((v) => MCP_METHODS.has(v.manifest.spec.install.method));
13189
- const rest = valid.filter((v) => !MCP_METHODS.has(v.manifest.spec.install.method));
14337
+ const mcp = valid.filter((v) => MCP_METHODS.has(effectiveInstallMethod(v.manifest)));
14338
+ const rest = valid.filter((v) => !MCP_METHODS.has(effectiveInstallMethod(v.manifest)));
13190
14339
  const runMcpSerial = async () => {
13191
14340
  const out = [];
13192
14341
  for (const { manifest } of mcp) out.push(await runOne(manifest));
@@ -13404,6 +14553,24 @@ function printGrouped(b, prefix = "") {
13404
14553
  }
13405
14554
  }
13406
14555
  }
14556
+ function makeProgressPrinter(out = process.stdout) {
14557
+ if (out.isTTY !== true) return { onProgress: () => {
14558
+ }, done: () => {
14559
+ } };
14560
+ let width = 0;
14561
+ return {
14562
+ onProgress(ev) {
14563
+ const line = ` [${ev.done}/${ev.total}] ${ev.status} ${ev.name}`;
14564
+ width = Math.max(width, line.length);
14565
+ out.write(`\r${line.padEnd(width)}`);
14566
+ },
14567
+ done() {
14568
+ if (width === 0) return;
14569
+ out.write(`\r${" ".repeat(width)}\r`);
14570
+ width = 0;
14571
+ }
14572
+ };
14573
+ }
13407
14574
  function registerSetup(program2) {
13408
14575
  program2.command("setup").description(
13409
14576
  "One-shot onboarding: install workflow skills + base manifests to ~/.claude/ (immediate by default \u2014 use --dry-run for preview)"
@@ -13444,9 +14611,7 @@ function registerSetup(program2) {
13444
14611
  }
13445
14612
  const manifestPaths = await listBaseManifests2(pkgRoot);
13446
14613
  const forceFirstPass = raw.updateInstalled === true;
13447
- const progressPrinter = (ev) => {
13448
- console.log(` [${ev.done}/${ev.total}] ${ev.status} ${ev.name}`);
13449
- };
14614
+ const progress = makeProgressPrinter();
13450
14615
  console.log(
13451
14616
  `
13452
14617
  installing ${manifestPaths.length} upstream components (MCP serialized, rest parallel)...`
@@ -13454,8 +14619,9 @@ installing ${manifestPaths.length} upstream components (MCP serialized, rest par
13454
14619
  const b = await runStepBInstall(manifestPaths, {
13455
14620
  updateInstalled: forceFirstPass,
13456
14621
  quiet: true,
13457
- onProgress: progressPrinter
14622
+ onProgress: progress.onProgress
13458
14623
  });
14624
+ progress.done();
13459
14625
  const stepBMs = (b.elapsedMs / 1e3).toFixed(1);
13460
14626
  console.log(
13461
14627
  t("setup.step_b_complete", {
@@ -13483,8 +14649,9 @@ force-updating ${b.alreadyInstalled.length} plugin(s)...`);
13483
14649
  const b2 = await runStepBInstall(manifestPaths, {
13484
14650
  updateInstalled: true,
13485
14651
  quiet: true,
13486
- onProgress: progressPrinter
14652
+ onProgress: progress.onProgress
13487
14653
  });
14654
+ progress.done();
13488
14655
  const probe = await makeIdempotentProbe(manifestPaths);
13489
14656
  const reclass = await reclassifyForceUpdateFailures(b, b2, probe);
13490
14657
  b2.failed = reclass.failed;
@@ -14030,7 +15197,7 @@ var uninstallNpmCli = async (ctx) => {
14030
15197
  const m = install.cmd.match(/npm\s+(?:install|i)\s+(?:-g\s+)?(\S+)/);
14031
15198
  const pkg = m?.[1] ?? ctx.manifest.metadata.upstream.source;
14032
15199
  const isWin = process.platform === "win32";
14033
- const result = await new Promise((resolve21) => {
15200
+ const result = await new Promise((resolve24) => {
14034
15201
  const child = isWin ? spawn("cmd.exe", ["/c", "npm", "uninstall", "-g", pkg], { windowsHide: true }) : spawn("npm", ["uninstall", "-g", pkg], { shell: false });
14035
15202
  let stderr = "";
14036
15203
  child.stderr?.setEncoding("utf8").on("data", (c) => {
@@ -14038,15 +15205,15 @@ var uninstallNpmCli = async (ctx) => {
14038
15205
  });
14039
15206
  const timer = setTimeout(() => {
14040
15207
  child.kill("SIGKILL");
14041
- resolve21({ exitCode: -1, stderr: `${stderr}[timeout]` });
15208
+ resolve24({ exitCode: -1, stderr: `${stderr}[timeout]` });
14042
15209
  }, 3e4);
14043
15210
  child.on("error", (e) => {
14044
15211
  clearTimeout(timer);
14045
- resolve21({ exitCode: -1, stderr: e.message });
15212
+ resolve24({ exitCode: -1, stderr: e.message });
14046
15213
  });
14047
15214
  child.on("close", (code) => {
14048
15215
  clearTimeout(timer);
14049
- resolve21({ exitCode: code ?? -1, stderr });
15216
+ resolve24({ exitCode: code ?? -1, stderr });
14050
15217
  });
14051
15218
  });
14052
15219
  if (result.exitCode !== 0) {
@@ -14614,6 +15781,8 @@ registerRetro(program);
14614
15781
  registerInjectState(program);
14615
15782
  registerStopHook(program);
14616
15783
  registerEval(program);
15784
+ registerCheckDocs(program);
15785
+ registerFacts(program);
14617
15786
  var bare = parseBareInvocation(process.argv.slice(2));
14618
15787
  if (bare.here) {
14619
15788
  void runHere({ json: bare.json });