@opendesignai/harness 0.4.0-alpha.0 → 0.5.0-alpha.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.
package/dist/cli.mjs CHANGED
@@ -4,14 +4,15 @@ import { isDeepStrictEqual, parseArgs } from "node:util";
4
4
  import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
5
5
  import path from "node:path";
6
6
  import { Visitor, parseSync } from "oxc-parser";
7
- import { closeSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
7
+ import { closeSync, constants, copyFileSync, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
8
8
  import { createHash, randomUUID } from "node:crypto";
9
9
  import { LineCounter, isMap, isScalar, parse, parseAllDocuments, parseDocument } from "yaml";
10
- import { tmpdir } from "node:os";
10
+ import { availableParallelism, tmpdir } from "node:os";
11
11
  import { runJscpd } from "jscpd";
12
12
  import { createInterface } from "node:readline";
13
- import semver from "semver";
14
13
  import { createRequire } from "node:module";
14
+ import semver from "semver";
15
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
15
16
  // src/plugin/meta.ts
16
17
  const DOCS_BASE = "https://github.com/nexu-io/od-harness/blob/main/docs/rules";
17
18
  function docsUrl(rule) {
@@ -221,6 +222,122 @@ function compileRegExp(pattern, flags, option) {
221
222
  // src/plugin/rules/no-api-path-literal.ts
222
223
  const RULE$12 = "no-api-path-literal";
223
224
  const DEFAULT_PREFIXES = ["/api/", "/motion-api/"];
225
+ const ROUTE_METHODS = /* @__PURE__ */ new Set([
226
+ "get",
227
+ "post",
228
+ "put",
229
+ "patch",
230
+ "delete",
231
+ "head",
232
+ "options",
233
+ "connect",
234
+ "trace",
235
+ "all",
236
+ "use",
237
+ "route",
238
+ "on"
239
+ ]);
240
+ const ROUTER_NAMES = /* @__PURE__ */ new Set([
241
+ "app",
242
+ "router",
243
+ "routes",
244
+ "server",
245
+ "hono",
246
+ "fastify"
247
+ ]);
248
+ const ROUTER_CONSTRUCTORS = /* @__PURE__ */ new Set([
249
+ "Hono",
250
+ "Router",
251
+ "KoaRouter"
252
+ ]);
253
+ const ROUTER_FACTORIES = /* @__PURE__ */ new Set([
254
+ "express",
255
+ "Router",
256
+ "fastify"
257
+ ]);
258
+ const CLIENT_NAMES = /* @__PURE__ */ new Set([
259
+ "axios",
260
+ "ky",
261
+ "client"
262
+ ]);
263
+ const HANDLER_REFERENCES = /* @__PURE__ */ new Set([
264
+ "Identifier",
265
+ "MemberExpression",
266
+ "CallExpression",
267
+ "ArrayExpression",
268
+ "SpreadElement"
269
+ ]);
270
+ const HTTP_METHOD = /^(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|CONNECT|TRACE)$/i;
271
+ const EQUALITY_OPERATORS = /* @__PURE__ */ new Set([
272
+ "==",
273
+ "===",
274
+ "!=",
275
+ "!=="
276
+ ]);
277
+ function isHttpMethod(node) {
278
+ const method = staticString(node);
279
+ return method !== null && HTTP_METHOD.test(method);
280
+ }
281
+ function routeMethod(callee) {
282
+ const method = callee && propertyName(callee);
283
+ return method !== null && ROUTE_METHODS.has(method) ? method : null;
284
+ }
285
+ function routeRoot(node) {
286
+ let root = unwrap(node) ?? node;
287
+ while (root.type === "CallExpression") {
288
+ const callee = unwrap(root.callee);
289
+ if (callee?.type !== "MemberExpression" || routeMethod(callee) === null) break;
290
+ root = unwrap(callee.object) ?? callee.object;
291
+ }
292
+ return root;
293
+ }
294
+ function followedByRouteCall(call) {
295
+ const member = call.parent;
296
+ if (member?.type !== "MemberExpression" || member.object !== call) return false;
297
+ const next = member.parent;
298
+ return next?.type === "CallExpression" && next.callee === member && routeMethod(member) !== null;
299
+ }
300
+ function isRouteRegistration(node, call, callee) {
301
+ const method = routeMethod(callee);
302
+ if (method === null) return false;
303
+ const pathIndex = method === "on" ? 1 : 0;
304
+ const path = call.arguments[pathIndex];
305
+ const isOnPathElement = method === "on" && path?.type === "ArrayExpression" && node.parent === path;
306
+ if (path !== node && !isOnPathElement) return false;
307
+ if (method === "on") {
308
+ const verbs = unwrap(call.arguments[0]);
309
+ if (!(verbs?.type === "ArrayExpression" ? verbs.elements.length > 0 && verbs.elements.every(isHttpMethod) : isHttpMethod(verbs))) return false;
310
+ }
311
+ const root = routeRoot(callee.object);
312
+ const receiver = calleeName(root.type === "CallExpression" || root.type === "NewExpression" ? root.callee : root);
313
+ if (receiver !== null && CLIENT_NAMES.has(receiver)) return false;
314
+ let routerNames = ROUTER_NAMES;
315
+ if (root.type === "CallExpression") routerNames = ROUTER_FACTORIES;
316
+ if (root.type === "NewExpression") routerNames = ROUTER_CONSTRUCTORS;
317
+ const namedRouter = receiver !== null && routerNames.has(receiver);
318
+ if (method === "route") return namedRouter && (call.arguments.length >= 2 || followedByRouteCall(call));
319
+ return call.arguments.slice(pathIndex + 1).some((argument) => {
320
+ const handler = unwrap(argument);
321
+ return handler !== null && (handler.type === "ArrowFunctionExpression" || handler.type === "FunctionExpression" || namedRouter && HANDLER_REFERENCES.has(handler.type));
322
+ });
323
+ }
324
+ function isPathname(node) {
325
+ const value = unwrap(node);
326
+ if (!value) return false;
327
+ return value.type === "Identifier" ? value.name === "pathname" : propertyName(value) === "pathname";
328
+ }
329
+ function isRouteDefinition(node) {
330
+ const parent = node.parent;
331
+ if (!parent) return false;
332
+ if (parent.type === "BinaryExpression" && EQUALITY_OPERATORS.has(parent.operator)) return parent.left === node && isPathname(parent.right) || parent.right === node && isPathname(parent.left);
333
+ if (parent.type === "SwitchCase" && parent.test === node) return parent.parent?.type === "SwitchStatement" && isPathname(parent.parent.discriminant);
334
+ const call = parent.type === "ArrayExpression" ? parent.parent : parent;
335
+ if (call?.type !== "CallExpression") return false;
336
+ const callee = unwrap(call.callee);
337
+ if (callee?.type !== "MemberExpression") return false;
338
+ if (propertyName(callee) === "startsWith") return call.arguments[0] === node && isPathname(callee.object);
339
+ return isRouteRegistration(node, call, callee);
340
+ }
224
341
  const noApiPathLiteral = {
225
342
  meta: {
226
343
  type: "problem",
@@ -259,7 +376,9 @@ const noApiPathLiteral = {
259
376
  function check(node, text) {
260
377
  if (isModuleSource(node) || isInTypePosition(node)) return;
261
378
  const prefix = matchPrefix(text);
262
- if (prefix !== null) context.report({
379
+ if (prefix === null) return;
380
+ if (staticString(node) !== null && isRouteDefinition(node)) return;
381
+ context.report({
263
382
  node,
264
383
  messageId: "apiPath",
265
384
  data: {
@@ -1651,7 +1770,7 @@ const noWindowBus = {
1651
1770
  };
1652
1771
  // src/plugin/version.ts
1653
1772
  /** Kept in sync with package.json by test/plugin.test.ts. */
1654
- const VERSION = "0.4.0-alpha.0";
1773
+ const VERSION = "0.5.0-alpha.0";
1655
1774
  // src/plugin/index.ts
1656
1775
  const plugin = {
1657
1776
  meta: {
@@ -1821,32 +1940,36 @@ function resolveRef(cwd, ref) {
1821
1940
  if (result.status !== 0) throw new EnvironmentError(`cannot resolve base ref ${JSON.stringify(ref)}. In CI, check out with full history (fetch-depth: 0) or fetch the base commit first.`);
1822
1941
  return result.stdout.trim();
1823
1942
  }
1824
- /**
1825
- * The commit `git merge-base HEAD <ref>` names, or why there is none: `ref` does not resolve (not
1826
- * fetched), or HEAD and `ref` share no history (unrelated, or cut off by a shallow clone).
1827
- */
1828
- function mergeBase(cwd, ref) {
1829
- const resolved = spawnSync("git", [
1943
+ function readGitRef(cwd, args, absent) {
1944
+ const result = spawnSync("git", args, {
1945
+ cwd,
1946
+ encoding: "utf8"
1947
+ });
1948
+ if (result.status === absent) return null;
1949
+ if (result.status !== 0) throw new EnvironmentError(gitFailure(args, result.error ?? result));
1950
+ return result.stdout;
1951
+ }
1952
+ /** Local checks need the commit where HEAD diverged from the selected base. */
1953
+ function mergeBase(cwd, ref, read = readGitRef) {
1954
+ const sha = read(cwd, [
1830
1955
  "rev-parse",
1831
1956
  "--verify",
1832
1957
  "--quiet",
1958
+ "--end-of-options",
1833
1959
  `${ref}^{commit}`
1834
- ], {
1835
- cwd,
1836
- encoding: "utf8"
1837
- });
1838
- if (resolved.status !== 0) return { skip: `cannot resolve ${ref} (fetch it to enable the check)` };
1839
- const result = spawnSync("git", [
1960
+ ], 1);
1961
+ if (!sha) {
1962
+ const branch = /^origin\/([a-z0-9_./][a-z0-9_./-]*)$/i.exec(ref)?.[1];
1963
+ const fetch = branch ? `git fetch origin ${branch}:refs/remotes/origin/${branch}` : "git fetch";
1964
+ throw new EnvironmentError(`cannot resolve ${JSON.stringify(ref)}. Run \`${fetch}\` or select an available base commit from this branch's history.`);
1965
+ }
1966
+ const commit = read(cwd, [
1840
1967
  "merge-base",
1841
1968
  "HEAD",
1842
- resolved.stdout.trim()
1843
- ], {
1844
- cwd,
1845
- encoding: "utf8"
1846
- });
1847
- const commit = result.status === 0 ? result.stdout.trim() : "";
1848
- if (commit === "") return { skip: `no merge base with ${ref} (fetch more history to enable the check)` };
1849
- return { commit };
1969
+ sha.trim()
1970
+ ], 1)?.trim();
1971
+ if (!commit) throw new EnvironmentError(`no merge base with ${JSON.stringify(ref)}. In a shallow clone, run \`git fetch --unshallow\`. For unrelated histories, select the intended base from this branch's history.`);
1972
+ return commit;
1850
1973
  }
1851
1974
  /** `<commit>:<path>` with the path read relative to the working directory, like the working tree. */
1852
1975
  function revPath(commit, file) {
@@ -3638,6 +3761,30 @@ function childEnv(extra) {
3638
3761
  function isGitHubActions() {
3639
3762
  return process.env.GITHUB_ACTIONS === "true";
3640
3763
  }
3764
+ function enabled$1(value) {
3765
+ return !/^(?:|0|false|no|off)$/i.test(value?.trim() ?? "");
3766
+ }
3767
+ function verifySlotEnv() {
3768
+ return {
3769
+ bypass: enabled$1(process.env.CI) || enabled$1(process.env.GITHUB_ACTIONS) || process.env["OD_HARNESS_NO_SLOT"] === "1",
3770
+ capacity: process.env["OD_HARNESS_VERIFY_SLOTS"],
3771
+ directory: process.env["OD_HARNESS_SLOT_DIR"]
3772
+ };
3773
+ }
3774
+ function verifyThrottleEnv(activeSlots, ncpu = availableParallelism()) {
3775
+ if (activeSlots <= 1) return {};
3776
+ const perSlot = Math.max(2, Math.floor(ncpu / activeSlots));
3777
+ return Object.fromEntries(Object.entries({
3778
+ GOMAXPROCS: String(perSlot),
3779
+ RAYON_NUM_THREADS: String(perSlot),
3780
+ UV_THREADPOOL_SIZE: String(perSlot),
3781
+ VITEST_MAX_WORKERS: String(Math.max(2, Math.min(4, perSlot))),
3782
+ PNPM_WORKSPACE_CONCURRENCY: String(Math.min(3, perSlot))
3783
+ }).filter(([name]) => process.env[name] === void 0));
3784
+ }
3785
+ function hookLogMode() {
3786
+ return process.env["OD_HARNESS_HOOK_LOG"];
3787
+ }
3641
3788
  // src/cli/diagnostic.ts
3642
3789
  function diagnosticMessage({ message, fix, exemption, docs, severity }) {
3643
3790
  return [
@@ -3692,10 +3839,8 @@ function printReport(report) {
3692
3839
  }
3693
3840
  function printGate(command, outcome, summary, format, relativeTo) {
3694
3841
  const status = outcome.ok ? 0 : 1;
3695
- const skipped = outcome.skipped === void 0 ? "" : `skipped: ${outcome.skipped}.`;
3696
3842
  if (format === "text") {
3697
- if (skipped) console.warn(`od-harness ${command}: ${skipped}`);
3698
- else print(command, outcome, summary);
3843
+ print(command, outcome, summary);
3699
3844
  if (!isGitHubActions()) return status;
3700
3845
  }
3701
3846
  const prefix = relativeTo && outcome.diagnostics.length > 0 ? repositoryPrefix(relativeTo) : "";
@@ -3710,20 +3855,16 @@ function printGate(command, outcome, summary, format, relativeTo) {
3710
3855
  diagnostics
3711
3856
  };
3712
3857
  if (summary) report.summary = summary;
3713
- if (skipped) report.notes = [skipped];
3714
- else if (outcome.notes.length > 0) report.notes = outcome.notes;
3858
+ if (outcome.notes.length > 0) report.notes = outcome.notes;
3715
3859
  printReport(report);
3716
3860
  return status;
3717
3861
  }
3718
3862
  for (const diagnostic of diagnostics) reportDiagnostic(diagnostic, { format: "github" });
3719
- if (format === "github") {
3720
- if (skipped) console.warn(`od-harness ${command}: ${skipped}`);
3721
- else print(command, {
3722
- ok: outcome.ok,
3723
- errors: [],
3724
- notes: []
3725
- }, summary);
3726
- }
3863
+ if (format === "github") print(command, {
3864
+ ok: outcome.ok,
3865
+ errors: [],
3866
+ notes: []
3867
+ }, summary);
3727
3868
  return status;
3728
3869
  }
3729
3870
  // src/cli/comments.ts
@@ -4241,6 +4382,46 @@ function checkHarnessSource(root) {
4241
4382
  if (pnpmLock.length > 0 && !checkPnpmLock(pnpmLock, pins, workspace)) errors.push(`pnpm-lock.yaml must resolve ${HARNESS_PACKAGE} from the npm registry at the pinned version with integrity.`);
4242
4383
  return errors;
4243
4384
  }
4385
+ // src/cli/verify-process.ts
4386
+ function vitestBin(cwd, config) {
4387
+ const project = config ? path.dirname(path.resolve(cwd, config)) : cwd;
4388
+ for (const directory of /* @__PURE__ */ new Set([project, cwd])) try {
4389
+ const manifest = createRequire(path.join(directory, "package.json")).resolve("vitest/package.json");
4390
+ return path.join(path.dirname(manifest), "vitest.mjs");
4391
+ } catch (error) {
4392
+ const code = error.code;
4393
+ if (code !== "MODULE_NOT_FOUND" && code !== "ERR_PACKAGE_PATH_NOT_EXPORTED") throw error;
4394
+ }
4395
+ }
4396
+ function invoke(cwd, base, bin, args, extraEnv) {
4397
+ const env = childEnv({
4398
+ ...extraEnv,
4399
+ HARNESS_BASE_REF: base
4400
+ });
4401
+ env.PATH = [path.join(cwd, "node_modules", ".bin"), env.PATH].filter(Boolean).join(path.delimiter);
4402
+ return new Promise((resolve) => {
4403
+ execFile(bin, args, {
4404
+ cwd,
4405
+ env,
4406
+ encoding: "utf8",
4407
+ maxBuffer: 67108864
4408
+ }, (error, stdout, stderr) => {
4409
+ const code = error ? typeof error.code === "number" ? error.code : null : 0;
4410
+ resolve({
4411
+ code,
4412
+ stdout,
4413
+ stderr,
4414
+ problem: code === null ? error?.message ?? "Process aborted" : null
4415
+ });
4416
+ });
4417
+ });
4418
+ }
4419
+ function commandOutput(result) {
4420
+ return [result.stderr.trim(), result.stdout.trim()].filter(Boolean).join("\n");
4421
+ }
4422
+ function shellCommand(bin, args) {
4423
+ return [bin, ...args].map((arg) => /^[\w+./=@:-]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`).join(" ");
4424
+ }
4244
4425
  // src/cli/doctor.ts
4245
4426
  function checkInstallation(root) {
4246
4427
  const file = `node_modules/${HARNESS_PACKAGE}/package.json`;
@@ -4252,7 +4433,19 @@ function checkInstallation(root) {
4252
4433
  if (manifest["name"] !== "@opendesignai/harness" || versions.some((version) => version !== manifest["version"])) return [`Installed ${HARNESS_PACKAGE} does not match the declared version (${[...new Set(versions)].join(", ")}). Reinstall from the lockfile.`];
4253
4434
  return [];
4254
4435
  }
4255
- async function runDoctor(cwd) {
4436
+ function spotlightNote(root, platform) {
4437
+ if (platform !== "darwin") return void 0;
4438
+ try {
4439
+ if (!lstatSync(path.join(root, ".git"), { throwIfNoEntry: false })?.isFile()) return void 0;
4440
+ const marker = ".metadata_never_index";
4441
+ const parentMarker = path.join(path.dirname(root), marker);
4442
+ if (existsSync(path.join(root, marker)) || existsSync(parentMarker)) return void 0;
4443
+ return `Reduce Spotlight indexing during parallel worktree runs with \`${shellCommand("touch", [parentMarker])}\`.`;
4444
+ } catch {
4445
+ return;
4446
+ }
4447
+ }
4448
+ async function runDoctor(cwd, platform = process.platform) {
4256
4449
  const root = projectRoot(cwd);
4257
4450
  const errors = checkInstallation(root);
4258
4451
  const notes = errors.length === 0 ? [`${HARNESS_PACKAGE} is installed at the declared version.`] : [];
@@ -4263,12 +4456,254 @@ async function runDoctor(cwd) {
4263
4456
  } catch (error) {
4264
4457
  errors.push(`Could not inspect Codex trust (${error.message}). Check that Codex CLI with hooks/list is on PATH.`);
4265
4458
  }
4459
+ const advisory = spotlightNote(root, platform);
4460
+ if (advisory) notes.push(advisory);
4266
4461
  return {
4267
4462
  ok: errors.length === 0,
4268
4463
  errors,
4269
4464
  notes
4270
4465
  };
4271
4466
  }
4467
+ // src/hook/runtime/io.ts
4468
+ function missing(error) {
4469
+ return error?.code === "ENOENT";
4470
+ }
4471
+ // src/hook/runtime/state.ts
4472
+ var UnsafeTempDirectoryError = class extends Error {
4473
+ constructor(options) {
4474
+ super("Set TMPDIR to a directory you own or one protected by the sticky bit.", options);
4475
+ }
4476
+ };
4477
+ function checkedTempDirectory(dir, uid) {
4478
+ let parent;
4479
+ let stat;
4480
+ try {
4481
+ parent = realpathSync.native(dir);
4482
+ stat = lstatSync(parent);
4483
+ } catch (cause) {
4484
+ throw new UnsafeTempDirectoryError({ cause });
4485
+ }
4486
+ if (!stat.isDirectory() || stat.uid !== uid && (stat.mode & 512) === 0) throw new UnsafeTempDirectoryError();
4487
+ return parent;
4488
+ }
4489
+ function stateDirectory(create = true) {
4490
+ const uid = process.getuid?.();
4491
+ const parent = uid === void 0 ? tmpdir() : checkedTempDirectory(tmpdir(), uid);
4492
+ const dir = path.join(parent, uid === void 0 ? "od-harness" : `od-harness-${uid}`);
4493
+ if (create) mkdirSync(dir, {
4494
+ recursive: true,
4495
+ mode: 448
4496
+ });
4497
+ const stat = lstatSync(dir);
4498
+ if (!stat.isDirectory() || uid !== void 0 && (stat.uid !== uid || (stat.mode & 63) !== 0)) throw new Error("Hook state directory must be owned by the current user and private");
4499
+ return dir;
4500
+ }
4501
+ function stopMarker(dir, root) {
4502
+ const key = createHash("sha256").update(root).digest("hex");
4503
+ return path.join(dir, `stop-${key}.unverified`);
4504
+ }
4505
+ function hasUnverifiedStop(cwd) {
4506
+ try {
4507
+ const dir = stateDirectory(false);
4508
+ const root = realpathSync.native(repositoryRoot$1(cwd));
4509
+ return existsSync(stopMarker(dir, root));
4510
+ } catch {
4511
+ return false;
4512
+ }
4513
+ }
4514
+ // src/hook/runtime/decision-log.ts
4515
+ function decisionLogName(now, daysAgo = 0) {
4516
+ return `decisions-${(/* @__PURE__ */ new Date(now - daysAgo * 864e5)).toISOString().slice(0, 10)}.jsonl`;
4517
+ }
4518
+ function openLogFile(file, access) {
4519
+ const fd = openSync(file, access | constants.O_NOFOLLOW | constants.O_NONBLOCK, 384);
4520
+ try {
4521
+ const stat = fstatSync(fd);
4522
+ if (!stat.isFile() || stat.nlink !== 1 || process.getuid && (stat.uid !== process.getuid() || (stat.mode & 63) !== 0)) throw new Error("Hook decision log must be a private regular file owned by the current user");
4523
+ return {
4524
+ fd,
4525
+ size: stat.size
4526
+ };
4527
+ } catch (error) {
4528
+ closeSync(fd);
4529
+ throw error;
4530
+ }
4531
+ }
4532
+ function openDecisionLog(file, append = false) {
4533
+ if (!append) return {
4534
+ ...openLogFile(file, constants.O_RDONLY),
4535
+ created: false
4536
+ };
4537
+ const access = constants.O_WRONLY | constants.O_APPEND;
4538
+ try {
4539
+ return {
4540
+ ...openLogFile(file, access),
4541
+ created: false
4542
+ };
4543
+ } catch (error) {
4544
+ if (!missing(error)) throw error;
4545
+ }
4546
+ try {
4547
+ return {
4548
+ ...openLogFile(file, access | constants.O_CREAT | constants.O_EXCL),
4549
+ created: true
4550
+ };
4551
+ } catch (error) {
4552
+ if (error.code !== "EEXIST") throw error;
4553
+ return {
4554
+ ...openLogFile(file, access),
4555
+ created: false
4556
+ };
4557
+ }
4558
+ }
4559
+ // src/hook/types.ts
4560
+ function isAgentKind(value) {
4561
+ return value === "cc" || value === "codex" || value === "agy";
4562
+ }
4563
+ function isHookEventKind(value) {
4564
+ return value === "pre-bash" || value === "pre-edit" || value === "post-tool" || value === "stop" || value === "session-start" || value === "pre-invocation";
4565
+ }
4566
+ // src/cli/hooks-report.ts
4567
+ const HOOKS_REPORT_USAGE = "Usage: od-harness hooks report [--days N] [--format text|json]";
4568
+ function parseRow(line) {
4569
+ try {
4570
+ const row = JSON.parse(line);
4571
+ if (row && typeof row.agent === "string" && isAgentKind(row.agent) && (row.decision === "allow" || row.decision === "allow-with-notice" || row.decision === "ask" || row.decision === "deny") && typeof row.ruleId === "string" && /^[a-z0-9-]+$/.test(row.ruleId) && typeof row.reason === "string" && (row.command === void 0 || typeof row.command === "string")) return row;
4572
+ } catch {
4573
+ return;
4574
+ }
4575
+ }
4576
+ function readDay(dir, name) {
4577
+ try {
4578
+ const { fd } = openDecisionLog(path.join(dir, name));
4579
+ try {
4580
+ return readFileSync(fd, "utf8");
4581
+ } finally {
4582
+ closeSync(fd);
4583
+ }
4584
+ } catch (error) {
4585
+ if (missing(error)) return "";
4586
+ throw error;
4587
+ }
4588
+ }
4589
+ function* decisionLines(days) {
4590
+ try {
4591
+ const dir = stateDirectory(false);
4592
+ const now = Date.now();
4593
+ for (let i = 0; i < days; i++) for (const line of readDay(dir, decisionLogName(now, i)).split("\n")) if (line !== "") yield line;
4594
+ } catch (error) {
4595
+ if (missing(error)) return;
4596
+ throw new EnvironmentError("Cannot read hook decision logs. Set TMPDIR (TEMP on Windows) to a directory you own, or ensure the hook state directory and log files are private, owned by you, and free of links.", { cause: error });
4597
+ }
4598
+ }
4599
+ function summarize(days, full) {
4600
+ const grouped = /* @__PURE__ */ new Map();
4601
+ const agents = {
4602
+ cc: 0,
4603
+ codex: 0,
4604
+ agy: 0
4605
+ };
4606
+ const interventions = /* @__PURE__ */ new Map();
4607
+ const commandSamples = [];
4608
+ let total = 0;
4609
+ let skipped = 0;
4610
+ for (const line of decisionLines(days)) {
4611
+ const row = parseRow(line);
4612
+ if (!row) {
4613
+ skipped++;
4614
+ continue;
4615
+ }
4616
+ const { agent, decision, ruleId, reason, command } = row;
4617
+ total++;
4618
+ agents[agent]++;
4619
+ const key = `${agent}/${decision}/${ruleId}`;
4620
+ const group = grouped.get(key) ?? {
4621
+ agent,
4622
+ decision,
4623
+ ruleId,
4624
+ count: 0
4625
+ };
4626
+ group.count++;
4627
+ grouped.set(key, group);
4628
+ if (decision !== "allow") {
4629
+ const rule = interventions.get(ruleId) ?? {
4630
+ ruleId,
4631
+ count: 0,
4632
+ exampleReason: reason
4633
+ };
4634
+ rule.count++;
4635
+ interventions.set(ruleId, rule);
4636
+ if (full && command !== void 0 && commandSamples.length < 5) commandSamples.push({
4637
+ agent,
4638
+ decision,
4639
+ ruleId,
4640
+ command
4641
+ });
4642
+ }
4643
+ }
4644
+ const groups = [...grouped.values()].toSorted((a, b) => a.agent.localeCompare(b.agent) || a.decision.localeCompare(b.decision) || a.ruleId.localeCompare(b.ruleId)).map((group) => ({
4645
+ ...group,
4646
+ ratio: group.count / total,
4647
+ agentRatio: group.count / agents[group.agent]
4648
+ }));
4649
+ const topRules = [...interventions.values()].toSorted((a, b) => b.count - a.count || a.ruleId.localeCompare(b.ruleId)).map((rule) => ({
4650
+ ...rule,
4651
+ ratio: rule.count / total
4652
+ }));
4653
+ const notes = skipped > 0 ? [`Skipped ${skipped} invalid decision log rows.`] : [];
4654
+ return {
4655
+ days,
4656
+ total,
4657
+ groups,
4658
+ topRules,
4659
+ notes,
4660
+ ...full ? { commandSamples } : {}
4661
+ };
4662
+ }
4663
+ function percentage(ratio) {
4664
+ return `${(ratio * 100).toFixed(2)}%`;
4665
+ }
4666
+ function runHooksReport(args) {
4667
+ const { values } = parseArgs({
4668
+ args,
4669
+ options: {
4670
+ days: { type: "string" },
4671
+ format: formatOption,
4672
+ help: { type: "boolean" }
4673
+ }
4674
+ });
4675
+ if (values.help) {
4676
+ console.log(HOOKS_REPORT_USAGE);
4677
+ return 0;
4678
+ }
4679
+ if (values.format !== void 0 && values.format !== "text" && values.format !== "json") throw new UsageError("--format accepts text or json");
4680
+ const format = outputFormat(values.format);
4681
+ const rawDays = values.days ?? String(14);
4682
+ const days = Number(rawDays);
4683
+ if (!/^[0-9]+$/.test(rawDays) || days < 1 || days > 14) throw new UsageError(`--days must be a decimal integer from 1 to 14`);
4684
+ const stats = summarize(days, hookLogMode() === "full");
4685
+ const summary = `${stats.total} recorded decisions over ${days} UTC ${days === 1 ? "day" : "days"}`;
4686
+ if (format === "json") {
4687
+ printReport({
4688
+ ok: true,
4689
+ diagnostics: [],
4690
+ summary,
4691
+ ...stats
4692
+ });
4693
+ return 0;
4694
+ }
4695
+ print("hooks report", {
4696
+ ok: true,
4697
+ errors: [],
4698
+ notes: stats.notes
4699
+ }, summary);
4700
+ for (const { agent, decision, ruleId, count, ratio, agentRatio } of stats.groups) console.log(` ${agent} ${decision} ${ruleId}: ${count} (${percentage(ratio)} overall, ${percentage(agentRatio)} of ${agent})`);
4701
+ if (stats.topRules.length > 0) console.log("Rules with the most interventions:");
4702
+ for (const { ruleId, count, exampleReason } of stats.topRules) console.log(` ${ruleId}: ${count} (${JSON.stringify(exampleReason)})`);
4703
+ if (stats.commandSamples?.length) console.log("Command samples:");
4704
+ for (const { agent, decision, ruleId, command } of stats.commandSamples ?? []) console.log(` ${agent} ${decision} ${ruleId}: ${JSON.stringify(command)}`);
4705
+ return 0;
4706
+ }
4272
4707
  // src/hook/paths.ts
4273
4708
  const D_CLASS_PATTERNS = [
4274
4709
  "oxlint-suppressions.json",
@@ -4292,13 +4727,6 @@ const D_CLASS_PATTERNS = [
4292
4727
  "**/node_modules/.pnpm/@opendesignai+harness@*/**",
4293
4728
  "**/node_modules/.pnpm/@opendesignai+harness@*"
4294
4729
  ];
4295
- // src/hook/types.ts
4296
- function isAgentKind(value) {
4297
- return value === "cc" || value === "codex" || value === "agy";
4298
- }
4299
- function isHookEventKind(value) {
4300
- return value === "pre-bash" || value === "pre-edit" || value === "post-tool" || value === "stop" || value === "session-start" || value === "pre-invocation";
4301
- }
4302
4730
  // src/hook/runtime/launcher.ts
4303
4731
  const LAUNCHER = [
4304
4732
  "const fs=require('node:fs'),p=require('node:path'),m=require('node:module'),u=require('node:url')",
@@ -4894,7 +5322,7 @@ const RENAMED = "git sees the rename";
4894
5322
  function seesRename(base) {
4895
5323
  return `git sees the rename at 30% similarity or more (\`git diff -M30% -l0 ${base}\`)`;
4896
5324
  }
4897
- /** The commit to compare with, how messages name it, or why there is none. */
5325
+ /** The commit to compare with and how to name it in diagnostics. */
4898
5326
  function baseCommit(options) {
4899
5327
  const { cwd, base, mergeBase: other } = options;
4900
5328
  if (base && other) throw new UsageError("use --base or --merge-base, not both");
@@ -4907,13 +5335,11 @@ function baseCommit(options) {
4907
5335
  };
4908
5336
  }
4909
5337
  if (other) {
4910
- const found = mergeBase(cwd, other);
4911
- if ("skip" in found) return found;
4912
- const ref = found.commit.slice(0, 12);
5338
+ const commit = mergeBase(cwd, other);
4913
5339
  return {
4914
- commit: found.commit,
4915
- ref,
4916
- label: `the merge base with ${other} (${found.commit.slice(0, 10)})`
5340
+ commit,
5341
+ ref: commit.slice(0, 12),
5342
+ label: `the merge base with ${other} (${commit.slice(0, 10)})`
4917
5343
  };
4918
5344
  }
4919
5345
  throw new UsageError("missing --base <ref> or --merge-base <ref>");
@@ -4980,15 +5406,7 @@ function parsedVersion(spec, workspace) {
4980
5406
  }
4981
5407
  function runRatchet(options) {
4982
5408
  const { cwd } = options;
4983
- const found = baseCommit(options);
4984
- if ("skip" in found) return {
4985
- ok: true,
4986
- errors: [],
4987
- diagnostics: [],
4988
- notes: [],
4989
- skipped: found.skip
4990
- };
4991
- const { commit, ref, label: at } = found;
5409
+ const { commit, ref, label: at } = baseCommit(options);
4992
5410
  const suppressionsPath = options.suppressions ?? "oxlint-suppressions.json";
4993
5411
  const lintConfig = options.lintConfig ?? ".oxlintrc.json";
4994
5412
  const errors = [];
@@ -5578,49 +5996,7 @@ function readVerifyConfig(cwd) {
5578
5996
  }
5579
5997
  function verifyBase(cwd, flag, configured, env = childEnv({})) {
5580
5998
  const envBase = env.OD_HARNESS_BASE?.trim() || void 0;
5581
- const ref = flag ?? envBase ?? configured ?? "origin/main";
5582
- const result = mergeBase(cwd, ref);
5583
- if ("commit" in result) return result.commit;
5584
- const branch = /^origin\/([a-z0-9_./][a-z0-9_./-]*)$/i.exec(ref)?.[1];
5585
- const fetch = branch ? `git fetch origin ${branch}` : "git fetch";
5586
- throw new EnvironmentError(`${result.skip}. Try \`${fetch}\`.`);
5587
- }
5588
- // src/cli/verify-process.ts
5589
- function vitestBin(cwd, config) {
5590
- const project = config ? path.dirname(path.resolve(cwd, config)) : cwd;
5591
- for (const directory of /* @__PURE__ */ new Set([project, cwd])) try {
5592
- const manifest = createRequire(path.join(directory, "package.json")).resolve("vitest/package.json");
5593
- return path.join(path.dirname(manifest), "vitest.mjs");
5594
- } catch (error) {
5595
- const code = error.code;
5596
- if (code !== "MODULE_NOT_FOUND" && code !== "ERR_PACKAGE_PATH_NOT_EXPORTED") throw error;
5597
- }
5598
- }
5599
- function invoke(cwd, base, bin, args) {
5600
- const env = childEnv({ HARNESS_BASE_REF: base });
5601
- env.PATH = [path.join(cwd, "node_modules", ".bin"), env.PATH].filter(Boolean).join(path.delimiter);
5602
- return new Promise((resolve) => {
5603
- execFile(bin, args, {
5604
- cwd,
5605
- env,
5606
- encoding: "utf8",
5607
- maxBuffer: 67108864
5608
- }, (error, stdout, stderr) => {
5609
- const code = error ? typeof error.code === "number" ? error.code : null : 0;
5610
- resolve({
5611
- code,
5612
- stdout,
5613
- stderr,
5614
- problem: code === null ? error?.message ?? "Process aborted" : null
5615
- });
5616
- });
5617
- });
5618
- }
5619
- function commandOutput(result) {
5620
- return [result.stderr.trim(), result.stdout.trim()].filter(Boolean).join("\n");
5621
- }
5622
- function shellCommand(bin, args) {
5623
- return [bin, ...args].map((arg) => /^[\w+./=@:-]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`).join(" ");
5999
+ return mergeBase(cwd, flag ?? envBase ?? configured ?? "origin/main");
5624
6000
  }
5625
6001
  // src/cli/verify-lint.ts
5626
6002
  const DOCS$1 = "https://github.com/nexu-io/od-harness/blob/main/docs/verify.md";
@@ -5712,7 +6088,7 @@ function batches(files) {
5712
6088
  }
5713
6089
  return groups;
5714
6090
  }
5715
- async function lintChanged(cwd, base, files, ci, annotate) {
6091
+ async function lintChanged(cwd, base, files, ci, annotate, runProcess) {
5716
6092
  const scripts = files.filter((file) => SCRIPT$1.test(file));
5717
6093
  if (!ci && scripts.length === 0) return {
5718
6094
  ok: true,
@@ -5732,7 +6108,7 @@ async function lintChanged(cwd, base, files, ci, annotate) {
5732
6108
  if (existsSync(path.join(cwd, ".oxlintrc.json"))) args.push("-c", ".oxlintrc.json");
5733
6109
  args.push("--no-error-on-unmatched-pattern", "--", ...batch);
5734
6110
  }
5735
- const output = await invoke(cwd, base, process.execPath, [bin, ...args]);
6111
+ const output = await runProcess(process.execPath, [bin, ...args]);
5736
6112
  if (output.code === 0) continue;
5737
6113
  let rows;
5738
6114
  try {
@@ -5753,7 +6129,7 @@ async function lintChanged(cwd, base, files, ci, annotate) {
5753
6129
  const diagnostics = markChangedLines(cwd, base, (rows.length ? rows : raw).map((item) => lintDiagnostic(item, cwd)));
5754
6130
  if (!diagnostics.length) throw new EnvironmentError("Oxlint failed without diagnostics. Run oxlint --deny-warnings to inspect the failure.");
5755
6131
  const prefix = repositoryPrefix(cwd);
5756
- const annotations = ci && annotate ? await nativeAnnotations(cwd, base, bin, prefix) : void 0;
6132
+ const annotations = ci && annotate ? await nativeAnnotations(runProcess, bin, prefix) : void 0;
5757
6133
  return {
5758
6134
  ok: false,
5759
6135
  diagnostics: diagnostics.map((item) => ({
@@ -5764,8 +6140,8 @@ async function lintChanged(cwd, base, files, ci, annotate) {
5764
6140
  ...annotations ? { annotations } : {}
5765
6141
  };
5766
6142
  }
5767
- async function nativeAnnotations(cwd, base, bin, prefix) {
5768
- const output = await invoke(cwd, base, process.execPath, [
6143
+ async function nativeAnnotations(runProcess, bin, prefix) {
6144
+ const output = await runProcess(process.execPath, [
5769
6145
  bin,
5770
6146
  "--deny-warnings",
5771
6147
  "--format",
@@ -5775,6 +6151,155 @@ async function nativeAnnotations(cwd, base, bin, prefix) {
5775
6151
  const annotations = output.stdout.split(/\r?\n/).filter((line) => /^::(?:error|warning|notice) (?:file|title)=/.test(line)).map((line) => line.replace(/^::(?:error|warning|notice) file=/, (start) => start + property));
5776
6152
  return annotations.length > 0 ? annotations : void 0;
5777
6153
  }
6154
+ // src/cli/verify-slot.ts
6155
+ const releases = /* @__PURE__ */ new Set();
6156
+ function verifySlotCapacity(ncpu, override) {
6157
+ const capacity = Number(override);
6158
+ return Number.isSafeInteger(capacity) && capacity > 0 ? capacity : Math.max(2, Math.floor(ncpu / 4));
6159
+ }
6160
+ function ownerIsGone(file) {
6161
+ let pid;
6162
+ try {
6163
+ pid = JSON.parse(readFileSync(file, "utf8"))?.pid;
6164
+ } catch (error) {
6165
+ if (errorCode(error) === "ENOENT") return true;
6166
+ if (error instanceof SyntaxError) return false;
6167
+ throw error;
6168
+ }
6169
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0 || pid > 0x7fffffff) return false;
6170
+ try {
6171
+ process.kill(pid, 0);
6172
+ return false;
6173
+ } catch (error) {
6174
+ return errorCode(error) === "ESRCH";
6175
+ }
6176
+ }
6177
+ function removeEmptySlot(directory) {
6178
+ try {
6179
+ rmdirSync(directory);
6180
+ } catch (error) {
6181
+ if (![
6182
+ "ENOENT",
6183
+ "ENOTEMPTY",
6184
+ "EEXIST"
6185
+ ].includes(errorCode(error) ?? "")) throw error;
6186
+ }
6187
+ }
6188
+ function removeOwner(directory, owner) {
6189
+ try {
6190
+ unlinkSync(path.join(directory, owner));
6191
+ } catch (error) {
6192
+ if (errorCode(error) !== "ENOENT") throw error;
6193
+ }
6194
+ removeEmptySlot(directory);
6195
+ }
6196
+ function slotOccupied(directory, reclaim = false) {
6197
+ let entries;
6198
+ try {
6199
+ entries = readdirSync(directory, { withFileTypes: true });
6200
+ } catch (error) {
6201
+ if (errorCode(error) === "ENOENT") return false;
6202
+ throw error;
6203
+ }
6204
+ const [entry] = entries;
6205
+ if (!entry) {
6206
+ if (reclaim) removeEmptySlot(directory);
6207
+ return false;
6208
+ }
6209
+ if (entries.length !== 1 || !entry.isFile() || !entry.name.endsWith(".json")) return true;
6210
+ if (!ownerIsGone(path.join(directory, entry.name))) return true;
6211
+ if (reclaim) removeOwner(directory, entry.name);
6212
+ return false;
6213
+ }
6214
+ function publishSlot(root, directory, owner) {
6215
+ const pending = mkdtempSync(path.join(root, "pending-"));
6216
+ let published = false;
6217
+ try {
6218
+ const fd = openSync(path.join(pending, owner), "wx", 384);
6219
+ try {
6220
+ writeFileSync(fd, JSON.stringify({
6221
+ pid: process.pid,
6222
+ startedAt: Date.now()
6223
+ }));
6224
+ } finally {
6225
+ closeSync(fd);
6226
+ }
6227
+ try {
6228
+ renameSync(pending, directory);
6229
+ published = true;
6230
+ return true;
6231
+ } catch (error) {
6232
+ const code = errorCode(error);
6233
+ if (code === "EEXIST" || code === "ENOTEMPTY") return false;
6234
+ if (process.platform === "win32" && code === "EPERM" && existsSync(directory)) return false;
6235
+ throw error;
6236
+ }
6237
+ } finally {
6238
+ if (!published) rmSync(pending, {
6239
+ recursive: true,
6240
+ force: true
6241
+ });
6242
+ }
6243
+ }
6244
+ function releaseOnSignal(signal) {
6245
+ for (const release of releases) try {
6246
+ release();
6247
+ } catch {}
6248
+ if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
6249
+ }
6250
+ function registerRelease(directory, owner) {
6251
+ const release = () => {
6252
+ if (!releases.delete(release)) return;
6253
+ if (releases.size === 0) {
6254
+ process.off("SIGINT", releaseOnSignal);
6255
+ process.off("SIGTERM", releaseOnSignal);
6256
+ }
6257
+ removeOwner(directory, owner);
6258
+ };
6259
+ if (releases.size === 0) {
6260
+ process.on("SIGINT", releaseOnSignal);
6261
+ process.on("SIGTERM", releaseOnSignal);
6262
+ }
6263
+ releases.add(release);
6264
+ return release;
6265
+ }
6266
+ async function acquireVerifySlot({ mode, noSlot }) {
6267
+ if (mode === "quick" || noSlot) return void 0;
6268
+ const env = verifySlotEnv();
6269
+ if (env.bypass) return void 0;
6270
+ const defaultDirectory = typeof process.getuid === "function" ? `od-harness-verify-slots-${process.getuid()}` : "od-harness-verify-slots";
6271
+ const root = path.resolve(env.directory?.trim() || path.join(tmpdir(), defaultDirectory));
6272
+ const maxSlots = verifySlotCapacity(availableParallelism(), env.capacity);
6273
+ mkdirSync(root, {
6274
+ recursive: true,
6275
+ mode: 448
6276
+ });
6277
+ const owner = `${randomUUID()}.json`;
6278
+ for (;;) {
6279
+ for (let slotIndex = 0; slotIndex < maxSlots; slotIndex++) {
6280
+ const directory = path.join(root, `slot-${slotIndex}`);
6281
+ if (slotOccupied(directory, true) || !publishSlot(root, directory, owner)) continue;
6282
+ return {
6283
+ slotIndex,
6284
+ maxSlots,
6285
+ get activeSlots() {
6286
+ let entries;
6287
+ try {
6288
+ entries = readdirSync(root, { withFileTypes: true });
6289
+ } catch (error) {
6290
+ if (errorCode(error) === "ENOENT") return 1;
6291
+ throw error;
6292
+ }
6293
+ const slots = entries.filter((entry) => entry.isDirectory() && /^slot-\d+$/.test(entry.name));
6294
+ if (slots.length === 1) return 1;
6295
+ return slots.filter((entry) => slotOccupied(path.join(root, entry.name))).length;
6296
+ },
6297
+ release: registerRelease(directory, owner)
6298
+ };
6299
+ }
6300
+ await setTimeout$1(200 + Math.floor(Math.random() * 301));
6301
+ }
6302
+ }
5778
6303
  // src/cli/verify-tests.ts
5779
6304
  const TEST_FILE = /\.test\.[^/]+$/;
5780
6305
  const SCRIPT = new RegExp(`\\.(?:${SCRIPT_EXTENSIONS.join("|")})$`);
@@ -5881,9 +6406,9 @@ function checkCommand(id, run, output) {
5881
6406
  const status = output.problem || output.code === 126 || output.code === 127 ? "error" : "failed";
5882
6407
  return failedCheck(id, `${run} ${reason}.${detail ? `\n${detail}` : ""}`, `Run \`${run}\`, address the reported errors, then rerun od-harness verify.`, status);
5883
6408
  }
5884
- async function harnessGate(cwd, cli, base, gate, ref) {
6409
+ async function harnessGate(runProcess, cli, gate, ref) {
5885
6410
  const args = gate === "size" ? [] : ["--base", ref];
5886
- const output = await invoke(cwd, base, process.execPath, [
6411
+ const output = await runProcess(process.execPath, [
5887
6412
  cli,
5888
6413
  gate,
5889
6414
  ...args,
@@ -5901,10 +6426,10 @@ async function harnessGate(cwd, cli, base, gate, ref) {
5901
6426
  function noTests(id, detail) {
5902
6427
  return failedCheck(id, detail, "Add or restore a matching <stem>*.test.* file, or correct the runner configuration and verify.tests paths or roots.");
5903
6428
  }
5904
- async function runTests(cwd, base, ci, project, id, files) {
6429
+ async function runTests(cwd, runProcess, ci, project, id, files) {
5905
6430
  if (!ci && files.length === 0) return noTests(id, "No test files matched the changed files.");
5906
6431
  if (ci && project.run) {
5907
- const output = await invoke(cwd, base, "bash", [
6432
+ const output = await runProcess("bash", [
5908
6433
  "-eo",
5909
6434
  "pipefail",
5910
6435
  "-c",
@@ -5919,7 +6444,7 @@ async function runTests(cwd, base, ci, project, id, files) {
5919
6444
  "--test-reporter=tap",
5920
6445
  ...ci ? project.glob ? [project.glob] : [] : files
5921
6446
  ];
5922
- const output = await invoke(cwd, base, process.execPath, args);
6447
+ const output = await runProcess(process.execPath, args);
5923
6448
  if (NO_TESTS.test(commandOutput(output))) return noTests(id, "Node ran zero tests.");
5924
6449
  return checkCommand(id, shellCommand("node", args), output);
5925
6450
  }
@@ -5935,7 +6460,7 @@ async function runTests(cwd, base, ci, project, id, files) {
5935
6460
  if (project.config) args.push("--config", project.config);
5936
6461
  args.push(...files);
5937
6462
  const bin = vitestBin(cwd, project.config);
5938
- const output = bin ? await invoke(cwd, base, process.execPath, [bin, ...args]) : await invoke(cwd, base, "vitest", args);
6463
+ const output = bin ? await runProcess(process.execPath, [bin, ...args]) : await runProcess("vitest", args);
5939
6464
  const rerunArgs = ["run", ...project.config ? ["--config", project.config] : []];
5940
6465
  const rerun = shellCommand("vitest", rerunArgs);
5941
6466
  try {
@@ -5970,11 +6495,11 @@ async function runTests(cwd, base, ci, project, id, files) {
5970
6495
  });
5971
6496
  }
5972
6497
  }
5973
- function commandTask(cwd, base, id, run) {
6498
+ function commandTask(runProcess, id, run) {
5974
6499
  return {
5975
6500
  id,
5976
6501
  async run() {
5977
- return checkCommand(id, run, await invoke(cwd, base, "bash", [
6502
+ return checkCommand(id, run, await runProcess("bash", [
5978
6503
  "-eo",
5979
6504
  "pipefail",
5980
6505
  "-c",
@@ -5983,7 +6508,7 @@ function commandTask(cwd, base, id, run) {
5983
6508
  }
5984
6509
  };
5985
6510
  }
5986
- function checkRegistry(options, config, base, changed, present, annotate) {
6511
+ function checkRegistry(options, config, base, changed, present, annotate, runProcess) {
5987
6512
  const { cwd, cli, mode } = options;
5988
6513
  const ci = mode === "ci";
5989
6514
  const quick = mode === "quick";
@@ -6004,7 +6529,7 @@ function checkRegistry(options, config, base, changed, present, annotate) {
6004
6529
  });
6005
6530
  if (config.lint && (ci || present.length > 0)) tasks.push({
6006
6531
  id: "lint",
6007
- run: () => lintChanged(cwd, base, present, ci, annotate)
6532
+ run: () => lintChanged(cwd, base, present, ci, annotate, runProcess)
6008
6533
  });
6009
6534
  for (const gate of [
6010
6535
  "size",
@@ -6015,10 +6540,10 @@ function checkRegistry(options, config, base, changed, present, annotate) {
6015
6540
  const ref = gate === "ratchet" && options.mode === "ci" ? options.base : base;
6016
6541
  tasks.push({
6017
6542
  id: gate,
6018
- run: () => harnessGate(cwd, cli, base, gate, ref)
6543
+ run: () => harnessGate(runProcess, cli, gate, ref)
6019
6544
  });
6020
6545
  }
6021
- const typecheck = config.typecheck.filter((project) => ci || touches(project.paths)).map((project) => commandTask(cwd, base, `typecheck/${project.id}`, project.run));
6546
+ const typecheck = config.typecheck.filter((project) => ci || touches(project.paths)).map((project) => commandTask(runProcess, `typecheck/${project.id}`, project.run));
6022
6547
  const tests = [];
6023
6548
  const presentFiles = new Set(present);
6024
6549
  let files;
@@ -6030,16 +6555,16 @@ function checkRegistry(options, config, base, changed, present, annotate) {
6030
6555
  const id = `tests/${project.id}`;
6031
6556
  tests.push({
6032
6557
  id,
6033
- run: () => runTests(cwd, base, ci, project, id, selected)
6558
+ run: () => runTests(cwd, runProcess, ci, project, id, selected)
6034
6559
  });
6035
6560
  }
6036
- const prepare = config.prepare.filter(({ when }) => ci || when.includes("typecheck") && typecheck.length > 0 || when.includes("tests") && tests.length > 0).map(({ run }, i) => commandTask(cwd, base, `prepare/${i + 1}`, run));
6561
+ const prepare = config.prepare.filter(({ when }) => ci || when.includes("typecheck") && typecheck.length > 0 || when.includes("tests") && tests.length > 0).map(({ run }, i) => commandTask(runProcess, `prepare/${i + 1}`, run));
6037
6562
  for (const [i, task] of prepare.entries()) {
6038
6563
  const previous = prepare[i - 1];
6039
6564
  if (previous) task.needs = [previous];
6040
6565
  }
6041
6566
  for (const task of [...typecheck, ...tests]) task.needs = prepare;
6042
- const extra = config.extra.filter(({ when, quick: fast }) => ci || (!quick || fast) && (when === "always" || touches(when))).map(({ id, run }) => commandTask(cwd, base, `extra/${id}`, run));
6567
+ const extra = config.extra.filter(({ when, quick: fast }) => ci || (!quick || fast) && (when === "always" || touches(when))).map(({ id, run }) => commandTask(runProcess, `extra/${id}`, run));
6043
6568
  for (const [i, task] of extra.entries()) {
6044
6569
  const previous = extra[i - 1];
6045
6570
  task.after = [...ci ? prepare : [], ...previous ? [previous] : []];
@@ -6064,14 +6589,28 @@ function checkRegistry(options, config, base, changed, present, annotate) {
6064
6589
  ];
6065
6590
  }
6066
6591
  async function runVerify(options) {
6067
- const { cwd, mode, format } = options;
6592
+ const { cwd } = options;
6068
6593
  const start = performance.now();
6594
+ if (options.mode !== "ci" && hasUnverifiedStop(cwd)) console.error("NOT VERIFIED: the previous Stop check could not verify changes in this worktree.");
6069
6595
  const config = readVerifyConfig(cwd);
6070
6596
  const base = options.mode === "ci" ? resolveRef(cwd, options.base) : verifyBase(cwd, options.base, config.base);
6597
+ const slot = await acquireVerifySlot(options);
6598
+ try {
6599
+ const runProcess = (bin, args) => invoke(cwd, base, bin, args, slot && {
6600
+ ...verifyThrottleEnv(slot.activeSlots),
6601
+ OD_HARNESS_NO_SLOT: "1"
6602
+ });
6603
+ return await verifyChecks(options, config, base, start, runProcess);
6604
+ } finally {
6605
+ slot?.release();
6606
+ }
6607
+ }
6608
+ async function verifyChecks(options, config, base, start, runProcess) {
6609
+ const { cwd, mode, format } = options;
6071
6610
  const changed = [...new Set(changedFiles(cwd, base, true))].toSorted();
6072
6611
  const present = changed.filter((file) => statSync(path.join(cwd, file), { throwIfNoEntry: false })?.isFile());
6073
6612
  const annotate = format === "github" || format === "text" && isGitHubActions();
6074
- const tasks = checkRegistry(options, config, base, changed, present, annotate);
6613
+ const tasks = checkRegistry(options, config, base, changed, present, annotate, runProcess);
6075
6614
  if (mode === "ci" && tasks.length === 0) tasks.push({
6076
6615
  id: "setup",
6077
6616
  run: async () => failedCheck("verify/no-checks", "No CI checks are enabled.", "Enable a gate or add a command to verify in .harness/config.json.")
@@ -6125,8 +6664,7 @@ Commands:
6125
6664
  adoption change.
6126
6665
  --merge-base <ref> instead of --base, for local runs: compare
6127
6666
  with \`git merge-base HEAD <ref>\` (for
6128
- example origin/main); skipped with a warning
6129
- when there is none
6667
+ example origin/main); requires common history
6130
6668
  --suppressions <path> default: oxlint-suppressions.json
6131
6669
  --lint-config <path> default: .oxlintrc.json
6132
6670
  clones --base <ref> Fail on duplicated code (jscpd) that <ref> does not have.
@@ -6137,7 +6675,7 @@ Commands:
6137
6675
  --check report drift without writing files
6138
6676
  agents docs [--json] Check references in agent instruction files.
6139
6677
  agents size [--json] Check expanded agent instruction sizes and AGENTS.md chains.
6140
- ${includeVerify ? " verify [--quick | --ci] Run the repository checks together. CI requires --base <ref>.\n" : ""} baseline move <from> <to> After moving files (git mv, staged), move their entries in both
6678
+ ${includeVerify ? " verify [--quick | --ci] Run the repository checks together. CI requires --base <ref>.\n --no-slot bypass host verification slots\n" : ""} baseline move <from> <to> After moving files (git mv, staged), move their entries in both
6141
6679
  baselines to the new paths. Each new file must be a rename git
6142
6680
  sees (git diff -M30% -l0), as ratchet requires.
6143
6681
  --suppressions <path> default: oxlint-suppressions.json
@@ -6145,6 +6683,7 @@ ${includeVerify ? " verify [--quick | --ci] Run the repository checks togeth
6145
6683
  (a pre-check: ratchet decides)
6146
6684
  init [--check] Generate repository agent configuration or check it without writing.
6147
6685
  doctor Check the installed harness version and Codex hook trust.
6686
+ hooks report [--days N] Summarize local hook decisions (--format text|json).
6148
6687
 
6149
6688
  Options:
6150
6689
  --format text|json|github Diagnostic output for lint-scope, size, ratchet, clones, unused, comments,
@@ -6156,7 +6695,7 @@ Options:
6156
6695
 
6157
6696
  Run from the repository root.`;
6158
6697
  }
6159
- const VERIFY_USAGE = "Usage: od-harness verify [--quick | --ci] [--base <ref>] [--skip lint-scope] [--json | --format text|json|github]";
6698
+ const VERIFY_USAGE = "Usage: od-harness verify [--quick | --ci] [--base <ref>] [--skip lint-scope] [--no-slot] [--json | --format text|json|github]";
6160
6699
  /** An option's value, which must not be empty. */
6161
6700
  function nonEmpty(option, value) {
6162
6701
  if (value.trim() === "") throw new UsageError(`${option} needs a value`);
@@ -6179,6 +6718,11 @@ function run(command, rest, cwd) {
6179
6718
  console.log(VERSION);
6180
6719
  return 0;
6181
6720
  }
6721
+ if (command === "hooks") {
6722
+ const [sub, ...args] = rest;
6723
+ if (sub !== "report") throw new UsageError(`unknown hooks command "${sub ?? ""}"`);
6724
+ return runHooksReport(args);
6725
+ }
6182
6726
  if (REPOSITORY_COMMANDS.some((candidate) => candidate === command)) requireWorkTree(cwd);
6183
6727
  if (command === "lint-scope") {
6184
6728
  const { values } = parseArgs({
@@ -6360,6 +6904,7 @@ function verify(rest, cwd, cli) {
6360
6904
  ci: { type: "boolean" },
6361
6905
  base: { type: "string" },
6362
6906
  skip: { type: "string" },
6907
+ "no-slot": { type: "boolean" },
6363
6908
  json: { type: "boolean" },
6364
6909
  format: formatOption,
6365
6910
  help: { type: "boolean" }
@@ -6376,35 +6921,35 @@ function verify(rest, cwd, cli) {
6376
6921
  const base = values.base === void 0 ? void 0 : nonEmpty("--base", values.base);
6377
6922
  const requested = outputFormat(values.format);
6378
6923
  if (values.json && values.format !== void 0 && requested !== "json") throw new UsageError(`--json conflicts with --format ${requested}`);
6379
- const format = values.json ? "json" : requested;
6924
+ const options = {
6925
+ cwd,
6926
+ cli,
6927
+ format: values.json ? "json" : requested,
6928
+ skipLintScope,
6929
+ noSlot: values["no-slot"] ?? false
6930
+ };
6380
6931
  if (values.ci) {
6381
6932
  if (base === void 0) throw new UsageError("verify --ci requires --base <ref>");
6382
6933
  return runVerify({
6383
- cwd,
6384
- cli,
6934
+ ...options,
6385
6935
  mode: "ci",
6386
- base,
6387
- format,
6388
- skipLintScope
6936
+ base
6389
6937
  });
6390
6938
  }
6391
6939
  return runVerify({
6392
- cwd,
6393
- cli,
6940
+ ...options,
6394
6941
  mode: values.quick ? "quick" : "default",
6395
- base,
6396
- format,
6397
- skipLintScope
6942
+ base
6398
6943
  });
6399
6944
  }
6400
6945
  function main(argv, cwd = process.cwd(), cli = fileURLToPath(new URL("./index.ts", import.meta.url))) {
6401
6946
  const [command, ...rest] = argv;
6402
6947
  const onError = (error) => {
6403
6948
  if (error instanceof UsageError || error.code?.startsWith("ERR_PARSE_ARGS")) {
6404
- console.error(`od-harness: ${error.message}\n\n${command === "verify" ? VERIFY_USAGE : help(false)}`);
6949
+ console.error(`od-harness: ${error.message}\n\n${command === "verify" ? VERIFY_USAGE : command === "hooks" ? HOOKS_REPORT_USAGE : help(false)}`);
6405
6950
  return 2;
6406
6951
  }
6407
- const name = command === "baseline" ? "baseline move" : command;
6952
+ const name = command === "baseline" ? "baseline move" : command === "hooks" ? "hooks report" : command;
6408
6953
  if (error instanceof EnvironmentError) {
6409
6954
  const prefix = error instanceof HarnessConfigError ? "od-harness" : `od-harness ${name}`;
6410
6955
  console.error(`${prefix}: ${error.message}`);