cocheck 0.0.0-stage → 0.4.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.
Files changed (305) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -2
  3. package/THIRD_PARTY_NOTICES.md +279 -0
  4. package/bin/cocheck.mjs +8 -0
  5. package/dist/agent-transcripts.js +541 -0
  6. package/dist/attribution/basis.js +31 -0
  7. package/dist/attribution/evidence.js +311 -0
  8. package/dist/attribution/hooks/cocheck-preload.cjs +254 -0
  9. package/dist/attribution/hooks/sitecustomize.py +245 -0
  10. package/dist/attribution/names.js +163 -0
  11. package/dist/attribution/reconstruct.js +128 -0
  12. package/dist/attribution/tag.js +246 -0
  13. package/dist/attribution/write-scope-win.js +615 -0
  14. package/dist/attribution/write-scope.js +1668 -0
  15. package/dist/build-info.json +1 -0
  16. package/dist/cli-main.js +8 -0
  17. package/dist/cli.js +193 -0
  18. package/dist/codex-config.js +107 -0
  19. package/dist/connector/after-gap.js +56 -0
  20. package/dist/connector/after-snapshot.js +244 -0
  21. package/dist/connector/before-snapshot.js +168 -0
  22. package/dist/connector/builtins.js +93 -0
  23. package/dist/connector/changes-v1.js +276 -0
  24. package/dist/connector/claimed-state.js +40 -0
  25. package/dist/connector/claimed.js +86 -0
  26. package/dist/connector/conformance.js +458 -0
  27. package/dist/connector/diff-object.js +81 -0
  28. package/dist/connector/diff-samples.js +64 -0
  29. package/dist/connector/diff.js +273 -0
  30. package/dist/connector/doc-level.js +20 -0
  31. package/dist/connector/enabled-types.js +87 -0
  32. package/dist/connector/export-view.js +13 -0
  33. package/dist/connector/file-capture.js +265 -0
  34. package/dist/connector/frozen.js +213 -0
  35. package/dist/connector/installed-manifests.js +72 -0
  36. package/dist/connector/installed-match.js +161 -0
  37. package/dist/connector/local-process.js +119 -0
  38. package/dist/connector/nothing-changed-rule.js +23 -0
  39. package/dist/connector/old-rows.js +66 -0
  40. package/dist/connector/png-pixels.js +4 -0
  41. package/dist/connector/registry.js +78 -0
  42. package/dist/connector/requires.js +30 -0
  43. package/dist/connector/row-doc.js +54 -0
  44. package/dist/connector/run-argv.js +25 -0
  45. package/dist/connector/runner.js +325 -0
  46. package/dist/connector/schema.js +242 -0
  47. package/dist/connector/subject.js +8 -0
  48. package/dist/connector/subjects.js +113 -0
  49. package/dist/connector/validate.js +200 -0
  50. package/dist/connector-auth.js +101 -0
  51. package/dist/connector-create.js +55 -0
  52. package/dist/connector-doctor.js +167 -0
  53. package/dist/connector-test-cli.js +627 -0
  54. package/dist/connector-types-cli.js +43 -0
  55. package/dist/connectors/microsoft-excel/cocheck-connector.json +13 -0
  56. package/dist/connectors/microsoft-excel/connector.mjs +11 -0
  57. package/dist/connectors/microsoft-powerpoint/cocheck-connector.json +13 -0
  58. package/dist/connectors/microsoft-powerpoint/connector.mjs +11 -0
  59. package/dist/connectors/microsoft-word/cocheck-connector.json +13 -0
  60. package/dist/connectors/microsoft-word/connector.mjs +11 -0
  61. package/dist/copies.js +151 -0
  62. package/dist/copilot-helpers.js +246 -0
  63. package/dist/coverage.js +277 -0
  64. package/dist/credit-guard.js +330 -0
  65. package/dist/display.js +78 -0
  66. package/dist/file-lock.js +145 -0
  67. package/dist/fingerprint.js +25 -0
  68. package/dist/formats/files/align.js +84 -0
  69. package/dist/formats/files/csv.js +78 -0
  70. package/dist/formats/files/layer.js +274 -0
  71. package/dist/formats/files/scan.js +86 -0
  72. package/dist/formats/files/textlike.js +21 -0
  73. package/dist/formats/layer.js +48 -0
  74. package/dist/helpers/pdfpages +0 -0
  75. package/dist/home-page.js +173 -0
  76. package/dist/home-perms.js +59 -0
  77. package/dist/hook-adapter.js +3415 -0
  78. package/dist/hook-cli.js +505 -0
  79. package/dist/hook-journal.js +147 -0
  80. package/dist/hook.js +25 -0
  81. package/dist/hosts/claude.js +250 -0
  82. package/dist/hosts/codex-bin-macos.js +2 -0
  83. package/dist/hosts/codex-bin.js +35 -0
  84. package/dist/hosts/codex-trust-probe.js +52 -0
  85. package/dist/hosts/codex-trust.js +46 -0
  86. package/dist/hosts/codex.js +355 -0
  87. package/dist/hosts/copilot.js +236 -0
  88. package/dist/hosts/index.js +52 -0
  89. package/dist/hosts/session-titles.js +327 -0
  90. package/dist/hosts/shared.js +31 -0
  91. package/dist/hosts/types.js +26 -0
  92. package/dist/html.js +4 -0
  93. package/dist/install.js +676 -0
  94. package/dist/items.js +105 -0
  95. package/dist/ledger.js +2097 -0
  96. package/dist/narration.js +202 -0
  97. package/dist/normalize.js +82 -0
  98. package/dist/office/connector/apps.js +34 -0
  99. package/dist/office/connector/docx/layer.js +247 -0
  100. package/dist/office/connector/docx/reader.js +284 -0
  101. package/dist/office/connector/excel/align.js +284 -0
  102. package/dist/office/connector/excel/answer.js +352 -0
  103. package/dist/office/connector/excel/diff.js +1310 -0
  104. package/dist/office/connector/excel/errors.js +44 -0
  105. package/dist/office/connector/excel/look.js +121 -0
  106. package/dist/office/connector/excel/print-boxes.js +432 -0
  107. package/dist/office/connector/excel/print-grid-previous.js +206 -0
  108. package/dist/office/connector/excel/print-setup.js +168 -0
  109. package/dist/office/connector/excel/workbook.js +374 -0
  110. package/dist/office/connector/export-driver.js +9 -0
  111. package/dist/office/connector/helpers/cocheck-screen +0 -0
  112. package/dist/office/connector/issues.js +31 -0
  113. package/dist/office/connector/mac-guard.js +16 -0
  114. package/dist/office/connector/main.js +23 -0
  115. package/dist/office/connector/nothing-changed.js +18 -0
  116. package/dist/office/connector/office-job.js +416 -0
  117. package/dist/office/connector/office-macos.js +473 -0
  118. package/dist/office/connector/office-win-export.js +107 -0
  119. package/dist/office/connector/office-win-lifecycle.js +194 -0
  120. package/dist/office/connector/office-win.js +209 -0
  121. package/dist/office/connector/office-win.ps1 +451 -0
  122. package/dist/office/connector/open-watch.js +46 -0
  123. package/dist/office/connector/pictures.js +156 -0
  124. package/dist/office/connector/pptx/diff.js +589 -0
  125. package/dist/office/connector/pptx/frames.js +105 -0
  126. package/dist/office/connector/pptx/layer.js +148 -0
  127. package/dist/office/connector/pptx/links.js +59 -0
  128. package/dist/office/connector/pptx/reader.js +744 -0
  129. package/dist/office/connector/pptx/spans.js +70 -0
  130. package/dist/office/connector/pptx/tags.js +86 -0
  131. package/dist/office/connector/pptx/xml.js +96 -0
  132. package/dist/office/connector/pptx/zip.js +223 -0
  133. package/dist/office/connector/pptx-boxes.js +238 -0
  134. package/dist/office/connector/print-copy-cap.js +19 -0
  135. package/dist/office/connector/print-copy.js +13 -0
  136. package/dist/office/connector/program.js +291 -0
  137. package/dist/office/connector/reach.js +27 -0
  138. package/dist/office/connector/refusal.js +16 -0
  139. package/dist/office/connector/screen-macos.js +193 -0
  140. package/dist/office/connector/screen-windows.js +34 -0
  141. package/dist/office/connector/shared/chart-diff.js +376 -0
  142. package/dist/office/connector/shared/docprops-noise.js +13 -0
  143. package/dist/office/connector/shared/lock.js +107 -0
  144. package/dist/office/connector/shared/ooxml-names.js +347 -0
  145. package/dist/office/connector/shared/owner.js +57 -0
  146. package/dist/office/connector/shared/package-media.js +703 -0
  147. package/dist/office/connector/shared/preflight.js +226 -0
  148. package/dist/office/connector/shared/structure-check.js +623 -0
  149. package/dist/office/connector/word-boxes.js +364 -0
  150. package/dist/office/connector/word-print-copy.js +234 -0
  151. package/dist/office/connector/xlsx/diff.js +1038 -0
  152. package/dist/office/connector/xlsx/formula.js +410 -0
  153. package/dist/office/connector/xlsx/layer.js +621 -0
  154. package/dist/office/connector/xlsx/memo.js +39 -0
  155. package/dist/office/connector/xlsx/numbers.js +31 -0
  156. package/dist/office/connector/xlsx/numfmt.js +913 -0
  157. package/dist/office/connector/xlsx/parts.js +66 -0
  158. package/dist/office/connector/xlsx/reader.js +394 -0
  159. package/dist/office/connector/xlsx/types.js +20 -0
  160. package/dist/office/connector/xlsx/written.js +446 -0
  161. package/dist/open-pick.js +99 -0
  162. package/dist/patch-secrets.js +194 -0
  163. package/dist/paths.js +65 -0
  164. package/dist/platform/darwin.js +179 -0
  165. package/dist/platform/index.js +61 -0
  166. package/dist/platform/spawn.js +115 -0
  167. package/dist/platform/stub.js +21 -0
  168. package/dist/platform/task-folder.js +41 -0
  169. package/dist/platform/types.js +20 -0
  170. package/dist/platform/win32-docrender.js +7 -0
  171. package/dist/platform/win32.js +265 -0
  172. package/dist/preferences.js +49 -0
  173. package/dist/reason.js +103 -0
  174. package/dist/region-delivery.js +148 -0
  175. package/dist/registry.js +68 -0
  176. package/dist/reveal.js +45 -0
  177. package/dist/review-process.js +154 -0
  178. package/dist/review-refresh-process.js +17 -0
  179. package/dist/review-refresh.js +120 -0
  180. package/dist/review-server.js +2079 -0
  181. package/dist/review-view-server.js +106 -0
  182. package/dist/review.js +8 -0
  183. package/dist/seal.js +315 -0
  184. package/dist/secret-files.js +34 -0
  185. package/dist/secret-hashes.js +27 -0
  186. package/dist/secret-rules.generated.js +3519 -0
  187. package/dist/secret-scan.js +127 -0
  188. package/dist/session-context.js +18 -0
  189. package/dist/signoff.js +419 -0
  190. package/dist/skill.js +110 -0
  191. package/dist/states.js +192 -0
  192. package/dist/tasks.js +1001 -0
  193. package/dist/timeline/attribution.js +207 -0
  194. package/dist/timeline/broken.js +55 -0
  195. package/dist/timeline/describe.js +413 -0
  196. package/dist/timeline/generic.js +195 -0
  197. package/dist/timeline/load.js +464 -0
  198. package/dist/timeline/loading.js +49 -0
  199. package/dist/timeline/notes.js +208 -0
  200. package/dist/timeline/page.js +178 -0
  201. package/dist/timeline/picture.js +303 -0
  202. package/dist/timeline/rail/assets/cocheck-icon.svg +1 -0
  203. package/dist/timeline/rail/assets/files-view.js +198 -0
  204. package/dist/timeline/rail/assets/loaders/icon-intro.json +1 -0
  205. package/dist/timeline/rail/assets/loaders/loader-orbit.json +1 -0
  206. package/dist/timeline/rail/assets/loaders/loader-spin.json +1 -0
  207. package/dist/timeline/rail/assets/review.css +992 -0
  208. package/dist/timeline/rail/assets/review.js +3365 -0
  209. package/dist/timeline/rail/assets/view-table.js +683 -0
  210. package/dist/timeline/rail/failure-line.js +26 -0
  211. package/dist/timeline/rail/files-model.js +45 -0
  212. package/dist/timeline/rail/live.js +49 -0
  213. package/dist/timeline/rail/made-pictures.js +48 -0
  214. package/dist/timeline/rail/mcp-card.js +307 -0
  215. package/dist/timeline/rail/model.js +1317 -0
  216. package/dist/timeline/rail/page.js +167 -0
  217. package/dist/timeline/rail/passes.js +106 -0
  218. package/dist/timeline/rail/regions.js +26 -0
  219. package/dist/timeline/rail/send-back.js +154 -0
  220. package/dist/timeline/rail/stop-status.js +164 -0
  221. package/dist/timeline/read-signal.js +743 -0
  222. package/dist/timeline/render/claimed.js +13 -0
  223. package/dist/timeline/render/fallback.js +36 -0
  224. package/dist/timeline/render/pdf-helper.js +71 -0
  225. package/dist/timeline/render/pdf.js +410 -0
  226. package/dist/timeline/render/pixel-pages.js +168 -0
  227. package/dist/timeline/render/png-crop.js +281 -0
  228. package/dist/timeline/render/registry.js +7 -0
  229. package/dist/timeline/render/text.js +366 -0
  230. package/dist/timeline/render/types.js +1 -0
  231. package/dist/timeline/render/view-v1.js +148 -0
  232. package/dist/timeline/render/whole.js +6 -0
  233. package/dist/timeline/rollout-failures.js +40 -0
  234. package/dist/timeline/runs.js +836 -0
  235. package/dist/timeline/stored-image.js +34 -0
  236. package/dist/timeline/subject-display.js +44 -0
  237. package/dist/timeline/timeline.js +1114 -0
  238. package/dist/timeline/write-signal.js +403 -0
  239. package/dist/tool-label.js +201 -0
  240. package/dist/tracking.js +87 -0
  241. package/dist/vendor/pdfjs/LICENSE +177 -0
  242. package/dist/vendor/pdfjs/pdf.min.mjs +27 -0
  243. package/dist/vendor/pdfjs/pdf.worker.min.mjs +27 -0
  244. package/package.json +66 -4
  245. package/public-kit/GUIDE.md +189 -0
  246. package/public-kit/README.md +10 -0
  247. package/public-kit/conformance/README.md +13 -0
  248. package/public-kit/conformance/cases/C1.json +12 -0
  249. package/public-kit/conformance/cases/C10.json +15 -0
  250. package/public-kit/conformance/cases/C11.json +16 -0
  251. package/public-kit/conformance/cases/C12.json +18 -0
  252. package/public-kit/conformance/cases/C13.json +23 -0
  253. package/public-kit/conformance/cases/C14.json +16 -0
  254. package/public-kit/conformance/cases/C16.json +15 -0
  255. package/public-kit/conformance/cases/C17.json +25 -0
  256. package/public-kit/conformance/cases/C2.json +13 -0
  257. package/public-kit/conformance/cases/C3.json +44 -0
  258. package/public-kit/conformance/cases/C4.json +13 -0
  259. package/public-kit/conformance/cases/C5.json +16 -0
  260. package/public-kit/conformance/cases/C6.json +58 -0
  261. package/public-kit/conformance/generate-large.mjs +15 -0
  262. package/public-kit/examples/toy-export/cocheck-connector.json +10 -0
  263. package/public-kit/examples/toy-export/connector.mjs +28 -0
  264. package/public-kit/examples/toy-helpers/cocheck-connector.json +10 -0
  265. package/public-kit/examples/toy-helpers/connector.mjs +69 -0
  266. package/public-kit/examples/toy-level-1/cocheck-connector.json +10 -0
  267. package/public-kit/examples/toy-level-1/connector.mjs +61 -0
  268. package/public-kit/examples/toy-level-3/cocheck-connector.json +10 -0
  269. package/public-kit/examples/toy-level-3/connector.mjs +82 -0
  270. package/public-kit/examples/toy-tracker/cocheck-connector.json +14 -0
  271. package/public-kit/examples/toy-tracker/connector.mjs +46 -0
  272. package/public-kit/examples/toy-tracker/samples/history.json +10 -0
  273. package/public-kit/examples/toy-tracker/samples/samples.json +7 -0
  274. package/public-kit/examples/toy-vendor/cocheck-connector.json +15 -0
  275. package/public-kit/examples/toy-vendor/connector.mjs +62 -0
  276. package/public-kit/helpers/pdf-text-layout.d.mts +35 -0
  277. package/public-kit/helpers/pdf-text-layout.mjs +602 -0
  278. package/public-kit/helpers/pdf-text.d.mts +56 -0
  279. package/public-kit/helpers/pdf-text.mjs +375 -0
  280. package/public-kit/helpers/pdf.d.mts +61 -0
  281. package/public-kit/helpers/pdf.mjs +251 -0
  282. package/public-kit/helpers/png.d.mts +15 -0
  283. package/public-kit/helpers/png.mjs +88 -0
  284. package/public-kit/helpers/spec.d.mts +4 -0
  285. package/public-kit/helpers/spec.mjs +2 -0
  286. package/public-kit/scaffold/README.md +23 -0
  287. package/public-kit/scaffold/template/README.md +13 -0
  288. package/public-kit/scaffold/template/cocheck-connector.json +10 -0
  289. package/public-kit/scaffold/template/connector.mjs +50 -0
  290. package/public-kit/spec/README.md +408 -0
  291. package/public-kit/spec/v1.md +598 -0
  292. package/public-kit/toy-product/README.md +7 -0
  293. package/public-kit/toy-product/notes-store.mjs +30 -0
  294. package/public-kit/toy-product/states/create.after.json +16 -0
  295. package/public-kit/toy-product/states/create.before.json +12 -0
  296. package/public-kit/toy-product/states/delete.after.json +8 -0
  297. package/public-kit/toy-product/states/delete.before.json +12 -0
  298. package/public-kit/toy-product/states/edit.after.json +12 -0
  299. package/public-kit/toy-product/states/edit.before.json +12 -0
  300. package/public-kit/toy-product/states/malformed.after.json +1 -0
  301. package/public-kit/toy-product/states/malformed.before.json +12 -0
  302. package/public-kit/toy-product/states/no-change.after.json +12 -0
  303. package/public-kit/toy-product/states/no-change.before.json +12 -0
  304. package/scripts/hook-launch.mjs +58 -0
  305. package/scripts/hook-launch.sh +52 -0
