cocheck 0.4.0 → 0.4.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.
Files changed (81) hide show
  1. package/README.md +17 -3
  2. package/dist/agent-transcripts.js +15 -12
  3. package/dist/attribution/evidence.js +2 -1
  4. package/dist/attribution/reconstruct.js +19 -0
  5. package/dist/attribution/tag.js +3 -3
  6. package/dist/build-info.json +1 -1
  7. package/dist/cli.js +31 -11
  8. package/dist/connector/export-view.js +1 -1
  9. package/dist/coverage.js +5 -3
  10. package/dist/credit-guard.js +59 -54
  11. package/dist/harness-cmd/create.js +76 -0
  12. package/dist/harness-cmd/index.js +19 -0
  13. package/dist/harness-cmd/record.js +327 -0
  14. package/dist/harness-cmd/scrub.js +25 -0
  15. package/dist/harness-cmd/test.js +318 -0
  16. package/dist/harnesses/README.md +5 -0
  17. package/dist/harnesses/claude/cocheck-harness.json +344 -0
  18. package/dist/harnesses/codex/cocheck-harness.json +212 -0
  19. package/dist/harnesses/copilot/cocheck-harness.json +296 -0
  20. package/dist/{copilot-helpers.js → helper-linker.js} +43 -32
  21. package/dist/hook-adapter.js +287 -63
  22. package/dist/hook-cli.js +73 -36
  23. package/dist/hook-journal.js +40 -12
  24. package/dist/hosts/claude.js +23 -159
  25. package/dist/hosts/codex.js +41 -81
  26. package/dist/hosts/compile.js +275 -0
  27. package/dist/hosts/copilot.js +7 -162
  28. package/dist/hosts/extras.js +55 -0
  29. package/dist/hosts/harnesses.js +66 -0
  30. package/dist/hosts/index.js +176 -8
  31. package/dist/hosts/install-block.js +332 -0
  32. package/dist/hosts/manifest.js +372 -0
  33. package/dist/hosts/shared.js +21 -0
  34. package/dist/hosts/tool-classes.js +6 -0
  35. package/dist/hosts/types.js +1 -0
  36. package/dist/install.js +69 -22
  37. package/dist/ledger.js +11 -0
  38. package/dist/normalize.js +33 -9
  39. package/dist/open-pick.js +5 -3
  40. package/dist/patch-secrets.js +11 -11
  41. package/dist/review-server.js +2 -2
  42. package/dist/timeline/attribution.js +2 -2
  43. package/dist/timeline/describe.js +20 -17
  44. package/dist/timeline/load.js +2 -2
  45. package/dist/timeline/rail/assets/review.js +1 -1
  46. package/dist/timeline/rail/model.js +8 -8
  47. package/dist/timeline/read-signal.js +4 -4
  48. package/dist/timeline/render/view-v1.js +2 -13
  49. package/dist/timeline/runs.js +9 -9
  50. package/dist/timeline/timeline.js +8 -8
  51. package/dist/timeline/write-signal.js +4 -3
  52. package/package.json +2 -2
  53. package/public-kit/harness/GUIDE.md +81 -0
  54. package/public-kit/harness/README.md +10 -0
  55. package/public-kit/harness/cases/claude/shell-writes-file.json +120 -0
  56. package/public-kit/harness/cases/codex/apply-patch-writes-files.json +177 -0
  57. package/public-kit/harness/cases/codex/helper-writes-file.json +160 -0
  58. package/public-kit/harness/cases/codex/shell-writes-and-fails.json +110 -0
  59. package/public-kit/harness/cases/copilot/camel-case-patch-and-failure.json +126 -0
  60. package/public-kit/harness/cases/copilot/helper-writes-file.json +209 -0
  61. package/public-kit/harness/cases/copilot/vscode-helper-writes-file.json +236 -0
  62. package/public-kit/harness/examples/toyagent/cases/write-notes.json +142 -0
  63. package/public-kit/harness/examples/toyagent/cocheck-harness.json +47 -0
  64. package/public-kit/harness/examples/toyagent/recordings/payloads.jsonl +8 -0
  65. package/public-kit/harness/harnesses/antigravity/README.md +32 -0
  66. package/public-kit/harness/harnesses/antigravity/cases/failed-edit.json +99 -0
  67. package/public-kit/harness/harnesses/antigravity/cases/helper-writes-file.json +270 -0
  68. package/public-kit/harness/harnesses/antigravity/cases/shell-ok-fail-and-denied.json +211 -0
  69. package/public-kit/harness/harnesses/antigravity/cases/write-then-edit.json +191 -0
  70. package/public-kit/harness/harnesses/antigravity/cocheck-harness.json +62 -0
  71. package/public-kit/harness/harnesses/antigravity/recordings/payloads.jsonl +63 -0
  72. package/public-kit/harness/harnesses/cursor/README.md +40 -0
  73. package/public-kit/harness/harnesses/cursor/cases/editor-write-edit-shell-helper.json +359 -0
  74. package/public-kit/harness/harnesses/cursor/cases/read-then-write-one-call-id.json +159 -0
  75. package/public-kit/harness/harnesses/cursor/cocheck-harness.json +67 -0
  76. package/public-kit/harness/harnesses/cursor/recordings/payloads.jsonl +28 -0
  77. package/public-kit/harness/scaffold/README.md +42 -0
  78. package/public-kit/harness/scaffold/cocheck-harness.json +72 -0
  79. package/public-kit/harness/scaffold/recordings/.gitkeep +0 -0
  80. package/public-kit/harness/spec/v1.md +286 -0
  81. package/scripts/hook-launch.sh +1 -1
