harnessed 4.37.0 → 4.39.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 (31) hide show
  1. package/bin/harnessed-inject-state.mjs +22 -2
  2. package/dist/cli.mjs +258 -10
  3. package/dist/cli.mjs.map +1 -1
  4. package/dist/index.mjs +1 -1
  5. package/dist/index.mjs.map +1 -1
  6. package/manifests/optional/perturn-inject-invalidate.yaml +57 -0
  7. package/package.json +1 -1
  8. package/workflows/capabilities.yaml +110 -110
  9. package/workflows/defaults.yaml +17 -7
  10. package/workflows/discuss/phase/workflow.yaml +0 -1
  11. package/workflows/discuss/strategic/workflow.yaml +0 -2
  12. package/workflows/discuss/subtask/workflow.yaml +0 -1
  13. package/workflows/judgments/stage-routing.yaml +10 -0
  14. package/workflows/plan/architecture/workflow.yaml +0 -1
  15. package/workflows/plan/phase/workflow.yaml +0 -1
  16. package/workflows/research/workflow.yaml +0 -6
  17. package/workflows/retro/workflow.yaml +0 -1
  18. package/workflows/task/clarify/workflow.yaml +0 -1
  19. package/workflows/task/code/workflow.yaml +0 -1
  20. package/workflows/task/deliver/workflow.yaml +0 -1
  21. package/workflows/task/test/workflow.yaml +0 -1
  22. package/workflows/verify/auto/SKILL.md +11 -0
  23. package/workflows/verify/auto/SKILL.zh-Hans.md +11 -0
  24. package/workflows/verify/auto/workflow.yaml +10 -1
  25. package/workflows/verify/code-review/workflow.yaml +0 -1
  26. package/workflows/verify/paranoid/workflow.yaml +0 -1
  27. package/workflows/verify/progress/workflow.yaml +0 -1
  28. package/workflows/verify/second-opinion/SKILL.md +89 -0
  29. package/workflows/verify/second-opinion/SKILL.zh-Hans.md +88 -0
  30. package/workflows/verify/second-opinion/workflow.yaml +50 -0
  31. package/workflows/verify/simplify/workflow.yaml +0 -1
@@ -11,7 +11,7 @@ import { dirname, join as join4, resolve } from 'node:path'
11
11
 
12
12
  // src/checkpoint/injectCache.ts
13
13
  import { createHash } from 'node:crypto'
14
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
14
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
15
15
  import { join } from 'node:path'
16
16
  var DEFAULT_REFRESH_TURNS = 10
17
17
  function decidePcEmission(cache, pcHash, refreshN, nowMs) {
@@ -56,6 +56,14 @@ function writeInjectCache(root, key, entry) {
56
56
  return false
57
57
  }
58
58
  }
59
+ function invalidateInjectCache(root) {
60
+ try {
61
+ rmSync(join(root, 'inject-cache'), { recursive: true, force: true })
62
+ return true
63
+ } catch {
64
+ return false
65
+ }
66
+ }
59
67
 
60
68
  // src/checkpoint/injectState.ts
61
69
  import {
@@ -238,6 +246,12 @@ function buildWorkflowStateBlock(wf, forward, ledgerAgeMs) {
238
246
  `ENGINE: mid state-machine \u2014 drive sub '${next}' via \`harnessed prompt ${next}\` \u2192 spawn \u2192 \`harnessed checkpoint complete/fail\`. Do NOT freestyle the orchestration or skip the ledger; run \`harnessed status --recover\` if unsure where you are.`,
239
247
  )
240
248
  }