@@ -0,0 +1,246 @@
1
+ // The per-call tag on a Claude Code Bash call (built on a recorded probe).
2
+ //
3
+ // The form is a trailing shell comment line, `<command>\n# cocheck-call:<tool_use_id>:<agent_id|main>`, set by the PreToolUse hook through
4
+ // `hookSpecificOutput.updatedInput`. Chosen on evidence (see docs/attribution-tag.md):
5
+ // - A comment executes nothing and is not a subcommand, so the command's own subcommands are unchanged text: Claude Code's deny and ask
6
+ // rules ("apply when any subcommand matches") still see every one of them, and an allow rule has no new subcommand to fail on. The
7
+ // rejected forms each add or hide a subcommand: `export X=..;` and a pid-registry write are a new subcommand an allow rule must also
8
+ // match (and the registry's `>>` redirect is checked as a file write); `X=.. cmd` stops allow rules ("An allow rule won't match past an
9
+ // assignment of any other variable"); `env X=.. cmd` and `bash -c '..'` hide the command from deny rules, a security bug.
10
+ // - It is not in the environment, so no env dump prints it (the env form leaked in 5 of 30 probe cases).
11
+ // - Children find it in their ancestor shell's argv: Claude Code runs `<shell> -c "... eval '<command>' ..."`, so the comment is in the
12
+ // command line of the shell that runs the call (observed on 2.1.309), and the Python and Node write hooks walk up to it.
13
+ // A trailing line, not a leading one, so every line number an error message quotes stays the same. A command whose end is not at the
14
+ // shell's top level (an unterminated heredoc, a trailing backslash) or that does not parse is left untagged: the comment would become data.
15
+ import { spawnSync } from "node:child_process";
16
+ import { existsSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
17
+ import path from "node:path";
18
+ import { platform } from "../platform/index.js";
19
+ const TAG_PREFIX = "# cocheck-call:";
20
+ const ID = /^[A-Za-z0-9_-]{1,128}$/;
21
+ /** The tag as it appears anywhere (a process command line renders the newline as `\012` or a space); the last one wins. */
22
+ const TAG_ANYWHERE = /# cocheck-call:([A-Za-z0-9_-]{1,128}):([A-Za-z0-9_-]{1,128})/g;
23
+ /** The tag exactly as `tagCommand` appends it, at the very end of a command. */
24
+ const TAG_AT_END = /\n# cocheck-call:[A-Za-z0-9_-]{1,128}:[A-Za-z0-9_-]{1,128}$/;
25
+ /** Claude Code always prompts for a command past 10,000 characters; stay well clear so the tag never pushes one over. */
26
+ const MAX_COMMAND = 9_000;
27
+ const MAIN_AGENT = "main";
28
+ /**
29
+ * `--attribution-tag on|auto|off` wins over `COCHECK_ATTRIBUTION_TAG`; `on` when neither says. `on` tags in every permission mode: the
30
+ * a fenced live run showed a tagged `git status` still matched `Bash(git status:*)` under dontAsk and a tagged `rm -f x` was
31
+ * still denied by `Bash(rm:*)`. `auto` tags only in bypassPermissions (the earlier, more cautious default); `off` never tags, sets no
32
+ * environment and reads no evidence.
33
+ */
34
+ export function parseTagSetting(argv, env) {
35
+ const i = argv.indexOf("--attribution-tag");
36
+ const raw = (i >= 0 ? argv[i + 1] : env.COCHECK_ATTRIBUTION_TAG)?.trim().toLowerCase();
37
+ if (raw === "off" || raw === "0" || raw === "false" || raw === "no")
38
+ return "off";
39
+ if (raw === "auto")
40
+ return "auto";
41
+ return "on";
42
+ }
43
+ /** Whether a call in this permission mode is tagged under `setting`. */
44
+ export function tagsInMode(setting, permissionMode) {
45
+ if (setting === "off")
46
+ return false;
47
+ if (setting === "on")
48
+ return true;
49
+ return permissionMode === "bypassPermissions";
50
+ }
51
+ /** The shell Claude Code runs Bash calls in: `CLAUDE_CODE_SHELL`, else `SHELL`; only bash and zsh are tagged. */
52
+ export function callShell(env) {
53
+ for (const s of [env.CLAUDE_CODE_SHELL, env.SHELL]) {
54
+ if (!s || !path.isAbsolute(s))
55
+ continue;
56
+ const base = path.basename(s);
57
+ if ((base === "bash" || base === "zsh") && existsSync(s))
58
+ return s;
59
+ }
60
+ return undefined;
61
+ }
62
+ /** `sh -n` on `text`: true when it parses. Nothing runs (noexec). Any failure to check is "does not parse". */
63
+ function parses(shell, text) {
64
+ const args = path.basename(shell) === "zsh" ? ["-f", "-n", "-c", text] : ["-n", "-c", text];
65
+ const r = spawnSync(shell, args, { stdio: ["ignore", "ignore", "ignore"], timeout: 2_000, env: { PATH: "/usr/bin:/bin", HOME: "/nonexistent" } });
66
+ return r.status === 0 && r.error === undefined;
67
+ }
68
+ /** Bash's `set -v` / `set -o verbose` (and zsh's `setopt verbose`) echo every line read, the comment included: such a command is left untagged. */
69
+ const VERBOSE = /(^|[^\w-])set\s+[^;&|\n]*(-[A-Za-z]*v|-o\s*verbose)|setopt\s+[^;&|\n]*v_?e_?r_?b_?o_?s_?e/i;
70
+ /**
71
+ * The command with the tag appended, or null when it is left as it is: an id that is not plain, an empty or oversized command, one that
72
+ * turns on verbose echo, still holds `# cocheck-call:` after any trailing tag lines are stripped, ends in a backslash, does not parse in
73
+ * `shell`, or whose end is not at the top level (appending an unmatched quote still parses, so the end sits inside a heredoc body). A
74
+ * command that already ends in tag lines (copied from an earlier call) has them replaced by this call's.
75
+ */
76
+ export function tagCommand(raw, callId, agentId, shell) {
77
+ if (typeof raw !== "string" || typeof callId !== "string" || !ID.test(callId))
78
+ return null;
79
+ const agent = agentId === undefined || agentId === null || agentId === "" ? MAIN_AGENT : agentId;
80
+ if (typeof agent !== "string" || !ID.test(agent))
81
+ return null;
82
+ let command = raw;
83
+ while (TAG_AT_END.test(command))
84
+ command = command.replace(TAG_AT_END, "");
85
+ if (command.trim() === "" || command.length > MAX_COMMAND || command.includes("\0") || command.includes(TAG_PREFIX))
86
+ return null;
87
+ if (VERBOSE.test(command))
88
+ return null;
89
+ if (/\\\s*$/.test(command))
90
+ return null;
91
+ if (!parses(shell, command))
92
+ return null;
93
+ if (parses(shell, `${command}\n'`))
94
+ return null;
95
+ const tagged = `${command}\n${TAG_PREFIX}${callId}:${agent}`;
96
+ if (!parses(shell, tagged))
97
+ return null;
98
+ return tagged;
99
+ }
100
+ /** The command without a tag `tagCommand` appended; anything else is returned unchanged. */
101
+ export function stripTag(command) {
102
+ return command.replace(TAG_AT_END, "");
103
+ }
104
+ /** The call and agent of the last tag in a process command line, if any. */
105
+ export function tagInCommandLine(text) {
106
+ let last;
107
+ for (const m of text.matchAll(TAG_ANYWHERE))
108
+ last = m;
109
+ return last ? { call: last[1], agent: last[2] } : undefined;
110
+ }
111
+ /** Where the write hooks append their records: `<home>/attribution/`, never inside a watched folder (the home is refused there). */
112
+ export const evidenceDir = (home) => path.join(home, "attribution");
113
+ /** The write hooks as shipped (src/ or dist/). Never named in the environment: a Homebrew upgrade can remove this folder mid-session. */
114
+ export const writeHooksDir = () => path.join(import.meta.dirname, "hooks");
115
+ /** The stable guard loaders the environment names, under the CoCheck home: each runs its target only if the target still exists. */
116
+ export const guardDir = (home) => path.join(evidenceDir(home), "hooks");
117
+ /** Per session, a marker that a Pre tagged one of its calls; the write hooks look for nothing (no process walk) in a session without one. */
118
+ export const activeDir = (home) => path.join(evidenceDir(home), "active");
119
+ /** Per session, a marker that SessionStart set the write hooks' environment; a Pre tags only a session that has one. */
120
+ const readyDir = (home) => path.join(evidenceDir(home), "ready");
121
+ /** Per session, a file that exists only while the session is tracked (made by `cocheck track start`, removed by `stop`); the environment lines load no guard without it. */
122
+ export const onDir = (home) => path.join(evidenceDir(home), "on");
123
+ export const rootsFile = (home) => path.join(evidenceDir(home), "roots.json");
124
+ export const SESSION = /^[A-Za-z0-9_-]{1,128}$/;
125
+ const KEEP_MS = 3 * 86_400_000;
126
+ const dq = (s) => `"${s.replace(/(["\\$`])/g, "\\$1")}"`;
127
+ function writeAtomic(file, text) {
128
+ const tmp = `${file}.tmp-${process.pid}`;
129
+ writeFileSync(tmp, text, { mode: 0o600 });
130
+ renameSync(tmp, file);
131
+ }
132
+ /** The Node guard: requires the shipped preload when it exists, else does nothing. It never throws into the program. */
133
+ const nodeGuard = (target) => `"use strict";\n// CoCheck guard: loads the attribution write hook only while it exists (an upgrade can remove it).\ntry {\n const t = ${JSON.stringify(target)};\n if (require("node:fs").existsSync(t)) require(t);\n} catch {}\n`;
134
+ /** The Python guard: runs the shipped sitecustomize when it exists, then chains to the next sitecustomize on sys.path either way. */
135
+ const pythonGuard = (target) => `# CoCheck guard: runs the attribution write hook only while it exists (an upgrade can remove it).
136
+ import os as _o
137
+ import sys as _s
138
+ _t = ${JSON.stringify(target)}
139
+ try:
140
+ if _o.path.isfile(_t):
141
+ with open(_t, "rb") as _f:
142
+ exec(compile(_f.read(), _t, "exec"), {"__file__": _t, "__name__": "_cocheck_write_hook", "_COCHECK_GUARDED": True})
143
+ except Exception:
144
+ pass
145
+
146
+
147
+ def _cocheck_chain():
148
+ import importlib.machinery
149
+ import importlib.util
150
+ here = _o.path.dirname(_o.path.abspath(__file__))
151
+ rest = [p for p in _s.path if _o.path.abspath(p or ".") != here]
152
+ spec = importlib.machinery.PathFinder.find_spec("sitecustomize", rest)
153
+ if spec is None or spec.loader is None or not spec.origin or _o.path.dirname(_o.path.abspath(spec.origin)) == here:
154
+ return
155
+ module = importlib.util.module_from_spec(spec)
156
+ spec.loader.exec_module(module)
157
+
158
+
159
+ try:
160
+ _cocheck_chain()
161
+ except Exception:
162
+ pass
163
+ `;
164
+ /**
165
+ * SessionStart: writes the guard loaders and the folders the hooks may log (the registered folders, as given and resolved), prunes old
166
+ * session markers, and returns the lines for `CLAUDE_ENV_FILE`. Every path the lines name lives under the CoCheck home, and each line
167
+ * re-checks its file before each Bash call (the env file runs before every command), so a missing file sets nothing.
168
+ */
169
+ export function prepareSession(home, session, roots, nowMs, hooksDir = writeHooksDir(), dialect = platform().shellDialect.kind) {
170
+ const dir = guardDir(home);
171
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
172
+ mkdirSync(activeDir(home), { recursive: true, mode: 0o700 });
173
+ mkdirSync(readyDir(home), { recursive: true, mode: 0o700 });
174
+ writeAtomic(path.join(dir, "cocheck-preload.cjs"), nodeGuard(path.join(hooksDir, "cocheck-preload.cjs")));
175
+ writeAtomic(path.join(dir, "sitecustomize.py"), pythonGuard(path.join(hooksDir, "sitecustomize.py")));
176
+ const all = new Set();
177
+ for (const r of roots) {
178
+ if (!path.isAbsolute(r))
179
+ continue;
180
+ all.add(path.resolve(r));
181
+ try {
182
+ all.add(realpathSync(r));
183
+ }
184
+ catch {
185
+ // a folder that is gone logs nothing
186
+ }
187
+ }
188
+ writeAtomic(rootsFile(home), JSON.stringify([...all].sort()) + "\n");
189
+ for (const d of [activeDir(home), readyDir(home)]) {
190
+ for (const name of readdirSync(d)) {
191
+ const f = path.join(d, name);
192
+ try {
193
+ if (nowMs - statSync(f).mtimeMs > KEEP_MS)
194
+ rmSync(f, { force: true });
195
+ }
196
+ catch {
197
+ // raced with another session
198
+ }
199
+ }
200
+ }
201
+ if (typeof session !== "string" || !SESSION.test(session))
202
+ return "";
203
+ writeFileSync(path.join(readyDir(home), session), "", { mode: 0o600 });
204
+ return sessionEnvLines(home, session, dialect);
205
+ }
206
+ /** Whether SessionStart set the write hooks' environment for `session` (an install from before the write hooks has no SessionStart entry). */
207
+ export function sessionReady(home, session) {
208
+ return typeof session === "string" && SESSION.test(session) && existsSync(path.join(readyDir(home), session));
209
+ }
210
+ /** Marks `session` as tagged, so its Bash calls' children look for the tag. Throws when it cannot: the call is then left untagged. */
211
+ export function markSessionTagged(home, session) {
212
+ if (typeof session !== "string" || !SESSION.test(session))
213
+ throw new Error("session id is not plain");
214
+ mkdirSync(activeDir(home), { recursive: true, mode: 0o700 });
215
+ writeFileSync(path.join(activeDir(home), session), "", { mode: 0o600 });
216
+ }
217
+ /**
218
+ * The lines a SessionStart hook appends to `CLAUDE_ENV_FILE`. They are session-wide and carry no call id. Each export is guarded by a
219
+ * file test, so a guard that is gone sets nothing; the Node path is quoted again inside NODE_OPTIONS.
220
+ */
221
+ export function sessionEnvLines(home, session, dialect = platform().shellDialect.kind) {
222
+ if (session === undefined)
223
+ return "";
224
+ // The per-call tag is posix-only (the platform's shell dialect says so), so a session on any other dialect sets nothing:
225
+ // a preload or a guard path that the session's node cannot load would break every node, python and `cocheck` run in it.
226
+ if (dialect !== "posix")
227
+ return "";
228
+ const dir = guardDir(home);
229
+ const preload = path.join(dir, "cocheck-preload.cjs");
230
+ const nodeOpt = `--require ${JSON.stringify(preload)}`;
231
+ // Every line tests the session's `on` file, so an untracked or stopped session loads no guard and sets nothing (the env file is
232
+ // read before every Bash call, so the switch takes effect on the next call). One statement per line: callers may join the lines.
233
+ const on = `[ -f ${dq(path.join(onDir(home), session))} ]`;
234
+ // The call's tag, read from this shell's own command line while the shell is alive, for a child that outlives it (a forked pipeline
235
+ // stage whose shell aborted: no ancestor is left for the hook to read). Set per call, and cleared on an untagged one. The value is
236
+ // "<call>:<agent>", with no "cocheck-call" in it; it shows in an env dump.
237
+ const callTag = `_it=$(/bin/ps -ww -o command= -p $$ 2>/dev/null | /usr/bin/grep -Eo '# cocheck-call:[A-Za-z0-9_-]{1,128}:[A-Za-z0-9_-]{1,128}' | /usr/bin/tail -n 1); ` +
238
+ `if [ -n "$_it" ]; then export COCHECK_WRITE_CALL="\${_it#*:}"; else unset COCHECK_WRITE_CALL; fi; unset _it`;
239
+ return [
240
+ `if ${on}; then ${callTag}; fi`,
241
+ `if ${on}; then export COCHECK_WRITE_LOG=${dq(evidenceDir(home))} COCHECK_TAG_SESSION=${dq(session)}; fi`,
242
+ `if ${on} && [ -f ${dq(path.join(dir, "sitecustomize.py"))} ]; then export PYTHONPATH=${dq(dir)}"\${PYTHONPATH:+:\$PYTHONPATH}"; fi`,
243
+ `if ${on} && [ -f ${dq(preload)} ]; then export NODE_OPTIONS=${dq(nodeOpt)}"\${NODE_OPTIONS:+ \$NODE_OPTIONS}"; fi`,
244
+ "",
245
+ ].join("\n");
246
+ }