harnessed 4.32.22 → 4.36.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 +1201 -235
  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 +94 -39
  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 +19 -7
  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 +7 -3
  70. package/workflows/task/test/SKILL.zh-Hans.md +7 -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 +33 -14
  90. package/workflows/verify/qa/SKILL.zh-Hans.md +33 -14
  91. package/workflows/verify/qa/workflow.yaml +55 -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
@@ -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.36.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(spawn6, maxIter) {
3129
+ let last = "";
3130
+ let sessionId;
3131
+ for (let i = 0; i < maxIter; i++) {
3132
+ last = await spawn6(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, {
@@ -3175,6 +3451,99 @@ var init_retroMeta = __esm({
3175
3451
  }
3176
3452
  });
3177
3453
 
3454
+ // src/checkpoint/progress.ts
3455
+ var progress_exports = {};
3456
+ __export(progress_exports, {
3457
+ PLATEAU_THRESHOLD: () => PLATEAU_THRESHOLD,
3458
+ evidenceDigest: () => evidenceDigest,
3459
+ isPlateaued: () => isPlateaued,
3460
+ sampleProgress: () => sampleProgress
3461
+ });
3462
+ function evidenceDigest(refs) {
3463
+ if (refs.length === 0) return "";
3464
+ return refs.map((r) => r.sha256.slice(0, 12)).sort().join(",");
3465
+ }
3466
+ function sampleProgress(prev, sample) {
3467
+ const count = sample.failing_tests;
3468
+ if (usableCount(count)) {
3469
+ const before = prev?.metric === "failing_tests" ? prev.failing_tests : void 0;
3470
+ const stalled = usableCount(before) && count >= before;
3471
+ return {
3472
+ metric: "failing_tests",
3473
+ failing_tests: count,
3474
+ stale_count: stalled ? (prev?.stale_count ?? 0) + 1 : 0
3475
+ };
3476
+ }
3477
+ const digest = sample.evidence_digest;
3478
+ if (typeof digest === "string" && digest !== "") {
3479
+ const before = prev?.metric === "evidence_digest" ? prev.evidence_digest : void 0;
3480
+ const stalled = !!before && digest === before;
3481
+ return {
3482
+ metric: "evidence_digest",
3483
+ evidence_digest: digest,
3484
+ stale_count: stalled ? (prev?.stale_count ?? 0) + 1 : 0
3485
+ };
3486
+ }
3487
+ return null;
3488
+ }
3489
+ function isPlateaued(mark) {
3490
+ return (mark?.stale_count ?? 0) >= PLATEAU_THRESHOLD;
3491
+ }
3492
+ var PLATEAU_THRESHOLD, usableCount;
3493
+ var init_progress = __esm({
3494
+ "src/checkpoint/progress.ts"() {
3495
+ PLATEAU_THRESHOLD = 2;
3496
+ usableCount = (n) => typeof n === "number" && Number.isInteger(n) && n >= 0;
3497
+ }
3498
+ });
3499
+
3500
+ // src/checkpoint/budget.ts
3501
+ var budget_exports = {};
3502
+ __export(budget_exports, {
3503
+ DEFAULT_ATTEMPT_BUDGET: () => DEFAULT_ATTEMPT_BUDGET,
3504
+ FALLBACK_HARD_UPPER_LIMIT: () => FALLBACK_HARD_UPPER_LIMIT,
3505
+ isBudgetExhausted: () => isBudgetExhausted,
3506
+ resolveAttemptBudget: () => resolveAttemptBudget
3507
+ });
3508
+ function entryValues(entry) {
3509
+ if (typeof entry === "number" && Number.isFinite(entry)) return [entry];
3510
+ if (entry && typeof entry === "object") {
3511
+ return Object.values(entry).filter(
3512
+ (v) => typeof v === "number" && Number.isFinite(v)
3513
+ );
3514
+ }
3515
+ return [];
3516
+ }
3517
+ function tableValues(table, sub) {
3518
+ const exact = entryValues(table[sub]);
3519
+ if (exact.length > 0) return exact;
3520
+ const suffix = `-${sub}`;
3521
+ return Object.keys(table).filter((k) => k.endsWith(suffix)).flatMap((k) => entryValues(table[k]));
3522
+ }
3523
+ async function resolveAttemptBudget(sub, packageRoot) {
3524
+ try {
3525
+ const doc = parse(
3526
+ await readFile(resolve(packageRoot, "workflows", "defaults.yaml"), "utf8")
3527
+ );
3528
+ const cap = typeof doc?.hard_upper_limit === "number" && Number.isFinite(doc.hard_upper_limit) ? doc.hard_upper_limit : FALLBACK_HARD_UPPER_LIMIT;
3529
+ const values = tableValues(doc?.ralph_max_iterations ?? {}, sub);
3530
+ if (values.length > 0) return Math.min(Math.max(...values), cap);
3531
+ return DEFAULT_ATTEMPT_BUDGET;
3532
+ } catch {
3533
+ return DEFAULT_ATTEMPT_BUDGET;
3534
+ }
3535
+ }
3536
+ function isBudgetExhausted(attempts, budget) {
3537
+ return attempts >= budget;
3538
+ }
3539
+ var DEFAULT_ATTEMPT_BUDGET, FALLBACK_HARD_UPPER_LIMIT;
3540
+ var init_budget = __esm({
3541
+ "src/checkpoint/budget.ts"() {
3542
+ DEFAULT_ATTEMPT_BUDGET = 20;
3543
+ FALLBACK_HARD_UPPER_LIMIT = 100;
3544
+ }
3545
+ });
3546
+
3178
3547
  // src/checkpoint/breakLoop.ts
3179
3548
  var breakLoop_exports = {};
3180
3549
  __export(breakLoop_exports, {
@@ -3259,14 +3628,13 @@ async function absorbIntentFor(sub) {
3259
3628
  } catch {
3260
3629
  }
3261
3630
  }
3262
- async function serialOrderBlockers(sub, deps = defaultRunDeps) {
3631
+ async function readLedgerSafe(deps = defaultRunDeps) {
3263
3632
  try {
3264
3633
  const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
3265
- const { findSerialBlockers: findSerialBlockers2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
3266
3634
  const wf = await readCurrentWorkflow2();
3267
- return findSerialBlockers2(wf?.sub_progress ?? [], sub);
3635
+ return wf?.sub_progress ?? [];
3268
3636
  } catch (e) {
3269
- deps.warn(`[harnessed] serial-order guard skipped (fail-soft): ${e.message}`);
3637
+ deps.warn(`[harnessed] ledger read skipped (fail-soft): ${e.message}`);
3270
3638
  return [];
3271
3639
  }
3272
3640
  }
@@ -3362,7 +3730,8 @@ async function runCheckpointStart(sub, opts, deps = defaultRunDeps) {
3362
3730
  }
3363
3731
  async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
3364
3732
  const { completePhase: completePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
3365
- if (!enforceSerialOrder("complete", sub, await serialOrderBlockers(sub, deps), opts.force, deps)) {
3733
+ const preLedger = await readLedgerSafe(deps);
3734
+ if (!enforceSerialOrder("complete", sub, findSerialBlockers(preLedger, sub), opts.force, deps)) {
3366
3735
  deps.exit(1);
3367
3736
  return;
3368
3737
  }
@@ -3372,7 +3741,32 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
3372
3741
  const result = await checkArtifacts2(sub, getAssetsRoot2());
3373
3742
  const { checkPlanningSync: checkPlanningSync2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
3374
3743
  const syncResult = await checkPlanningSync2(process.cwd(), null);
3375
- const allMissing = [...result.missing, ...syncResult.missing];
3744
+ const boundaryBlocks = [];
3745
+ try {
3746
+ const { checkTddBoundary: checkTddBoundary2, isTddEvidencePath: isTddEvidencePath2 } = await Promise.resolve().then(() => (init_tddBoundary(), tddBoundary_exports));
3747
+ const evidenceArtifact = result.found.find((f) => isTddEvidencePath2(f.path));
3748
+ if (evidenceArtifact) {
3749
+ for (const f of await checkTddBoundary2(process.cwd(), evidenceArtifact.path)) {
3750
+ if (f.kind === "block") boundaryBlocks.push(`boundary(${f.id}): ${f.message}`);
3751
+ else deps.warn(`\u26A0\uFE0F [harnessed] boundary warning (${f.id}): ${f.message}`);
3752
+ }
3753
+ }
3754
+ } catch {
3755
+ }
3756
+ const { verifyCompletionClaim: verifyCompletionClaim2 } = await Promise.resolve().then(() => (init_completionClaim(), completionClaim_exports));
3757
+ const claim = await verifyCompletionClaim2({
3758
+ ...opts.result !== void 0 ? { result: opts.result } : {},
3759
+ ...opts.resultFile !== void 0 ? { resultFile: opts.resultFile } : {}
3760
+ });
3761
+ const claimBlocks = claim.verdict === "incomplete" ? [
3762
+ `completion promise not met (${claim.source}): the subagent output carries no verbatim <promise>COMPLETE</promise> and no structured COMPLETE status on a successful run`
3763
+ ] : [];
3764
+ if (claim.verdict === "not_provided") {
3765
+ deps.warn(
3766
+ `\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).`
3767
+ );
3768
+ }
3769
+ const allMissing = [...result.missing, ...syncResult.missing, ...boundaryBlocks, ...claimBlocks];
3376
3770
  if (allMissing.length > 0 && !opts.force) {
3377
3771
  deps.error(
3378
3772
  `[harnessed] checkpoint complete BLOCKED: ${sub} \u2014 ${allMissing.length} item(s) missing (evidence guard + .planning/ sync, fail-closed):`
@@ -3386,7 +3780,11 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
3386
3780
  if (allMissing.length > 0 && opts.force) evidenceStatus = "overridden";
3387
3781
  else if (result.status === "verified") evidenceStatus = "verified";
3388
3782
  else evidenceStatus = "none_declared";
3389
- const markOpts = evidenceStatus === "none_declared" ? { evidence_status: evidenceStatus } : { evidence: result.found, evidence_status: evidenceStatus };
3783
+ const markOpts = evidenceStatus === "none_declared" ? { evidence_status: evidenceStatus, completion_claim: claim.verdict } : {
3784
+ evidence: result.found,
3785
+ evidence_status: evidenceStatus,
3786
+ completion_claim: claim.verdict
3787
+ };
3390
3788
  await mutateSubProgress2((e) => markIfSeeded(e, sub, "done", markOpts));
3391
3789
  await absorbIntentFor(sub);
3392
3790
  const { collectScaleMetrics: collectScaleMetrics2, assessScale: assessScale2 } = await Promise.resolve().then(() => (init_scale(), scale_exports));
@@ -3455,12 +3853,35 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
3455
3853
  }
3456
3854
  async function runCheckpointFail(sub, opts, deps = defaultRunDeps) {
3457
3855
  const { completePhase: completePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
3458
- if (!enforceSerialOrder("fail", sub, await serialOrderBlockers(sub, deps), opts.force, deps)) {
3856
+ const preLedger = await readLedgerSafe(deps);
3857
+ if (!enforceSerialOrder("fail", sub, findSerialBlockers(preLedger, sub), opts.force, deps)) {
3459
3858
  deps.exit(1);
3460
3859
  return;
3461
3860
  }
3861
+ const { sampleProgress: sampleProgress2, isPlateaued: isPlateaued2, evidenceDigest: evidenceDigest2, PLATEAU_THRESHOLD: PLATEAU_THRESHOLD2 } = await Promise.resolve().then(() => (init_progress(), progress_exports));
3862
+ const { getAssetsRoot: getAssetsRoot2 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
3863
+ const assetsRoot = getAssetsRoot2();
3864
+ const failingTests = opts.failingTests !== void 0 ? Number(opts.failingTests) : void 0;
3865
+ let digest = "";
3866
+ try {
3867
+ const { checkArtifacts: checkArtifacts2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
3868
+ digest = evidenceDigest2((await checkArtifacts2(sub, assetsRoot)).found);
3869
+ } catch {
3870
+ }
3871
+ const prev = preLedger.find((e) => e.sub === sub)?.progress;
3872
+ const nextProgress = sampleProgress2(prev, {
3873
+ ...failingTests !== void 0 && Number.isFinite(failingTests) ? { failing_tests: failingTests } : {},
3874
+ evidence_digest: digest
3875
+ });
3876
+ const { resolveAttemptBudget: resolveAttemptBudget2, isBudgetExhausted: isBudgetExhausted2 } = await Promise.resolve().then(() => (init_budget(), budget_exports));
3877
+ const budget = await resolveAttemptBudget2(sub, assetsRoot);
3462
3878
  const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
3463
- await mutateSubProgress2((e) => markIfSeeded(e, sub, "failed"));
3879
+ await mutateSubProgress2(
3880
+ (e) => markIfSeeded(e, sub, "failed", {
3881
+ attempt_budget: budget,
3882
+ ...nextProgress ? { progress: nextProgress } : {}
3883
+ })
3884
+ );
3464
3885
  await absorbIntentFor(sub);
3465
3886
  await completePhase2({
3466
3887
  phaseId: sub,
@@ -3478,6 +3899,17 @@ async function runCheckpointFail(sub, opts, deps = defaultRunDeps) {
3478
3899
  `[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
3900
  );
3480
3901
  }
3902
+ const attempts = latest?.sub_progress?.find((e) => e.sub === sub)?.fail_count ?? 0;
3903
+ if (isBudgetExhausted2(attempts, budget)) {
3904
+ deps.error(
3905
+ `[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.`
3906
+ );
3907
+ }
3908
+ if (isPlateaued2(nextProgress)) {
3909
+ deps.error(
3910
+ `[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.`
3911
+ );
3912
+ }
3481
3913
  deps.error(
3482
3914
  `[harnessed] checkpoint FAILED recorded: ${sub}${opts.summary ? ` \u2014 ${opts.summary}` : ""}`
3483
3915
  );
@@ -3493,6 +3925,15 @@ function registerCheckpoint(program2) {
3493
3925
  ).option(
3494
3926
  "--tokens <n>",
3495
3927
  "complete only \u2014 conversation token count; auto-compacts the ledger when >= the shouldCompact threshold (Phase 14)"
3928
+ ).option(
3929
+ "--result <text>",
3930
+ "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"
3931
+ ).option(
3932
+ "--result-file <path>",
3933
+ "complete only \u2014 same as --result but read from a file (quoting-safe on Windows); wins over --result"
3934
+ ).option(
3935
+ "--failing-tests <n>",
3936
+ "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
3937
  ).action(
3497
3938
  async (action, sub, opts) => {
3498
3939
  if (!isAction(action)) {
@@ -3613,7 +4054,7 @@ function compute(d) {
3613
4054
  const gitFirst = d.where("git")[0];
3614
4055
  if (gitFirst && /git\.exe$/i.test(gitFirst)) {
3615
4056
  const root = dirname8(dirname8(gitFirst));
3616
- for (const cand of [join18(root, "bin", "bash.exe"), join18(root, "usr", "bin", "bash.exe")]) {
4057
+ for (const cand of [join19(root, "bin", "bash.exe"), join19(root, "usr", "bin", "bash.exe")]) {
3617
4058
  if (d.exists(cand) && usable(cand)) return { path: cand, source: "git-derived", wslOnPath };
3618
4059
  }
3619
4060
  }
@@ -3621,13 +4062,13 @@ function compute(d) {
3621
4062
  d.env.ProgramFiles,
3622
4063
  d.env.ProgramW6432,
3623
4064
  d.env["ProgramFiles(x86)"],
3624
- d.env.LOCALAPPDATA ? join18(d.env.LOCALAPPDATA, "Programs") : void 0
4065
+ d.env.LOCALAPPDATA ? join19(d.env.LOCALAPPDATA, "Programs") : void 0
3625
4066
  ];
3626
4067
  for (const base of bases) {
3627
4068
  if (!base) continue;
3628
4069
  for (const cand of [
3629
- join18(base, "Git", "bin", "bash.exe"),
3630
- join18(base, "Git", "usr", "bin", "bash.exe")
4070
+ join19(base, "Git", "bin", "bash.exe"),
4071
+ join19(base, "Git", "usr", "bin", "bash.exe")
3631
4072
  ]) {
3632
4073
  if (d.exists(cand) && usable(cand))
3633
4074
  return { path: cand, source: "standard-location", wslOnPath };
@@ -3640,10 +4081,10 @@ function compute(d) {
3640
4081
  }
3641
4082
  return { path: "bash", source: "path-fallback" };
3642
4083
  }
3643
- var dirname8, join18, WSL_STUB_RE, cache2;
4084
+ var dirname8, join19, WSL_STUB_RE, cache2;
3644
4085
  var init_resolveBash = __esm({
3645
4086
  "src/installers/lib/resolveBash.ts"() {
3646
- ({ dirname: dirname8, join: join18 } = win32);
4087
+ ({ dirname: dirname8, join: join19 } = win32);
3647
4088
  WSL_STUB_RE = /[\\/](windows[\\/](system32|sysnative|syswow64)|microsoft[\\/]windowsapps)[\\/]bash\.exe$/i;
3648
4089
  cache2 = null;
3649
4090
  }
@@ -3741,7 +4182,7 @@ function checkJq() {
3741
4182
  return {
3742
4183
  name: "jq present",
3743
4184
  status: "warn",
3744
- message: "jq not found in PATH (optional \u2014 needed by `harnessed audit-log --filter` and the ralph-loop plugin on Windows)",
4185
+ message: "jq not found in PATH (optional \u2014 needed by `harnessed audit-log --filter`)",
3745
4186
  fix,
3746
4187
  install_commands: [installCmd]
3747
4188
  };
@@ -3774,7 +4215,7 @@ function checkWinBash() {
3774
4215
  return {
3775
4216
  name: "bash flavor (win)",
3776
4217
  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`,
4218
+ 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
4219
  fix: "reorder PATH so Git Bash precedes WSL bash.exe (Settings \u2192 System \u2192 Environment Variables)"
3779
4220
  };
3780
4221
  }
@@ -4948,14 +5389,38 @@ function stripQuotes(token) {
4948
5389
  if (m?.[1] !== void 0) return { bare: m[1], quoted: true };
4949
5390
  return { bare: token, quoted: false };
4950
5391
  }
5392
+ function splitTokens(raw) {
5393
+ return raw.split(/\s+/).filter((t2) => t2.length > 0);
5394
+ }
5395
+ function hookMarkerAt(raw) {
5396
+ const tokens = splitTokens(raw);
5397
+ for (const [i, token] of tokens.entries()) {
5398
+ const { bare: bare2 } = stripQuotes(token);
5399
+ if (!isRelativeFileToken(bare2)) continue;
5400
+ const seg = bare2.split(/[\\/]/);
5401
+ const base = seg[seg.length - 1];
5402
+ if (base === void 0) return null;
5403
+ const id = COMPILED_HOOK_IDENTITIES.find((k) => base.includes(k));
5404
+ return { marker: id ?? base, index: i };
5405
+ }
5406
+ for (const [i, token] of tokens.entries()) {
5407
+ const { bare: bare2 } = stripQuotes(token);
5408
+ if (COMPILED_HOOK_IDENTITIES.includes(bare2))
5409
+ return { marker: bare2, index: i };
5410
+ }
5411
+ return null;
5412
+ }
4951
5413
  function resolveHookCommand(raw, deps) {
4952
- const marker = deps.compiledExecPath ? hookScriptMarker(raw) : null;
4953
- if (deps.compiledExecPath && marker && COMPILED_HOOK_IDENTITIES.includes(marker)) {
5414
+ const at = deps.compiledExecPath ? hookMarkerAt(raw) : null;
5415
+ if (deps.compiledExecPath && at && COMPILED_HOOK_IDENTITIES.includes(at.marker)) {
4954
5416
  const exe = deps.compiledExecPath();
4955
- if (exe) return `"${exe.replace(/\\/g, "/")}" ${marker}`;
5417
+ if (exe) {
5418
+ const tail = splitTokens(raw).slice(at.index + 1);
5419
+ return [`"${exe.replace(/\\/g, "/")}"`, at.marker, ...tail].join(" ");
5420
+ }
4956
5421
  }
4957
5422
  let root = null;
4958
- const tokens = raw.split(/\s+/).filter((t2) => t2.length > 0);
5423
+ const tokens = splitTokens(raw);
4959
5424
  const out = tokens.map((token) => {
4960
5425
  const { bare: bare2 } = stripQuotes(token);
4961
5426
  if (!isRelativeFileToken(bare2)) return token;
@@ -4967,21 +5432,8 @@ function resolveHookCommand(raw, deps) {
4967
5432
  return out.join(" ");
4968
5433
  }
4969
5434
  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;
5435
+ const at = hookMarkerAt(raw);
5436
+ return at === null ? null : at.marker;
4985
5437
  }
4986
5438
  function entryCommands(entry) {
4987
5439
  if (!entry || typeof entry !== "object") return [];
@@ -5031,7 +5483,7 @@ function detectCcHookInstalled(settingsRaw, ev, raw, matcher, deps) {
5031
5483
  var COMPILED_HOOK_IDENTITIES, ABSOLUTE_RE;
5032
5484
  var init_hookEntry = __esm({
5033
5485
  "src/installers/lib/hookEntry.ts"() {
5034
- COMPILED_HOOK_IDENTITIES = ["inject-state", "stop-hook"];
5486
+ COMPILED_HOOK_IDENTITIES = ["inject-state", "stop-hook", "check-docs"];
5035
5487
  ABSOLUTE_RE = /^([A-Za-z]:[\\/]|[\\/])/;
5036
5488
  }
5037
5489
  });
@@ -5415,6 +5867,7 @@ var judgmentResolver_exports = {};
5415
5867
  __export(judgmentResolver_exports, {
5416
5868
  TriggerNotFoundError: () => TriggerNotFoundError,
5417
5869
  _clearJudgmentCache: () => _clearJudgmentCache,
5870
+ resolveJudgmentExpression: () => resolveJudgmentExpression,
5418
5871
  resolveJudgmentGate: () => resolveJudgmentGate
5419
5872
  });
5420
5873
  async function resolveJudgmentGate(gateRef, context, packageRoot) {
@@ -5422,6 +5875,9 @@ async function resolveJudgmentGate(gateRef, context, packageRoot) {
5422
5875
  if (Array.isArray(userOverrides) && userOverrides.includes(gateRef)) {
5423
5876
  return true;
5424
5877
  }
5878
+ return evalGate(await resolveJudgmentExpression(gateRef, packageRoot), context);
5879
+ }
5880
+ async function resolveJudgmentExpression(gateRef, packageRoot) {
5425
5881
  const parts = gateRef.split(".");
5426
5882
  if (parts.length !== 4 || parts[0] !== "judgments") {
5427
5883
  throw new Error(`Invalid gate ref: ${gateRef}`);
@@ -5451,7 +5907,7 @@ async function resolveJudgmentGate(gateRef, context, packageRoot) {
5451
5907
  `Field '${fieldName}' has no expression in trigger '${triggerName}' of ${fileName}.yaml`
5452
5908
  );
5453
5909
  }
5454
- return evalGate(expr, context);
5910
+ return expr;
5455
5911
  }
5456
5912
  function _clearJudgmentCache() {
5457
5913
  _fileCache.clear();
@@ -5475,13 +5931,32 @@ var init_judgmentResolver = __esm({
5475
5931
  }
5476
5932
  });
5477
5933
 
5934
+ // src/workflow/skipGate.ts
5935
+ async function resolveSkipVeto(skipGateRef, context, packageRoot) {
5936
+ if (!skipGateRef) return null;
5937
+ try {
5938
+ const expr = await resolveJudgmentExpression(skipGateRef, packageRoot);
5939
+ if (!evalGate(expr, context)) return null;
5940
+ return `skip_gate ${skipGateRef} = true (skip condition met \u2014 sub vetoed despite its gate firing)`;
5941
+ } catch {
5942
+ return null;
5943
+ }
5944
+ }
5945
+ var init_skipGate = __esm({
5946
+ "src/workflow/skipGate.ts"() {
5947
+ init_exprBuilder();
5948
+ init_judgmentResolver();
5949
+ }
5950
+ });
5951
+
5478
5952
  // src/workflow/skipSubs.ts
5479
5953
  function matchSkipSub(requested, sub, master) {
5480
5954
  if (requested.has(sub)) return sub;
5481
5955
  const alias = `${master}-${sub}`;
5482
5956
  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;
5957
+ for (const [a, b] of Object.entries(SKIP_SYNONYMS)) {
5958
+ if (b === sub && requested.has(a)) return a;
5959
+ if (a === sub && requested.has(b)) return b;
5485
5960
  }
5486
5961
  return null;
5487
5962
  }
@@ -5529,14 +6004,27 @@ function buildDefaultGateContext(task, stage) {
5529
6004
  is_critical_release: false,
5530
6005
  phase: {
5531
6006
  stage,
5532
- is_critical_module: true,
6007
+ // T2.1 OQ2(c) — withdrawn: gated stage-routing.verify-paranoid-critical,
6008
+ // which meant the paranoid staff-engineer review fired on EVERY verify.
6009
+ is_critical_module: false,
5533
6010
  is_final_step: true,
5534
6011
  is_major_release: false,
5535
6012
  has_auth_or_secrets: false,
5536
6013
  has_design_changes: false,
5537
6014
  has_ui_changes: false,
6015
+ // T2.1 gap-close — stage-routing verify-eval-review-aiphase /
6016
+ // verify-validate-phase-coverage read these; neither was declared here nor
6017
+ // in PhaseShape, so the member was absent and both gates evaluated to a
6018
+ // silent false forever. Default FALSE (the non-firing side) on purpose:
6019
+ // both subs are expensive retroactive audits that should be requested by a
6020
+ // filled fact, not defaulted on. `harnessed facts verify` lists them as
6021
+ // nulls with hints so the model supplies the real answer.
6022
+ has_ai_phase: false,
6023
+ requires_coverage_audit: false,
5538
6024
  requires_creative_polish: false,
5539
- is_complex_architecture: true,
6025
+ // T2.1 OQ2(c) — withdrawn: gated stage-routing.plan-architecture-delegate,
6026
+ // which meant /plan always spawned the eng-review architecture sub.
6027
+ is_complex_architecture: false,
5540
6028
  has_cross_phase_data_flow: true,
5541
6029
  open_decisions: 2,
5542
6030
  scope_days: 2,
@@ -5546,9 +6034,11 @@ function buildDefaultGateContext(task, stage) {
5546
6034
  },
5547
6035
  subtask: {
5548
6036
  approaches: 2,
5549
- core_algorithm: true,
6037
+ // T2.1 OQ2(c) — withdrawn (both are subtask-gate.brainstorming OR-arms;
6038
+ // `approaches: 2` / `has_api_contract: true` stay as the safety net).
6039
+ core_algorithm: false,
5550
6040
  has_api_contract: true,
5551
- error_cost: "high",
6041
+ error_cost: "low",
5552
6042
  lines: 50,
5553
6043
  type: "general",
5554
6044
  is_core_business_logic: true,
@@ -5558,9 +6048,23 @@ function buildDefaultGateContext(task, stage) {
5558
6048
  reliability_required: true,
5559
6049
  communication_needed: false,
5560
6050
  needs_lib_docs: false,
5561
- needs_web_search: false,
6051
+ // T2.3 — web-search-routing.yaml declares Tavily/keyword THE default route,
6052
+ // and workflows/research/workflow.yaml now gates its 5 source lanes on those
6053
+ // triggers. Leaving needs_web_search=false + search_type='general' (not even
6054
+ // a member of the SearchType union in schema/phaseFactContext.ts) would make
6055
+ // every lane evaluate false → the research workflow would degrade to zero
6056
+ // sources, a regression vs the previously-unconditional fan-out step. The
6057
+ // non-default lanes (descriptive/academic → exa, site-crawl, lib-docs →
6058
+ // ctx7, single-url → WebFetch) stay opt-in via --context.
6059
+ needs_web_search: true,
6060
+ search_type: "keyword",
6061
+ // T2.3 — `browse` capability + web-testing-routing browse-probe fact. Default
6062
+ // FALSE (opt-in): it is an OR-arm of the browser-probe route, and defaulting
6063
+ // it true would route a browser lane on every eval — the same "most expensive
6064
+ // sub became the default path" defect 4.23.2 fixed. Reachable via --context
6065
+ // or a facts-extraction chain.
6066
+ needs_browser_automation: false,
5562
6067
  parallel_count: 1,
5563
- search_type: "general",
5564
6068
  test_type: "general"
5565
6069
  }
5566
6070
  };
@@ -5568,8 +6072,12 @@ function buildDefaultGateContext(task, stage) {
5568
6072
  function mergeGateContext(base, extra) {
5569
6073
  const merged = { ...base };
5570
6074
  for (const [k, v] of Object.entries(extra)) {
6075
+ if (v === null) continue;
5571
6076
  if ((k === "phase" || k === "subtask") && v && typeof v === "object" && !Array.isArray(v)) {
5572
- merged[k] = { ...base[k], ...v };
6077
+ const overrides = Object.fromEntries(
6078
+ Object.entries(v).filter(([, val]) => val !== null)
6079
+ );
6080
+ merged[k] = { ...base[k], ...overrides };
5573
6081
  } else {
5574
6082
  merged[k] = v;
5575
6083
  }
@@ -5584,7 +6092,9 @@ var init_gateContext = __esm({
5584
6092
  // src/cli/gates.ts
5585
6093
  var gates_exports = {};
5586
6094
  __export(gates_exports, {
6095
+ GATE_MASTERS: () => GATE_MASTERS,
5587
6096
  registerGates: () => registerGates,
6097
+ resolveMasterYamlPath: () => resolveMasterYamlPath,
5588
6098
  runGatesPlan: () => runGatesPlan
5589
6099
  });
5590
6100
  function resolveMasterYamlPath(master, packageRoot) {
@@ -5635,6 +6145,28 @@ async function runGatesPlan(master, raw, deps = defaultRunDeps) {
5635
6145
  const task = typeof raw.task === "string" ? raw.task : "";
5636
6146
  const stage = master;
5637
6147
  let ctx = buildDefaultGateContext(task, stage);
6148
+ if (typeof raw.contextFile === "string" && raw.contextFile.length > 0) {
6149
+ let rawJson;
6150
+ try {
6151
+ rawJson = await readFile(raw.contextFile, "utf8");
6152
+ } catch (err2) {
6153
+ deps.error(
6154
+ `error: failed to read --context-file at ${raw.contextFile} \u2014 ${err2.message}`
6155
+ );
6156
+ deps.exit(1);
6157
+ return;
6158
+ }
6159
+ let extra;
6160
+ try {
6161
+ extra = JSON.parse(rawJson);
6162
+ } catch (err2) {
6163
+ deps.error(`error: --context-file is not valid JSON \u2014 ${err2.message}`);
6164
+ deps.exit(1);
6165
+ return;
6166
+ }
6167
+ const unwrapped = unwrapFactsEnvelope(extra);
6168
+ if (unwrapped) ctx = mergeGateContext(ctx, unwrapped);
6169
+ }
5638
6170
  if (typeof raw.context === "string" && raw.context.length > 0) {
5639
6171
  let extra;
5640
6172
  try {
@@ -5671,11 +6203,13 @@ async function runGatesPlan(master, raw, deps = defaultRunDeps) {
5671
6203
  }
5672
6204
  try {
5673
6205
  const passes = await resolveJudgmentGate(clause.gate, ctx, packageRoot);
5674
- if (passes) {
5675
- fire.push(fireEntry(clause, master));
5676
- } else {
6206
+ if (!passes) {
5677
6207
  skip.push({ sub: clause.sub, reason: `gate ${clause.gate} = false` });
6208
+ continue;
5678
6209
  }
6210
+ const veto = await resolveSkipVeto(clause.skip_gate, ctx, packageRoot);
6211
+ if (veto) skip.push({ sub: clause.sub, reason: veto });
6212
+ else fire.push(fireEntry(clause, master));
5679
6213
  } catch (e) {
5680
6214
  if (isUndefinedVariableError(e)) {
5681
6215
  deps.warn(
@@ -5728,10 +6262,22 @@ function registerGates(program2) {
5728
6262
  "sub names to skip without gate eval (repeatable and/or comma-separated)",
5729
6263
  (v, prev) => [...prev, v],
5730
6264
  []
5731
- ).option("--context <json>", "JSON object merged over the default gate context").action(async (master, raw) => {
6265
+ ).option("--context <json>", "JSON object merged over the default gate context").option(
6266
+ "--context-file <path>",
6267
+ '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.'
6268
+ ).action(async (master, raw) => {
5732
6269
  await runGatesPlan(master, raw);
5733
6270
  });
5734
6271
  }
6272
+ function unwrapFactsEnvelope(parsed) {
6273
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
6274
+ const obj = parsed;
6275
+ const facts = obj.facts;
6276
+ if (facts && typeof facts === "object" && !Array.isArray(facts)) {
6277
+ return facts;
6278
+ }
6279
+ return obj;
6280
+ }
5735
6281
  function fireEntry(clause, master) {
5736
6282
  const isMaster = STAGE_MASTERS.has(clause.sub);
5737
6283
  const sub = master !== "auto" && !isMaster ? `${master}-${clause.sub}` : clause.sub;
@@ -5742,7 +6288,7 @@ function fireEntry(clause, master) {
5742
6288
  if (isMaster) entry.is_master = true;
5743
6289
  return entry;
5744
6290
  }
5745
- var VALID_MASTERS, STAGE_MASTERS, PARALLELISM_GATE;
6291
+ var GATE_MASTERS, VALID_MASTERS, STAGE_MASTERS, PARALLELISM_GATE;
5746
6292
  var init_gates = __esm({
5747
6293
  "src/cli/gates.ts"() {
5748
6294
  init_path_guard();
@@ -5750,10 +6296,12 @@ var init_gates = __esm({
5750
6296
  init_runDeps();
5751
6297
  init_exprBuilder();
5752
6298
  init_judgmentResolver();
6299
+ init_skipGate();
5753
6300
  init_skipSubs();
5754
6301
  init_detectHeadless();
5755
6302
  init_gateContext();
5756
- VALID_MASTERS = /* @__PURE__ */ new Set(["auto", "discuss", "plan", "task", "verify", "ship"]);
6303
+ GATE_MASTERS = ["auto", "discuss", "plan", "task", "verify", "ship"];
6304
+ VALID_MASTERS = new Set(GATE_MASTERS);
5757
6305
  STAGE_MASTERS = /* @__PURE__ */ new Set(["discuss", "plan", "task", "verify"]);
5758
6306
  PARALLELISM_GATE = "judgments.parallelism-gate.agent-teams-upgrade.fires";
5759
6307
  }
@@ -6451,10 +6999,10 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
6451
6999
  child.stderr?.setEncoding("utf8").on("data", (chunk) => {
6452
7000
  stderr += chunk;
6453
7001
  });
6454
- return await new Promise((resolve21) => {
7002
+ return await new Promise((resolve23) => {
6455
7003
  const timer = setTimeout(() => {
6456
7004
  child.kill("SIGKILL");
6457
- resolve21({
7005
+ resolve23({
6458
7006
  ok: false,
6459
7007
  phase: "spawn",
6460
7008
  error: {
@@ -6475,7 +7023,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
6475
7023
  child.on("error", (err2) => {
6476
7024
  clearTimeout(timer);
6477
7025
  const bashMissing = triedBash && err2.code === "ENOENT";
6478
- resolve21({
7026
+ resolve23({
6479
7027
  ok: false,
6480
7028
  phase: "spawn",
6481
7029
  error: {
@@ -6490,7 +7038,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
6490
7038
  });
6491
7039
  child.on("close", (code) => {
6492
7040
  clearTimeout(timer);
6493
- resolve21({ ok: true, exitCode: code ?? -1, stdout: stdout2, stderr });
7041
+ resolve23({ ok: true, exitCode: code ?? -1, stdout: stdout2, stderr });
6494
7042
  });
6495
7043
  });
6496
7044
  }
@@ -6691,7 +7239,7 @@ var init_idempotent = __esm({
6691
7239
  }
6692
7240
  });
6693
7241
  function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3) {
6694
- return new Promise((resolve21) => {
7242
+ return new Promise((resolve23) => {
6695
7243
  const isWin = process.platform === "win32";
6696
7244
  const stdio = ["ignore", "pipe", "pipe"];
6697
7245
  const child = isWin ? spawn("cmd.exe", ["/c", bin, ...args], { cwd, windowsHide: true, stdio }) : spawn(bin, args, { cwd, shell: false, stdio });
@@ -6705,17 +7253,17 @@ function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3) {
6705
7253
  });
6706
7254
  const timer = setTimeout(() => {
6707
7255
  child.kill("SIGKILL");
6708
- resolve21({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
7256
+ resolve23({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
6709
7257
  }, timeoutMs);
6710
7258
  child.on("error", (e) => {
6711
7259
  clearTimeout(timer);
6712
7260
  const enoent = e.code === "ENOENT";
6713
7261
  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}` });
7262
+ resolve23({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
6715
7263
  });
6716
7264
  child.on("close", (code) => {
6717
7265
  clearTimeout(timer);
6718
- resolve21({ exitCode: code ?? -1, stdout: stdout2, stderr });
7266
+ resolve23({ exitCode: code ?? -1, stdout: stdout2, stderr });
6719
7267
  });
6720
7268
  });
6721
7269
  }
@@ -6798,7 +7346,7 @@ var init_ccPluginMarketplace2 = __esm({
6798
7346
  `cc-plugin-marketplace cmd must contain \`plugin install <plugin>@<marketplace>\` (parsed from: '${install.cmd.slice(0, 100)}')`,
6799
7347
  "cc-plugin-shape"
6800
7348
  ),
6801
- suggest: "see manifests/tools/ralph-loop.yaml or manifests/tools/superpowers.yaml for shape"
7349
+ suggest: "see manifests/tools/superpowers.yaml for shape"
6802
7350
  }
6803
7351
  };
6804
7352
  }
@@ -6971,7 +7519,7 @@ var init_packSkillAudit = __esm({
6971
7519
  }
6972
7520
  });
6973
7521
  function gitRevParseHead(cwd, timeoutMs = 1e4) {
6974
- return new Promise((resolve21) => {
7522
+ return new Promise((resolve23) => {
6975
7523
  const isWin = process.platform === "win32";
6976
7524
  const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
6977
7525
  let stdout2 = "";
@@ -6980,15 +7528,15 @@ function gitRevParseHead(cwd, timeoutMs = 1e4) {
6980
7528
  });
6981
7529
  const timer = setTimeout(() => {
6982
7530
  child.kill("SIGKILL");
6983
- resolve21({ sha: "", exit: -1 });
7531
+ resolve23({ sha: "", exit: -1 });
6984
7532
  }, timeoutMs);
6985
7533
  child.on("error", () => {
6986
7534
  clearTimeout(timer);
6987
- resolve21({ sha: "", exit: -1 });
7535
+ resolve23({ sha: "", exit: -1 });
6988
7536
  });
6989
7537
  child.on("close", (code) => {
6990
7538
  clearTimeout(timer);
6991
- resolve21({ sha: stdout2.trim(), exit: code ?? -1 });
7539
+ resolve23({ sha: stdout2.trim(), exit: code ?? -1 });
6992
7540
  });
6993
7541
  });
6994
7542
  }
@@ -8143,6 +8691,19 @@ function buildWorkflowStateBlock(wf, forward, ledgerAgeMs) {
8143
8691
  `BREAK-LOOP: sub '${l.sub}' failed ${l.count}x \u2014 stop retrying, run break-loop skill`
8144
8692
  );
8145
8693
  }
8694
+ for (const e of ledger) {
8695
+ const attempts = e.fail_count ?? 0;
8696
+ if (e.attempt_budget !== void 0 && attempts >= e.attempt_budget) {
8697
+ lines.push(
8698
+ `BUDGET-EXHAUSTED: sub '${e.sub}' spent ${attempts}/${e.attempt_budget} attempts \u2014 do NOT spawn it again; re-scope, fix the blocker, or escalate`
8699
+ );
8700
+ }
8701
+ if ((e.progress?.stale_count ?? 0) >= PLATEAU_THRESHOLD) {
8702
+ lines.push(
8703
+ `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`
8704
+ );
8705
+ }
8706
+ }
8146
8707
  if (wf.ship_ready) {
8147
8708
  lines.push(
8148
8709
  `SHIP-READY: ${wf.ship_commits ?? 0} commit(s) since the last release tag \u2014 consider shipping (harnessed release-preflight, then /ship)`
@@ -8258,6 +8819,7 @@ var init_injectState = __esm({
8258
8819
  init_forwardStep();
8259
8820
  init_ledger();
8260
8821
  init_planningScan();
8822
+ init_progress();
8261
8823
  INTENT_TTL_MS = 24 * 60 * 60 * 1e3;
8262
8824
  STALE_LEDGER_MS = 24 * 60 * 60 * 1e3;
8263
8825
  DEFAULT_INJECT_BUDGET = 1500;
@@ -9183,9 +9745,9 @@ function realSelfUpdateDeps() {
9183
9745
  return res.text();
9184
9746
  },
9185
9747
  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"], {
9748
+ const { execFile: execFile3 } = await import('child_process');
9749
+ const { promisify: promisify4 } = await import('util');
9750
+ const { stdout: stdout2 } = await promisify4(execFile3)(bin, ["--version"], {
9189
9751
  timeout: 3e4,
9190
9752
  windowsHide: true
9191
9753
  });
@@ -9482,7 +10044,7 @@ function renderHumanTable(records) {
9482
10044
  }
9483
10045
  }
9484
10046
  function pipeToJq(filterExpr, lines) {
9485
- return new Promise((resolve21, reject) => {
10047
+ return new Promise((resolve23, reject) => {
9486
10048
  const child = spawn("jq", [filterExpr], {
9487
10049
  stdio: ["pipe", "inherit", "inherit"],
9488
10050
  windowsHide: true
@@ -9491,12 +10053,12 @@ function pipeToJq(filterExpr, lines) {
9491
10053
  const e = err2;
9492
10054
  if (e.code === "ENOENT") {
9493
10055
  console.error(t("audit_log.jq_missing"));
9494
- resolve21(1);
10056
+ resolve23(1);
9495
10057
  } else {
9496
10058
  reject(err2);
9497
10059
  }
9498
10060
  });
9499
- child.on("close", (code) => resolve21(code ?? 0));
10061
+ child.on("close", (code) => resolve23(code ?? 0));
9500
10062
  child.stdin.write(lines.join("\n"));
9501
10063
  child.stdin.end();
9502
10064
  });
@@ -9592,6 +10154,157 @@ function registerBackupList(program2) {
9592
10154
  });
9593
10155
  }
9594
10156
 
10157
+ // src/cli/checkDocs.ts
10158
+ init_i18n();
10159
+ var DEFAULT_MAX_STATE_LINES = 100;
10160
+ var KEY_DECISIONS_SECTION_RE = /^##\s+.*关键决议\s*ship\s*总结/gm;
10161
+ var KEY_DECISIONS_SECTION_LIMIT = 1;
10162
+ var HISTORICAL_ERRATA_RE = /W-[1-9]\s+errata|sister\s+review\s+M[1-9]\s+修正/;
10163
+ var ROADMAP_NARRATIVE_SIGNALS = [
10164
+ { id: "commit-hash", test: hasCommitHash },
10165
+ { id: "test-tally", test: (l) => /\b\d{2,}\s*\/\s*0\b/.test(l) },
10166
+ { id: "ci-verdict", test: (l) => /\bCI\s+(green|red|绿|红)/i.test(l) },
10167
+ { id: "lesson", test: (l) => /(教训|lesson\s*[::]|lessons?\s+learned)/i.test(l) }
10168
+ ];
10169
+ function hasCommitHash(line) {
10170
+ for (const m of line.matchAll(/\b[0-9a-f]{7,40}\b/g)) {
10171
+ if (/\d/.test(m[0]) && /[a-f]/.test(m[0])) return true;
10172
+ }
10173
+ return false;
10174
+ }
10175
+ function read(cwd, rel) {
10176
+ const p7 = join(cwd, rel);
10177
+ if (!existsSync(p7)) return null;
10178
+ try {
10179
+ return readFileSync(p7, "utf8");
10180
+ } catch {
10181
+ return null;
10182
+ }
10183
+ }
10184
+ function contentLines(content) {
10185
+ const lines = content.split(/\r?\n/);
10186
+ if (lines[lines.length - 1] === "") lines.pop();
10187
+ return lines;
10188
+ }
10189
+ function collectDocViolations(opts) {
10190
+ const limit = opts.maxStateLines ?? DEFAULT_MAX_STATE_LINES;
10191
+ const out = [];
10192
+ const state = read(opts.cwd, join(".planning", "STATE.md"));
10193
+ if (state !== null) {
10194
+ const lines = contentLines(state);
10195
+ if (lines.length > limit && !opts.allowLongState) {
10196
+ out.push({
10197
+ rule: "state-digest-line-limit",
10198
+ tier: "halt",
10199
+ file: ".planning/STATE.md",
10200
+ message: t("check_docs.state_line_limit", { lines: lines.length, limit })
10201
+ });
10202
+ }
10203
+ const sections = state.match(KEY_DECISIONS_SECTION_RE) ?? [];
10204
+ if (sections.length > KEY_DECISIONS_SECTION_LIMIT) {
10205
+ out.push({
10206
+ rule: "state-key-decisions-section-limit",
10207
+ tier: "warn",
10208
+ file: ".planning/STATE.md",
10209
+ message: t("check_docs.state_key_decisions", {
10210
+ count: sections.length,
10211
+ limit: KEY_DECISIONS_SECTION_LIMIT
10212
+ })
10213
+ });
10214
+ }
10215
+ for (let i = 0; i < lines.length; i++) {
10216
+ const line = lines[i] ?? "";
10217
+ if (HISTORICAL_ERRATA_RE.test(line)) {
10218
+ out.push({
10219
+ rule: "state-historical-errata",
10220
+ tier: "warn",
10221
+ file: ".planning/STATE.md",
10222
+ line: i + 1,
10223
+ message: t("check_docs.state_errata", { excerpt: line.trim().slice(0, 80) })
10224
+ });
10225
+ }
10226
+ }
10227
+ }
10228
+ const roadmap = read(opts.cwd, join(".planning", "ROADMAP.md"));
10229
+ if (roadmap !== null) {
10230
+ const lines = contentLines(roadmap);
10231
+ for (let i = 0; i < lines.length; i++) {
10232
+ const line = lines[i] ?? "";
10233
+ const hits = ROADMAP_NARRATIVE_SIGNALS.filter((s) => s.test(line)).map((s) => s.id);
10234
+ if (hits.length > 0) {
10235
+ out.push({
10236
+ rule: "roadmap-no-inline-narrative",
10237
+ tier: "warn",
10238
+ file: ".planning/ROADMAP.md",
10239
+ line: i + 1,
10240
+ message: t("check_docs.roadmap_narrative", { signals: hits.join(", ") })
10241
+ });
10242
+ }
10243
+ }
10244
+ }
10245
+ return out;
10246
+ }
10247
+ function exitCodeFor(violations) {
10248
+ if (violations.some((v) => v.tier === "halt")) return 2;
10249
+ return violations.length > 0 ? 1 : 0;
10250
+ }
10251
+ function shouldGateForHookPayload(raw) {
10252
+ if (!raw.trim()) return false;
10253
+ let payload;
10254
+ try {
10255
+ payload = JSON.parse(raw);
10256
+ } catch {
10257
+ return false;
10258
+ }
10259
+ if (payload?.tool_name !== "Bash") return false;
10260
+ const cmd = payload.tool_input?.command;
10261
+ return typeof cmd === "string" && /\bgit\s+(?:-\S+\s+)*commit\b/.test(cmd);
10262
+ }
10263
+ async function readStdin() {
10264
+ if (process.stdin.isTTY) return "";
10265
+ try {
10266
+ const chunks = [];
10267
+ for await (const c of process.stdin) chunks.push(c);
10268
+ return Buffer.concat(chunks).toString("utf8");
10269
+ } catch {
10270
+ return "";
10271
+ }
10272
+ }
10273
+ function registerCheckDocs(program2) {
10274
+ program2.command("check-docs").description(
10275
+ "Documentation-discipline gate over .planning/ (STATE digest limit + archive cadence + ROADMAP pointer-not-narrative). Exits 2 on a blocking violation, 1 on advisory-only."
10276
+ ).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(
10277
+ async (opts) => {
10278
+ if (opts.hook && !shouldGateForHookPayload(await readStdin())) process.exit(0);
10279
+ const parsed = Number(opts.maxStateLines);
10280
+ const violations = collectDocViolations({
10281
+ cwd: opts.cwd ?? process.cwd(),
10282
+ ...Number.isFinite(parsed) && parsed > 0 ? { maxStateLines: parsed } : {},
10283
+ allowLongState: !!process.env.HARNESSED_ALLOW_LONG_STATE
10284
+ });
10285
+ const code = exitCodeFor(violations);
10286
+ const summary = code === 2 ? "halt" : code === 1 ? "warn" : "pass";
10287
+ if (opts.json) {
10288
+ console.log(JSON.stringify({ violations, summary, exit_code: code }, null, 2));
10289
+ } else if (violations.length === 0) {
10290
+ console.log(t("check_docs.clean"));
10291
+ } else {
10292
+ for (const v of violations) {
10293
+ const where = v.line === void 0 ? v.file : `${v.file}:${v.line}`;
10294
+ console.error(`${v.tier === "halt" ? "\u2717" : "\u26A0"} ${where} [${v.rule}] ${v.message}`);
10295
+ }
10296
+ console.error(
10297
+ code === 2 ? t("check_docs.summary_halt", {
10298
+ halt: violations.filter((v) => v.tier === "halt").length,
10299
+ warn: violations.filter((v) => v.tier === "warn").length
10300
+ }) : t("check_docs.summary_warn", { warn: violations.length })
10301
+ );
10302
+ }
10303
+ process.exit(code);
10304
+ }
10305
+ );
10306
+ }
10307
+
9595
10308
  // src/cli.ts
9596
10309
  init_checkpoint();
9597
10310
 
@@ -9621,7 +10334,15 @@ function registerDoctor(program2) {
9621
10334
  program2.command("doctor").description(
9622
10335
  "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
10336
  ).option("--json", "output JSON instead of human-readable").action(async (opts) => {
9624
- const results = await Promise.all(CHECKS.map((c) => c()));
10337
+ const settled = await Promise.allSettled(CHECKS.map((c) => c()));
10338
+ const results = settled.map(
10339
+ (s, i) => s.status === "fulfilled" ? s.value : {
10340
+ name: `check #${i + 1}`,
10341
+ status: "warn",
10342
+ message: `check crashed: ${s.reason instanceof Error ? s.reason.message : String(s.reason)}`,
10343
+ fix: "this check was skipped; the other checks above are unaffected"
10344
+ }
10345
+ );
9625
10346
  const hasFail = results.some((r) => r.status === "fail");
9626
10347
  const hasWarn = results.some((r) => r.status === "warn");
9627
10348
  if (opts.json) {
@@ -10284,6 +11005,224 @@ function registerExemptGateguard(program2) {
10284
11005
  });
10285
11006
  }
10286
11007
 
11008
+ // src/cli/facts.ts
11009
+ init_path_guard();
11010
+ init_assetsRoot();
11011
+ init_runDeps();
11012
+ init_exprBuilder();
11013
+ init_judgmentResolver();
11014
+ init_gates();
11015
+ var VALID_MASTERS2 = new Set(GATE_MASTERS);
11016
+ function deriveGitFacts(run) {
11017
+ let lines = 0;
11018
+ let sawNumstat = false;
11019
+ for (const args of [
11020
+ ["diff", "--numstat"],
11021
+ ["diff", "--cached", "--numstat"]
11022
+ ]) {
11023
+ const out = run(args);
11024
+ if (out === null) continue;
11025
+ sawNumstat = true;
11026
+ for (const row of out.split(/\r?\n/)) {
11027
+ const m = /^(\d+)\t(\d+)\t/.exec(row);
11028
+ if (m) lines += Number(m[1]) + Number(m[2]);
11029
+ }
11030
+ }
11031
+ const files = /* @__PURE__ */ new Set();
11032
+ let sawNames = false;
11033
+ for (const args of [
11034
+ ["diff", "--name-only"],
11035
+ ["diff", "--cached", "--name-only"]
11036
+ ]) {
11037
+ const out = run(args);
11038
+ if (out === null) continue;
11039
+ sawNames = true;
11040
+ for (const row of out.split(/\r?\n/)) {
11041
+ const p7 = row.trim();
11042
+ if (p7) files.add(p7);
11043
+ }
11044
+ }
11045
+ return {
11046
+ lines: sawNumstat && lines > 0 ? lines : null,
11047
+ files_touched: sawNames && files.size > 0 ? files.size : null
11048
+ };
11049
+ }
11050
+ function defaultGitRun(args) {
11051
+ try {
11052
+ return execFileSync("git", args, {
11053
+ cwd: process.cwd(),
11054
+ encoding: "utf8",
11055
+ stdio: ["ignore", "pipe", "ignore"]
11056
+ });
11057
+ } catch {
11058
+ return null;
11059
+ }
11060
+ }
11061
+ function factNamesOf(expression) {
11062
+ return _parserSingleton.parse(expression).variables({ withMembers: true });
11063
+ }
11064
+ async function readDelegates(master, packageRoot) {
11065
+ const yamlPath = resolveMasterYamlPath(master, packageRoot);
11066
+ const parsed = parse(await readFile(yamlPath, "utf8"));
11067
+ const delegates = parsed?.delegates_to;
11068
+ return Array.isArray(delegates) ? delegates : [];
11069
+ }
11070
+ async function collectGatedFactNames(master, packageRoot) {
11071
+ const names = /* @__PURE__ */ new Set();
11072
+ for (const clause of await readDelegates(master, packageRoot)) {
11073
+ for (const ref of [clause.gate, clause.skip_gate]) {
11074
+ if (!ref) continue;
11075
+ let expr;
11076
+ try {
11077
+ expr = await resolveJudgmentExpression(ref, packageRoot);
11078
+ } catch {
11079
+ continue;
11080
+ }
11081
+ try {
11082
+ for (const n of factNamesOf(expr)) names.add(n);
11083
+ } catch {
11084
+ }
11085
+ }
11086
+ }
11087
+ return [...names].sort();
11088
+ }
11089
+ var FACT_HINTS = {
11090
+ // phase tier
11091
+ "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.",
11092
+ "phase.stage": "Current stage name (derived from the invocation; do not edit).",
11093
+ "phase.open_decisions": "How many implementation decisions are still genuinely open for this phase (>=2 opens the phase-tier discussion).",
11094
+ "phase.scope_days": "Estimated phase size in days (>1 opens the phase-tier discussion).",
11095
+ "phase.single_task": "true if the phase is one self-contained task with no sub-structure.",
11096
+ "phase.scope_locked_in_history": "true if the scope was already decided in an earlier session / design doc, so re-litigating it is waste.",
11097
+ "phase.files_touched": "How many files this phase changes (derived from git when a diff exists; estimate it if the tree is still clean).",
11098
+ "phase.has_cross_phase_data_flow": "true if this phase shares a data flow, API contract or dependency with another phase.",
11099
+ "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.",
11100
+ "phase.is_critical_module": "true if this touches a module where a regression is expensive (auth, payments, data migration, the release path).",
11101
+ "phase.is_major_release": "true if this phase ships a major version / externally visible launch.",
11102
+ "phase.is_final_step": "true if this is the last step of the phase (enables the simplify pass).",
11103
+ "phase.has_ui_changes": "true if user-visible UI changed (opens the QA lane).",
11104
+ "phase.has_design_changes": "true if visual design / design-system tokens changed (opens the design-review lane).",
11105
+ "phase.has_auth_or_secrets": "true if auth, credentials, tokens or secret handling changed (opens the security lane).",
11106
+ "phase.has_ai_phase": "true if this phase ships LLM/AI behaviour needing an eval-coverage audit.",
11107
+ "phase.requires_coverage_audit": "true if the phase needs a requirements-coverage audit rather than ordinary verification.",
11108
+ // subtask tier
11109
+ "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.",
11110
+ "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.",
11111
+ "subtask.approaches": "How many genuinely different implementations you are choosing between (>=2 means the choice deserves a decision, not a coin flip).",
11112
+ "subtask.core_algorithm": "true if this designs an algorithm or data structure rather than wiring existing pieces together.",
11113
+ "subtask.has_api_contract": "true if this defines or changes an interface other code must conform to.",
11114
+ "subtask.error_cost": "Cost of getting this wrong: 'low' | 'medium' | 'high'. 'high' = data migration, concurrency, a performance-critical path, anything not cheaply reversible.",
11115
+ "subtask.is_core_business_logic": "true if this is core domain logic rather than glue or config.",
11116
+ "subtask.is_algorithm": "true if correctness depends on an algorithm you could get subtly wrong.",
11117
+ "subtask.is_data_processing": "true if this transforms, parses or migrates data.",
11118
+ "subtask.regression_risk": "How likely a silent regression is here: 'low' | 'medium' | 'high'.",
11119
+ "subtask.reliability_required": "true if this must keep working unattended (hooks, CI gates, release path).",
11120
+ // root-flat
11121
+ is_critical_release: "true if this verification guards a critical release (escalates to the multi-specialist review team).",
11122
+ user_understanding_unclear: "true if YOU do not yet understand the request well enough to plan it (opens the research stage)."
11123
+ };
11124
+ function hintFor(name) {
11125
+ return FACT_HINTS[name] ?? `Judgement call consumed by a gate expression in workflows/judgments/ \u2014 read the trigger that references '${name}' before filling it.`;
11126
+ }
11127
+ function setNested(target, dotted, value) {
11128
+ const parts = dotted.split(".");
11129
+ if (parts.length === 1) {
11130
+ target[dotted] = value;
11131
+ return;
11132
+ }
11133
+ const [group, key] = parts;
11134
+ let bucket = target[group];
11135
+ if (!bucket) {
11136
+ bucket = {};
11137
+ target[group] = bucket;
11138
+ }
11139
+ bucket[key] = value;
11140
+ }
11141
+ function buildFactsEnvelope(master, gatedNames, derived) {
11142
+ const facts = {};
11143
+ const hints = {};
11144
+ const all = [.../* @__PURE__ */ new Set([...gatedNames, ...Object.keys(derived)])].sort();
11145
+ for (const name of all) {
11146
+ const value = derived[name]?.value ?? null;
11147
+ setNested(facts, name, value);
11148
+ if (value === null) hints[name] = hintFor(name);
11149
+ }
11150
+ return {
11151
+ master,
11152
+ facts,
11153
+ hints,
11154
+ derived,
11155
+ 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.`
11156
+ };
11157
+ }
11158
+ async function runFactsPlan(master, raw, deps = defaultRunDeps, gitRun = defaultGitRun) {
11159
+ if (!VALID_MASTERS2.has(master)) {
11160
+ deps.error(
11161
+ `error: unknown master '${master}'. Expected one of: ${[...GATE_MASTERS].join(", ")}.`
11162
+ );
11163
+ deps.exit(1);
11164
+ return;
11165
+ }
11166
+ try {
11167
+ checkPathSafe(master);
11168
+ } catch {
11169
+ deps.error("error: invalid master name (path traversal rejected)");
11170
+ deps.exit(1);
11171
+ return;
11172
+ }
11173
+ const packageRoot = getAssetsRoot();
11174
+ let gated;
11175
+ try {
11176
+ gated = await collectGatedFactNames(master, packageRoot);
11177
+ } catch (err2) {
11178
+ deps.error(
11179
+ `error: failed to read master workflow.yaml at ${resolveMasterYamlPath(master, packageRoot)} \u2014 ${err2.message}`
11180
+ );
11181
+ deps.exit(1);
11182
+ return;
11183
+ }
11184
+ const git = deriveGitFacts(gitRun);
11185
+ const derived = {
11186
+ // `harnessed gates` seeds phase.stage from the master argument, so facts MUST
11187
+ // report the same thing: deriving a stage from the ledger instead could hand
11188
+ // back a STALE stage that then overrides the real one through --context-file
11189
+ // and turn every `phase.stage == '<x>'` gate false.
11190
+ "phase.stage": {
11191
+ value: master,
11192
+ source: `master argument (mirrors \`harnessed gates ${master}\`)`
11193
+ },
11194
+ "subtask.lines": {
11195
+ value: git.lines,
11196
+ source: "git diff --numstat + --cached --numstat (added+deleted; null when no repo / clean tree)"
11197
+ },
11198
+ "phase.files_touched": {
11199
+ value: git.files_touched,
11200
+ source: "git diff --name-only + --cached --name-only (unique paths; null when no repo / clean tree)"
11201
+ }
11202
+ };
11203
+ const envelope = buildFactsEnvelope(master, gated, derived);
11204
+ const json = JSON.stringify(envelope, null, 2);
11205
+ if (raw.out) {
11206
+ try {
11207
+ await writeFile(raw.out, json, "utf8");
11208
+ } catch (err2) {
11209
+ deps.error(`error: failed to write --out ${raw.out} \u2014 ${err2.message}`);
11210
+ deps.exit(1);
11211
+ return;
11212
+ }
11213
+ }
11214
+ deps.log(json);
11215
+ deps.exit(0);
11216
+ return;
11217
+ }
11218
+ function registerFacts(program2) {
11219
+ program2.command("facts").description(
11220
+ "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`."
11221
+ ).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) => {
11222
+ await runFactsPlan(master, raw);
11223
+ });
11224
+ }
11225
+
10287
11226
  // src/cli.ts
10288
11227
  init_gates();
10289
11228
  init_gc();
@@ -10848,29 +11787,7 @@ async function loadAllApplied(disciplines_applied, packageRoot) {
10848
11787
  return out;
10849
11788
  }
10850
11789
 
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
- }
11790
+ // src/discipline/enforcement/before-commit.ts
10874
11791
  var TS_JS_RE = /\.(ts|tsx|js|mjs)$/;
10875
11792
  async function runBeforeCommitHook(ctx) {
10876
11793
  const d = await loadDiscipline("operational", ctx.packageRoot);
@@ -10912,17 +11829,58 @@ async function runBeforeCommitHook(ctx) {
10912
11829
  async function loadDisciplinesForPhase(disciplines_applied, packageRoot) {
10913
11830
  return loadAllApplied(disciplines_applied, packageRoot);
10914
11831
  }
10915
-
10916
- // src/discipline/enforcement/before-spawn.ts
11832
+ var IMPL_TIER = {
11833
+ gstack: "gstack",
11834
+ gsd: "gsd",
11835
+ superpowers: "superpowers",
11836
+ "mattpocock-skills": "mattpocock",
11837
+ // agent-teams-create / -send-message / -shutdown — 子任务并行机制 (Agent Teams).
11838
+ "claude-platform": "parallel"
11839
+ };
11840
+ var NAME_TIER = {
11841
+ "planning-with-files": "planning-with-files",
11842
+ "karpathy-guidelines": "karpathy"
11843
+ };
11844
+ var _implCache = /* @__PURE__ */ new Map();
11845
+ async function loadCapabilityImpls(packageRoot) {
11846
+ const cached = _implCache.get(packageRoot);
11847
+ if (cached) return cached;
11848
+ const out = /* @__PURE__ */ new Map();
11849
+ try {
11850
+ const raw = await readFile(resolve(packageRoot, "workflows", "capabilities.yaml"), "utf8");
11851
+ const parsed = parse(raw);
11852
+ for (const [name, entry] of Object.entries(parsed?.capabilities ?? {})) {
11853
+ if (entry && typeof entry.impl === "string") out.set(name, entry.impl);
11854
+ }
11855
+ } catch (err2) {
11856
+ console.warn(
11857
+ `\u26A0\uFE0F before-spawn: capabilities.yaml unreadable (${err2.message}); arbitrating without capability\u2192tier resolution (ADR 0029 fail-soft \u2014 fired order preserved).`
11858
+ );
11859
+ return out;
11860
+ }
11861
+ _implCache.set(packageRoot, out);
11862
+ return out;
11863
+ }
11864
+ function resolveTier(cap, impls) {
11865
+ if (cap.tier !== void 0) return cap.tier;
11866
+ const byName = NAME_TIER[cap.name];
11867
+ if (byName) return byName;
11868
+ const impl = impls.get(cap.name);
11869
+ return impl ? IMPL_TIER[impl] : void 0;
11870
+ }
10917
11871
  async function arbitrateBeforeSpawn(fired, packageRoot) {
10918
11872
  if (fired.length <= 1) return fired;
10919
11873
  const d = await loadDiscipline("priority", packageRoot);
10920
11874
  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));
11875
+ const impls = await loadCapabilityImpls(packageRoot);
11876
+ return fired.map((cap) => {
11877
+ const tier = resolveTier(cap, impls);
11878
+ const i = tier === void 0 ? -1 : hierarchy.indexOf(tier);
11879
+ return {
11880
+ cap: tier === void 0 ? cap : { ...cap, tier },
11881
+ rank: i === -1 ? Number.MAX_SAFE_INTEGER : i
11882
+ };
11883
+ }).sort((a, b) => a.rank - b.rank).map((e) => e.cap);
10926
11884
  }
10927
11885
 
10928
11886
  // src/workflow/run.ts
@@ -10985,75 +11943,7 @@ async function isVetoed() {
10985
11943
 
10986
11944
  // src/workflow/run.ts
10987
11945
  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
- }
11946
+ init_ralphLoop();
11057
11947
 
11058
11948
  // src/workflow/lib/completionSchema.ts
11059
11949
  var COMPLETION_SCHEMA = {
@@ -11066,8 +11956,11 @@ var COMPLETION_SCHEMA = {
11066
11956
  // v3.5.0 Phase 2 — Option 1-Lite signal-driven Agent Teams escalation.
11067
11957
  // spawned subagent SHOULD set this when any of parallelism-gate.yaml 5
11068
11958
  // 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).
11959
+ // user opens the team in the main Claude Code session — a spawned subagent
11960
+ // cannot form one itself (originally because the SDK never exposed the create
11961
+ // tool; since CC v2.1.178 there IS no create tool at all — teams form
11962
+ // implicitly on the lead's first background teammate spawn, and teammates
11963
+ // cannot nest teammates. See PHASE-2-SPEC.md § Why for the original rationale).
11071
11964
  needs_teams_escalation: { type: "boolean" },
11072
11965
  escalation_reason: { type: "string" }
11073
11966
  },
@@ -11303,6 +12196,11 @@ var DelegationClause = Type.Object(
11303
12196
  // sub-stage workflow name e.g. 'strategic' / 'phase' / 'subtask'
11304
12197
  gate: Type.Optional(Type.String()),
11305
12198
  // judgments.<file>.<trigger>.fires 4-level ref
12199
+ // T2.1 D-5 NEW — judgments.<file>.<trigger>.skips 4-level ref. Evaluated ONLY
12200
+ // when `gate` fired; true ⇒ veto the sub. Any fault (undefined variable /
12201
+ // missing trigger / no skips_when) ⇒ no veto, so a broken skip expression can
12202
+ // never silently delete a governance step (src/workflow/skipGate.ts).
12203
+ skip_gate: Type.Optional(Type.String()),
11306
12204
  mode: Type.Optional(Type.Union([Type.Literal("parallel"), Type.Literal("serial")])),
11307
12205
  order: Type.Optional(Type.Number())
11308
12206
  // serial-only: explicit ordering (K9 mitigation enforced in check-workflow-schema)
@@ -11330,7 +12228,7 @@ var WorkflowPhaseV3 = Type.Object(
11330
12228
  name: Type.Optional(Type.String()),
11331
12229
  upstream: Type.Optional(Type.String()),
11332
12230
  capability: Type.Optional(Type.String()),
11333
- // '{{ capabilities.ralph-loop.cmd }}'
12231
+ // '{{ capabilities.completion-gate.cmd }}'
11334
12232
  model: Type.Optional(ModelTier3),
11335
12233
  invokes: Type.Optional(Type.String()),
11336
12234
  // legacy slash-cmd OR JINJA template
@@ -11414,6 +12312,7 @@ function loadPhases(yamlPath, vars) {
11414
12312
  init_subAnchor();
11415
12313
  init_exprBuilder();
11416
12314
  init_judgmentResolver();
12315
+ init_skipGate();
11417
12316
  init_skipSubs();
11418
12317
  function resolveMasterYamlPath2(masterName, packageRoot) {
11419
12318
  return masterName === "auto" ? resolve(packageRoot, "workflows", "auto", "workflow.yaml") : resolve(packageRoot, "workflows", masterName, "auto", "workflow.yaml");
@@ -11566,11 +12465,12 @@ async function runMasterOrchestrator(masterName, context, packageRoot, spawnDriv
11566
12465
  }
11567
12466
  try {
11568
12467
  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
- });
12468
+ if (!passes) {
12469
+ gateEvalled.push({ clause, passes: false, reason: `gate ${clause.gate} = false` });
12470
+ continue;
12471
+ }
12472
+ const veto = await resolveSkipVeto(clause.skip_gate, context, packageRoot);
12473
+ gateEvalled.push(veto ? { clause, passes: false, reason: veto } : { clause, passes: true });
11574
12474
  } catch (e) {
11575
12475
  if (isUndefinedVariableError(e)) {
11576
12476
  console.warn(
@@ -11652,7 +12552,7 @@ async function runMasterOrchestrator(masterName, context, packageRoot, spawnDriv
11652
12552
  var MASTER_NAMES = ["discuss", "plan", "task", "verify", "auto"];
11653
12553
  var RALPH_DEFAULT_MAX_ITER = 20;
11654
12554
  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).
12555
+ 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
12556
 
11657
12557
  Five triggers (any one suffices):
11658
12558
 
@@ -11673,11 +12573,11 @@ var TRANSPARENT_SKIP_RULES = `When you encounter a phase gate or routing decisio
11673
12573
  (\u4E2D\u6587: "\u8FD9\u6B21\u8DF3\u8FC7\u4E86 <phase>, \u56E0\u4E3A <reason>. \u5982\u679C\u4F60\u8BA4\u4E3A\u9700\u8981\u8BF7\u660E\u8BF4.")
11674
12574
 
11675
12575
  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):
12576
+ 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
12577
 
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.
12578
+ 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
12579
 
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.
12580
+ 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
12581
 
11682
12582
  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
12583
 
@@ -11848,8 +12748,11 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
11848
12748
  const invokesTools = "invokes_tools" in ph && Array.isArray(ph.invokes_tools) ? ph.invokes_tools : void 0;
11849
12749
  if (invokesTools && invokesTools.length > 1) {
11850
12750
  try {
11851
- const firedCaps = invokesTools.map((c) => ({ name: c.tool, tier: c.tool }));
11852
- await arbitrateBeforeSpawn(firedCaps, packageRoot);
12751
+ const firedCaps = invokesTools.map((c) => ({ name: c.tool }));
12752
+ const arbitrated = await arbitrateBeforeSpawn(firedCaps, packageRoot);
12753
+ console.warn(
12754
+ `\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).`
12755
+ );
11853
12756
  } catch (err2) {
11854
12757
  console.warn(
11855
12758
  `\u26A0\uFE0F phase ${ph.id} before-spawn arbitrate failed (${err2.message}); proceeding default tool order (K14 warn-not-halt).`
@@ -11901,23 +12804,9 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
11901
12804
  if (r.needsTeamsEscalation === true) {
11902
12805
  const reason = r.escalationReason ?? "unspecified trigger";
11903
12806
  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.`
12807
+ `\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
12808
  );
11906
12809
  }
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
12810
  if (r.triggers_commit === true) {
11922
12811
  try {
11923
12812
  await runBeforeCommitHook({
@@ -11976,6 +12865,13 @@ async function buildToolsSection(sub, packageRoot) {
11976
12865
  const cmd = caps[tool]?.cmd;
11977
12866
  const impl = caps[tool]?.impl;
11978
12867
  lines.push(cmd ? `- Invoke \`${cmd}\` (${tool}${impl ? `, ${impl}` : ""})` : `- ${tool}`);
12868
+ const aliases = (caps[tool]?.aliases ?? []).filter((a) => typeof a.cmd === "string");
12869
+ if (cmd && aliases.length > 0) {
12870
+ const rendered = aliases.map((a) => `\`${a.cmd}\`${a.impl ? ` (${a.impl})` : ""}`).join(", ");
12871
+ lines.push(
12872
+ ` - 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}\`.`
12873
+ );
12874
+ }
11979
12875
  }
11980
12876
  if (lines.length === 0) return "";
11981
12877
  return `
@@ -11987,6 +12883,12 @@ ${lines.join("\n")}
11987
12883
  return "";
11988
12884
  }
11989
12885
  }
12886
+ var CHAT_TRIGGER_RE = /response\.target\s*==\s*['"]chat['"]/;
12887
+ 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):";
12888
+ function isChatScoped(trigger) {
12889
+ const s = Array.isArray(trigger) ? trigger.join(" ") : typeof trigger === "string" ? trigger : "";
12890
+ return CHAT_TRIGGER_RE.test(s);
12891
+ }
11990
12892
  async function buildDisciplinesSection(sub, packageRoot, locale = getLocale()) {
11991
12893
  try {
11992
12894
  const workflowsDir = resolve(packageRoot, "workflows");
@@ -12000,9 +12902,20 @@ async function buildDisciplinesSection(sub, packageRoot, locale = getLocale()) {
12000
12902
  const dRaw = await readFile(resolveLocaleYaml(disciplinesDir, name, locale), "utf8");
12001
12903
  const dDoc = parse(dRaw);
12002
12904
  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")}`);
12905
+ const always = [];
12906
+ const chat = [];
12907
+ for (const r of rules) {
12908
+ const desc = typeof r.description === "string" ? r.description.trim().replace(/\s+/g, " ") : "";
12909
+ if (desc.length === 0) continue;
12910
+ (isChatScoped(r.trigger) ? chat : always).push(desc);
12911
+ }
12912
+ const lines = always.map((d) => ` - ${d}`);
12913
+ if (chat.length > 0) {
12914
+ lines.push(` - ${CHAT_SCOPE_NOTE}`);
12915
+ lines.push(...chat.map((d) => ` - ${d}`));
12916
+ }
12917
+ if (lines.length > 0) blocks.push(`- **${name}**:
12918
+ ${lines.join("\n")}`);
12006
12919
  } catch {
12007
12920
  }
12008
12921
  }
@@ -12016,13 +12929,31 @@ ${blocks.join("\n")}
12016
12929
  return "";
12017
12930
  }
12018
12931
  }
12019
- function buildLanguageSection() {
12932
+ 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).";
12933
+ async function loadPreserveCategories(packageRoot) {
12934
+ try {
12935
+ const path = resolve(packageRoot, "workflows", "disciplines", "language.yaml");
12936
+ const doc = parse(await readFile(path, "utf8"));
12937
+ const rule = (Array.isArray(doc?.rules) ? doc.rules : []).find(
12938
+ (r) => r?.id === "preserve-english-categories"
12939
+ );
12940
+ const desc = typeof rule?.description === "string" ? rule.description : "";
12941
+ return desc.split("\n").map((l) => l.trim()).filter((l) => /^\d+\.\s+\S/.test(l));
12942
+ } catch {
12943
+ return [];
12944
+ }
12945
+ }
12946
+ async function buildLanguageSection(packageRoot) {
12020
12947
  const code = process.env.HARNESSED_USER_LANG;
12021
12948
  if (!code) return "";
12022
12949
  const name = LANG_NAMES[code] ?? code;
12950
+ const categories = await loadPreserveCategories(packageRoot);
12951
+ const preserve = categories.length > 0 ? `The following always stay in their original English form (do not translate, transliterate, or rewrite them):
12952
+ ${categories.join("\n")}` : PRESERVE_FALLBACK;
12023
12953
  return `
12024
12954
  ## 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).
12955
+ Respond in ${name}.
12956
+ ${preserve}
12026
12957
  `;
12027
12958
  }
12028
12959
  var PROTOCOLS = `
@@ -12072,8 +13003,9 @@ ${raw.task}
12072
13003
  ` : "";
12073
13004
  const toolsSection = await buildToolsSection(sub, packageRoot);
12074
13005
  const disciplinesSection = await buildDisciplinesSection(sub, packageRoot);
13006
+ const languageSection = await buildLanguageSection(packageRoot);
12075
13007
  const fullPrompt = `${taskSection}${body}
12076
- ${toolsSection}${disciplinesSection}${PROTOCOLS}${buildLanguageSection()}`;
13008
+ ${toolsSection}${disciplinesSection}${PROTOCOLS}${languageSection}`;
12077
13009
  if (raw.json) {
12078
13010
  const maxIterations = await resolveMaxIterations2(sub, packageRoot);
12079
13011
  const rp = rolePrompts[sub];
@@ -12381,7 +13313,7 @@ function registerRun(program2) {
12381
13313
  "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
13314
  ).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
13315
  "--max-iterations <n>",
12384
- "ralph-loop max iter (default 20; honored Phase 3 onward)",
13316
+ "SDK-path retry-loop max iter (default 20; honored Phase 3 onward)",
12385
13317
  (v) => parseInt(v, 10)
12386
13318
  ).option("--model <model>", "subagent model: 'haiku' | 'sonnet' | 'opus'").option(
12387
13319
  "--dry-run",
@@ -12744,13 +13676,12 @@ function spawnLoopSteps(indent) {
12744
13676
  const i = indent;
12745
13677
  return [
12746
13678
  `${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).`,
13679
+ `${i}b. Spawn a CC-native subagent (Task / Agent tool) with that \`prompt\` and \`model\`, then drive delivery with harnessed's own completion gate:`,
13680
+ `${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>\`.`,
13681
+ `${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.`,
13682
+ `${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
13683
  `${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>"\`.`
13684
+ `${i}d. On \`<promise>COMPLETE</promise>\`: Bash \`harnessed checkpoint complete <sub> --result-file <path> --summary "<one-line>"\`.`
12754
13685
  ];
12755
13686
  }
12756
13687
  function buildInteractiveBody(name, prompt) {
@@ -12796,8 +13727,8 @@ function buildOrchestratorBody(name, prompt) {
12796
13727
  const leafIndent = " ";
12797
13728
  const leafSpawnLoop = [
12798
13729
  ...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.`
13730
+ `${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).`,
13731
+ `${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
13732
  ];
12802
13733
  return [
12803
13734
  `# /${name}`,
@@ -12822,11 +13753,26 @@ function buildOrchestratorBody(name, prompt) {
12822
13753
  `Drive this exact sequence (it is the state machine \u2014 follow the file, don't improvise from memory):`,
12823
13754
  ``,
12824
13755
  ...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)." : ""}`,
13756
+ // T2.1 — MUST stay in lockstep with `factsStepEn` in
13757
+ // scripts/rewrite-skill-invoke-sections.mjs (copied verbatim; the SKILL is
13758
+ // the sister rendering of this same sequence). Without this step the gates
13759
+ // below evaluate against generic defaults, which is the audit-S2 defect
13760
+ // itself: every judgement-call fact pinned to its firing side and no caller
13761
+ // ever passing context, i.e. criteria with zero discriminating power.
13762
+ `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.`,
13763
+ `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
13764
  `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.`,
13765
+ // 4.34.0 — MUST stay in lockstep with the Agent Teams step 4 in
13766
+ // workflows/*/SKILL.md (see scripts/rewrite-skill-invoke-sections.mjs). CC
13767
+ // v2.1.178+ removed the two team lifecycle tools: the team forms implicitly on
13768
+ // the first background teammate spawn, `team_name` is accepted but ignored,
13769
+ // shutdown is a BY-NAME request rather than a tool call, and the team directory
13770
+ // is removed at session exit. Deliberately not naming the removed tools here —
13771
+ // tests/workflow/agentTeamsApiMigration.test.ts fails on those literals anywhere
13772
+ // in the live instruction surface, and this generator IS that surface.
13773
+ `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
13774
  `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.`,
13775
+ ` - **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
13776
  ` - **Else (leaf sub)** \u2014 spawn it, then checkpoint the outcome:`,
12831
13777
  ...leafSpawnLoop,
12832
13778
  `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 +13862,7 @@ var V3_4_3_SIGNATURE_MASTER_RX = /\*\*Preferred path\*\*[\s\S]*dispatch to the p
12916
13862
  function shouldOverwriteFile(content) {
12917
13863
  return HARNESSED_MARKER_RX2.test(content) || V3_4_3_SIGNATURE_SUB_RX.test(content) || V3_4_3_SIGNATURE_MASTER_RX.test(content);
12918
13864
  }
12919
- async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync20 = (p7) => readFileSync(p7, "utf8")) {
13865
+ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync21 = (p7) => readFileSync(p7, "utf8")) {
12920
13866
  const results = [];
12921
13867
  const aggregatedWarnings = /* @__PURE__ */ new Set();
12922
13868
  for (const name of slashNames) {
@@ -12935,7 +13881,7 @@ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabiliti
12935
13881
  if (fileExists2(path)) {
12936
13882
  let existing = "";
12937
13883
  try {
12938
- existing = readFileSync20(path);
13884
+ existing = readFileSync21(path);
12939
13885
  } catch {
12940
13886
  existing = "";
12941
13887
  }
@@ -13185,8 +14131,8 @@ async function runStepBInstall(manifestPaths, runOpts = {}) {
13185
14131
  return emit({ status: "failed", name, reason: String(e) });
13186
14132
  }
13187
14133
  };
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));
14134
+ const mcp = valid.filter((v) => MCP_METHODS.has(effectiveInstallMethod(v.manifest)));
14135
+ const rest = valid.filter((v) => !MCP_METHODS.has(effectiveInstallMethod(v.manifest)));
13190
14136
  const runMcpSerial = async () => {
13191
14137
  const out = [];
13192
14138
  for (const { manifest } of mcp) out.push(await runOne(manifest));
@@ -13404,6 +14350,24 @@ function printGrouped(b, prefix = "") {
13404
14350
  }
13405
14351
  }
13406
14352
  }
14353
+ function makeProgressPrinter(out = process.stdout) {
14354
+ if (out.isTTY !== true) return { onProgress: () => {
14355
+ }, done: () => {
14356
+ } };
14357
+ let width = 0;
14358
+ return {
14359
+ onProgress(ev) {
14360
+ const line = ` [${ev.done}/${ev.total}] ${ev.status} ${ev.name}`;
14361
+ width = Math.max(width, line.length);
14362
+ out.write(`\r${line.padEnd(width)}`);
14363
+ },
14364
+ done() {
14365
+ if (width === 0) return;
14366
+ out.write(`\r${" ".repeat(width)}\r`);
14367
+ width = 0;
14368
+ }
14369
+ };
14370
+ }
13407
14371
  function registerSetup(program2) {
13408
14372
  program2.command("setup").description(
13409
14373
  "One-shot onboarding: install workflow skills + base manifests to ~/.claude/ (immediate by default \u2014 use --dry-run for preview)"
@@ -13444,9 +14408,7 @@ function registerSetup(program2) {
13444
14408
  }
13445
14409
  const manifestPaths = await listBaseManifests2(pkgRoot);
13446
14410
  const forceFirstPass = raw.updateInstalled === true;
13447
- const progressPrinter = (ev) => {
13448
- console.log(` [${ev.done}/${ev.total}] ${ev.status} ${ev.name}`);
13449
- };
14411
+ const progress = makeProgressPrinter();
13450
14412
  console.log(
13451
14413
  `
13452
14414
  installing ${manifestPaths.length} upstream components (MCP serialized, rest parallel)...`
@@ -13454,8 +14416,9 @@ installing ${manifestPaths.length} upstream components (MCP serialized, rest par
13454
14416
  const b = await runStepBInstall(manifestPaths, {
13455
14417
  updateInstalled: forceFirstPass,
13456
14418
  quiet: true,
13457
- onProgress: progressPrinter
14419
+ onProgress: progress.onProgress
13458
14420
  });
14421
+ progress.done();
13459
14422
  const stepBMs = (b.elapsedMs / 1e3).toFixed(1);
13460
14423
  console.log(
13461
14424
  t("setup.step_b_complete", {
@@ -13483,8 +14446,9 @@ force-updating ${b.alreadyInstalled.length} plugin(s)...`);
13483
14446
  const b2 = await runStepBInstall(manifestPaths, {
13484
14447
  updateInstalled: true,
13485
14448
  quiet: true,
13486
- onProgress: progressPrinter
14449
+ onProgress: progress.onProgress
13487
14450
  });
14451
+ progress.done();
13488
14452
  const probe = await makeIdempotentProbe(manifestPaths);
13489
14453
  const reclass = await reclassifyForceUpdateFailures(b, b2, probe);
13490
14454
  b2.failed = reclass.failed;
@@ -14030,7 +14994,7 @@ var uninstallNpmCli = async (ctx) => {
14030
14994
  const m = install.cmd.match(/npm\s+(?:install|i)\s+(?:-g\s+)?(\S+)/);
14031
14995
  const pkg = m?.[1] ?? ctx.manifest.metadata.upstream.source;
14032
14996
  const isWin = process.platform === "win32";
14033
- const result = await new Promise((resolve21) => {
14997
+ const result = await new Promise((resolve23) => {
14034
14998
  const child = isWin ? spawn("cmd.exe", ["/c", "npm", "uninstall", "-g", pkg], { windowsHide: true }) : spawn("npm", ["uninstall", "-g", pkg], { shell: false });
14035
14999
  let stderr = "";
14036
15000
  child.stderr?.setEncoding("utf8").on("data", (c) => {
@@ -14038,15 +15002,15 @@ var uninstallNpmCli = async (ctx) => {
14038
15002
  });
14039
15003
  const timer = setTimeout(() => {
14040
15004
  child.kill("SIGKILL");
14041
- resolve21({ exitCode: -1, stderr: `${stderr}[timeout]` });
15005
+ resolve23({ exitCode: -1, stderr: `${stderr}[timeout]` });
14042
15006
  }, 3e4);
14043
15007
  child.on("error", (e) => {
14044
15008
  clearTimeout(timer);
14045
- resolve21({ exitCode: -1, stderr: e.message });
15009
+ resolve23({ exitCode: -1, stderr: e.message });
14046
15010
  });
14047
15011
  child.on("close", (code) => {
14048
15012
  clearTimeout(timer);
14049
- resolve21({ exitCode: code ?? -1, stderr });
15013
+ resolve23({ exitCode: code ?? -1, stderr });
14050
15014
  });
14051
15015
  });
14052
15016
  if (result.exitCode !== 0) {
@@ -14614,6 +15578,8 @@ registerRetro(program);
14614
15578
  registerInjectState(program);
14615
15579
  registerStopHook(program);
14616
15580
  registerEval(program);
15581
+ registerCheckDocs(program);
15582
+ registerFacts(program);
14617
15583
  var bare = parseBareInvocation(process.argv.slice(2));
14618
15584
  if (bare.here) {
14619
15585
  void runHere({ json: bare.json });