@erzhe/harness-kit 0.5.0 → 0.5.1

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.
package/README.md CHANGED
@@ -25,6 +25,17 @@ Onboard 本仓库到 harness-kit:跑 npx -y @erzhe/harness-kit@latest onboard
25
25
 
26
26
  全程走 `npx`,不全局安装 npm 包;你一发新版,所有人下次执行就用上了。唯一的用户级文件例外是 Codex linked-worktree 的显式安全分发器(见下文),因为当前 Codex 在不同启动环境里可能忽略项目 Hook,也可能与用户 Hook 同时执行。
27
27
 
28
+ 已有仓库升级不需要重新 `init` / `onboard`,也不需要把 Harness 加进业务依赖:
29
+
30
+ ```bash
31
+ npx -y @erzhe/harness-kit@0.5.1 upgrade --repo . --check
32
+ npx -y @erzhe/harness-kit@0.5.1 upgrade --repo .
33
+ ```
34
+
35
+ `--check` 完全只读:已是当前版本返回 0,需要升级返回 2,阻塞或状态损坏返回 1。正式 apply 要求目标 Git scope 干净,并把 manifest(仅在迁移确实改变时)、全部生成入口和 `.agents/harness.lock.json` 放进同一仓内文件事务。版本获取由调用方决定,所以公共 npm、公司内部镜像、本地固定二进制都能使用同一接口。0.5.1 不在 `upgrade` 里改 Hook;Hook 仍通过 `install-hooks` 单独管理。
36
+
37
+ `--json` 始终只输出一份 `ai-harness/upgrade-report/v1`,包含 `status`、from/to version、pending/applied migrations、changed/dirty files、errors 和 post-upgrade verification。状态文件同样是确定性协议:`ai-harness/upgrade-state/v1` 只保存 package、version、manifest spec 与已应用 migration IDs;它应随代码提交,没有时间戳,也没有“使用哪些 Agent”的名单。
38
+
28
39
  运行要求:Node.js 18 或更高版本。发布前会用打包后的 CLI 在真实 Node 18 上做 `help / doctor / verify` smoke。
29
40
 
30
41
  ---
@@ -46,7 +57,7 @@ Onboard 本仓库到 harness-kit:跑 npx -y @erzhe/harness-kit@latest onboard
46
57
  modules.md ← [生成] 模块卡:每个子系统的职责/入口/坑