249
+ const nextEntry = next ? ledger.find((e) => e.sub === next) : void 0
250
+ if (nextEntry?.reason && (nextEntry.fail_count ?? 0) > 0) {
251
+ lines.push(
252
+ `REOPENED: sub '${next}' was sent back (attempt ${nextEntry.fail_count}${nextEntry.attempt_budget !== void 0 ? `/${nextEntry.attempt_budget}` : ''}) \u2014 ${nextEntry.reason}. Address THAT before re-running it; a repeat of the same attempt burns the budget.`,
253
+ )
254
+ }
241
255
  if (!next && forward && (forward.unit.kind === 'phase' || forward.unit.kind === 'task')) {
242
256
  const n = forward.remainingPhases
243
257
  lines.push(
@@ -455,6 +469,10 @@ function shouldEmitPc(root, repoRoot, sid, pc) {
455
469
  function main() {
456
470
  try {
457
471
  const root = harnessedRoot()
472
+ if (process.argv.includes('--invalidate')) {
473
+ invalidateInjectCache(root)
474
+ return
475
+ }
458
476
  const key = repoKey(process.cwd())
459
477
  const envName = sessionIdEnvName()
460
478
  const sid = envName ? process.env[envName]?.trim() : void 0
@@ -464,9 +482,11 @@ function main() {
464
482
  learningsMd = readFileSync4(join4(key, '.planning', 'LEARNINGS.md'), 'utf8')
465
483
  } catch {}
466
484
  const budget = Number(process.env.HARNESSED_INJECT_BUDGET) || DEFAULT_INJECT_BUDGET
485
+ const pcOff = process.env.HARNESSED_INJECT_PC_OFF === '1'
486
+ const pcGate = pcOff ? () => false : sid ? (pc) => shouldEmitPc(root, key, sid, pc) : void 0
467
487
  const out = buildInjection(key, wf, learningsMd, budget, intent, Date.now(), {
468
488
  ledgerAgeMs,
469
- pcGate: sid ? (pc) => shouldEmitPc(root, key, sid, pc) : void 0,
489
+ pcGate,
470
490
  })
471
491
  if (out)
472
492
  process.stdout.write(`${out}
package/dist/cli.mjs CHANGED
@@ -38,7 +38,7 @@ var init_package = __esm({
38
38
  "package.json"() {
39
39
  package_default = {
40
40
  name: "harnessed",
41
- version: "4.37.0",
41
+ version: "4.39.0",
42
42
  description: "AI coding harness package manager + composition orchestrator",
43
43
  type: "module",
44
44
  license: "Apache-2.0",
@@ -881,6 +881,7 @@ __export(ledger_exports, {
881
881
  findSerialBlockers: () => findSerialBlockers,
882
882
  markSub: () => markSub,
883
883
  nextPending: () => nextPending,
884
+ reopenSub: () => reopenSub,
884
885
  seedLedger: () => seedLedger
885
886
  });
886
887
  function seedLedger(plan) {
@@ -928,6 +929,27 @@ function markSub(entries, sub, status, opts) {
928
929
  next[idx] = updated;
929
930
  return next;
930
931
  }
932
+ function reopenSub(entries, sub, reason) {
933
+ const idx = entries.findIndex((e) => e.sub === sub);
934
+ if (idx === -1) {
935
+ throw new Error(
936
+ `reopenSub: sub '${sub}' not found in ledger (${entries.length} entries). It must be seeded before it can be reopened.`
937
+ );
938
+ }
939
+ const current = entries[idx];
940
+ if (current.status === "pending") {
941
+ throw new Error(`reopenSub: sub '${sub}' is already pending \u2014 nothing to send back.`);
942
+ }
943
+ const { evidence, evidence_status, completion_claim, ...rest } = current;
944
+ const next = entries.slice();
945
+ next[idx] = {
946
+ ...rest,
947
+ status: "pending",
948
+ fail_count: (current.fail_count ?? 0) + 1,
949
+ reason
950
+ };
951
+ return next;
952
+ }
931
953
  function nextPending(entries) {
932
954
  return entries.find((e) => e.status === "pending")?.sub ?? null;
933
955
  }
@@ -3743,6 +3765,7 @@ __export(checkpoint_exports, {
3743
3765
  registerCheckpoint: () => registerCheckpoint,
3744
3766
  runCheckpointComplete: () => runCheckpointComplete,
3745
3767
  runCheckpointFail: () => runCheckpointFail,
3768
+ runCheckpointReopen: () => runCheckpointReopen,
3746
3769
  runCheckpointStart: () => runCheckpointStart
3747
3770
  });
3748
3771
  function isAction(a) {
@@ -4081,9 +4104,62 @@ async function runCheckpointFail(sub, opts, deps = defaultRunDeps) {
4081
4104
  deps.exit(1);
4082
4105
  return;
4083
4106
  }
4107
+ async function runCheckpointReopen(sub, opts, deps = defaultRunDeps) {
4108
+ const reason = opts.reason?.trim();
4109
+ if (!reason) {
4110
+ deps.error(
4111
+ "[harnessed] checkpoint reopen: --reason <text> is required (why is it coming back?)"
4112
+ );
4113
+ deps.exit(1);
4114
+ return;
4115
+ }
4116
+ const { readCurrentWorkflow: readCurrentWorkflow2, mutateSubProgress: mutateSubProgress2, writeCurrentWorkflow: writeCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
4117
+ const wf = await readCurrentWorkflow2();
4118
+ if (!wf) {
4119
+ deps.error("[harnessed] checkpoint reopen: no active workflow \u2014 nothing to send back.");
4120
+ deps.exit(1);
4121
+ return;
4122
+ }
4123
+ const entries = wf.sub_progress ?? [];
4124
+ const { reopenSub: reopenSub2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
4125
+ try {
4126
+ reopenSub2(entries, sub, reason);
4127
+ } catch (e) {
4128
+ deps.error(`[harnessed] checkpoint reopen: ${e.message}`);
4129
+ deps.exit(1);
4130
+ return;
4131
+ }
4132
+ await mutateSubProgress2((e) => reopenSub2(e, sub, reason));
4133
+ if (wf.status === "complete") {
4134
+ await writeCurrentWorkflow2({ ...wf, status: "active" });
4135
+ }
4136
+ const latest = await readCurrentWorkflow2();
4137
+ const entry = latest?.sub_progress?.find((e) => e.sub === sub);
4138
+ const attempts = entry?.fail_count ?? 0;
4139
+ const budget = entry?.attempt_budget;
4140
+ if (budget !== void 0) {
4141
+ const { isBudgetExhausted: isBudgetExhausted2 } = await Promise.resolve().then(() => (init_budget(), budget_exports));
4142
+ if (isBudgetExhausted2(attempts, budget)) {
4143
+ deps.error(
4144
+ `[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.`
4145
+ );
4146
+ }
4147
+ }
4148
+ const { detectLoop: detectLoop2, LOOP_THRESHOLD: LOOP_THRESHOLD2 } = await Promise.resolve().then(() => (init_breakLoop(), breakLoop_exports));
4149
+ const looped = detectLoop2(latest?.sub_progress ?? []).find((l) => l.sub === sub);
4150
+ if (looped) {
4151
+ deps.error(
4152
+ `[harnessed] BREAK-LOOP: sub '${sub}' has been sent back / failed ${looped.count}x (>= ${LOOP_THRESHOLD2}). Stop retrying \u2014 run the break-loop skill for root-cause analysis and capture the lesson to .planning/.`
4153
+ );
4154
+ }
4155
+ deps.log(
4156
+ `[harnessed] checkpoint reopen: ${sub} \u2192 pending (attempt ${attempts}${budget !== void 0 ? `/${budget}` : ""}) \u2014 ${reason}`
4157
+ );
4158
+ deps.exit(0);
4159
+ }
4084
4160
  function registerCheckpoint(program2) {
4085
4161
  program2.command("checkpoint <action> <sub>").description(
4086
- "Record workflow progress: intent | start | complete | fail <sub-workflow> (writes to ~/.claude/harnessed/checkpoints/)"
4162
+ "Record workflow progress: intent | start | complete | fail | reopen <sub-workflow> (writes to ~/.claude/harnessed/checkpoints/)"
4087
4163
  ).option("--summary <text>", "short summary stored as the checkpoint lastTask").option("--plan <json>", "gates plan JSON (start only) \u2014 seeds the sub-progress ledger").option(
4088
4164
  "--force",
4089
4165
  "complete/fail \u2014 override a fail-closed guard: the missing-artifact evidence block (complete; records overridden) or the serial-order guard"
@@ -4096,6 +4172,9 @@ function registerCheckpoint(program2) {
4096
4172
  ).option(
4097
4173
  "--result-file <path>",
4098
4174
  "complete only \u2014 same as --result but read from a file (quoting-safe on Windows); wins over --result"
4175
+ ).option(
4176
+ "--reason <text>",
4177
+ "reopen only \u2014 why the sub is coming back (required); recorded on the ledger entry and surfaced by the per-turn injector"
4099
4178
  ).option(
4100
4179
  "--failing-tests <n>",
4101
4180
  "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)"
@@ -4147,6 +4226,10 @@ function registerCheckpoint(program2) {
4147
4226
  await runCheckpointComplete(sub, opts);
4148
4227
  return;
4149
4228
  }
4229
+ if (action === "reopen") {
4230
+ await runCheckpointReopen(sub, opts);
4231
+ return;
4232
+ }
4150
4233
  await runCheckpointFail(sub, opts);
4151
4234
  }
4152
4235
  );
@@ -4157,7 +4240,7 @@ var init_checkpoint = __esm({
4157
4240
  init_path_guard();
4158
4241
  init_runDeps();
4159
4242
  init_ledger();
4160
- ACTIONS = ["start", "complete", "fail", "intent"];
4243
+ ACTIONS = ["start", "complete", "fail", "reopen", "intent"];
4161
4244
  }
4162
4245
  });
4163
4246
  function realProbe(p7) {
@@ -5914,6 +5997,61 @@ var init_check_ecc = __esm({
5914
5997
  }
5915
5998
  });
5916
5999
 
6000
+ // src/cli/lib/check-inject-invalidate.ts
6001
+ var check_inject_invalidate_exports = {};
6002
+ __export(check_inject_invalidate_exports, {
6003
+ checkInjectInvalidate: () => checkInjectInvalidate
6004
+ });
6005
+ function commandsFor(hooks, event) {
6006
+ const arr = hooks?.[event];
6007
+ if (!Array.isArray(arr)) return [];
6008
+ return arr.flatMap((e) => entryCommands(e));
6009
+ }
6010
+ function checkInjectInvalidate(deps) {
6011
+ const settingsPath = deps?.settingsPath ?? getSettingsPath();
6012
+ const readText = deps?.readText ?? ((p7) => {
6013
+ try {
6014
+ return readFileSync(p7, "utf8");
6015
+ } catch {
6016
+ return null;
6017
+ }
6018
+ });
6019
+ const raw = readText(settingsPath);
6020
+ if (raw === null) return { name: NAME3, status: "pass", message: "no settings.json" };
6021
+ let hooks;
6022
+ try {
6023
+ const data = JSON.parse(raw);
6024
+ hooks = data.hooks && typeof data.hooks === "object" ? data.hooks : void 0;
6025
+ } catch {
6026
+ return { name: NAME3, status: "pass", message: "settings.json unreadable \u2014 skipped" };
6027
+ }
6028
+ const isInject = (c) => c.includes("inject-state");
6029
+ const perTurn = commandsFor(hooks, "UserPromptSubmit").some(isInject);
6030
+ if (!perTurn) {
6031
+ return { name: NAME3, status: "pass", message: "per-turn injection not installed" };
6032
+ }
6033
+ const paired = commandsFor(hooks, "SessionStart").some(
6034
+ (c) => isInject(c) && c.includes("--invalidate")
6035
+ );
6036
+ if (paired) {
6037
+ return { name: NAME3, status: "pass", message: "per-turn injection + SessionStart invalidation" };
6038
+ }
6039
+ return {
6040
+ name: NAME3,
6041
+ status: "warn",
6042
+ message: "perturn-inject is installed without its SessionStart invalidation half \u2014 after a compact/clear the delta cache keeps skipping <project-context> for up to HARNESSED_INJECT_REFRESH_TURNS turns",
6043
+ fix: "harnessed install perturn-inject-invalidate"
6044
+ };
6045
+ }
6046
+ var NAME3;
6047
+ var init_check_inject_invalidate = __esm({
6048
+ "src/cli/lib/check-inject-invalidate.ts"() {
6049
+ init_hookEntry();
6050
+ init_platform();
6051
+ NAME3 = "per-turn inject pairing";
6052
+ }
6053
+ });
6054
+
5917
6055
  // src/cli/lib/doctor-registry.ts
5918
6056
  var CHECKS;
5919
6057
  var init_doctor_registry = __esm({
@@ -5965,7 +6103,11 @@ var init_doctor_registry = __esm({
5965
6103
  // 4.32.22 — ECC per-harness detect (optional; pass unless CC-side ecc overlaps
5966
6104
  // the official chrome-devtools-mcp plugin → warn). CC plugin registry + codex
5967
6105
  // sync-clone probed independently.
5968
- async () => (await Promise.resolve().then(() => (init_check_ecc(), check_ecc_exports))).checkEcc()
6106
+ async () => (await Promise.resolve().then(() => (init_check_ecc(), check_ecc_exports))).checkEcc(),
6107
+ // 4.38.0 — half-installed per-turn injection (warn-only): perturn-inject
6108
+ // without perturn-inject-invalidate keeps skipping <project-context> after a
6109
+ // compact/clear has already dropped the copy it is skipping on behalf of.
6110
+ async () => (await Promise.resolve().then(() => (init_check_inject_invalidate(), check_inject_invalidate_exports))).checkInjectInvalidate()
5969
6111
  ];
5970
6112
  }
5971
6113
  });
@@ -6240,6 +6382,13 @@ function buildDefaultGateContext(task, stage) {
6240
6382
  // `harnessed gates --context-file`, and through `harnessed run`'s awaited
6241
6383
  // probe overlay.
6242
6384
  chrome_devtools_available: true,
6385
+ // Phase 54 T3 — seeded FALSE, the opposite of the line above and for the
6386
+ // same reason read the other way: this builder is synchronous and cannot
6387
+ // shell out to git, so the honest default is the direction where being
6388
+ // wrong costs least. Unknown must not ADD a review step — a gate that
6389
+ // fires when it cannot justify itself becomes noise, and noise gets
6390
+ // ignored. The measured value arrives via `harnessed facts`.
6391
+ requires_second_opinion: false,
6243
6392
  phase: {
6244
6393
  stage,
6245
6394
  // T2.1 OQ2(c) — withdrawn: gated stage-routing.verify-paranoid-critical,
@@ -8867,6 +9016,12 @@ function buildWorkflowStateBlock(wf, forward, ledgerAgeMs) {
8867
9016
  `ENGINE: mid state-machine \u2014 drive sub '${next}' via \`harnessed prompt ${next}\` \u2192 spawn \u2192 \`harnessed checkpoint complete/fail\`. Do NOT freestyle the orchestration or skip the ledger; run \`harnessed status --recover\` if unsure where you are.`
8868
9017
  );
8869
9018
  }
9019
+ const nextEntry = next ? ledger.find((e) => e.sub === next) : void 0;
9020
+ if (nextEntry?.reason && (nextEntry.fail_count ?? 0) > 0) {
9021
+ lines.push(
9022
+ `REOPENED: sub '${next}' was sent back (attempt ${nextEntry.fail_count}${nextEntry.attempt_budget !== void 0 ? `/${nextEntry.attempt_budget}` : ""}) \u2014 ${nextEntry.reason}. Address THAT before re-running it; a repeat of the same attempt burns the budget.`
9023
+ );
9024
+ }
8870
9025
  if (!next && forward && (forward.unit.kind === "phase" || forward.unit.kind === "task")) {
8871
9026
  const n = forward.remainingPhases;
8872
9027
  lines.push(
@@ -11235,6 +11390,41 @@ function deriveGitFacts(run) {
11235
11390
  files_touched: sawNames && files.size > 0 ? files.size : null
11236
11391
  };
11237
11392
  }
11393
+ var NEWLINE_RE = new RegExp(String.fromCharCode(13) + "?" + String.fromCharCode(10));
11394
+ var ORCHESTRATION_SURFACE = [
11395
+ "workflows/judgments/",
11396
+ "workflows/capabilities.yaml",
11397
+ "workflows/role-prompts",
11398
+ "workflows/disciplines/",
11399
+ "workflows/defaults.yaml",
11400
+ "src/workflow/schema/phaseFactContext.ts",
11401
+ "src/workflow/judgmentResolver.ts",
11402
+ "src/workflow/exprBuilder.ts",
11403
+ "src/cli/facts.ts",
11404
+ "src/checkpoint/ledger.ts"
11405
+ ];
11406
+ function onOrchestrationSurface(path) {
11407
+ const p7 = path.split(String.fromCharCode(92)).join("/").trim();
11408
+ if (p7 === "") return false;
11409
+ if (/^workflows\/.+\/SKILL(\.[A-Za-z-]+)?\.md$/.test(p7)) return true;
11410
+ return ORCHESTRATION_SURFACE.some((s) => s.endsWith("/") ? p7.startsWith(s) : p7 === s);
11411
+ }
11412
+ function deriveSecondOpinion(run) {
11413
+ const tagOut = run(["describe", "--tags", "--abbrev=0"]);
11414
+ const tag = tagOut === null ? null : tagOut.trim();
11415
+ if (!tag) {
11416
+ return {
11417
+ fires: false,
11418
+ reason: "no release tag found (git describe --tags failed or the repo has no tags)"
11419
+ };
11420
+ }
11421
+ const diff = run(["diff", "--name-only", tag]);
11422
+ if (diff === null) {
11423
+ return { fires: false, reason: `git diff --name-only ${tag} failed` };
11424
+ }
11425
+ const fires = diff.split(NEWLINE_RE).some(onOrchestrationSurface);
11426
+ return { fires, reason: null };
11427
+ }
11238
11428
  function defaultGitRun(args) {
11239
11429
  try {
11240
11430
  return execFileSync("git", args, {
@@ -11343,6 +11533,9 @@ function buildFactsEnvelope(master, gatedNames, derived) {
11343
11533
  usage: `Fill every null in \`facts\` with your honest judgement (leave a fact null to accept harnessed's default), write that object to a file, then run: harnessed gates ${master} --task "<locked spec>" --context-file <path>. The output of this command can be passed back verbatim \u2014 the envelope is unwrapped automatically.`
11344
11534
  };
11345
11535
  }
11536
+ function secondOpinionFromGit() {
11537
+ return deriveSecondOpinion(defaultGitRun);
11538
+ }
11346
11539
  async function runFactsPlan(master, raw, deps = defaultRunDeps, gitRun = defaultGitRun, probeCdt = () => probeChromeDevtools()) {
11347
11540
  if (!VALID_MASTERS2.has(master)) {
11348
11541
  deps.error(
@@ -11370,6 +11563,7 @@ async function runFactsPlan(master, raw, deps = defaultRunDeps, gitRun = default
11370
11563
  return;
11371
11564
  }
11372
11565
  const git = deriveGitFacts(gitRun);
11566
+ const secondOpinion = deriveSecondOpinion(gitRun);
11373
11567
  const cdt = await probeCdt();
11374
11568
  const derived = {
11375
11569
  // `harnessed gates` seeds phase.stage from the master argument, so facts MUST
@@ -11394,6 +11588,14 @@ async function runFactsPlan(master, raw, deps = defaultRunDeps, gitRun = default
11394
11588
  chrome_devtools_available: {
11395
11589
  value: chromeDevtoolsAvailable(cdt),
11396
11590
  source: chromeDevtoolsFactSource(cdt)
11591
+ },
11592
+ // Phase 54 T3 — root-flat, sister chrome_devtools_available above. `source`
11593
+ // doubles as the UNAVAILABLE REASON: when the criterion cannot be computed
11594
+ // the value is false AND the reason says why, so a repo that can never
11595
+ // answer is visibly unavailable rather than quietly never firing.
11596
+ requires_second_opinion: {
11597
+ value: secondOpinion.fires,
11598
+ source: secondOpinion.reason === null ? "git diff --name-only <last release tag> \u2229 orchestration surface (judgments/capabilities/facts/resolver/ledger/disciplines/SKILL.md)" : `criterion unavailable \u2014 ${secondOpinion.reason}`
11397
11599
  }
11398
11600
  };
11399
11601
  const envelope = buildFactsEnvelope(master, gated, derived);
@@ -11426,7 +11628,7 @@ init_gc();
11426
11628
  // src/cli/injectStateCmd.ts
11427
11629
  init_assetsRoot();
11428
11630
  function registerInjectState(program2) {
11429
- program2.command("inject-state").description("(internal) per-turn <workflow-state> hook output \u2014 used by the perturn hook").action(async () => {
11631
+ program2.command("inject-state").description("(internal) per-turn <workflow-state> hook output \u2014 used by the perturn hook").option("--invalidate", "(internal) drop the per-session <project-context> delta cache").action(async () => {
11430
11632
  try {
11431
11633
  const mjs = join(getAssetsRoot(), "bin", "harnessed-inject-state.mjs");
11432
11634
  if (!existsSync(mjs)) return;
@@ -12829,7 +13031,7 @@ function isRalphLoopOptIn(phase) {
12829
13031
  if (fb?.max_iterations_exceeded !== void 0) return true;
12830
13032
  return false;
12831
13033
  }
12832
- function resolveMaxIterations(phase, gateContext) {
13034
+ function resolveMaxIterations(phase, gateContext, fromDefaults) {
12833
13035
  const fromCli = typeof gateContext.maxIterations === "number" ? gateContext.maxIterations : void 0;
12834
13036
  let fromYaml;
12835
13037
  if (phase && typeof phase === "object") {
@@ -12840,7 +13042,8 @@ function resolveMaxIterations(phase, gateContext) {
12840
13042
  if (Number.isFinite(n) && n > 0) fromYaml = n;
12841
13043
  }
12842
13044
  }
12843
- const chosen = fromCli ?? fromYaml ?? RALPH_DEFAULT_MAX_ITER;
13045
+ const fromTable = typeof fromDefaults === "number" && Number.isFinite(fromDefaults) && fromDefaults > 0 ? fromDefaults : void 0;
13046
+ const chosen = fromCli ?? fromYaml ?? fromTable ?? RALPH_DEFAULT_MAX_ITER;
12844
13047
  return Math.min(Math.max(1, chosen), RALPH_HARD_UPPER_LIMIT);
12845
13048
  }
12846
13049
  var _dispatchSkillStub = {
@@ -12902,11 +13105,31 @@ var _dispatchSkillStub = {
12902
13105
  };
12903
13106
  }
12904
13107
  };
13108
+ function loadMaxIterTable(packageRoot) {
13109
+ try {
13110
+ const doc = parse(
13111
+ readFileSync(join(packageRoot, "workflows", "defaults.yaml"), "utf8")
13112
+ );
13113
+ const out = {};
13114
+ for (const [wf, phases] of Object.entries(doc?.ralph_max_iterations ?? {})) {
13115
+ if (!phases || typeof phases !== "object") continue;
13116
+ const row = {};
13117
+ for (const [id, v] of Object.entries(phases)) {
13118
+ if (typeof v === "number" && Number.isFinite(v) && v > 0) row[id] = v;
13119
+ }
13120
+ out[wf] = row;
13121
+ }
13122
+ return out;
13123
+ } catch {
13124
+ return {};
13125
+ }
13126
+ }
12905
13127
  async function runWorkflow(yamlPath, vars, opts = {}) {
12906
13128
  const parsed = loadPhases(yamlPath, vars);
12907
13129
  const yamlDir = dirname(resolve(yamlPath));
12908
13130
  const inferredRoot = resolve(yamlDir, "..", "..");
12909
13131
  const packageRoot = opts.packageRoot ?? inferredRoot;
13132
+ const maxIterTable = loadMaxIterTable(packageRoot);
12910
13133
  const gateContext = { ...opts.gateContext ?? {} };
12911
13134
  let rolePrompts = {};
12912
13135
  try {
@@ -12985,7 +13208,7 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
12985
13208
  }
12986
13209
  }
12987
13210
  const skillName = "skills" in ph && ph.skills?.[0] || ph.id;
12988
- const maxIter = resolveMaxIterations(ph, gateContext);
13211
+ const maxIter = resolveMaxIterations(ph, gateContext, maxIterTable[workflowName]?.[ph.id]);
12989
13212
  const fallback = "fallback" in ph && ph.fallback?.max_iterations_exceeded ? ph.fallback.max_iterations_exceeded : void 0;
12990
13213
  const r = await _dispatchSkillStub.fn(skillName, ph, {
12991
13214
  maxIter,
@@ -13564,6 +13787,11 @@ function registerRun(program2) {
13564
13787
  // overlay the MEASURED value (never throws; unknown still resolves true —
13565
13788
  // see src/cli/lib/probe-chrome-devtools.ts).
13566
13789
  chrome_devtools_available: await isChromeDevtoolsAvailable(),
13790
+ // Phase 54 T3 — same treatment, opposite default: the synchronous builder
13791
+ // seeds `false` (unknown must not add work), so overlay the MEASURED value
13792
+ // here. Never throws — an unavailable criterion resolves false and the
13793
+ // reason surfaces through `harnessed facts` and the per-turn breadcrumb.
13794
+ requires_second_opinion: secondOpinionFromGit().fires,
13567
13795
  ...raw.model ? { modelOverride: raw.model } : {},
13568
13796
  ...raw.maxIterations ? { maxIterations: raw.maxIterations } : {},
13569
13797
  ...raw.staged ? { staged: true } : {},
@@ -14065,7 +14293,7 @@ var V3_4_3_SIGNATURE_MASTER_RX = /\*\*Preferred path\*\*[\s\S]*dispatch to the p
14065
14293
  function shouldOverwriteFile(content) {
14066
14294
  return HARNESSED_MARKER_RX2.test(content) || V3_4_3_SIGNATURE_SUB_RX.test(content) || V3_4_3_SIGNATURE_MASTER_RX.test(content);
14067
14295
  }
14068
- async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync22 = (p7) => readFileSync(p7, "utf8")) {
14296
+ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync24 = (p7) => readFileSync(p7, "utf8")) {
14069
14297
  const results = [];
14070
14298
  const aggregatedWarnings = /* @__PURE__ */ new Set();
14071
14299
  for (const name of slashNames) {
@@ -14084,7 +14312,7 @@ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabiliti
14084
14312
  if (fileExists2(path)) {
14085
14313
  let existing = "";
14086
14314
  try {
14087
- existing = readFileSync22(path);
14315
+ existing = readFileSync24(path);
14088
14316
  } catch {
14089
14317
  existing = "";
14090
14318
  }
@@ -15045,6 +15273,19 @@ function extractCloneTarget2(cmd) {
15045
15273
  }
15046
15274
  return dest;
15047
15275
  }
15276
+ function hasUncommittedWork(dir) {
15277
+ if (!existsSync(join(dir, ".git"))) return null;
15278
+ try {
15279
+ const status = execFileSync("git", ["status", "--porcelain"], {
15280
+ cwd: dir,
15281
+ encoding: "utf8",
15282
+ stdio: ["ignore", "pipe", "ignore"]
15283
+ });
15284
+ return status.trim().length > 0;
15285
+ } catch {
15286
+ return null;
15287
+ }
15288
+ }
15048
15289
  var uninstallGitCloneWithSetup = async (ctx) => {
15049
15290
  const install = ctx.manifest.spec.install;
15050
15291
  if (install.method !== "git-clone-with-setup") {
@@ -15060,6 +15301,13 @@ var uninstallGitCloneWithSetup = async (ctx) => {
15060
15301
  error: `git-clone-with-setup cmd missing parseable 'git clone <url> <dest>': '${install.cmd.slice(0, 80)}'`
15061
15302
  };
15062
15303
  }
15304
+ if (process.env.HARNESSED_FORCE_UNINSTALL !== "1" && hasUncommittedWork(cloneTarget) === true) {
15305
+ return {
15306
+ ok: false,
15307
+ phase: "preflight",
15308
+ error: `'${cloneTarget}' has uncommitted changes \u2014 refusing to delete it. Commit or copy the work out first, then re-run; set HARNESSED_FORCE_UNINSTALL=1 to delete it anyway.`
15309
+ };
15310
+ }
15063
15311
  await rm(cloneTarget, { recursive: true, force: true, maxRetries: 3 });
15064
15312
  return { ok: true, removedPaths: [cloneTarget] };
15065
15313
  };