harnessed 4.23.2 → 4.25.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.
@@ -13,7 +13,8 @@
13
13
  // Phase 15 repo-aware: resolves the active repo's slot from
14
14
  // workflows.json[repoKey(cwd)] (legacy current-workflow.json as a fallback).
15
15
  // Root: HARNESSED_ROOT_OVERRIDE if set, else <homedir>/.claude/harnessed.
16
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
16
+ import { createHash } from 'node:crypto'
17
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
17
18
  import { homedir } from 'node:os'
18
19
  import { dirname, join, resolve } from 'node:path'
19
20
 
@@ -50,6 +51,60 @@ function sessionIdEnvName() {
50
51
  return 'CLAUDE_CODE_SESSION_ID' // claude (default)
51
52
  }
52
53
 
54
+ // ── 4.25.0 (intel B1) — session-scoped delta cache for <project-context>.
55
+ // Inline mirror of src/checkpoint/injectCache.ts (this file is self-contained
56
+ // plain JS by contract); the delta cells in tests/checkpoint/injectState.test.ts
57
+ // hold the two implementations together. Fail-soft: the cache may only ever
58
+ // SAVE tokens, never lose context — a skip is honored only when the
59
+ // incremented entry was persisted (else `turns` would freeze and the periodic
60
+ // compaction-hedge refresh would never fire). ──
61
+
62
+ const DEFAULT_REFRESH_TURNS = 10
63
+
64
+ function parseRefreshTurns(raw) {
65
+ const n = Number.parseInt(raw ?? '', 10)
66
+ return Number.isInteger(n) && n > 0 ? n : DEFAULT_REFRESH_TURNS
67
+ }
68
+
69
+ function decidePcEmission(cache, pcHash, refreshN, nowMs) {
70
+ if (cache && cache.pcHash === pcHash && cache.turns < refreshN) {
71
+ return { emit: false, next: { pcHash, ts: cache.ts, turns: cache.turns + 1 } }
72
+ }
73
+ return { emit: true, next: { pcHash, ts: nowMs, turns: 0 } }
74
+ }
75
+
76
+ /** true ⇔ the full pc block should be emitted this turn (default on ANY trouble). */
77
+ function shouldEmitPc(root, repoRoot, sid, pc) {
78
+ try {
79
+ const key = createHash('sha256').update(`${repoRoot}::${sid}`).digest('hex').slice(0, 16)
80
+ const file = join(root, 'inject-cache', `${key}.json`)
81
+ let cache = null
82
+ try {
83
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
84
+ if (
85
+ parsed &&
86
+ typeof parsed.pcHash === 'string' &&
87
+ typeof parsed.ts === 'number' &&
88
+ typeof parsed.turns === 'number'
89
+ ) {
90
+ cache = parsed
91
+ }
92
+ } catch {}
93
+ const pcHash = createHash('sha256').update(pc).digest('hex')
94
+ const refreshN = parseRefreshTurns(process.env.HARNESSED_INJECT_REFRESH_TURNS)
95
+ const d = decidePcEmission(cache, pcHash, refreshN, Date.now())
96
+ try {
97
+ mkdirSync(join(root, 'inject-cache'), { recursive: true })
98
+ writeFileSync(file, `${JSON.stringify(d.next)}\n`, 'utf8')
99
+ } catch {
100
+ return true // could not persist the increment — never skip on an unpersisted decision
101
+ }
102
+ return d.emit
103
+ } catch {
104
+ return true
105
+ }
106
+ }
107
+
53
108
  // Phase 35 — try the session-scoped slot first, then the bare repoKey slot, then
54
109
  // the legacy singleton (dual-write anchor). `keys` is ordered most→least specific.
55
110
  // 4.22.0 — also surfaces the intent sidecar (same key order) for the freestyle nag.
@@ -371,7 +426,13 @@ try {
371
426
  )
372
427
  const used = rel.reduce((a, e) => a + tok(e.raw), 0)
373
428
  const ctx = findPhaseContextExcerpt(key, wf.phase, Math.max(0, budget - used))
374
- const pc = projectContextBlock(rel, ctx ?? undefined)
429
+ let pc = projectContextBlock(rel, ctx ?? undefined)
430
+
431
+ // 4.25.0 (intel B1) — same session + byte-identical pc already injected on a
432
+ // recent turn → skip it (the content is in the conversation); periodic
433
+ // refresh + hash-miss re-emission handled by the cache decision. No sid or
434
+ // any cache trouble → full injection, byte-identical to pre-4.25.0.
435
+ if (pc && sid && !shouldEmitPc(root, key, sid, pc)) pc = ''
375
436
 
376
437
  const normal = pc ? `${ws}\n${pc}` : ws
377
438
  process.stdout.write(`${ib ? `${ib}\n${normal}` : normal}\n`)
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.23.2",
41
+ version: "4.25.0",
42
42
  description: "AI coding harness package manager + composition orchestrator",
43
43
  type: "module",
44
44
  license: "Apache-2.0",