47
58
  ```
48
59
 
49
- 以后改工程结构 → 编辑 `manifest.yaml` → `harness-kit sync`。`sync` 只重生成确定性文件,不会替你声称“知识已经复核”。业务文档仍在原路径更新;Agent 完成语义审查后再运行 `record-context-review` 留证。
60
+ 以后改工程结构 → 编辑 `manifest.yaml` → `harness-kit sync`。Harness Kit 发新版后,用新版 CLI 运行 `harness-kit upgrade` 做原地迁移;它只修改仓库内 Harness 状态,不依赖 GitHub / GitLab / CI。`sync` 只重生成确定性文件,不会替你声称“知识已经复核”。业务文档仍在原路径更新;Agent 完成语义审查后再运行 `record-context-review` 留证。
50
61
 
51
62
  ---
52
63
 
@@ -74,6 +85,7 @@ harness-kit 的长期价值不在首次接入,而在**代码演进时上下文
74
85
  | `harness-kit onboard` | 打印 onboard skill 给 Agent(配合 npx,永远最新、零安装) |
75
86
  | `harness-kit init` | 铺 `.agents/` 骨架 + 空白 manifest |
76
87
  | `harness-kit sync` | manifest → 事务生成 AGENTS.md / CLAUDE.md / reference / routing / modules;不刷新知识复核 |
88
+ | `harness-kit upgrade [--check] [--json]` | 把仓库原地升级到当前运行 CLI 版本;确定性迁移 + 生成物刷新 + doctor/verify,不访问 registry/CI/代码托管,也不改 Hook |
77
89
  | `harness-kit prepare-adoption` | 在仓外生成私有 blind-audit bundle;包含旧入口、嵌套 AGENTS/CLAUDE 及它们显式引用的文档证据和确定性候选,不改仓内文件 |
78
90
  | `harness-kit record-adoption-audit` | 把声明的 pass/fail、理由和审计报告 hash 绑定到一版候选 |
79
91
  | `harness-kit sync --adopt-existing --candidate ... --audit ...` | 首次接管:只有 live legacy、候选、manifest 和 pass receipt 逐字节一致才事务写入 |
package/SPEC-v0.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # AI-Harness SPEC v0.4
2
2
 
3
3
  > 一套 AI-friendly 的仓库规范。定义"任何仓库要让 Agent 冷启动即可高效工作、且人人构建出一致范式,必须声明什么、怎么声明、怎么防过期"。
4
- > 配套 CLI:`ai-harness`(`init` / `sync` / `doctor` / `verify`)。基础仓继续兼容 `ai-harness/v0`;使用 validation gates 的仓必须显式升级到 `ai-harness/v1`。
4
+ > 配套 CLI:`ai-harness`(`init` / `sync` / `upgrade` / `doctor` / `verify`)。基础仓继续兼容 `ai-harness/v0`;使用 validation gates 的仓必须显式升级到 `ai-harness/v1`。
5
5
  >
6
6
  > 本文件是随仓库与 npm 包公开分发的规范正文。
7
7
  >
@@ -194,8 +194,10 @@ generate:
194
194
  - `manifest.yaml` 是生成结构的真相源;`.agents/knowledge/` 及 `root: repo` 登记的业务文档仍是手写语义源。
195
195
  - `harness sync` 幂等渲染工具文件,先对**全部目标**做安全 preflight,再写同目录临时文件。缺失目标用 hard-link no-replace 安装;已有普通文件先移到唯一 rollback 位并再次核对 identity/bytes,再 no-replace 安装候选。中途失败尽力恢复;若同时有别的进程写入,优先保留较新的路径和原文件 backup、明确失败,绝不静默覆盖。跨平台 Node 没有“比较 inode 后原子替换”的 CAS,因此普通文件替换存在极短路径空窗;这里承诺的是数据保全的 best-effort 文件事务,不冒充数据库级原子性。已完全一致的普通文件不得无谓重写。
196
196
  - 最终路径及其父目录不能跟随 symlink。唯一允许保留的语义 alias 是仓库根的相对 `CLAUDE.md -> AGENTS.md`,且解析后必须精确落在同仓 `AGENTS.md`;其它 symlink、目录、越界父目录全部 fail closed。
197
- - `init` 先统一预检 manifest、domain、conventions、journal/playbooks `.gitkeep` 和 adoption log;非 `--force` 时任一 scaffold 目标已存在就必须零写入拒绝。首次接管已有普通入口文件前,`init` 仅对 Harness 将接管的 managed entry 保存逐字节 legacy snapshot、mode/hash(symlink 保存 link target)。snapshot/index 的父链必须是仓内真实目录,读取使用 no-follow,snapshot 用排他 no-replace 写,index 用绑定旧字节的事务写;索引提交失败时初始化整体失败,已安全落下的 append-only snapshot 原位保留并在错误中给出恢复路径,绝不冒险删除可能被并发改写的 inode。嵌套 `AGENTS.md` / `CLAUDE.md` 及它们递归显式引用的仓内文本文档始终留在原地,不写入仓内 `.agents/adoption/legacy`;`prepare-adoption` 才把这些 guidance 复制到仓外私有 bundle,不按业务目录名猜测(Git 不可用时仍完整扫描,VCS 元数据与 Harness 自身 adoption evidence 除外)。guidance path/type/bytes/hash/mode/link target 纳入 candidate 绑定并在 apply 时重新发现、逐项重验;缺失、二进制、越界或指向仓外的 symlink 引用 fail closed,普通代码/资产链接与 Markdown 图片不当作 guidance。普通 `sync` 必须拒绝覆盖;`prepare-adoption` 不写真实入口。盲审报告经 `record-adoption-audit` 形成 `assurance=declared / independence=unverified` 的 pass/fail receipt;它证明被声明审查的是哪些字节,不证明审计身份或语义质量。只有带精确 candidate+pass receipt 的 `sync --adopt-existing` 才会在同次写入 preflight 里重新核对 live legacy、snapshot/index、guidance、manifest、所有候选字节及报告 hash。任一漂移都拒绝,`--force` 不能绕过。
197
+ - `init` 先统一预检 manifest、`.agents/harness.lock.json`、domain、conventions、journal/playbooks `.gitkeep` 和 adoption log;非 `--force` 时任一 scaffold 目标已存在就必须零写入拒绝。首次接管已有普通入口文件前,`init` 仅对 Harness 将接管的 managed entry 保存逐字节 legacy snapshot、mode/hash(symlink 保存 link target)。snapshot/index 的父链必须是仓内真实目录,读取使用 no-follow,snapshot 用排他 no-replace 写,index 用绑定旧字节的事务写;索引提交失败时初始化整体失败,已安全落下的 append-only snapshot 原位保留并在错误中给出恢复路径,绝不冒险删除可能被并发改写的 inode。嵌套 `AGENTS.md` / `CLAUDE.md` 及它们递归显式引用的仓内文本文档始终留在原地,不写入仓内 `.agents/adoption/legacy`;`prepare-adoption` 才把这些 guidance 复制到仓外私有 bundle,不按业务目录名猜测(Git 不可用时仍完整扫描,VCS 元数据与 Harness 自身 adoption evidence 除外)。guidance path/type/bytes/hash/mode/link target 纳入 candidate 绑定并在 apply 时重新发现、逐项重验;缺失、二进制、越界或指向仓外的 symlink 引用 fail closed,普通代码/资产链接与 Markdown 图片不当作 guidance。普通 `sync` 必须拒绝覆盖;`prepare-adoption` 不写真实入口。盲审报告经 `record-adoption-audit` 形成 `assurance=declared / independence=unverified` 的 pass/fail receipt;它证明被声明审查的是哪些字节,不证明审计身份或语义质量。只有带精确 candidate+pass receipt 的 `sync --adopt-existing` 才会在同次写入 preflight 里重新核对 live legacy、snapshot/index、guidance、manifest、所有候选字节及报告 hash。任一漂移都拒绝,`--force` 不能绕过。
198
198
  - `sync` **只生成确定性文件**,绝不写新鲜度 baseline 或自动“接受”知识。语义复核只能由 Agent 完成分析后显式调用 `record-context-review`。
199
+ - `upgrade` 以当前运行 CLI 的版本为迁移目标,不自行访问 registry、CI 或代码托管平台。`.agents/harness.lock.json` 只记录确定性的 package/version、manifest spec 与有序 migration IDs,不含时间戳或 Agent 清单。`--check` 只读(current=0、available=2、blocked=1);apply 要求目标 Git scope 干净,先在内存执行有序的必需结构迁移并验证最终 manifest,再把确有语义变化的 manifest、全部生成入口和 lock 交给同一个 managed-file 事务。只解析未迁移时必须保留 manifest 原始字节。可选产品能力不能自动开启。0.5.1 的 upgrade 不修改 lifecycle Hook;Hook 继续由 `install-hooks` 显式管理。
200
+ - upgrade state 协议是 `ai-harness/upgrade-state/v1`:`{ schema, package, version, manifestSpec, appliedMigrations }`。JSON 命令协议是单份 `ai-harness/upgrade-report/v1`:`status` 取 `current | upgrade-available | upgraded | incomplete | blocked`,并携带 from/to version、pending/applied migrations、changed/dirty files、`hooksChanged`、errors/notes,以及 apply 后可选的 doctor/verify 结果。结构迁移已写入但后置校验失败时必须报告 `incomplete` 和非零退出,不能把已落盘事实伪装成零写入失败。
199
201
  - 生成文件不进人工编辑;要改结构就改 manifest 再 sync。已有业务文档不搬入 `.agents/`,仍在原路径维护。
200
202
 
201
203
  ## 5. 校验契约(`doctor` / `verify`)
@@ -251,6 +253,7 @@ GAPS 不计入失败,但会打印数量(`verify: OK (N gap(s))`)。配套*
251
253
  | `harness prepare-adoption --out <external-dir>` | 在仓库外生成私有 legacy+candidate 审计 bundle,不修改真实入口 |
252
254
  | `harness record-adoption-audit --candidate <dir> --verdict pass\|fail --report <file> --reason <text> [--out]` | 生成内容绑定的声明式审计回执;不证明身份或语义质量 |
253
255
  | `harness sync [--adopt-existing --candidate <dir> --audit <receipt>]` | 事务生成工具文件;首次接管要求精确 pass receipt 且应用瞬间重新渲染核对;不刷新 context review |
256
+ | `harness upgrade [--check] [--json]` | 升级到当前 CLI 版本;平台无关的确定性迁移、生成物刷新和 doctor/verify;不修改 Hook |
254
257
  | `harness doctor` | 开发期体检:完整性 + 漂移 + 新鲜度 + 技术债 + 影响面 owns 空匹配 / playbook 存在性 |
255
258
  | `harness verify [--json]` | 本地/CI 门禁:跑全部可执行 checks,任一失败即 fail;JSON 为单文档稳定协议 |
256
259
  | `harness accept-contract [--id]` | 把当前契约指纹记为已接受基线(有意变更后显式跑,与 sync 分开) |
@@ -5003,11 +5003,11 @@ var require_picomatch = __commonJS({
5003
5003
  return { isMatch: false, output: "" };
5004
5004
  }
5005
5005
  const opts = options || {};
5006
- const format = opts.format || (posix ? utils.toPosixSlashes : null);
5006
+ const format2 = opts.format || (posix ? utils.toPosixSlashes : null);
5007
5007
  let match = input === glob;
5008
- let output = match && format ? format(input) : input;
5008
+ let output = match && format2 ? format2(input) : input;
5009
5009
  if (match === false) {
5010
- output = format ? format(input) : input;
5010
+ output = format2 ? format2(input) : input;
5011
5011
  match = output === glob;
5012
5012
  }
5013
5013
  if (match === false || opts.capture === true) {
@@ -7430,14 +7430,14 @@ var require_bool = __commonJS({
7430
7430
  var require_stringifyNumber = __commonJS({
7431
7431
  "node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyNumber.js"(exports2) {
7432
7432
  "use strict";
7433
- function stringifyNumber({ format, minFractionDigits, tag, value }) {
7433
+ function stringifyNumber({ format: format2, minFractionDigits, tag, value }) {
7434
7434
  if (typeof value === "bigint")
7435
7435
  return String(value);
7436
7436
  const num = typeof value === "number" ? value : Number(value);
7437
7437
  if (!isFinite(num))
7438
7438
  return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf";
7439
7439
  let n = Object.is(value, -0) ? "-0" : JSON.stringify(value);
7440
- if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) {
7440
+ if (!format2 && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) {
7441
7441
  let i = n.indexOf(".");
7442
7442
  if (i < 0) {
7443
7443
  i = n.length;
@@ -12298,7 +12298,7 @@ var require_public_api = __commonJS({
12298
12298
  return docs;
12299
12299
  return Object.assign([], { empty: true }, composer$1.streamInfo());
12300
12300
  }
12301
- function parseDocument(source, options = {}) {
12301
+ function parseDocument2(source, options = {}) {
12302
12302
  const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
12303
12303
  const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
12304
12304
  const composer$1 = new composer.Composer(options);
@@ -12324,7 +12324,7 @@ var require_public_api = __commonJS({
12324
12324
  } else if (options === void 0 && reviver && typeof reviver === "object") {
12325
12325
  options = reviver;
12326
12326
  }
12327
- const doc = parseDocument(src, options);
12327
+ const doc = parseDocument2(src, options);
12328
12328
  if (!doc)
12329
12329
  return null;
12330
12330
  doc.warnings.forEach((warning) => log.warn(doc.options.logLevel, warning));
@@ -12360,7 +12360,7 @@ var require_public_api = __commonJS({
12360
12360
  }
12361
12361
  exports2.parse = parse;
12362
12362
  exports2.parseAllDocuments = parseAllDocuments;
12363
- exports2.parseDocument = parseDocument;
12363
+ exports2.parseDocument = parseDocument2;
12364
12364
  exports2.stringify = stringify;
12365
12365
  }
12366
12366
  });
@@ -13170,7 +13170,7 @@ var require_fill_range = __commonJS({
13170
13170
  let padded = zeros(startString) || zeros(endString) || zeros(stepString);
13171
13171
  let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
13172
13172
  let toNumber = padded === false && stringify(start, end, options) === false;
13173
- let format = options.transform || transform(toNumber);
13173
+ let format2 = options.transform || transform(toNumber);
13174
13174
  if (options.toRegex && step === 1) {
13175
13175
  return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
13176
13176
  }
@@ -13182,7 +13182,7 @@ var require_fill_range = __commonJS({
13182
13182
  if (options.toRegex === true && step > 1) {
13183
13183
  push(a);
13184
13184
  } else {
13185
- range.push(pad(format(a, index), maxLen, toNumber));
13185
+ range.push(pad(format2(a, index), maxLen, toNumber));
13186
13186
  }
13187
13187
  a = descending ? a - step : a + step;
13188
13188
  index++;
@@ -13196,7 +13196,7 @@ var require_fill_range = __commonJS({
13196
13196
  if (!isNumber(start) && start.length > 1 || !isNumber(end) && end.length > 1) {
13197
13197
  return invalidRange(start, end, options);
13198
13198
  }
13199
- let format = options.transform || ((val) => String.fromCharCode(val));
13199
+ let format2 = options.transform || ((val) => String.fromCharCode(val));
13200
13200
  let a = `${start}`.charCodeAt(0);
13201
13201
  let b = `${end}`.charCodeAt(0);
13202
13202
  let descending = a > b;
@@ -13208,7 +13208,7 @@ var require_fill_range = __commonJS({
13208
13208
  let range = [];
13209
13209
  let index = 0;
13210
13210
  while (descending ? a >= b : a <= b) {
13211
- range.push(format(a, index));
13211
+ range.push(format2(a, index));
13212
13212
  a = descending ? a - step : a + step;
13213
13213
  index++;
13214
13214
  }
@@ -15459,11 +15459,11 @@ var require_picomatch3 = __commonJS({
15459
15459
  return { isMatch: false, output: "" };
15460
15460
  }
15461
15461
  const opts = options || {};
15462
- const format = opts.format || (posix ? utils.toPosixSlashes : null);
15462
+ const format2 = opts.format || (posix ? utils.toPosixSlashes : null);
15463
15463
  let match = input === glob;
15464
- let output = match && format ? format(input) : input;
15464
+ let output = match && format2 ? format2(input) : input;
15465
15465
  if (match === false) {
15466
- output = format ? format(input) : input;
15466
+ output = format2 ? format2(input) : input;
15467
15467
  match = output === glob;
15468
15468
  }
15469
15469
  if (match === false || opts.capture === true) {
@@ -18185,7 +18185,7 @@ var import_node_path18 = require("node:path");
18185
18185
  // package.json
18186
18186
  var package_default = {
18187
18187
  name: "@erzhe/harness-kit",
18188
- version: "0.5.0",
18188
+ version: "0.5.1",
18189
18189
  type: "module",
18190
18190
  description: "AI-friendly repo harness: a manifest.yaml single source of truth that generates AGENTS.md / CLAUDE.md / Cursor rules and enforces invariants, contracts and drift via `harness-kit verify`.",
18191
18191
  keywords: [
@@ -20352,6 +20352,449 @@ function assertManagedFileAdoption(_repo, inspections, adoptExisting) {
20352
20352
  );
20353
20353
  }
20354
20354
 
20355
+ // src/upgrade.ts
20356
+ var import_yaml2 = __toESM(require_dist(), 1);
20357
+
20358
+ // src/git.ts
20359
+ var import_node_child_process3 = require("node:child_process");
20360
+ var import_node_crypto5 = require("node:crypto");
20361
+ var import_node_fs6 = require("node:fs");
20362
+ var import_node_path6 = require("node:path");
20363
+ var GitDiffError = class extends Error {
20364
+ constructor(kind, message) {
20365
+ super(message);
20366
+ this.kind = kind;
20367
+ this.name = "GitDiffError";
20368
+ }
20369
+ kind;
20370
+ };
20371
+ var EMPTY_TREE_BASE = "(empty-tree)";
20372
+ function errorText(error) {
20373
+ const e = error;
20374
+ const stderr = Buffer.isBuffer(e.stderr) ? e.stderr.toString("utf8") : e.stderr;
20375
+ return String(stderr || e.message || error).trim();
20376
+ }
20377
+ function git(repo, args) {
20378
+ try {
20379
+ return (0, import_node_child_process3.execFileSync)("git", args, {
20380
+ cwd: repo,
20381
+ encoding: "utf8",
20382
+ stdio: ["ignore", "pipe", "pipe"],
20383
+ maxBuffer: 32 * 1024 * 1024
20384
+ });
20385
+ } catch (error) {
20386
+ throw new GitDiffError("diff-failed", `git ${args[0] ?? "command"} failed: ${errorText(error)}`);
20387
+ }
20388
+ }
20389
+ function tryCommit(repo, ref) {
20390
+ try {
20391
+ return (0, import_node_child_process3.execFileSync)("git", ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`], {
20392
+ cwd: repo,
20393
+ encoding: "utf8",
20394
+ stdio: ["ignore", "pipe", "pipe"]
20395
+ }).trim();
20396
+ } catch {
20397
+ return null;
20398
+ }
20399
+ }
20400
+ function gitRoot(repo) {
20401
+ try {
20402
+ return (0, import_node_child_process3.execFileSync)("git", ["rev-parse", "--show-toplevel"], {
20403
+ cwd: repo,
20404
+ encoding: "utf8",
20405
+ stdio: ["ignore", "pipe", "pipe"]
20406
+ }).trim();
20407
+ } catch (error) {
20408
+ throw new GitDiffError("not-a-repo", `not a git repo: ${errorText(error)}`);
20409
+ }
20410
+ }
20411
+ function gitAdminDir(repo) {
20412
+ try {
20413
+ return (0, import_node_child_process3.execFileSync)("git", ["rev-parse", "--absolute-git-dir"], {
20414
+ cwd: repo,
20415
+ encoding: "utf8",
20416
+ stdio: ["ignore", "pipe", "pipe"]
20417
+ }).trim();
20418
+ } catch (error) {
20419
+ throw new GitDiffError("not-a-repo", `cannot resolve git metadata dir: ${errorText(error)}`);
20420
+ }
20421
+ }
20422
+ function parseNameStatus(raw, layer) {
20423
+ const fields = raw.split("\0");
20424
+ if (fields.at(-1) === "") fields.pop();
20425
+ const entries = [];
20426
+ for (let i = 0; i < fields.length; ) {
20427
+ const status = fields[i++] ?? "";
20428
+ const code = status[0] ?? "M";
20429
+ const first = fields[i++];
20430
+ if (first === void 0) throw new GitDiffError("diff-failed", "git diff returned malformed name-status output");
20431
+ if (code === "R") {
20432
+ const second = fields[i++];
20433
+ if (second === void 0) throw new GitDiffError("diff-failed", "git diff returned malformed rename output");
20434
+ entries.push({ path: first, status: "D", layer }, { path: second, status: "A", layer });
20435
+ } else if (code === "C") {
20436
+ const second = fields[i++];
20437
+ if (second === void 0) throw new GitDiffError("diff-failed", "git diff returned malformed copy output");
20438
+ entries.push({ path: second, status: "A", layer });
20439
+ } else {
20440
+ entries.push({ path: first, status: code, layer });
20441
+ }
20442
+ }
20443
+ return entries;
20444
+ }
20445
+ function nulList(raw) {
20446
+ return raw.split("\0").filter(Boolean);
20447
+ }
20448
+ function canonicalPath(path) {
20449
+ try {
20450
+ return (0, import_node_fs6.realpathSync)(path);
20451
+ } catch {
20452
+ return (0, import_node_path6.resolve)(path);
20453
+ }
20454
+ }
20455
+ function targetPrefix(root, target) {
20456
+ const native = (0, import_node_path6.relative)(root, target);
20457
+ if (!native) return "";
20458
+ if ((0, import_node_path6.isAbsolute)(native) || native === ".." || native.startsWith(`..${import_node_path6.sep}`))
20459
+ throw new GitDiffError("not-a-repo", `target is outside its Git worktree: ${target}`);
20460
+ return native.split(import_node_path6.sep).join("/");
20461
+ }
20462
+ function scopeEntries(entries, prefix) {
20463
+ if (!prefix) return entries;
20464
+ const start = `${prefix}/`;
20465
+ return entries.filter((entry) => entry.path.startsWith(start)).map((entry) => ({ ...entry, path: entry.path.slice(start.length) }));
20466
+ }
20467
+ function digestPath(repo, rel) {
20468
+ const abs = (0, import_node_path6.join)(repo, rel);
20469
+ try {
20470
+ const stat = (0, import_node_fs6.lstatSync)(abs);
20471
+ if (stat.isSymbolicLink()) return `symlink:${(0, import_node_fs6.readlinkSync)(abs)}`;
20472
+ if (stat.isDirectory()) {
20473
+ try {
20474
+ const head = (0, import_node_child_process3.execFileSync)("git", ["-C", abs, "rev-parse", "--verify", "HEAD"], {
20475
+ encoding: "utf8",
20476
+ stdio: ["ignore", "pipe", "pipe"]
20477
+ }).trim();
20478
+ const nested = collectChanges(abs, "HEAD", { mode: "exact" });
20479
+ return `gitlink:${head}:${nested.fingerprint}`;
20480
+ } catch {
20481
+ return `directory:${stat.mode}`;
20482
+ }
20483
+ }
20484
+ if (!stat.isFile()) return `other:${stat.mode}`;
20485
+ const gitMode = stat.mode & 73 ? "100755" : "100644";
20486
+ return `file:${gitMode}:${(0, import_node_crypto5.createHash)("sha256").update((0, import_node_fs6.readFileSync)(abs)).digest("hex")}`;
20487
+ } catch {
20488
+ return "(missing)";
20489
+ }
20490
+ }
20491
+ function digestIndex(repo, rel) {
20492
+ try {
20493
+ const entry = (0, import_node_child_process3.execFileSync)("git", ["ls-files", "--stage", "-z", "--", rel], {
20494
+ cwd: repo,
20495
+ encoding: "utf8",
20496
+ stdio: ["ignore", "pipe", "pipe"]
20497
+ });
20498
+ return entry || "(missing-index)";
20499
+ } catch (error) {
20500
+ throw new GitDiffError("diff-failed", `cannot fingerprint Git index entry ${rel}: ${errorText(error)}`);
20501
+ }
20502
+ }
20503
+ function fingerprint(repo, resolvedBase, entries) {
20504
+ const hash = (0, import_node_crypto5.createHash)("sha256");
20505
+ hash.update("harness-kit/change-fingerprint/v1\0");
20506
+ hash.update(resolvedBase ?? EMPTY_TREE_BASE);
20507
+ for (const entry of entries) {
20508
+ hash.update("\0");
20509
+ hash.update(entry.layer);
20510
+ hash.update("\0");
20511
+ hash.update(entry.status);
20512
+ hash.update("\0");
20513
+ hash.update(entry.path);
20514
+ hash.update("\0");
20515
+ hash.update(entry.layer === "index" ? digestIndex(repo, entry.path) : digestPath(repo, entry.path));
20516
+ }
20517
+ return hash.digest("hex");
20518
+ }
20519
+ function collectChanges(repoInput, base = "HEAD", opts = {}) {
20520
+ const target = canonicalPath(repoInput);
20521
+ const root = canonicalPath(gitRoot(target));
20522
+ const prefix = targetPrefix(root, target);
20523
+ const head = tryCommit(root, "HEAD");
20524
+ let baseCommit;
20525
+ if (base === EMPTY_TREE_BASE) {
20526
+ baseCommit = null;
20527
+ } else {
20528
+ baseCommit = tryCommit(root, base);
20529
+ if (!baseCommit && base === "HEAD" && !head) baseCommit = null;
20530
+ else if (!baseCommit) throw new GitDiffError("invalid-base", `invalid base ref: ${base}`);
20531
+ }
20532
+ let resolvedBase = baseCommit;
20533
+ if ((opts.mode ?? "merge-base") === "merge-base" && baseCommit && head) {
20534
+ try {
20535
+ resolvedBase = git(root, ["merge-base", baseCommit, head]).trim();
20536
+ } catch (error) {
20537
+ throw new GitDiffError("invalid-base", `invalid base ref or no merge base: ${base} (${error.message})`);
20538
+ }
20539
+ }
20540
+ let entries;
20541
+ if (resolvedBase) {
20542
+ entries = parseNameStatus(git(root, ["diff", "--cached", "--name-status", "-z", resolvedBase, "--"]), "index");
20543
+ } else {
20544
+ entries = nulList(git(root, ["ls-files", "--cached", "-z"])).map((path) => ({ path, status: "A", layer: "index" }));
20545
+ }
20546
+ entries.push(...parseNameStatus(git(root, ["diff", "--name-status", "-z", "--"]), "worktree"));
20547
+ for (const path of nulList(git(root, ["ls-files", "--others", "--exclude-standard", "-z"]))) {
20548
+ entries.push({ path, status: "A", layer: "untracked" });
20549
+ }
20550
+ entries = scopeEntries(entries, prefix);
20551
+ entries = entries.sort((a, b) => a.path.localeCompare(b.path) || a.layer.localeCompare(b.layer) || a.status.localeCompare(b.status));
20552
+ const files = [...new Set(entries.map((entry) => entry.path))];
20553
+ return {
20554
+ requestedBase: base,
20555
+ resolvedBase,
20556
+ head,
20557
+ files,
20558
+ entries,
20559
+ fingerprint: fingerprint(target, resolvedBase, entries)
20560
+ };
20561
+ }
20562
+
20563
+ // src/upgrade.ts
20564
+ var UPGRADE_STATE_REL = ".agents/harness.lock.json";
20565
+ var UPGRADE_STATE_SCHEMA = "ai-harness/upgrade-state/v1";
20566
+ var UPGRADE_REPORT_SCHEMA = "ai-harness/upgrade-report/v1";
20567
+ var UPGRADE_MIGRATIONS = [
20568
+ {
20569
+ id: "upgrade-state-v1",
20570
+ migrate: () => {
20571
+ }
20572
+ }
20573
+ ];
20574
+ function parseSemver(value) {
20575
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(
20576
+ value
20577
+ );
20578
+ if (!match) return null;
20579
+ const prerelease = match[4]?.split(".") ?? [];
20580
+ const core = [Number(match[1]), Number(match[2]), Number(match[3])];
20581
+ if (core.some((part) => !Number.isSafeInteger(part))) return null;
20582
+ if (prerelease.some((part) => /^\d+$/.test(part) && part.length > 1 && part.startsWith("0"))) return null;
20583
+ return {
20584
+ major: core[0],
20585
+ minor: core[1],
20586
+ patch: core[2],
20587
+ prerelease
20588
+ };
20589
+ }
20590
+ function comparePrerelease(left, right) {
20591
+ if (!left.length || !right.length) return left.length === right.length ? 0 : left.length ? -1 : 1;
20592
+ const length = Math.max(left.length, right.length);
20593
+ for (let index = 0; index < length; index++) {
20594
+ const a = left[index];
20595
+ const b = right[index];
20596
+ if (a === void 0 || b === void 0) return a === b ? 0 : a === void 0 ? -1 : 1;
20597
+ if (a === b) continue;
20598
+ const aNumeric = /^\d+$/.test(a);
20599
+ const bNumeric = /^\d+$/.test(b);
20600
+ if (aNumeric && bNumeric) return a.length === b.length ? a < b ? -1 : 1 : a.length < b.length ? -1 : 1;
20601
+ if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;
20602
+ return a < b ? -1 : 1;
20603
+ }
20604
+ return 0;
20605
+ }
20606
+ function compareSemver(left, right) {
20607
+ for (const key of ["major", "minor", "patch"]) {
20608
+ if (left[key] !== right[key]) return left[key] < right[key] ? -1 : 1;
20609
+ }
20610
+ return comparePrerelease(left.prerelease, right.prerelease);
20611
+ }
20612
+ function reportBase(options) {
20613
+ return {
20614
+ schema: UPGRADE_REPORT_SCHEMA,
20615
+ status: "blocked",
20616
+ package: options.packageName,
20617
+ fromVersion: null,
20618
+ toVersion: options.targetVersion,
20619
+ manifestSpec: null,
20620
+ pendingMigrations: [],
20621
+ appliedMigrations: [],
20622
+ changedFiles: [],
20623
+ dirtyFiles: [],
20624
+ hooksChanged: false,
20625
+ errors: [],
20626
+ notes: ["upgrade does not install, remove, or rewrite lifecycle hooks"]
20627
+ };
20628
+ }
20629
+ function fail(report, message) {
20630
+ report.status = "blocked";
20631
+ report.errors.push(message);
20632
+ return report;
20633
+ }
20634
+ function parseState(content, options, report) {
20635
+ let value;
20636
+ try {
20637
+ value = JSON.parse(content);
20638
+ } catch (error) {
20639
+ return fail(report, `${UPGRADE_STATE_REL} is not valid JSON: ${error.message}`);
20640
+ }
20641
+ if (!value || typeof value !== "object" || Array.isArray(value))
20642
+ return fail(report, `${UPGRADE_STATE_REL} root must be an object`);
20643
+ const candidate = value;
20644
+ if (candidate.schema !== UPGRADE_STATE_SCHEMA)
20645
+ return fail(report, `${UPGRADE_STATE_REL} has unsupported schema: ${String(candidate.schema)}`);
20646
+ if (candidate.package !== options.packageName)
20647
+ return fail(report, `${UPGRADE_STATE_REL} belongs to ${String(candidate.package)}, not ${options.packageName}`);
20648
+ if (typeof candidate.version !== "string" || !parseSemver(candidate.version))
20649
+ return fail(report, `${UPGRADE_STATE_REL} has invalid version: ${String(candidate.version)}`);
20650
+ if (typeof candidate.manifestSpec !== "string" || !candidate.manifestSpec)
20651
+ return fail(report, `${UPGRADE_STATE_REL} has invalid manifestSpec`);
20652
+ if (!Array.isArray(candidate.appliedMigrations) || candidate.appliedMigrations.some((id) => typeof id !== "string"))
20653
+ return fail(report, `${UPGRADE_STATE_REL} appliedMigrations must be a string array`);
20654
+ const unique = new Set(candidate.appliedMigrations);
20655
+ if (unique.size !== candidate.appliedMigrations.length)
20656
+ return fail(report, `${UPGRADE_STATE_REL} appliedMigrations contains duplicates`);
20657
+ const known = new Set(UPGRADE_MIGRATIONS.map((migration) => migration.id));
20658
+ const unknown = candidate.appliedMigrations.filter((id) => !known.has(id));
20659
+ if (unknown.length) return fail(report, `${UPGRADE_STATE_REL} contains unknown migrations: ${unknown.join(", ")}`);
20660
+ return candidate;
20661
+ }
20662
+ function sameInspection(left, right) {
20663
+ return left.relativePath === right.relativePath && left.absolutePath === right.absolutePath && left.kind === right.kind && left.currentContent === right.currentContent && left.linkTarget === right.linkTarget;
20664
+ }
20665
+ function renderState(state) {
20666
+ return `${JSON.stringify(state, null, 2)}
20667
+ `;
20668
+ }
20669
+ function asManifest(document, report) {
20670
+ if (document.errors.length)
20671
+ return fail(report, `${MANIFEST_REL} YAML is invalid: ${document.errors.map((error) => error.message).join("; ")}`);
20672
+ const value = document.toJS();
20673
+ if (!value || typeof value !== "object" || Array.isArray(value))
20674
+ return fail(report, `${MANIFEST_REL} root must be an object`);
20675
+ const manifest = value;
20676
+ const errors = validateManifest(manifest).filter((issue) => issue.level === "error");
20677
+ if (errors.length) return fail(report, `manifest invalid: ${errors.map((issue) => issue.msg).join("; ")}`);
20678
+ return manifest;
20679
+ }
20680
+ function internalUpgrade(repo, options) {
20681
+ const report = reportBase(options);
20682
+ const targetSemver = parseSemver(options.targetVersion);
20683
+ if (!targetSemver) return fail(report, `running harness-kit has an invalid version: ${options.targetVersion}`);
20684
+ const changes = collectChanges(repo, "HEAD", { mode: "exact" });
20685
+ report.dirtyFiles = changes.files;
20686
+ if (!options.check && report.dirtyFiles.length)
20687
+ return fail(report, `repository has uncommitted changes: ${report.dirtyFiles.join(", ")}`);
20688
+ const sourceInspections = inspectManagedFiles(repo, [
20689
+ [MANIFEST_REL, ""],
20690
+ [UPGRADE_STATE_REL, ""]
20691
+ ]);
20692
+ const manifestInspection = sourceInspections[0];
20693
+ const stateInspection = sourceInspections[1];
20694
+ if (manifestInspection.kind === "missing" || manifestInspection.currentContent === null)
20695
+ return fail(report, `${MANIFEST_REL} is missing; run harness-kit init first`);
20696
+ let state = null;
20697
+ if (stateInspection.kind !== "missing") {
20698
+ if (stateInspection.currentContent === null) return fail(report, `${UPGRADE_STATE_REL} is not a readable regular file`);
20699
+ const parsed = parseState(stateInspection.currentContent, options, report);
20700
+ if ("status" in parsed) return parsed;
20701
+ state = parsed;
20702
+ report.fromVersion = state.version;
20703
+ report.appliedMigrations = [...state.appliedMigrations];
20704
+ const currentSemver = parseSemver(state.version);
20705
+ if (compareSemver(currentSemver, targetSemver) > 0)
20706
+ return fail(report, `refusing downgrade from ${state.version} to ${options.targetVersion}`);
20707
+ }
20708
+ const document = (0, import_yaml2.parseDocument)(manifestInspection.currentContent);
20709
+ const sourceManifest = asManifest(document, report);
20710
+ if ("status" in sourceManifest) return sourceManifest;
20711
+ report.manifestSpec = sourceManifest.spec;
20712
+ const normalizedSource = document.toString();
20713
+ const applied = new Set(state?.appliedMigrations ?? []);
20714
+ const pending = UPGRADE_MIGRATIONS.filter((migration) => !applied.has(migration.id));
20715
+ report.pendingMigrations = pending.map((migration) => migration.id);
20716
+ for (const migration of pending) migration.migrate(document);
20717
+ const finalManifest = asManifest(document, report);
20718
+ if ("status" in finalManifest) return finalManifest;
20719
+ const migratedManifestContent = document.toString();
20720
+ const nextState = {
20721
+ schema: UPGRADE_STATE_SCHEMA,
20722
+ package: options.packageName,
20723
+ version: options.targetVersion,
20724
+ manifestSpec: finalManifest.spec,
20725
+ appliedMigrations: UPGRADE_MIGRATIONS.map((migration) => migration.id)
20726
+ };
20727
+ const manifestChanged = migratedManifestContent !== normalizedSource;
20728
+ const finalManifestContent = manifestChanged ? migratedManifestContent : manifestInspection.currentContent;
20729
+ const targets = [
20730
+ // Keep an unchanged manifest in the transaction preflight so generated
20731
+ // files can never be committed from bytes that changed after planning.
20732
+ [MANIFEST_REL, finalManifestContent],
20733
+ ...renderTargets(finalManifest),
20734
+ [UPGRADE_STATE_REL, renderState(nextState)]
20735
+ ];
20736
+ const preflight = inspectManagedFiles(repo, targets);
20737
+ const generatedPaths = new Set(renderTargets(finalManifest).map(([path]) => path));
20738
+ try {
20739
+ assertManagedFileAdoption(
20740
+ repo,
20741
+ preflight.filter((inspection) => generatedPaths.has(inspection.relativePath)),
20742
+ false
20743
+ );
20744
+ } catch (error) {
20745
+ return fail(report, error.message);
20746
+ }
20747
+ report.changedFiles = preflight.filter((inspection) => !inspection.satisfiesDesired).map((inspection) => inspection.relativePath);
20748
+ const stateMatchesManifest = state?.manifestSpec === finalManifest.spec;
20749
+ const stateMatchesVersion = state?.version === options.targetVersion;
20750
+ const stateMatchesMigrations = state?.appliedMigrations.join("\0") === nextState.appliedMigrations.join("\0");
20751
+ const needsUpgrade = report.changedFiles.length > 0 || !stateMatchesManifest || !stateMatchesVersion || !stateMatchesMigrations;
20752
+ if (options.check) {
20753
+ report.status = needsUpgrade ? "upgrade-available" : "current";
20754
+ return report;
20755
+ }
20756
+ if (!needsUpgrade) {
20757
+ report.status = "current";
20758
+ report.pendingMigrations = [];
20759
+ return report;
20760
+ }
20761
+ const expected = new Map(preflight.map((inspection) => [inspection.relativePath, inspection]));
20762
+ const result = writeManagedFiles(repo, targets, {
20763
+ authorize: (inspections) => {
20764
+ for (const inspection of inspections) {
20765
+ const prior = expected.get(inspection.relativePath);
20766
+ if (!prior || !sameInspection(prior, inspection))
20767
+ throw new Error(`upgrade target changed after inspection: ${inspection.relativePath}`);
20768
+ }
20769
+ assertManagedFileAdoption(
20770
+ repo,
20771
+ inspections.filter((inspection) => generatedPaths.has(inspection.relativePath)),
20772
+ false
20773
+ );
20774
+ }
20775
+ });
20776
+ report.status = "upgraded";
20777
+ report.changedFiles = result.written;
20778
+ report.appliedMigrations = nextState.appliedMigrations;
20779
+ return report;
20780
+ }
20781
+ function upgradeRepository(repo, options) {
20782
+ try {
20783
+ return internalUpgrade(repo, options);
20784
+ } catch (error) {
20785
+ return fail(reportBase(options), error.message);
20786
+ }
20787
+ }
20788
+ function initialUpgradeState(packageName, version, manifestSpec) {
20789
+ return renderState({
20790
+ schema: UPGRADE_STATE_SCHEMA,
20791
+ package: packageName,
20792
+ version,
20793
+ manifestSpec,
20794
+ appliedMigrations: UPGRADE_MIGRATIONS.map((migration) => migration.id)
20795
+ });
20796
+ }
20797
+
20355
20798
  // src/commands/init.ts
