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,311 @@
1
+ // Positive write evidence. The Python and Node write hooks (hooks/) append one JSON line per file a tagged Bash call's child opened
2
+ // for writing, renamed or removed, to `<home>/attribution/writes-<UTC date>.jsonl`. Each hook event reads what was appended since its
3
+ // folder's cursor and keeps, per changed path inside the folder, the calls that wrote it. Attribution consults this ahead of open-call
4
+ // windows (hook-adapter.ts, `#proven`); with no record for a path, or a record it cannot trust, the open-call rule is unchanged.
5
+ import { closeSync, openSync, readdirSync, readSync, rmSync, statSync } from "node:fs";
6
+ import path from "node:path";
7
+ import { evidenceDir } from "./tag.js";
8
+ const LOG_NAME = /^writes-(\d{4}-\d{2}-\d{2})\.jsonl$/;
9
+ const ID = /^[A-Za-z0-9_-]{1,128}$/;
10
+ /** Read at most this much of the logs in one event; the rest waits for the next. */
11
+ const READ_CAP_BYTES = 8 * 1024 * 1024;
12
+ /** Paths kept at most; the oldest go first. */
13
+ const PATHS_KEPT = 2_000;
14
+ /** Log files older than this many days are deleted by whichever event sees them. */
15
+ const LOG_DAYS_KEPT = 3;
16
+ const emptyEvidence = () => ({ cursors: {}, byPath: {} });
17
+ function parseRecord(line) {
18
+ let d;
19
+ try {
20
+ d = JSON.parse(line);
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ if (d === null || typeof d !== "object" || d.v !== 1)
26
+ return undefined;
27
+ if (typeof d.call !== "string" || !ID.test(d.call) || typeof d.agent !== "string" || !ID.test(d.agent))
28
+ return undefined;
29
+ if (typeof d.path !== "string" || (d.op !== "write" && d.op !== "remove" && d.op !== "spawn" && d.op !== "start"))
30
+ return undefined;
31
+ if (d.op !== "spawn" && d.op !== "start" && !path.isAbsolute(d.path))
32
+ return undefined;
33
+ return { call: d.call, agent: d.agent, path: d.path, op: d.op, ts: typeof d.ts === "number" ? d.ts : 0, ...(Number.isInteger(d.pid) ? { pid: d.pid } : {}), ...(Number.isInteger(d.ppid) ? { ppid: d.ppid } : {}) };
34
+ }
35
+ /**
36
+ * Reads every record appended since `st.cursors` and merges those whose path `keyOf` accepts (returns the folder's key for it) into
37
+ * `st.byPath`. A log that shrank is read from its start. A missing directory is no evidence. Never throws for a bad line.
38
+ */
39
+ export function readEvidence(home, st, keyOf, nowMs, onRecord) {
40
+ const dir = evidenceDir(home);
41
+ let names;
42
+ try {
43
+ names = readdirSync(dir).filter((n) => LOG_NAME.test(n)).sort();
44
+ }
45
+ catch {
46
+ return;
47
+ }
48
+ const oldest = new Date(nowMs - LOG_DAYS_KEPT * 86_400_000).toISOString().slice(0, 10);
49
+ let budget = READ_CAP_BYTES;
50
+ const live = new Set();
51
+ for (const name of names) {
52
+ const file = path.join(dir, name);
53
+ if (name.match(LOG_NAME)[1] < oldest) {
54
+ rmSync(file, { force: true });
55
+ continue;
56
+ }
57
+ live.add(name);
58
+ let size;
59
+ try {
60
+ size = statSync(file).size;
61
+ }
62
+ catch {
63
+ continue;
64
+ }
65
+ let from = st.cursors[name] ?? 0;
66
+ if (from > size)
67
+ from = 0;
68
+ const len = Math.min(size - from, budget);
69
+ if (len <= 0) {
70
+ st.cursors[name] = from;
71
+ continue;
72
+ }
73
+ const buf = Buffer.alloc(len);
74
+ const fd = openSync(file, "r");
75
+ let got = 0;
76
+ try {
77
+ got = readSync(fd, buf, 0, len, from);
78
+ }
79
+ finally {
80
+ closeSync(fd);
81
+ }
82
+ const end = buf.subarray(0, got).lastIndexOf(0x0a);
83
+ if (end < 0) {
84
+ st.cursors[name] = from;
85
+ continue;
86
+ }
87
+ budget -= end + 1;
88
+ for (const line of buf.subarray(0, end).toString("utf8").split("\n")) {
89
+ const r = parseRecord(line);
90
+ if (!r)
91
+ continue;
92
+ onRecord?.(r, r.op === "spawn" || r.op === "start" ? undefined : keyOf(r.path));
93
+ if (r.op === "start")
94
+ continue;
95
+ if (r.op === "spawn") {
96
+ const un = (st.unobserved ??= []);
97
+ if (!un.includes(r.call))
98
+ un.push(r.call);
99
+ if (un.length > PATHS_KEPT)
100
+ un.splice(0, un.length - PATHS_KEPT);
101
+ continue;
102
+ }
103
+ const key = keyOf(r.path);
104
+ if (key === undefined)
105
+ continue;
106
+ const hit = (st.byPath[key] ??= { calls: [], at: 0 });
107
+ if (!hit.calls.includes(r.call))
108
+ hit.calls = [...hit.calls, r.call].sort();
109
+ hit.at = Math.max(hit.at, r.ts);
110
+ }
111
+ st.cursors[name] = from + end + 1;
112
+ }
113
+ for (const name of Object.keys(st.cursors))
114
+ if (!live.has(name))
115
+ delete st.cursors[name];
116
+ const keys = Object.keys(st.byPath);
117
+ if (keys.length > PATHS_KEPT) {
118
+ keys.sort((a, b) => st.byPath[a].at - st.byPath[b].at);
119
+ for (const k of keys.slice(0, keys.length - PATHS_KEPT))
120
+ delete st.byPath[k];
121
+ }
122
+ }
123
+ /** Starts a folder's cursors at the logs' current ends, so records written before the folder was first seen are never read. */
124
+ export function startEvidence(home) {
125
+ const st = emptyEvidence();
126
+ try {
127
+ for (const name of readdirSync(evidenceDir(home))) {
128
+ if (LOG_NAME.test(name))
129
+ st.cursors[name] = statSync(path.join(evidenceDir(home), name)).size;
130
+ }
131
+ }
132
+ catch {
133
+ // no logs yet
134
+ }
135
+ return st;
136
+ }
137
+ /** Programs whose children carry a write hook (Python without -I/-E/-S, Node), and builtins and readers that write nothing without a redirect. */
138
+ const PYTHON = /^python(\d+(\.\d+)*)?$/;
139
+ const READERS = new Set(["cd", "echo", "printf", "true", "false", "pwd", "ls", "cat", "head", "tail", "wc", "grep", "test", "[", "sleep", "wait", ":"]);
140
+ /** `command` split into simple commands at `&&`, `||`, `;`, `|`, `&` and newlines outside quotes; null when it holds a redirect, a substitution or an unclosed quote. */
141
+ function segments(command) {
142
+ const out = [];
143
+ let words = [];
144
+ let word = "";
145
+ let inWord = false;
146
+ let q = null;
147
+ const endWord = () => {
148
+ if (inWord)
149
+ words.push(word);
150
+ word = "";
151
+ inWord = false;
152
+ };
153
+ const endSeg = () => {
154
+ endWord();
155
+ if (words.length > 0)
156
+ out.push(words);
157
+ words = [];
158
+ };
159
+ for (let i = 0; i < command.length; i++) {
160
+ const c = command[i];
161
+ if (q === "'") {
162
+ if (c === "'")
163
+ q = null;
164
+ else
165
+ word += c;
166
+ continue;
167
+ }
168
+ if (c === "`" || (c === "$" && command[i + 1] === "("))
169
+ return null;
170
+ if (q === '"') {
171
+ if (c === '"')
172
+ q = null;
173
+ else if (c === "\\" && i + 1 < command.length)
174
+ word += command[++i];
175
+ else
176
+ word += c;
177
+ continue;
178
+ }
179
+ if (c === "'" || c === '"') {
180
+ q = c;
181
+ inWord = true;
182
+ continue;
183
+ }
184
+ if (c === ">" || c === "<")
185
+ return null;
186
+ if (c === "\\") {
187
+ if (i + 1 < command.length)
188
+ word += command[++i];
189
+ inWord = true;
190
+ continue;
191
+ }
192
+ if (c === "#" && !inWord) {
193
+ while (i < command.length && command[i] !== "\n")
194
+ i++;
195
+ endSeg();
196
+ continue;
197
+ }
198
+ if (c === ";" || c === "&" || c === "|" || c === "\n" || c === "(" || c === ")") {
199
+ endSeg();
200
+ continue;
201
+ }
202
+ if (c === " " || c === "\t") {
203
+ endWord();
204
+ continue;
205
+ }
206
+ word += c;
207
+ inWord = true;
208
+ }
209
+ if (q !== null)
210
+ return null;
211
+ endSeg();
212
+ return out;
213
+ }
214
+ /**
215
+ * Whether every write a Bash call could make goes through an observed channel: each simple command is Python (without -I, -E or -S, which
216
+ * skip the hook) or Node, or a builtin or reader that writes nothing, and there is no redirect, substitution, `exec` or any other program.
217
+ * A Python or Node child that starts another program is caught separately (a `spawn` record makes the call unobserved).
218
+ */
219
+ export function observedOnly(command) {
220
+ const segs = segments(command);
221
+ if (segs === null)
222
+ return false;
223
+ for (const seg of segs) {
224
+ let i = 0;
225
+ while (i < seg.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(seg[i]))
226
+ i++;
227
+ if (i >= seg.length)
228
+ continue;
229
+ const prog = path.basename(seg[i]);
230
+ if (READERS.has(prog))
231
+ continue;
232
+ if (prog === "node")
233
+ continue;
234
+ if (PYTHON.test(prog)) {
235
+ for (const a of seg.slice(i + 1)) {
236
+ if (!a.startsWith("-") || a === "-")
237
+ break;
238
+ if (a === "-c" || a === "-m")
239
+ break;
240
+ if (/^-[A-Za-z]*[IES]/.test(a))
241
+ return false;
242
+ }
243
+ continue;
244
+ }
245
+ return false;
246
+ }
247
+ return true;
248
+ }
249
+ /**
250
+ * The strict rule behind the `WriteEvidence` seam: the calls whose children's writes to `file` were recorded, when they are
251
+ * all among `candidates` (the calls open at the sweep) and every other candidate that may write the file could have written only where a
252
+ * hook sees: a tagged Bash call whose command is Python, Node and non-writing builtins only (`observedOnly`), none of whose children
253
+ * started another program (`unobserved`), whose children provably carried the hook (`hooked`), and whose command does not name the
254
+ * file. Otherwise undefined: the window rule decides.
255
+ */
256
+ export function strictWriters(file, candidates, writers, factsOf, unobserved) {
257
+ if (writers === undefined || writers.length === 0 || !writers.every((w) => candidates.includes(w)))
258
+ return undefined;
259
+ const base = path.basename(file).toLowerCase();
260
+ for (const id of candidates) {
261
+ if (writers.includes(id))
262
+ continue;
263
+ const c = factsOf(id);
264
+ if (c === undefined)
265
+ return undefined;
266
+ if (!c.mayWrite)
267
+ continue;
268
+ if (c.tool !== "Bash" || !c.tagged || !c.hooked || !observedOnly(c.command) || c.command.toLowerCase().includes(base) || unobserved.has(id))
269
+ return undefined;
270
+ }
271
+ return [...writers].sort();
272
+ }
273
+ /**
274
+ * The timeline's side of the seam: who the live adapter proved wrote `file` at the ledger step `stepId`, from the ops' `provenWrites`. Only
275
+ * writers among `candidates`; undefined when no op proved a write of this file at that step.
276
+ */
277
+ export function writeEvidenceFromOps(ops) {
278
+ const byKey = new Map();
279
+ for (const op of ops) {
280
+ let args = op.args;
281
+ if (args === undefined && typeof op.args_json === "string") {
282
+ try {
283
+ args = JSON.parse(op.args_json);
284
+ }
285
+ catch {
286
+ args = undefined;
287
+ }
288
+ }
289
+ const call = args?.tool_use_id;
290
+ const pw = args?.provenWrites;
291
+ if (typeof call !== "string" || !Array.isArray(pw))
292
+ continue;
293
+ for (const w of pw) {
294
+ const p = w?.path;
295
+ const step = w?.step;
296
+ if (typeof p !== "string" || typeof step !== "number" || !Number.isInteger(step))
297
+ continue;
298
+ const key = `${step}\0${p}`;
299
+ (byKey.get(key) ?? byKey.set(key, new Set()).get(key)).add(call);
300
+ }
301
+ }
302
+ return (file, candidates, stepId) => {
303
+ if (stepId === undefined || stepId === null)
304
+ return undefined;
305
+ const hit = byKey.get(`${stepId}\0${file}`);
306
+ if (hit === undefined)
307
+ return undefined;
308
+ const writers = [...hit].sort();
309
+ return writers.every((w) => candidates.includes(w)) ? writers : undefined;
310
+ };
311
+ }
@@ -0,0 +1,254 @@
1
+ // CoCheck: records which Claude Code Bash call wrote a file, from inside a Node child.
2
+ //
3
+ // Required by the guard loader CoCheck writes under its home (NODE_OPTIONS names the guard, never this file, which an upgrade can
4
+ // remove). Does nothing unless COCHECK_WRITE_LOG names a directory and the session (COCHECK_TAG_SESSION) has had a call tagged. On
5
+ // the process's first write or program start it looks for the call's tag ("# cocheck-call:<call>:<agent>") in its ancestors' command
6
+ // lines, nearest first; with no tag it stops for good. Writes are recorded only under the registered folders (roots.json); starting
7
+ // a program other than node or python is recorded as "spawn", since that program's writes are not seen. It wraps fs's write entry points, keeps
8
+ // their behaviour (arguments, return values, throws and callbacks pass through untouched), never prints, and guards against
9
+ // re-entry: its own log write and its `ps` lookup run on the original functions with the guard held.
10
+ "use strict";
11
+ (() => {
12
+ const logDir = process.env.COCHECK_WRITE_LOG;
13
+ const session = process.env.COCHECK_TAG_SESSION || "";
14
+ if (!logDir || !require("node:path").isAbsolute(logDir)) return;
15
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(session)) return;
16
+ const fs = require("node:fs");
17
+ const path = require("node:path");
18
+ const orig = {
19
+ openSync: fs.openSync,
20
+ writeSync: fs.writeSync,
21
+ closeSync: fs.closeSync,
22
+ readFileSync: fs.readFileSync,
23
+ existsSync: fs.existsSync,
24
+ realpathSync: fs.realpathSync,
25
+ mkdirSync: fs.mkdirSync,
26
+ };
27
+ const TAG = /# cocheck-call:([A-Za-z0-9_-]{1,128}):([A-Za-z0-9_-]{1,128})/g;
28
+ const logPrefix = path.join(logDir, path.sep);
29
+ const seen = new Set();
30
+ let busy = false;
31
+ let looked = false;
32
+ let tag = null;
33
+ let roots = [];
34
+ const HOOKED = /^(python(\d+(\.\d+)*)?|node)$/;
35
+
36
+ const look = () => {
37
+ if (looked) return tag;
38
+ looked = true;
39
+ if (!orig.existsSync(path.join(logDir, "active", session))) return null;
40
+ tag = findTag();
41
+ try {
42
+ const r = JSON.parse(orig.readFileSync(path.join(logDir, "roots.json"), "utf8"));
43
+ roots = Array.isArray(r) ? r.filter((x) => typeof x === "string" && x.startsWith("/")) : [];
44
+ } catch {
45
+ roots = [];
46
+ }
47
+ return tag;
48
+ };
49
+ const inRoot = (p) => roots.some((r) => p === r || p.startsWith(r.replace(/\/+$/, "") + "/"));
50
+ const underRoots = (p) => {
51
+ if (inRoot(p)) return true;
52
+ try {
53
+ return inRoot(path.join(orig.realpathSync(path.dirname(p)), path.basename(p)));
54
+ } catch {
55
+ return false;
56
+ }
57
+ };
58
+
59
+ const commandLine = (pid) => {
60
+ try {
61
+ const cmd = orig.readFileSync(`/proc/${pid}/cmdline`).toString("utf8").split("\0").join(" ");
62
+ const stat = orig.readFileSync(`/proc/${pid}/stat`).toString("utf8");
63
+ const ppid = Number(stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/)[1]);
64
+ return { ppid, cmd };
65
+ } catch {}
66
+ try {
67
+ const r = require("node:child_process").spawnSync("/bin/ps", ["-ww", "-o", "ppid=,command=", "-p", String(pid)], {
68
+ stdio: ["ignore", "pipe", "ignore"],
69
+ timeout: 2000,
70
+ });
71
+ const out = r.stdout ? r.stdout.toString("utf8").trim() : "";
72
+ if (!out) return null;
73
+ const sp = out.indexOf(" ");
74
+ return { ppid: Number(sp < 0 ? out : out.slice(0, sp)), cmd: sp < 0 ? "" : out.slice(sp + 1) };
75
+ } catch {
76
+ return null;
77
+ }
78
+ };
79
+
80
+ const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh"]);
81
+ const isCShell = (cmd) => {
82
+ const w = cmd.split(/\s+/).filter(Boolean);
83
+ if (w.length === 0 || !SHELLS.has(path.basename(w[0]).replace(/^-+/, ""))) return false;
84
+ return w.slice(1, 4).some((x) => /^-[A-Za-z]*c[A-Za-z]*$/.test(x));
85
+ };
86
+
87
+ // The call's own shell put "<call>:<agent>" in the environment before the command ran; a child that outlives that shell
88
+ // inherits it, when no ancestor is left to read the tag from.
89
+ const envTag = () => {
90
+ const m = /^([A-Za-z0-9_-]{1,128}):([A-Za-z0-9_-]{1,128})$/.exec(process.env.COCHECK_WRITE_CALL || "");
91
+ return m ? [m[1], m[2]] : null;
92
+ };
93
+
94
+ const findTag = () => {
95
+ let pid = process.ppid;
96
+ if (pid <= 1) return envTag();
97
+ for (let i = 0; i < 12 && pid > 1; i++) {
98
+ const got = commandLine(pid);
99
+ if (!got) return envTag();
100
+ let last = null;
101
+ for (const m of got.cmd.matchAll(TAG)) last = m;
102
+ if (last) return [last[1], last[2]];
103
+ // The nearest `<shell> -c` is the call's own shell: never look past it (a nested session's outer call).
104
+ if (isCShell(got.cmd)) return null;
105
+ pid = got.ppid;
106
+ }
107
+ return null;
108
+ };
109
+
110
+ const pathOf = (p) => {
111
+ if (typeof p === "string") return p;
112
+ if (Buffer.isBuffer(p)) return p.toString("utf8");
113
+ if (p instanceof URL && p.protocol === "file:") return require("node:url").fileURLToPath(p);
114
+ return null;
115
+ };
116
+
117
+ const record = (op, target) => {
118
+ if (busy || (looked && tag === null)) return;
119
+ busy = true;
120
+ try {
121
+ let p;
122
+ if (op === "spawn" || op === "start") p = String(target);
123
+ else {
124
+ p = pathOf(target);
125
+ if (!p) return;
126
+ p = path.resolve(p);
127
+ if (p.startsWith(logPrefix) || p.startsWith("/dev/")) return;
128
+ }
129
+ const key = `${op}\0${p}`;
130
+ if (seen.has(key)) return;
131
+ if (look() === null) return;
132
+ if (op !== "spawn" && op !== "start" && !underRoots(p)) return;
133
+ seen.add(key);
134
+ const now = new Date();
135
+ const line = JSON.stringify({ v: 1, call: tag[0], agent: tag[1], pid: process.pid, ts: now.getTime(), op, path: p, via: "node", ...(op === "start" ? { ppid: process.ppid } : {}) }) + "\n";
136
+ const name = path.join(logDir, `writes-${now.toISOString().slice(0, 10)}.jsonl`);
137
+ let fd;
138
+ try {
139
+ fd = orig.openSync(name, "a", 0o600);
140
+ } catch (e) {
141
+ if (!e || e.code !== "ENOENT") throw e;
142
+ orig.mkdirSync(logDir, { recursive: true, mode: 0o700 });
143
+ fd = orig.openSync(name, "a", 0o600);
144
+ }
145
+ try {
146
+ orig.writeSync(fd, line);
147
+ } finally {
148
+ orig.closeSync(fd);
149
+ }
150
+ } catch {
151
+ // never into the program
152
+ } finally {
153
+ busy = false;
154
+ }
155
+ };
156
+
157
+ const WRITE_FLAGS = fs.constants.O_WRONLY | fs.constants.O_RDWR | fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_TRUNC;
158
+ const writesFlag = (flags) => (flags === undefined || flags === null ? false : typeof flags === "number" ? (flags & WRITE_FLAGS) !== 0 : /[wa+x]/.test(String(flags)));
159
+ const fdLike = (p) => typeof p === "number" || (p && typeof p === "object" && typeof p.fd === "number" && !(p instanceof URL));
160
+
161
+ const PROMISIFY = require("node:util").promisify.custom;
162
+
163
+ /**
164
+ * Wraps `obj[name]` so `pick(args)` names what it writes; the original runs exactly as called. The original's own properties carry
165
+ * over (exec and execFile hold `util.promisify.custom`, without which `promisify(execFile)` resolves to a bare stdout and its
166
+ * errors lose .stdout/.stderr); a promisify hook is itself wrapped so it records like the plain call, once.
167
+ */
168
+ const wrap = (obj, name, pick) => {
169
+ const fn = obj && obj[name];
170
+ if (typeof fn !== "function" || fn.__cocheckWrapped) return;
171
+ let inner = 0; // > 0 while a wrapped promisify hook runs: a call it makes back into `wrapped` is already recorded
172
+ const note = (args) => {
173
+ if (busy || inner > 0) return;
174
+ try {
175
+ for (const [op, target] of pick(args)) if (!fdLike(target)) record(op, target);
176
+ } catch {}
177
+ };
178
+ const wrapped = function (...args) {
179
+ note(args);
180
+ return fn.apply(this, args);
181
+ };
182
+ for (const key of Reflect.ownKeys(fn)) {
183
+ if (key === "length" || key === "name" || key === "prototype") continue;
184
+ const d = Object.getOwnPropertyDescriptor(fn, key);
185
+ if (key === PROMISIFY && typeof d.value === "function") {
186
+ const custom = d.value;
187
+ const hook = function (...args) {
188
+ note(args);
189
+ inner++;
190
+ try {
191
+ return custom.apply(this, args);
192
+ } finally {
193
+ inner--;
194
+ }
195
+ };
196
+ Object.defineProperty(hook, "name", { value: custom.name });
197
+ Object.defineProperty(hook, "length", { value: custom.length });
198
+ d.value = hook;
199
+ }
200
+ try {
201
+ Object.defineProperty(wrapped, key, d);
202
+ } catch {}
203
+ }
204
+ Object.defineProperty(wrapped, "__cocheckWrapped", { value: true });
205
+ Object.defineProperty(wrapped, "name", { value: fn.name });
206
+ Object.defineProperty(wrapped, "length", { value: fn.length });
207
+ obj[name] = wrapped;
208
+ };
209
+
210
+ const flagsArg = (opt, dflt) => (typeof opt === "string" ? dflt : opt && typeof opt === "object" && opt.flag !== undefined ? opt.flag : dflt);
211
+ const openPick = ([p, flags]) => (writesFlag(flags) ? [["write", p]] : []);
212
+ const writeFilePick = ([p, , opt]) => (writesFlag(flagsArg(opt, "w")) ? [["write", p]] : []);
213
+ const appendPick = ([p, , opt]) => (writesFlag(flagsArg(opt, "a")) ? [["write", p]] : []);
214
+ const renamePick = ([a, b]) => [["remove", a], ["write", b]];
215
+ const copyPick = ([, b]) => [["write", b]];
216
+ const removePick = ([p]) => [["remove", p]];
217
+ const streamPick = ([p, opt]) => (writesFlag(flagsArg(opt, "w")) ? [["write", p]] : []);
218
+
219
+ for (const [name, pick] of [
220
+ ["open", openPick], ["openSync", openPick],
221
+ ["writeFile", writeFilePick], ["writeFileSync", writeFilePick],
222
+ ["appendFile", appendPick], ["appendFileSync", appendPick],
223
+ ["rename", renamePick], ["renameSync", renamePick],
224
+ ["copyFile", copyPick], ["copyFileSync", copyPick], ["cp", copyPick], ["cpSync", copyPick],
225
+ ["unlink", removePick], ["unlinkSync", removePick],
226
+ ["truncate", removePick.length ? ([p]) => [["write", p]] : null], ["truncateSync", ([p]) => [["write", p]]],
227
+ ["createWriteStream", streamPick],
228
+ ]) if (pick) wrap(fs, name, pick);
229
+ const cp = require("node:child_process");
230
+ const exeName = (f) => path.basename(String(f || "?"));
231
+ const spawnPick = ([file, a, o]) => {
232
+ const opts = Array.isArray(a) ? o : a;
233
+ const shell = opts && typeof opts === "object" && opts.shell;
234
+ const name = exeName(file);
235
+ return shell || !HOOKED.test(name) ? [["spawn", shell ? "sh" : name]] : [];
236
+ };
237
+ const shellPick = () => [["spawn", "sh"]];
238
+ for (const [name, pick] of [
239
+ ["spawn", spawnPick], ["spawnSync", spawnPick], ["execFile", spawnPick], ["execFileSync", spawnPick],
240
+ ["exec", shellPick], ["execSync", shellPick],
241
+ ]) wrap(cp, name, pick);
242
+ const fsp = fs.promises;
243
+ for (const [name, pick] of [
244
+ ["open", openPick], ["writeFile", writeFilePick], ["appendFile", appendPick],
245
+ ["rename", renamePick], ["copyFile", copyPick], ["cp", copyPick], ["unlink", removePick], ["truncate", ([p]) => [["write", p]]],
246
+ ]) wrap(fsp, name, pick);
247
+ // Once the tag is found, a "start" record names the call and this interpreter, so "logged no write" is only ever trusted for a
248
+ // call whose children provably carried the hook (one that never loaded, or found no tag, leaves no start record).
249
+ try {
250
+ if (orig.existsSync(path.join(logDir, "active", session))) record("start", process.execPath);
251
+ } catch {
252
+ // never into the program
253
+ }
254
+ })();