harnessed 4.37.0 → 4.38.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.
@@ -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.38.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
  });
@@ -8867,6 +9009,12 @@ function buildWorkflowStateBlock(wf, forward, ledgerAgeMs) {
8867
9009
  `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
9010
  );
8869
9011
  }
9012
+ const nextEntry = next ? ledger.find((e) => e.sub === next) : void 0;
9013
+ if (nextEntry?.reason && (nextEntry.fail_count ?? 0) > 0) {
9014
+ lines.push(
9015
+ `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.`
9016
+ );
9017
+ }
8870
9018
  if (!next && forward && (forward.unit.kind === "phase" || forward.unit.kind === "task")) {
8871
9019
  const n = forward.remainingPhases;
8872
9020
  lines.push(
@@ -11426,7 +11574,7 @@ init_gc();
11426
11574
  // src/cli/injectStateCmd.ts
11427
11575
  init_assetsRoot();
11428
11576
  function registerInjectState(program2) {
11429
- program2.command("inject-state").description("(internal) per-turn <workflow-state> hook output \u2014 used by the perturn hook").action(async () => {
11577
+ 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
11578
  try {
11431
11579
  const mjs = join(getAssetsRoot(), "bin", "harnessed-inject-state.mjs");
11432
11580
  if (!existsSync(mjs)) return;
@@ -14065,7 +14213,7 @@ var V3_4_3_SIGNATURE_MASTER_RX = /\*\*Preferred path\*\*[\s\S]*dispatch to the p
14065
14213
  function shouldOverwriteFile(content) {
14066
14214
  return HARNESSED_MARKER_RX2.test(content) || V3_4_3_SIGNATURE_SUB_RX.test(content) || V3_4_3_SIGNATURE_MASTER_RX.test(content);
14067
14215
  }
14068
- async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync22 = (p7) => readFileSync(p7, "utf8")) {
14216
+ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync23 = (p7) => readFileSync(p7, "utf8")) {
14069
14217
  const results = [];
14070
14218
  const aggregatedWarnings = /* @__PURE__ */ new Set();
14071
14219
  for (const name of slashNames) {
@@ -14084,7 +14232,7 @@ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabiliti
14084
14232
  if (fileExists2(path)) {
14085
14233
  let existing = "";
14086
14234
  try {
14087
- existing = readFileSync22(path);
14235
+ existing = readFileSync23(path);
14088
14236
  } catch {
14089
14237
  existing = "";
14090
14238
  }
@@ -15045,6 +15193,19 @@ function extractCloneTarget2(cmd) {
15045
15193
  }
15046
15194
  return dest;
15047
15195
  }
15196
+ function hasUncommittedWork(dir) {
15197
+ if (!existsSync(join(dir, ".git"))) return null;
15198
+ try {
15199
+ const status = execFileSync("git", ["status", "--porcelain"], {
15200
+ cwd: dir,
15201
+ encoding: "utf8",
15202
+ stdio: ["ignore", "pipe", "ignore"]
15203
+ });
15204
+ return status.trim().length > 0;
15205
+ } catch {
15206
+ return null;
15207
+ }
15208
+ }
15048
15209
  var uninstallGitCloneWithSetup = async (ctx) => {
15049
15210
  const install = ctx.manifest.spec.install;
15050
15211
  if (install.method !== "git-clone-with-setup") {
@@ -15060,6 +15221,13 @@ var uninstallGitCloneWithSetup = async (ctx) => {
15060
15221
  error: `git-clone-with-setup cmd missing parseable 'git clone <url> <dest>': '${install.cmd.slice(0, 80)}'`
15061
15222
  };
15062
15223
  }
15224
+ if (process.env.HARNESSED_FORCE_UNINSTALL !== "1" && hasUncommittedWork(cloneTarget) === true) {
15225
+ return {
15226
+ ok: false,
15227
+ phase: "preflight",
15228
+ 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.`
15229
+ };
15230
+ }
15063
15231
  await rm(cloneTarget, { recursive: true, force: true, maxRetries: 3 });
15064
15232
  return { ok: true, removedPaths: [cloneTarget] };
15065
15233
  };