20356
20799
  function manifestTemplate(name) {
20357
20800
  return `spec: ai-harness/v0
@@ -20402,6 +20845,7 @@ playbooks:
20402
20845
  function initCmd(repo, name, force) {
20403
20846
  const targets = [
20404
20847
  [".agents/manifest.yaml", manifestTemplate(name)],
20848
+ [UPGRADE_STATE_REL, initialUpgradeState(package_default.name, package_default.version, "ai-harness/v0")],
20405
20849
  [
20406
20850
  ".agents/knowledge/domain.md",
20407
20851
  `# ${name} \u2014 domain
@@ -20720,213 +21164,6 @@ var import_node_child_process4 = require("node:child_process");
20720
21164
  var import_node_fs7 = require("node:fs");
20721
21165
  var import_node_os = require("node:os");
20722
21166
  var import_node_path7 = require("node:path");
20723
-
20724
- // src/git.ts
20725
- var import_node_child_process3 = require("node:child_process");
20726
- var import_node_crypto5 = require("node:crypto");
20727
- var import_node_fs6 = require("node:fs");
20728
- var import_node_path6 = require("node:path");
20729
- var GitDiffError = class extends Error {
20730
- constructor(kind, message) {
20731
- super(message);
20732
- this.kind = kind;
20733
- this.name = "GitDiffError";
20734
- }
20735
- kind;
20736
- };
20737
- var EMPTY_TREE_BASE = "(empty-tree)";
20738
- function errorText(error) {
20739
- const e = error;
20740
- const stderr = Buffer.isBuffer(e.stderr) ? e.stderr.toString("utf8") : e.stderr;
20741
- return String(stderr || e.message || error).trim();
20742
- }
20743
- function git(repo, args) {
20744
- try {
20745
- return (0, import_node_child_process3.execFileSync)("git", args, {
20746
- cwd: repo,
20747
- encoding: "utf8",
20748
- stdio: ["ignore", "pipe", "pipe"],
20749
- maxBuffer: 32 * 1024 * 1024
20750
- });
20751
- } catch (error) {
20752
- throw new GitDiffError("diff-failed", `git ${args[0] ?? "command"} failed: ${errorText(error)}`);
20753
- }
20754
- }
20755
- function tryCommit(repo, ref) {
20756
- try {
20757
- return (0, import_node_child_process3.execFileSync)("git", ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`], {
20758
- cwd: repo,
20759
- encoding: "utf8",
20760
- stdio: ["ignore", "pipe", "pipe"]
20761
- }).trim();
20762
- } catch {
20763
- return null;
20764
- }
20765
- }
20766
- function gitRoot(repo) {
20767
- try {
20768
- return (0, import_node_child_process3.execFileSync)("git", ["rev-parse", "--show-toplevel"], {
20769
- cwd: repo,
20770
- encoding: "utf8",
20771
- stdio: ["ignore", "pipe", "pipe"]
20772
- }).trim();
20773
- } catch (error) {
20774
- throw new GitDiffError("not-a-repo", `not a git repo: ${errorText(error)}`);
20775
- }
20776
- }
20777
- function gitAdminDir(repo) {
20778
- try {
20779
- return (0, import_node_child_process3.execFileSync)("git", ["rev-parse", "--absolute-git-dir"], {
20780
- cwd: repo,
20781
- encoding: "utf8",
20782
- stdio: ["ignore", "pipe", "pipe"]
20783
- }).trim();
20784
- } catch (error) {
20785
- throw new GitDiffError("not-a-repo", `cannot resolve git metadata dir: ${errorText(error)}`);
20786
- }
20787
- }
20788
- function parseNameStatus(raw, layer) {
20789
- const fields = raw.split("\0");
20790
- if (fields.at(-1) === "") fields.pop();
20791
- const entries = [];
20792
- for (let i = 0; i < fields.length; ) {
20793
- const status = fields[i++] ?? "";
20794
- const code = status[0] ?? "M";
20795
- const first = fields[i++];
20796
- if (first === void 0) throw new GitDiffError("diff-failed", "git diff returned malformed name-status output");
20797
- if (code === "R") {
20798
- const second = fields[i++];
20799
- if (second === void 0) throw new GitDiffError("diff-failed", "git diff returned malformed rename output");
20800
- entries.push({ path: first, status: "D", layer }, { path: second, status: "A", layer });
20801
- } else if (code === "C") {
20802
- const second = fields[i++];
20803
- if (second === void 0) throw new GitDiffError("diff-failed", "git diff returned malformed copy output");
20804
- entries.push({ path: second, status: "A", layer });
20805
- } else {
20806
- entries.push({ path: first, status: code, layer });
20807
- }
20808
- }
20809
- return entries;
20810
- }
20811
- function nulList(raw) {
20812
- return raw.split("\0").filter(Boolean);
20813
- }
20814
- function canonicalPath(path) {
20815
- try {
20816
- return (0, import_node_fs6.realpathSync)(path);
20817
- } catch {
20818
- return (0, import_node_path6.resolve)(path);
20819
- }
20820
- }
20821
- function targetPrefix(root, target) {
20822
- const native = (0, import_node_path6.relative)(root, target);
20823
- if (!native) return "";
20824
- if ((0, import_node_path6.isAbsolute)(native) || native === ".." || native.startsWith(`..${import_node_path6.sep}`))
20825
- throw new GitDiffError("not-a-repo", `target is outside its Git worktree: ${target}`);
20826
- return native.split(import_node_path6.sep).join("/");
20827
- }
20828
- function scopeEntries(entries, prefix) {
20829
- if (!prefix) return entries;
20830
- const start = `${prefix}/`;
20831
- return entries.filter((entry) => entry.path.startsWith(start)).map((entry) => ({ ...entry, path: entry.path.slice(start.length) }));
20832
- }
20833
- function digestPath(repo, rel) {
20834
- const abs = (0, import_node_path6.join)(repo, rel);
20835
- try {
20836
- const stat = (0, import_node_fs6.lstatSync)(abs);
20837
- if (stat.isSymbolicLink()) return `symlink:${(0, import_node_fs6.readlinkSync)(abs)}`;
20838
- if (stat.isDirectory()) {
20839
- try {
20840
- const head = (0, import_node_child_process3.execFileSync)("git", ["-C", abs, "rev-parse", "--verify", "HEAD"], {
20841
- encoding: "utf8",
20842
- stdio: ["ignore", "pipe", "pipe"]
20843
- }).trim();
20844
- const nested = collectChanges(abs, "HEAD", { mode: "exact" });
20845
- return `gitlink:${head}:${nested.fingerprint}`;
20846
- } catch {
20847
- return `directory:${stat.mode}`;
20848
- }
20849
- }
20850
- if (!stat.isFile()) return `other:${stat.mode}`;
20851
- const gitMode = stat.mode & 73 ? "100755" : "100644";
20852
- return `file:${gitMode}:${(0, import_node_crypto5.createHash)("sha256").update((0, import_node_fs6.readFileSync)(abs)).digest("hex")}`;
20853
- } catch {
20854
- return "(missing)";
20855
- }
20856
- }
20857
- function digestIndex(repo, rel) {
20858
- try {
20859
- const entry = (0, import_node_child_process3.execFileSync)("git", ["ls-files", "--stage", "-z", "--", rel], {
20860
- cwd: repo,
20861
- encoding: "utf8",
20862
- stdio: ["ignore", "pipe", "pipe"]
20863
- });
20864
- return entry || "(missing-index)";
20865
- } catch (error) {
20866
- throw new GitDiffError("diff-failed", `cannot fingerprint Git index entry ${rel}: ${errorText(error)}`);
20867
- }
20868
- }
20869
- function fingerprint(repo, resolvedBase, entries) {
20870
- const hash = (0, import_node_crypto5.createHash)("sha256");
20871
- hash.update("harness-kit/change-fingerprint/v1\0");
20872
- hash.update(resolvedBase ?? EMPTY_TREE_BASE);
20873
- for (const entry of entries) {
20874
- hash.update("\0");
20875
- hash.update(entry.layer);
20876
- hash.update("\0");
20877
- hash.update(entry.status);
20878
- hash.update("\0");
20879
- hash.update(entry.path);
20880
- hash.update("\0");
20881
- hash.update(entry.layer === "index" ? digestIndex(repo, entry.path) : digestPath(repo, entry.path));
20882
- }
20883
- return hash.digest("hex");
20884
- }
20885
- function collectChanges(repoInput, base = "HEAD", opts = {}) {
20886
- const target = canonicalPath(repoInput);
20887
- const root = canonicalPath(gitRoot(target));
20888
- const prefix = targetPrefix(root, target);
20889
- const head = tryCommit(root, "HEAD");
20890
- let baseCommit;
20891
- if (base === EMPTY_TREE_BASE) {
20892
- baseCommit = null;
20893
- } else {
20894
- baseCommit = tryCommit(root, base);
20895
- if (!baseCommit && base === "HEAD" && !head) baseCommit = null;
20896
- else if (!baseCommit) throw new GitDiffError("invalid-base", `invalid base ref: ${base}`);
20897
- }
20898
- let resolvedBase = baseCommit;
20899
- if ((opts.mode ?? "merge-base") === "merge-base" && baseCommit && head) {
20900
- try {
20901
- resolvedBase = git(root, ["merge-base", baseCommit, head]).trim();
20902
- } catch (error) {
20903
- throw new GitDiffError("invalid-base", `invalid base ref or no merge base: ${base} (${error.message})`);
20904
- }
20905
- }
20906
- let entries;
20907
- if (resolvedBase) {
20908
- entries = parseNameStatus(git(root, ["diff", "--cached", "--name-status", "-z", resolvedBase, "--"]), "index");
20909
- } else {
20910
- entries = nulList(git(root, ["ls-files", "--cached", "-z"])).map((path) => ({ path, status: "A", layer: "index" }));
20911
- }
20912
- entries.push(...parseNameStatus(git(root, ["diff", "--name-status", "-z", "--"]), "worktree"));
20913
- for (const path of nulList(git(root, ["ls-files", "--others", "--exclude-standard", "-z"]))) {
20914
- entries.push({ path, status: "A", layer: "untracked" });
20915
- }
20916
- entries = scopeEntries(entries, prefix);
20917
- entries = entries.sort((a, b) => a.path.localeCompare(b.path) || a.layer.localeCompare(b.layer) || a.status.localeCompare(b.status));
20918
- const files = [...new Set(entries.map((entry) => entry.path))];
20919
- return {
20920
- requestedBase: base,
20921
- resolvedBase,
20922
- head,
20923
- files,
20924
- entries,
20925
- fingerprint: fingerprint(target, resolvedBase, entries)
20926
- };
20927
- }
20928
-
20929
- // src/codex-linked-hooks.ts
20930
21167
  var CODEX_LINKED_PROTOCOL = "ai-harness/codex-linked-dispatch/v1";
20931
21168
  var DISPATCH_ID = "codex-linked-dispatch-v1";
20932
21169
  var DISPATCHER_REL = `harness-kit/${DISPATCH_ID}.cjs`;
@@ -24217,6 +24454,99 @@ function recordAdoptionAuditCmd(repo, opts) {
24217
24454
  return 0;
24218
24455
  }
24219
24456
 
24457
+ // src/commands/upgrade.ts
24458
+ var import_node_util = require("node:util");
24459
+ function captureOutput(run) {
24460
+ const chunks = [];
24461
+ const originalLog = console.log;
24462
+ const originalWrite = process.stdout.write;
24463
+ console.log = (...args) => {
24464
+ chunks.push(`${(0, import_node_util.format)(...args)}
24465
+ `);
24466
+ };
24467
+ process.stdout.write = ((chunk) => {
24468
+ chunks.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8"));
24469
+ return true;
24470
+ });
24471
+ try {
24472
+ return { exitCode: run(), output: chunks.join("") };
24473
+ } catch (error) {
24474
+ return { exitCode: 1, output: chunks.join(""), error: error.message };
24475
+ } finally {
24476
+ console.log = originalLog;
24477
+ process.stdout.write = originalWrite;
24478
+ }
24479
+ }
24480
+ function runJsonVerification(repo, report) {
24481
+ const doctor = captureOutput(() => doctorCmd(repo, { details: true }));
24482
+ const verify = captureOutput(() => verifyCmd(repo, { json: true, details: true, recordManualEvidence: false }));
24483
+ let verifyReport;
24484
+ try {
24485
+ verifyReport = JSON.parse(verify.output);
24486
+ } catch {
24487
+ verifyReport = void 0;
24488
+ }
24489
+ report.verification = {
24490
+ doctor: { exitCode: doctor.exitCode, output: doctor.output, ...doctor.error ? { error: doctor.error } : {} },
24491
+ verify: verifyReport === void 0 ? { exitCode: verify.exitCode, output: verify.output, ...verify.error ? { error: verify.error } : {} } : { exitCode: verify.exitCode, report: verifyReport, ...verify.error ? { error: verify.error } : {} }
24492
+ };
24493
+ if (doctor.exitCode !== 0 || verify.exitCode !== 0) {
24494
+ report.status = "incomplete";
24495
+ report.errors.push("post-upgrade doctor or verify failed");
24496
+ return 1;
24497
+ }
24498
+ return 0;
24499
+ }
24500
+ function printHumanReport(report) {
24501
+ if (report.status === "blocked") {
24502
+ for (const message of report.errors) err(message);
24503
+ return;
24504
+ }
24505
+ if (report.status === "upgrade-available") {
24506
+ warn(`upgrade available: ${report.fromVersion ?? "untracked"} -> ${report.toVersion}`);
24507
+ if (report.pendingMigrations.length) info(`Pending migrations: ${report.pendingMigrations.join(", ")}`);
24508
+ if (report.changedFiles.length) info(`Files to update: ${report.changedFiles.join(", ")}`);
24509
+ if (report.dirtyFiles.length) warn("apply is blocked until the target Git scope is clean");
24510
+ return;
24511
+ }
24512
+ if (report.status === "current") {
24513
+ ok(`repository is current at ${report.toVersion}`);
24514
+ return;
24515
+ }
24516
+ ok(`upgraded repository: ${report.fromVersion ?? "untracked"} -> ${report.toVersion}`);
24517
+ for (const path of report.changedFiles) ok(`wrote ${path}`);
24518
+ info("Lifecycle hooks were not changed. Manage them explicitly with `harness-kit install-hooks`.");
24519
+ }
24520
+ function upgradeCmd(repo, options = {}) {
24521
+ const report = upgradeRepository(repo, {
24522
+ packageName: package_default.name,
24523
+ targetVersion: package_default.version,
24524
+ check: options.check
24525
+ });
24526
+ if (options.json) {
24527
+ let code = report.status === "blocked" ? 1 : report.status === "upgrade-available" ? 2 : 0;
24528
+ if (!options.check && (report.status === "upgraded" || report.status === "current"))
24529
+ code = runJsonVerification(repo, report);
24530
+ process.stdout.write(`${JSON.stringify(report)}
24531
+ `);
24532
+ return code;
24533
+ }
24534
+ printHumanReport(report);
24535
+ if (report.status === "blocked") return 1;
24536
+ if (report.status === "upgrade-available") return 2;
24537
+ if (options.check) return 0;
24538
+ info("\nRunning post-upgrade doctor --details ...");
24539
+ const doctorCode = doctorCmd(repo, { details: true });
24540
+ info("\nRunning post-upgrade verify --details ...");
24541
+ const verifyCode = verifyCmd(repo, { details: true, recordManualEvidence: false });
24542
+ if (doctorCode !== 0 || verifyCode !== 0) {
24543
+ err("upgrade applied, but post-upgrade verification is incomplete");
24544
+ return 1;
24545
+ }
24546
+ ok("upgrade complete; doctor and verify exited 0 (read their readiness output above)");
24547
+ return 0;
24548
+ }
24549
+
24220
24550
  // src/cli.ts
24221
24551
  function guard(fn) {
24222
24552
  try {
@@ -24246,6 +24576,7 @@ program2.command("sync").description("generate tool files (AGENTS.md, CLAUDE.md)
24246
24576
  })
24247
24577
  )
24248
24578
  );
24579
+ program2.command("upgrade").description("upgrade this repository to the running harness-kit version").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--check", "read-only; exit 2 when an upgrade is available", false).option("--json", "machine-readable single-report output", false).action((o) => guard(() => upgradeCmd(repoOf(o), { check: o.check, json: o.json })));
24249
24580
  program2.command("prepare-adoption").description("render a private, repository-external candidate bundle for blind legacy review").option("-C, --repo <dir>", "target repo dir (default: current directory)").requiredOption("--out <dir>", "new or empty output directory outside the repository").option("--json", "machine-readable output", false).action((o) => guard(() => prepareAdoptionCmd(repoOf(o), { output: o.out, json: o.json })));
24250
24581
  program2.command("record-adoption-audit").description("record a declared pass/fail review receipt bound to one adoption candidate and report").option("-C, --repo <dir>", "target repo dir (default: current directory)").requiredOption("--candidate <dir>", "prepared adoption bundle outside the repository").requiredOption("--verdict <pass|fail>", "declared audit verdict").requiredOption("--report <file>", "independent audit report to hash and bind").requiredOption("--reason <text>", "non-empty reviewer rationale").option("--out <receipt>", "receipt path outside the repository (default: candidate bundle)").option("--json", "machine-readable output", false).action(
24251
24582
  (o) => guard(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@erzhe/harness-kit",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "type": "module",
5
5
  "description": "AI-friendly repo harness: a manifest.yaml single source of truth that generates AGENTS.md / CLAUDE.md / Cursor rules and enforces invariants, contracts and drift via `harness-kit verify`.",
6
6
  "keywords": [