@@ -1,18 +1,17 @@
1
- // Codex. Its facts: no failure event (a failed call arrives as a Post); the call's words are in the rollout, found by session id under
2
- // ~/.codex/sessions; a tool call's hook `tool_use_id` equals the rollout's CommandExecution `id`; a subagent's words are in its own rollout, named by its thread id; no helper records, no settings install yet.
1
+ // Codex's first-party code, offered as named extras (src/hosts/extras.ts); its data is in harnesses/codex/cocheck-harness.json. Its facts: no failure event
2
+ // (a failed call arrives as a Post); the call's words are in the rollout, found by session id under ~/.codex/sessions; a tool call's hook `tool_use_id`
3
+ // equals the rollout's CommandExecution `id`; a subagent's words are in its own rollout, named by its thread id; no helper records.
3
4
  import { closeSync, lstatSync, openSync, readdirSync, readFileSync, readSync } from "node:fs";
4
5
  import { homedir } from "node:os";
5
6
  import path from "node:path";
6
7
  import { addCoCheckHooks, inlineHooksProblem, missingCoCheckEvents, removeCoCheckHooks } from "../codex-config.js";
7
8
  import { CLOSING_MAX, NARRATION_MAX, cut, joined, remember } from "../narration.js";
8
9
  import { platform } from "../platform/index.js";
9
- import { claudeShapeExtra, claudeShapeFailure } from "./shared.js";
10
- import { codexTrustProblem } from "./codex-trust.js";
11
- import { codexSessionTitle } from "./session-titles.js";
12
- import { SHARED_EVENT_KINDS, SHARED_FIELDS } from "./types.js";
10
+ import { claudeShapeFailure } from "./shared.js";
11
+ import { codexTrustProblem, readCodexHooksList } from "./codex-trust.js";
13
12
  const CODEX_LINE = /"(?:AgentMessage|CommandExecution|UserMessage|task_started)"/;
14
13
  /** One line of a Codex rollout. Only the four item kinds above are parsed; a UserMessage is parsed for its kind and never read. */