@@ -6016,6 +6016,7 @@ __export(skillIntegrity_exports, {
6016
6016
  attachCulprits: () => attachCulprits,
6017
6017
  auditInstalledSkills: () => auditInstalledSkills,
6018
6018
  buildCulpritIndex: () => buildCulpritIndex,
6019
+ healPreviewFix: () => healPreviewFix,
6019
6020
  integrityReportLines: () => integrityReportLines,
6020
6021
  ledgerPath: () => ledgerPath,
6021
6022
  readHashLedger: () => readHashLedger,
@@ -6132,6 +6133,10 @@ function attachCulprits(entries, culpritIndex) {
6132
6133
  (e) => e.status === "foreign" ? { ...e, culprit: culpritIndex.get(e.name) ?? e.culprit } : e
6133
6134
  );
6134
6135
  }
6136
+ function healPreviewFix(bad) {
6137
+ const names = bad.map((e) => e.name).join(", ");
6138
+ return `would reinstall: ${names}; run \`harnessed setup\` to heal (a backup of the current content is taken first, under \`~/.claude/harnessed/backups/\`)`;
6139
+ }
6135
6140
  function integrityReportLines(entries) {
6136
6141
  const bad = entries.filter((e) => e.status !== "ok");
6137
6142
  if (bad.length === 0) return [];
@@ -6192,7 +6197,9 @@ async function checkSkillIntegrity() {
6192
6197
  name,
6193
6198
  status: "warn",
6194
6199
  message: `${bad.length} workflow skill(s) diverged from the install-time state (foreign/tampered/stale/missing) \u2014 the slash command may NOT enter the engine: ${detail}`,
6195
- fix: "re-run `harnessed setup` (its end-of-run integrity pass restores + re-pins the shipped versions)"
6200
+ // 4.24.0 (intel G4) — heal preview: name what setup would reinstall +
6201
+ // the backup-first guarantee, instead of a generic "re-run setup".
6202
+ fix: healPreviewFix(bad)
6196
6203
  };
6197
6204
  } catch {
6198
6205
  return { name, status: "pass", message: "skipped (environment not auditable)" };
@@ -8937,6 +8944,66 @@ var init_resume = __esm({
8937
8944
  }
8938
8945
  });
8939
8946
 
8947
+ // src/cli/lib/skillBackup.ts
8948
+ var skillBackup_exports = {};
8949
+ __export(skillBackup_exports, {
8950
+ backupSkillDir: () => backupSkillDir,
8951
+ newBackupSessionDir: () => newBackupSessionDir,
8952
+ skillContentMatchesLedger: () => skillContentMatchesLedger
8953
+ });
8954
+ function newBackupSessionDir(label, root = getBackupRoot()) {
8955
+ const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-");
8956
+ return join(root, `${ts}-${label}`);
8957
+ }
8958
+ async function backupSkillDir(name, skillsBase, sessionDir) {
8959
+ const src = join(skillsBase, name);
8960
+ try {
8961
+ await stat(src);
8962
+ } catch (err2) {
8963
+ const code = err2.code;
8964
+ if (code === "ENOENT") return { ok: false, code: "ENOENT", message: "nothing on disk" };
8965
+ return { ok: false, code: "ERR", message: err2.message };
8966
+ }
8967
+ const dest = join(sessionDir, name);
8968
+ try {
8969
+ await mkdir(sessionDir, { recursive: true });
8970
+ await cp(src, dest, { recursive: true, force: true });
8971
+ } catch (err2) {
8972
+ return { ok: false, code: "ERR", message: err2.message };
8973
+ }
8974
+ try {
8975
+ await writeFile(
8976
+ join(sessionDir, "README.txt"),
8977
+ "Pre-overwrite copies of installed skill dirs, taken by `harnessed setup` before replacing them. Restore = copy a dir back into ~/.claude/skills/.\n",
8978
+ "utf8"
8979
+ );
8980
+ } catch {
8981
+ }
8982
+ return { ok: true, dir: dest };
8983
+ }
8984
+ async function skillContentMatchesLedger(name, skillsBase, ledger) {
8985
+ const record = ledger?.[name];
8986
+ if (!record) return null;
8987
+ let text;
8988
+ try {
8989
+ text = await readFile(join(skillsBase, name, "SKILL.md"), "utf8");
8990
+ } catch {
8991
+ return null;
8992
+ }
8993
+ if (typeof text !== "string") return null;
8994
+ try {
8995
+ return sha256Of(text) === record.sha256;
8996
+ } catch {
8997
+ return null;
8998
+ }
8999
+ }
9000
+ var init_skillBackup = __esm({
9001
+ "src/cli/lib/skillBackup.ts"() {
9002
+ init_backup();
9003
+ init_skillIntegrity();
9004
+ }
9005
+ });
9006
+
8940
9007
  // src/cli/lib/l4-rescue.ts
8941
9008
  var l4_rescue_exports = {};
8942
9009
  __export(l4_rescue_exports, {
@@ -11686,11 +11753,38 @@ Force-update pass complete: ${b2.installed.length} installed / ${b2.keptExisting
11686
11753
  }
11687
11754
  }
11688
11755
  }
11756
+ let skillBackupApi = null;
11757
+ let stepALedger = null;
11758
+ try {
11759
+ skillBackupApi = await Promise.resolve().then(() => (init_skillBackup(), skillBackup_exports));
11760
+ const { readHashLedger: readHashLedger2 } = await Promise.resolve().then(() => (init_skillIntegrity(), skillIntegrity_exports));
11761
+ stepALedger = await readHashLedger2();
11762
+ } catch {
11763
+ skillBackupApi = null;
11764
+ }
11765
+ let stepASession = null;
11766
+ const stepABackups = [];
11689
11767
  let skillsInstalled = 0;
11690
11768
  for (const wf of toInstall) {
11691
11769
  const src = join(workflowsDir, wf.relPath);
11692
11770
  const dst = join(skillsBase, wf.name);
11693
11771
  try {
11772
+ if (skillBackupApi) {
11773
+ try {
11774
+ const pristine = await skillBackupApi.skillContentMatchesLedger(
11775
+ wf.name,
11776
+ skillsBase,
11777
+ stepALedger
11778
+ );
11779
+ if (pristine !== true) {
11780
+ stepASession ??= skillBackupApi.newBackupSessionDir("step-a");
11781
+ const b2 = await skillBackupApi.backupSkillDir(wf.name, skillsBase, stepASession);
11782
+ if (b2.ok) stepABackups.push({ name: wf.name, dir: b2.dir });
11783
+ else if (b2.code !== "ENOENT") stepABackups.push({ name: wf.name, error: b2.message });
11784
+ }
11785
+ } catch {
11786
+ }
11787
+ }
11694
11788
  await cp(src, dst, { recursive: true, force: true });
11695
11789
  skillsInstalled++;
11696
11790
  } catch (e) {
@@ -11698,6 +11792,17 @@ Force-update pass complete: ${b2.installed.length} installed / ${b2.keptExisting
11698
11792
  process.exit(1);
11699
11793
  }
11700
11794
  }
11795
+ if (stepABackups.length > 0) {
11796
+ console.warn(
11797
+ `
11798
+ ${stepABackups.length} existing skill dir(s) were not the pristine installed state \u2014 backed up before overwriting:`
11799
+ );
11800
+ for (const b2 of stepABackups) {
11801
+ console.warn(
11802
+ b2.dir ? ` ${b2.name} \u2192 ${b2.dir}` : ` \u26A0 ${b2.name}: backup FAILED (${b2.error}) \u2014 overwritten anyway (engine integrity first)`
11803
+ );
11804
+ }
11805
+ }
11701
11806
  console.log(t("setup.step_a_complete", { count: skillsInstalled, path: skillsBase }));
11702
11807
  const skillNames = toInstall.map((wf) => wf.name);
11703
11808
  const rendered = await renderAllSkills(
@@ -11811,10 +11916,24 @@ ${b.failed.length} component(s) failed \u2014 see the notes in the tables above;
11811
11916
  for (const line of integrityReportLines2(audit)) console.warn(line);
11812
11917
  let healed = 0;
11813
11918
  const healedNames = [];
11919
+ let healSession = null;
11920
+ let healBackedUp = false;
11814
11921
  for (const e of bad) {
11815
11922
  const wf = toInstall.find((w) => w.name === e.name);
11816
11923
  if (!wf) continue;
11817
11924
  try {
11925
+ try {
11926
+ const skb = await Promise.resolve().then(() => (init_skillBackup(), skillBackup_exports));
11927
+ healSession ??= skb.newBackupSessionDir("skill-heal");
11928
+ const b2 = await skb.backupSkillDir(e.name, skillsBase, healSession);
11929
+ if (b2.ok) healBackedUp = true;
11930
+ else if (b2.code !== "ENOENT") {
11931
+ console.warn(
11932
+ ` \u26A0 backup of '${e.name}' FAILED (${b2.message}) \u2014 healing anyway (engine integrity first)`
11933
+ );
11934
+ }
11935
+ } catch {
11936
+ }
11818
11937
  await cp(join(workflowsDir, wf.relPath), join(skillsBase, wf.name), {
11819
11938
  recursive: true,
11820
11939
  force: true
@@ -11832,7 +11951,7 @@ ${b.failed.length} component(s) failed \u2014 see the notes in the tables above;
11832
11951
  }
11833
11952
  await recordSkillHashes2(healedNames, skillsBase);
11834
11953
  console.warn(
11835
- ` \u2713 restored ${healed} harnessed workflow skill(s) from the bundle (packs keep their other skills; the colliding name belongs to the engine)`
11954
+ ` \u2713 restored ${healed} harnessed workflow skill(s) from the bundle (packs keep their other skills; the colliding name belongs to the engine)${healBackedUp && healSession ? ` \u2014 replaced content backed up to ${healSession}` : ""}`
11836
11955
  );
11837
11956
  }
11838
11957
  }