15
- function codexLine(cur, line) {
14
+ export function codexLine(cur, line) {
16
15
  if (!CODEX_LINE.test(line))
17
16
  return;
18
17
  let d;
@@ -60,7 +59,7 @@ function codexLine(cur, line) {
60
59
  // Display only: the ledger keeps the host's words. Only this exact directive name followed by a brace group of `key="value"` pairs matches.
61
60
  const CITATION = /:codex-file-citation\{((?:\s*[A-Za-z_][\w-]*="(?:[^"\\]|\\.)*")*)\s*\}/g;
62
61
  const CITATION_PATH = /(?:^|\s)path="((?:[^"\\]|\\.)*)"/;
63
- function codexDisplayText(text) {
62
+ export function codexDisplayText(text) {
64
63
  if (!text.includes(":codex-file-citation{"))
65
64
  return text;
66
65
  const out = text.replace(CITATION, (_m, attrs) => {
@@ -73,7 +72,7 @@ function codexDisplayText(text) {
73
72
  }
74
73
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
75
74
  /** The rollout named by a thread id: today's folder and the two days before it, matched on the whole name with a full uuid, never on a suffix a longer id could share. */
76
- function locateRollout(thread, now, root) {
75
+ export function locateRollout(thread, now, root) {
77
76
  if (!UUID.test(thread))
78
77
  return undefined;
79
78
  const rollout = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-${thread}\\.jsonl$`, "i");
@@ -119,7 +118,7 @@ function rolloutHeader(file) {
119
118
  * A subagent writes its own rollout, named by its own thread id (the hook's `agent_id`). The file is used only when its header names
120
119
  * that thread and the calling session as its parent or root, so a helper never reads the parent's file or another helper's.
121
120
  */
122
- function locateHelperRollout(session, agent, now, root) {
121
+ export function locateHelperRollout(session, agent, now, root) {
123
122
  if (!UUID.test(session) || agent.toLowerCase() === session.toLowerCase())
124
123
  return undefined;
125
124
  const file = locateRollout(agent, now, root);
@@ -143,7 +142,7 @@ const callTextCache = new Map();
143
142
  * hook's `tool_use_id`). Read whole once per file state. Nothing else in the file is kept.
144
143
  * Bound: a call whose command and output do not name a file gives the credit no evidence about that file.
145
144
  */
146
- function rolloutCallText(file) {
145
+ export function rolloutCallText(file) {
147
146
  return rolloutCalls(file)?.texts;
148
147
  }
149
148
  /**
@@ -151,7 +150,7 @@ function rolloutCallText(file) {
151
150
  * nonzero number, or whose `status` is "failed" with no exit code. An item with exit code 0, or neither field, is not listed.
152
151
  * Bound: only a call whose item is already in the file is seen; the item is written just before the call's PostToolUse.
153
152
  */
154
- function rolloutCallExits(file) {
153
+ export function rolloutCallExits(file) {
155
154
  return rolloutCalls(file)?.exits;
156
155
  }
157
156
  function rolloutCalls(file) {
@@ -210,7 +209,7 @@ const SHELL_WRAP = /^\S*\/(?:zsh|bash|sh) -l?c '(.*)'$/s;
210
209
  * A rejection that quotes no command is listed with no `command`: the caller matches it by position. Bound: a command whose quote does
211
210
  * not unwrap to a shell wrapper and one single-quoted body is skipped.
212
211
  */
213
- function rolloutRefusedCommands(file) {
212
+ export function rolloutRefusedCommands(file) {
214
213
  try {
215
214
  const st = lstatSync(file);
216
215
  if (!st.isFile() || st.size > ROLLOUT_MAX_BYTES)
@@ -255,7 +254,7 @@ const codexEvents = ["SessionStart", "PreToolUse", "PostToolUse", "SubagentStart
255
254
  // A failed Bash call arrives as PostToolUse with the bare output as `tool_response` and no exit code (discrepancies.json codex-posttooluse-no-exit-code).
256
255
  // Inferred as failed only when every non-empty output line is a shell error line; any other output, and empty output, reads as no failure.
257
256
  const SHELL_ERROR_LINE = /^[^\s:][^\n]*: (?:.*: )?(?:No such file or directory|Permission denied|command not found|Not a directory|Is a directory|Operation not permitted)$/;
258
- function codexFailure(kind, p) {
257
+ export function codexFailure(kind, p) {
259
258
  const known = claudeShapeFailure(kind, p);
260
259
  if (known !== undefined || kind !== "tool-post" || typeof p.tool_response !== "string")
261
260
  return known;
@@ -283,73 +282,34 @@ export function codexToolName(reported, payload = {}) {
283
282
  }
284
283
  return reported;
285
284
  }
286
- export const codex = {
287
- key: "codex",
288
- displayName: "Codex",
289
- chip: "C",
290
- testedVersions: ["0.162.0-alpha.2", "0.164.0-alpha.11.1"],
291
- eventKinds: SHARED_EVENT_KINDS,
292
- capabilities: { failureEvent: false, argvTag: false, helperSessions: false, launchKey: false, readsForeignHooks: false },
293
- fields: { ...SHARED_FIELDS },
294
- toolName: codexToolName,
295
- failureOf: codexFailure,
296
- displayText: codexDisplayText,
297
- extraOf: claudeShapeExtra,
298
- narration: {
299
- // Codex writes the commentary to the rollout before the call runs but binds it to a call only when the call's item completes: the Pre claims it, the Post reads the bound one when the Pre found none.
300
- sources: [
301
- { kind: "commentary-before-call", readableAt: "pre", reason: true },
302
- { kind: "closing-message", readableAt: "post" },
303
- ],
304
- foldLine: codexLine,
305
- claimAtPre(cur, id) {
306
- const text = joined(cur.pending, NARRATION_MAX);
307
- cur.pending = [];
308
- if (text !== "")
309
- remember(cur, id, { text });
310
- },
311
- closing: (cur) => cur?.closing ?? "",
312
- },
313
- sessionTitle: codexSessionTitle,
314
- sessionFile: { bySessionId: true, locate: locateRollout, locateHelper: locateHelperRollout, callText: rolloutCallText, callExit: rolloutCallExits, refusedCommands: rolloutRefusedCommands },
315
- install: {
316
- skillRoot: path.join(".agents", "skills"),
317
- inBothAlias: true,
318
- reusesRecord: true,
319
- hostFlag: "codex",
320
- // Codex sets no project-folder variable; its payload carries the folder as `cwd`.
321
- folderFromPayloadCwd: true,
322
- // The events that fired in the probe run and that the adapter acts on; Codex sends no failure event.
323
- events: codexEvents,
324
- configFile: (env, userHome) => path.join(env.CODEX_HOME || path.join(userHome, ".codex"), "config.toml"),
325
- addHooks: (text, file, spec, plat = platform()) => {
326
- const problem = inlineHooksProblem(text);
327
- if (problem !== undefined) {
328
- throw new Error(`${file} already has ${problem} for hooks, and CoCheck's [[hooks.X]] entries would make the file invalid. Nothing was changed. Move your hooks to [[hooks.X]] tables, then run the installer again`);
329
- }
330
- const command = spec === undefined ? "" : plat.hookCommand.build(spec);
331
- return addCoCheckHooks(removeCoCheckHooks(text).toml, { command: () => command, events: [...codexEvents] }).toml;
332
- },
333
- removeHooks: (text) => {
334
- const r = removeCoCheckHooks(text);
335
- return { text: r.toml, changed: r.changed };
336
- },
337
- missingEvents: (text) => missingCoCheckEvents(text, codexEvents),
338
- trustProblem: (configFile, env, hookPath, read) => {
339
- if (read === undefined)
340
- return undefined;
341
- const result = read(path.dirname(configFile), env);
342
- return result === undefined ? undefined : codexTrustProblem(result, hookPath);
343
- },
344
- afterInstall: "Codex asks you to trust new hooks before they run: open Codex and trust the new hooks in Codex once, or CoCheck records nothing from it.",
285
+ /** The words the cursor holds, not yet bound, go to the call `id` at its Pre. */
286
+ export function codexClaimAtPre(cur, id) {
287
+ const text = joined(cur.pending, NARRATION_MAX);
288
+ cur.pending = [];
289
+ if (text !== "")
290
+ remember(cur, id, { text });
291
+ }
292
+ /** Codex's own hook config: TOML `[[hooks.X]]` tables in `$CODEX_HOME/config.toml`. */
293
+ export const CODEX_TOML_EDITOR = {
294
+ configFile: (env, userHome) => path.join(env.CODEX_HOME || path.join(userHome, ".codex"), "config.toml"),
295
+ addHooks: (text, file, spec, plat = platform()) => {
296
+ const problem = inlineHooksProblem(text);
297
+ if (problem !== undefined) {
298
+ throw new Error(`${file} already has ${problem} for hooks, and CoCheck's [[hooks.X]] entries would make the file invalid. Nothing was changed. Move your hooks to [[hooks.X]] tables, then run the installer again`);
299
+ }
300
+ const command = spec === undefined ? "" : plat.hookCommand.build(spec);
301
+ return addCoCheckHooks(removeCoCheckHooks(text).toml, { command: () => command, events: [...codexEvents] }).toml;
345
302
  },
346
- shape: {
347
- SessionStart: ["session_id"],
348
- SubagentStart: ["session_id", "agent_id"],
349
- SubagentStop: ["session_id", "agent_id"],
350
- PreToolUse: ["session_id", "tool_name", "tool_use_id", "tool_input"],
351
- PostToolUse: ["session_id", "tool_name", "tool_use_id", "tool_input", "tool_response"],
352
- Stop: ["session_id"],
353
- UserPromptSubmit: ["session_id", "prompt"],
303
+ removeHooks: (text) => {
304
+ const r = removeCoCheckHooks(text);
305
+ return { text: r.toml, changed: r.changed };
354
306
  },
307
+ missingEvents: (text) => missingCoCheckEvents(text, codexEvents),
308
+ };
309
+ /** Why Codex will not run CoCheck's installed hooks (its trust list), read live or through a stub. */
310
+ export const codexTrustProblemOf = (configFile, env, hookPath, read) => {
311
+ if (read === undefined)
312
+ return undefined;
313
+ const result = (read === "live" ? readCodexHooksList : read)(path.dirname(configFile), env);
314
+ return result === undefined ? undefined : codexTrustProblem(result, hookPath);
355
315
  };
@@ -0,0 +1,275 @@
1
+ // Manifest to profile: `compileManifest` turns a validated harness manifest (src/hosts/manifest.ts) into a HostProfile. The function members of a
2
+ // profile are generic code driven by the manifest's data (a path read, a failure rule, a refine rule, a name strip) or a named first-party extra.
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+ import { applyExtras } from "./extras.js";
6
+ import { argsKey } from "./shared.js";
7
+ import { jsonHookEditor } from "./install-block.js";
8
+ import { MATCH_INPUT_MAX } from "./manifest.js";
9
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
10
+ /** The value at a payload path (`a.b`, `a[0].b`), or undefined when any step is missing. */
11
+ export function readPath(root, p) {
12
+ let cur = root;
13
+ for (const m of p.matchAll(/([^.[\]]+)|\[(\d+)\]/g)) {
14
+ if (cur === null || typeof cur !== "object")
15
+ return undefined;
16
+ cur = m[2] !== undefined ? (Array.isArray(cur) ? cur[Number(m[2])] : undefined) : Object.hasOwn(cur, m[1]) ? cur[m[1]] : undefined;
17
+ }
18
+ return cur;
19
+ }
20
+ const text = (v) => (typeof v === "string" ? v : undefined);
21
+ /** The keys the normalizer reads from a compiled profile's payload (see `HostProfile.readPayload`). */
22
+ const FLAT = { eventName: "eventName", session: "session", cwd: "cwd", toolName: "toolName", toolInput: "toolInput", toolResponse: "toolResponse", toolUseId: "toolUseId", agentId: "agentId", agentType: "agentType", transcriptPath: "transcriptPath", lastAssistantMessage: "lastAssistantMessage", prompt: "prompt", parentSession: "parentSession" };
23
+ /** Tool arguments as an object: JSON text that holds an object is parsed; anything else passes through. */
24
+ function parseJsonText(value) {
25
+ if (typeof value !== "string")
26
+ return value;
27
+ try {
28
+ const parsed = JSON.parse(value);
29
+ return parsed !== null && typeof parsed === "object" ? parsed : typeof parsed === "string" ? parsed : value;
30
+ }
31
+ catch {
32
+ return value;
33
+ }
34
+ }
35
+ /** The text of a list of `{ text }` blocks, joined by a line break; a string is itself; anything else is not text. */
36
+ function blocksText(v) {
37
+ if (typeof v === "string")
38
+ return v;
39
+ if (!Array.isArray(v))
40
+ return undefined;
41
+ return v.flatMap((c) => (isObject(c) && typeof c.text === "string" ? [c.text] : [])).join("\n");
42
+ }
43
+ function failureFrom(kind, p, rules, capInput) {
44
+ if (kind !== "tool-failure" && kind !== "tool-post")
45
+ return undefined;
46
+ const rule = rules?.[kind];
47
+ if (kind === "tool-post" && rule === undefined)
48
+ return undefined;
49
+ const r = rule ?? {};
50
+ const flagged = r.flags?.some((f) => readPath(p, f) === true) === true;
51
+ let words = r.text?.map((t) => text(readPath(p, t))).find((t) => t !== undefined);
52
+ // tool-post with `nonEmpty`: words at a `text` path mean the call failed.
53
+ const saidFailed = r.nonEmpty === true && words !== undefined && words !== "";
54
+ if ((words === undefined || words === "") && flagged && r.flaggedText !== undefined) {
55
+ const alt = r.flaggedText.map((e) => (typeof e === "string" ? text(readPath(p, e)) : e.blocks === true ? blocksText(readPath(p, e.path)) : text(readPath(p, e.path)))).find((t) => t !== undefined);
56
+ if (alt !== undefined)
57
+ words = alt;
58
+ }
59
+ const interrupted = r.interrupt !== undefined && readPath(p, r.interrupt) === true;
60
+ const inferred = r.inferred === true ? { inferred: true } : {};
61
+ if (kind === "tool-failure")
62
+ return { raw: words ?? "", interrupted, ...inferred };
63
+ let said;
64
+ let failed = false;
65
+ if (r.exitCode !== undefined) {
66
+ said = text(readPath(p, r.exitCode.from));
67
+ const codes = said === undefined ? [] : [...(capInput ? said.slice(-MATCH_INPUT_MAX) : said).matchAll(new RegExp(r.exitCode.pattern, "g"))];
68
+ const last = codes.length === 0 ? undefined : Number(codes[codes.length - 1][1]);
69
+ failed = last !== undefined && Number.isFinite(last) && last !== 0;
70
+ }
71
+ return flagged || failed || saidFailed ? { raw: words ?? (failed ? said : undefined) ?? "", interrupted, ...inferred } : undefined;
72
+ }
73
+ function templateFill(tpl, env, vars, usedEnv) {
74
+ let out = "";
75
+ for (let i = 0; i < tpl.length; i++) {
76
+ if (tpl[i] !== "{") {
77
+ out += tpl[i];
78
+ continue;
79
+ }
80
+ let depth = 1;
81
+ let j = i + 1;
82
+ while (j < tpl.length && depth > 0)
83
+ (depth += tpl[j] === "{" ? 1 : tpl[j] === "}" ? -1 : 0), j++;
84
+ const token = tpl.slice(i + 1, j - 1);
85
+ if (token === "home")
86
+ out += homedir();
87
+ else if (token.startsWith("env:")) {
88
+ const [name, ...fallback] = token.slice(4).split("|");
89
+ if (env[name]) {
90
+ out += env[name];
91
+ if (usedEnv)
92
+ usedEnv.value = true;
93
+ }
94
+ else if (fallback.length > 0)
95
+ out += templateFill(fallback.join("|"), env, vars);
96
+ else
97
+ throw new Error(`the environment variable ${name} is not set`);
98
+ }
99
+ else if (token in vars)
100
+ out += vars[token];
101
+ else
102
+ throw new Error(`unknown token {${token}} in ${tpl}`);
103
+ i = j - 1;
104
+ }
105
+ return out;
106
+ }
107
+ const deepFolder = (v, folder) => typeof v === "string" ? v.split("{folder}").join(folder) : Array.isArray(v) ? v.map((x) => deepFolder(x, folder)) : isObject(v) ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, deepFolder(x, folder)])) : v;
108
+ const deepSlots = (v, vars) => typeof v === "string" ? (v.startsWith("{") && v.endsWith("}") && v.slice(1, -1) in vars ? vars[v.slice(1, -1)] : v) : Array.isArray(v) ? v.map((x) => deepSlots(x, vars)) : isObject(v) ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, deepSlots(x, vars)])) : v;
109
+ function argvTagFrom(a) {
110
+ return { tool: a.tool, envFileVar: a.envFileVar, shellEnv: a.shellEnv, sessionStartEvent: a.sessionStartEvent, preOutput: (eventName, updatedInput) => JSON.stringify(deepSlots(a.preOutput, { event: eventName, input: updatedInput })) + "\n" };
111
+ }
112
+ const INSTALL_OWN = new Set(["skillRoot", "hostFlag", "projectDirEnv", "folderFromPayloadCwd", "promptContext", "ownsFile", "inBothAlias", "reusesRecord", "timingLabel", "afterInstall", "checkPayload", "editorExtra", "notes"]);
113
+ /** The profile a validated manifest describes. `source` "outsider" marks a profile loaded from the user's folder (its events never prove more than "inferred"). */
114
+ export function compileManifest(m, source) {
115
+ const f = m.fields;
116
+ const callIdPath = m.callId !== undefined && "payload" in m.callId ? m.callId.payload : undefined;
117
+ const slots = [
118
+ [FLAT.session, f.session],
119
+ [FLAT.cwd, f.cwd],
120
+ [FLAT.toolName, f.toolName],
121
+ [FLAT.toolInput, f.toolInput],
122
+ [FLAT.toolResponse, f.toolResponse],
123
+ [FLAT.toolUseId, callIdPath],
124
+ [FLAT.agentId, f.agentId],
125
+ [FLAT.agentType, f.agentType],
126
+ [FLAT.transcriptPath, f.transcriptPath],
127
+ [FLAT.lastAssistantMessage, f.lastAssistantMessage],
128
+ [FLAT.prompt, f.prompt],
129
+ [FLAT.parentSession, f.parentSession],
130
+ [FLAT.eventName, "payload" in m.eventFrom ? m.eventFrom.payload : undefined],
131
+ ];
132
+ // A manifest whose paths are all top-level keys needs no payload reading: the fields name the payload's own keys, so code that reads a raw payload by key (the helper linker, the patch scrub) sees them.
133
+ const plain = slots.every(([, p]) => p === undefined || /^[A-Za-z_][\w-]*$/.test(p));
134
+ const fields = { ...FLAT, ...(plain ? Object.fromEntries(slots.filter(([, p]) => p !== undefined)) : {}), ...(f.callReason === undefined ? {} : { callReason: f.callReason }) };
135
+ if (f.toolResponse === undefined)
136
+ delete fields.toolResponse;
137
+ if (f.parentSession === undefined)
138
+ delete fields.parentSession;
139
+ const extraPaths = m.extraFields ?? {};
140
+ const refine = m.refine ?? [];
141
+ const strip = m.toolNameStrip === undefined ? undefined : new RegExp(`^(?:${m.toolNameStrip.prefix})`);
142
+ const failure = m.failure;
143
+ const sf = m.sessionFile;
144
+ const inst = m.install;
145
+ const block = inst === undefined || inst.editorExtra !== undefined ? undefined : Object.fromEntries(Object.entries(inst).filter(([k]) => !INSTALL_OWN.has(k)));
146
+ const base = {
147
+ key: m.key,
148
+ displayName: m.displayName,
149
+ ...(m.fullName === undefined ? {} : { fullName: m.fullName }),
150
+ chip: m.chip,
151
+ testedVersions: m.testedVersions ?? [],
152
+ ...(source === "outsider" ? { trust: "outsider" } : {}),
153
+ ...(m.sessionEnv === undefined ? {} : { sessionEnv: m.sessionEnv }),
154
+ ...(m.argvTag === undefined ? {} : { argvTag: argvTagFrom(m.argvTag) }),
155
+ ...(m.foreignHookFingerprint === undefined ? {} : { foreignHookFingerprint: m.foreignHookFingerprint }),
156
+ ...(m.readsConfigsOf === undefined ? {} : { readsConfigsOf: m.readsConfigsOf }),
157
+ ...(m.perAction === undefined ? {} : { perAction: m.perAction }),
158
+ eventKinds: m.events,
159
+ ...("arg" in m.eventFrom ? { eventFromArg: true } : {}),
160
+ ...(m.unverifiedEvents === undefined ? {} : { unverifiedEvents: m.unverifiedEvents }),
161
+ capabilities: { failureEvent: false, argvTag: false, helperSessions: false, launchKey: false, readsForeignHooks: false, ...m.capabilities },
162
+ fields,
163
+ ...(plain && !("arg" in m.eventFrom)
164
+ ? {}
165
+ : {
166
+ readPayload: (raw, eventArg) => {
167
+ if (!isObject(raw))
168
+ return raw;
169
+ const out = { ...raw };
170
+ for (const [flat, p] of slots)
171
+ out[flat] = p === undefined ? undefined : readPath(raw, p);
172
+ if ("arg" in m.eventFrom)
173
+ out[FLAT.eventName] = eventArg;
174
+ return out;
175
+ },
176
+ }),
177
+ failureOf: (kind, p) => failureFrom(kind, p, failure, source === "outsider"),
178
+ extraOf: (p) => {
179
+ const out = {};
180
+ for (const k of ["turnId", "permissionMode", "model"]) {
181
+ const v = extraPaths[k] === undefined ? undefined : readPath(p, extraPaths[k]);
182
+ if (typeof v === "string")
183
+ out[k] = v;
184
+ }
185
+ const hook = extraPaths.stopHookActive === undefined ? undefined : readPath(p, extraPaths.stopHookActive);
186
+ if (typeof hook === "boolean")
187
+ out.stopHookActive = hook;
188
+ return out;
189
+ },
190
+ ...(refine.length === 0
191
+ ? {}
192
+ : {
193
+ refineKind: (kind, p) => {
194
+ for (const r of refine) {
195
+ if (!r.kinds.includes(kind))
196
+ continue;
197
+ if (r.whenPresent !== undefined) {
198
+ const v = readPath(p, r.whenPresent);
199
+ if (typeof v !== "string" || v === "")
200
+ continue;
201
+ }
202
+ if (r.whenMatches !== undefined) {
203
+ const v = readPath(p, r.whenMatches.path);
204
+ if (typeof v !== "string" || !new RegExp(r.whenMatches.pattern).test(source === "outsider" ? v.trim().slice(0, MATCH_INPUT_MAX) : v.trim()))
205
+ continue;
206
+ }
207
+ return r.becomes;
208
+ }
209
+ return kind;
210
+ },
211
+ }),
212
+ ...(m.toolInputEncoding === "json-text" ? { parseToolInput: parseJsonText } : {}),
213
+ ...(strip === undefined
214
+ ? {}
215
+ : {
216
+ toolName: (reported) => {
217
+ const own = source === "outsider" ? reported.slice(0, MATCH_INPUT_MAX).replace(strip, "") + reported.slice(MATCH_INPUT_MAX) : reported.replace(strip, "");
218
+ return own === "" ? reported : own;
219
+ },
220
+ }),
221
+ toolClasses: m.toolClasses,
222
+ ...(m.callId?.synthesized === true ? { calls: { argsKey, syntheticId: (session, n) => `${m.key}-${session}-${n}` } } : {}),
223
+ narration: { sources: m.narration?.sources ?? [], foldLine: () => { }, closing: (cur) => cur?.closing ?? "", ...(m.narration?.closingWaitMs === undefined ? {} : { closingWaitMs: m.narration.closingWaitMs }) },
224
+ sessionFile: {
225
+ bySessionId: sf?.bySessionId === true,
226
+ locate: (session, _now, root) => {
227
+ if (sf?.file === undefined || !/^[A-Za-z0-9._-]+$/.test(session))
228
+ return undefined;
229
+ const used = { value: false };
230
+ let folder = root;
231
+ if (folder === undefined) {
232
+ if (sf.defaultRoot === undefined)
233
+ return undefined;
234
+ folder = templateFill(sf.defaultRoot, process.env, {}, used);
235
+ // Under the test runner the host's real folder is never read: the default root must come from an environment variable the test set.
236
+ if (!used.value && process.env.NODE_TEST_CONTEXT)
237
+ throw new Error(`the session folder of ${m.key} would fall back to the real home under the test runner; refusing`);
238
+ }
239
+ return path.normalize(templateFill(sf.file, process.env, { root: folder, session }));
240
+ },
241
+ },
242
+ ...(m.hostOwnedFiles === undefined ? {} : { hostOwnedFiles: m.hostOwnedFiles }),
243
+ ...(m.hostOwnedWhat === undefined ? {} : { hostOwnedWhat: m.hostOwnedWhat }),
244
+ ...(inst === undefined
245
+ ? {}
246
+ : {
247
+ install: {
248
+ skillRoot: path.join(...inst.skillRoot.split("/")),
249
+ hostFlag: inst.hostFlag,
250
+ ...(inst.projectDirEnv === undefined ? {} : { projectDirEnv: inst.projectDirEnv }),
251
+ ...(inst.folderFromPayloadCwd === undefined ? {} : { folderFromPayloadCwd: inst.folderFromPayloadCwd }),
252
+ ...(inst.promptContext === undefined ? {} : { promptContext: inst.promptContext }),
253
+ ...(inst.ownsFile === undefined ? {} : { ownsFile: inst.ownsFile }),
254
+ ...(inst.inBothAlias === undefined ? {} : { inBothAlias: inst.inBothAlias }),
255
+ ...(inst.reusesRecord === undefined ? {} : { reusesRecord: inst.reusesRecord }),
256
+ ...(inst.timingLabel === undefined ? {} : { timingLabel: inst.timingLabel }),
257
+ ...(inst.afterInstall === undefined ? {} : { afterInstall: inst.afterInstall }),
258
+ ...(inst.notes === undefined ? {} : { notes: ({ launcherDir, home }) => inst.notes.split("{launcherDir}").join(launcherDir).split("{home}").join(home) }),
259
+ events: block?.events ?? inst.events ?? [],
260
+ checkPayload: (folder) => deepFolder(inst.checkPayload, folder),
261
+ ...(block === undefined ? {} : jsonHookEditor(block)),
262
+ },
263
+ }),
264
+ shape: m.shape ?? {},
265
+ };
266
+ const names = [...new Set([...(m.extras ?? []), ...(inst?.editorExtra === undefined ? [] : [inst.editorExtra])])];
267
+ const templates = [m.install?.path, m.sessionFile?.defaultRoot, m.sessionFile?.file].filter((t) => typeof t === "string");
268
+ const homeEnv = [...new Set(templates.flatMap((t) => [...t.matchAll(/\{env:([A-Za-z_][A-Za-z0-9_]*)/g)].map((x) => x[1])))];
269
+ const out = applyExtras(homeEnv.length === 0 ? base : { ...base, homeEnv }, names);
270
+ const i = out.install;
271
+ if (i !== undefined && (i.configFile === undefined || i.addHooks === undefined || i.removeHooks === undefined || i.missingEvents === undefined)) {
272
+ throw new Error(`${m.key}/cocheck-harness.json: install: no editor (give the JSON install block, or name an editor extra)`);
273
+ }
274
+ return out;
275
+ }