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.
- package/LICENSE +21 -0
- package/README.md +104 -2
- package/THIRD_PARTY_NOTICES.md +279 -0
- package/bin/cocheck.mjs +8 -0
- package/dist/agent-transcripts.js +541 -0
- package/dist/attribution/basis.js +31 -0
- package/dist/attribution/evidence.js +311 -0
- package/dist/attribution/hooks/cocheck-preload.cjs +254 -0
- package/dist/attribution/hooks/sitecustomize.py +245 -0
- package/dist/attribution/names.js +163 -0
- package/dist/attribution/reconstruct.js +128 -0
- package/dist/attribution/tag.js +246 -0
- package/dist/attribution/write-scope-win.js +615 -0
- package/dist/attribution/write-scope.js +1668 -0
- package/dist/build-info.json +1 -0
- package/dist/cli-main.js +8 -0
- package/dist/cli.js +193 -0
- package/dist/codex-config.js +107 -0
- package/dist/connector/after-gap.js +56 -0
- package/dist/connector/after-snapshot.js +244 -0
- package/dist/connector/before-snapshot.js +168 -0
- package/dist/connector/builtins.js +93 -0
- package/dist/connector/changes-v1.js +276 -0
- package/dist/connector/claimed-state.js +40 -0
- package/dist/connector/claimed.js +86 -0
- package/dist/connector/conformance.js +458 -0
- package/dist/connector/diff-object.js +81 -0
- package/dist/connector/diff-samples.js +64 -0
- package/dist/connector/diff.js +273 -0
- package/dist/connector/doc-level.js +20 -0
- package/dist/connector/enabled-types.js +87 -0
- package/dist/connector/export-view.js +13 -0
- package/dist/connector/file-capture.js +265 -0
- package/dist/connector/frozen.js +213 -0
- package/dist/connector/installed-manifests.js +72 -0
- package/dist/connector/installed-match.js +161 -0
- package/dist/connector/local-process.js +119 -0
- package/dist/connector/nothing-changed-rule.js +23 -0
- package/dist/connector/old-rows.js +66 -0
- package/dist/connector/png-pixels.js +4 -0
- package/dist/connector/registry.js +78 -0
- package/dist/connector/requires.js +30 -0
- package/dist/connector/row-doc.js +54 -0
- package/dist/connector/run-argv.js +25 -0
- package/dist/connector/runner.js +325 -0
- package/dist/connector/schema.js +242 -0
- package/dist/connector/subject.js +8 -0
- package/dist/connector/subjects.js +113 -0
- package/dist/connector/validate.js +200 -0
- package/dist/connector-auth.js +101 -0
- package/dist/connector-create.js +55 -0
- package/dist/connector-doctor.js +167 -0
- package/dist/connector-test-cli.js +627 -0
- package/dist/connector-types-cli.js +43 -0
- package/dist/connectors/microsoft-excel/cocheck-connector.json +13 -0
- package/dist/connectors/microsoft-excel/connector.mjs +11 -0
- package/dist/connectors/microsoft-powerpoint/cocheck-connector.json +13 -0
- package/dist/connectors/microsoft-powerpoint/connector.mjs +11 -0
- package/dist/connectors/microsoft-word/cocheck-connector.json +13 -0
- package/dist/connectors/microsoft-word/connector.mjs +11 -0
- package/dist/copies.js +151 -0
- package/dist/copilot-helpers.js +246 -0
- package/dist/coverage.js +277 -0
- package/dist/credit-guard.js +330 -0
- package/dist/display.js +78 -0
- package/dist/file-lock.js +145 -0
- package/dist/fingerprint.js +25 -0
- package/dist/formats/files/align.js +84 -0
- package/dist/formats/files/csv.js +78 -0
- package/dist/formats/files/layer.js +274 -0
- package/dist/formats/files/scan.js +86 -0
- package/dist/formats/files/textlike.js +21 -0
- package/dist/formats/layer.js +48 -0
- package/dist/helpers/pdfpages +0 -0
- package/dist/home-page.js +173 -0
- package/dist/home-perms.js +59 -0
- package/dist/hook-adapter.js +3415 -0
- package/dist/hook-cli.js +505 -0
- package/dist/hook-journal.js +147 -0
- package/dist/hook.js +25 -0
- package/dist/hosts/claude.js +250 -0
- package/dist/hosts/codex-bin-macos.js +2 -0
- package/dist/hosts/codex-bin.js +35 -0
- package/dist/hosts/codex-trust-probe.js +52 -0
- package/dist/hosts/codex-trust.js +46 -0
- package/dist/hosts/codex.js +355 -0
- package/dist/hosts/copilot.js +236 -0
- package/dist/hosts/index.js +52 -0
- package/dist/hosts/session-titles.js +327 -0
- package/dist/hosts/shared.js +31 -0
- package/dist/hosts/types.js +26 -0
- package/dist/html.js +4 -0
- package/dist/install.js +676 -0
- package/dist/items.js +105 -0
- package/dist/ledger.js +2097 -0
- package/dist/narration.js +202 -0
- package/dist/normalize.js +82 -0
- package/dist/office/connector/apps.js +34 -0
- package/dist/office/connector/docx/layer.js +247 -0
- package/dist/office/connector/docx/reader.js +284 -0
- package/dist/office/connector/excel/align.js +284 -0
- package/dist/office/connector/excel/answer.js +352 -0
- package/dist/office/connector/excel/diff.js +1310 -0
- package/dist/office/connector/excel/errors.js +44 -0
- package/dist/office/connector/excel/look.js +121 -0
- package/dist/office/connector/excel/print-boxes.js +432 -0
- package/dist/office/connector/excel/print-grid-previous.js +206 -0
- package/dist/office/connector/excel/print-setup.js +168 -0
- package/dist/office/connector/excel/workbook.js +374 -0
- package/dist/office/connector/export-driver.js +9 -0
- package/dist/office/connector/helpers/cocheck-screen +0 -0
- package/dist/office/connector/issues.js +31 -0
- package/dist/office/connector/mac-guard.js +16 -0
- package/dist/office/connector/main.js +23 -0
- package/dist/office/connector/nothing-changed.js +18 -0
- package/dist/office/connector/office-job.js +416 -0
- package/dist/office/connector/office-macos.js +473 -0
- package/dist/office/connector/office-win-export.js +107 -0
- package/dist/office/connector/office-win-lifecycle.js +194 -0
- package/dist/office/connector/office-win.js +209 -0
- package/dist/office/connector/office-win.ps1 +451 -0
- package/dist/office/connector/open-watch.js +46 -0
- package/dist/office/connector/pictures.js +156 -0
- package/dist/office/connector/pptx/diff.js +589 -0
- package/dist/office/connector/pptx/frames.js +105 -0
- package/dist/office/connector/pptx/layer.js +148 -0
- package/dist/office/connector/pptx/links.js +59 -0
- package/dist/office/connector/pptx/reader.js +744 -0
- package/dist/office/connector/pptx/spans.js +70 -0
- package/dist/office/connector/pptx/tags.js +86 -0
- package/dist/office/connector/pptx/xml.js +96 -0
- package/dist/office/connector/pptx/zip.js +223 -0
- package/dist/office/connector/pptx-boxes.js +238 -0
- package/dist/office/connector/print-copy-cap.js +19 -0
- package/dist/office/connector/print-copy.js +13 -0
- package/dist/office/connector/program.js +291 -0
- package/dist/office/connector/reach.js +27 -0
- package/dist/office/connector/refusal.js +16 -0
- package/dist/office/connector/screen-macos.js +193 -0
- package/dist/office/connector/screen-windows.js +34 -0
- package/dist/office/connector/shared/chart-diff.js +376 -0
- package/dist/office/connector/shared/docprops-noise.js +13 -0
- package/dist/office/connector/shared/lock.js +107 -0
- package/dist/office/connector/shared/ooxml-names.js +347 -0
- package/dist/office/connector/shared/owner.js +57 -0
- package/dist/office/connector/shared/package-media.js +703 -0
- package/dist/office/connector/shared/preflight.js +226 -0
- package/dist/office/connector/shared/structure-check.js +623 -0
- package/dist/office/connector/word-boxes.js +364 -0
- package/dist/office/connector/word-print-copy.js +234 -0
- package/dist/office/connector/xlsx/diff.js +1038 -0
- package/dist/office/connector/xlsx/formula.js +410 -0
- package/dist/office/connector/xlsx/layer.js +621 -0
- package/dist/office/connector/xlsx/memo.js +39 -0
- package/dist/office/connector/xlsx/numbers.js +31 -0
- package/dist/office/connector/xlsx/numfmt.js +913 -0
- package/dist/office/connector/xlsx/parts.js +66 -0
- package/dist/office/connector/xlsx/reader.js +394 -0
- package/dist/office/connector/xlsx/types.js +20 -0
- package/dist/office/connector/xlsx/written.js +446 -0
- package/dist/open-pick.js +99 -0
- package/dist/patch-secrets.js +194 -0
- package/dist/paths.js +65 -0
- package/dist/platform/darwin.js +179 -0
- package/dist/platform/index.js +61 -0
- package/dist/platform/spawn.js +115 -0
- package/dist/platform/stub.js +21 -0
- package/dist/platform/task-folder.js +41 -0
- package/dist/platform/types.js +20 -0
- package/dist/platform/win32-docrender.js +7 -0
- package/dist/platform/win32.js +265 -0
- package/dist/preferences.js +49 -0
- package/dist/reason.js +103 -0
- package/dist/region-delivery.js +148 -0
- package/dist/registry.js +68 -0
- package/dist/reveal.js +45 -0
- package/dist/review-process.js +154 -0
- package/dist/review-refresh-process.js +17 -0
- package/dist/review-refresh.js +120 -0
- package/dist/review-server.js +2079 -0
- package/dist/review-view-server.js +106 -0
- package/dist/review.js +8 -0
- package/dist/seal.js +315 -0
- package/dist/secret-files.js +34 -0
- package/dist/secret-hashes.js +27 -0
- package/dist/secret-rules.generated.js +3519 -0
- package/dist/secret-scan.js +127 -0
- package/dist/session-context.js +18 -0
- package/dist/signoff.js +419 -0
- package/dist/skill.js +110 -0
- package/dist/states.js +192 -0
- package/dist/tasks.js +1001 -0
- package/dist/timeline/attribution.js +207 -0
- package/dist/timeline/broken.js +55 -0
- package/dist/timeline/describe.js +413 -0
- package/dist/timeline/generic.js +195 -0
- package/dist/timeline/load.js +464 -0
- package/dist/timeline/loading.js +49 -0
- package/dist/timeline/notes.js +208 -0
- package/dist/timeline/page.js +178 -0
- package/dist/timeline/picture.js +303 -0
- package/dist/timeline/rail/assets/cocheck-icon.svg +1 -0
- package/dist/timeline/rail/assets/files-view.js +198 -0
- package/dist/timeline/rail/assets/loaders/icon-intro.json +1 -0
- package/dist/timeline/rail/assets/loaders/loader-orbit.json +1 -0
- package/dist/timeline/rail/assets/loaders/loader-spin.json +1 -0
- package/dist/timeline/rail/assets/review.css +992 -0
- package/dist/timeline/rail/assets/review.js +3365 -0
- package/dist/timeline/rail/assets/view-table.js +683 -0
- package/dist/timeline/rail/failure-line.js +26 -0
- package/dist/timeline/rail/files-model.js +45 -0
- package/dist/timeline/rail/live.js +49 -0
- package/dist/timeline/rail/made-pictures.js +48 -0
- package/dist/timeline/rail/mcp-card.js +307 -0
- package/dist/timeline/rail/model.js +1317 -0
- package/dist/timeline/rail/page.js +167 -0
- package/dist/timeline/rail/passes.js +106 -0
- package/dist/timeline/rail/regions.js +26 -0
- package/dist/timeline/rail/send-back.js +154 -0
- package/dist/timeline/rail/stop-status.js +164 -0
- package/dist/timeline/read-signal.js +743 -0
- package/dist/timeline/render/claimed.js +13 -0
- package/dist/timeline/render/fallback.js +36 -0
- package/dist/timeline/render/pdf-helper.js +71 -0
- package/dist/timeline/render/pdf.js +410 -0
- package/dist/timeline/render/pixel-pages.js +168 -0
- package/dist/timeline/render/png-crop.js +281 -0
- package/dist/timeline/render/registry.js +7 -0
- package/dist/timeline/render/text.js +366 -0
- package/dist/timeline/render/types.js +1 -0
- package/dist/timeline/render/view-v1.js +148 -0
- package/dist/timeline/render/whole.js +6 -0
- package/dist/timeline/rollout-failures.js +40 -0
- package/dist/timeline/runs.js +836 -0
- package/dist/timeline/stored-image.js +34 -0
- package/dist/timeline/subject-display.js +44 -0
- package/dist/timeline/timeline.js +1114 -0
- package/dist/timeline/write-signal.js +403 -0
- package/dist/tool-label.js +201 -0
- package/dist/tracking.js +87 -0
- package/dist/vendor/pdfjs/LICENSE +177 -0
- package/dist/vendor/pdfjs/pdf.min.mjs +27 -0
- package/dist/vendor/pdfjs/pdf.worker.min.mjs +27 -0
- package/package.json +66 -4
- package/public-kit/GUIDE.md +189 -0
- package/public-kit/README.md +10 -0
- package/public-kit/conformance/README.md +13 -0
- package/public-kit/conformance/cases/C1.json +12 -0
- package/public-kit/conformance/cases/C10.json +15 -0
- package/public-kit/conformance/cases/C11.json +16 -0
- package/public-kit/conformance/cases/C12.json +18 -0
- package/public-kit/conformance/cases/C13.json +23 -0
- package/public-kit/conformance/cases/C14.json +16 -0
- package/public-kit/conformance/cases/C16.json +15 -0
- package/public-kit/conformance/cases/C17.json +25 -0
- package/public-kit/conformance/cases/C2.json +13 -0
- package/public-kit/conformance/cases/C3.json +44 -0
- package/public-kit/conformance/cases/C4.json +13 -0
- package/public-kit/conformance/cases/C5.json +16 -0
- package/public-kit/conformance/cases/C6.json +58 -0
- package/public-kit/conformance/generate-large.mjs +15 -0
- package/public-kit/examples/toy-export/cocheck-connector.json +10 -0
- package/public-kit/examples/toy-export/connector.mjs +28 -0
- package/public-kit/examples/toy-helpers/cocheck-connector.json +10 -0
- package/public-kit/examples/toy-helpers/connector.mjs +69 -0
- package/public-kit/examples/toy-level-1/cocheck-connector.json +10 -0
- package/public-kit/examples/toy-level-1/connector.mjs +61 -0
- package/public-kit/examples/toy-level-3/cocheck-connector.json +10 -0
- package/public-kit/examples/toy-level-3/connector.mjs +82 -0
- package/public-kit/examples/toy-tracker/cocheck-connector.json +14 -0
- package/public-kit/examples/toy-tracker/connector.mjs +46 -0
- package/public-kit/examples/toy-tracker/samples/history.json +10 -0
- package/public-kit/examples/toy-tracker/samples/samples.json +7 -0
- package/public-kit/examples/toy-vendor/cocheck-connector.json +15 -0
- package/public-kit/examples/toy-vendor/connector.mjs +62 -0
- package/public-kit/helpers/pdf-text-layout.d.mts +35 -0
- package/public-kit/helpers/pdf-text-layout.mjs +602 -0
- package/public-kit/helpers/pdf-text.d.mts +56 -0
- package/public-kit/helpers/pdf-text.mjs +375 -0
- package/public-kit/helpers/pdf.d.mts +61 -0
- package/public-kit/helpers/pdf.mjs +251 -0
- package/public-kit/helpers/png.d.mts +15 -0
- package/public-kit/helpers/png.mjs +88 -0
- package/public-kit/helpers/spec.d.mts +4 -0
- package/public-kit/helpers/spec.mjs +2 -0
- package/public-kit/scaffold/README.md +23 -0
- package/public-kit/scaffold/template/README.md +13 -0
- package/public-kit/scaffold/template/cocheck-connector.json +10 -0
- package/public-kit/scaffold/template/connector.mjs +50 -0
- package/public-kit/spec/README.md +408 -0
- package/public-kit/spec/v1.md +598 -0
- package/public-kit/toy-product/README.md +7 -0
- package/public-kit/toy-product/notes-store.mjs +30 -0
- package/public-kit/toy-product/states/create.after.json +16 -0
- package/public-kit/toy-product/states/create.before.json +12 -0
- package/public-kit/toy-product/states/delete.after.json +8 -0
- package/public-kit/toy-product/states/delete.before.json +12 -0
- package/public-kit/toy-product/states/edit.after.json +12 -0
- package/public-kit/toy-product/states/edit.before.json +12 -0
- package/public-kit/toy-product/states/malformed.after.json +1 -0
- package/public-kit/toy-product/states/malformed.before.json +12 -0
- package/public-kit/toy-product/states/no-change.after.json +12 -0
- package/public-kit/toy-product/states/no-change.before.json +12 -0
- package/scripts/hook-launch.mjs +58 -0
- package/scripts/hook-launch.sh +52 -0
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
# CoCheck: records which Claude Code Bash call wrote a file, from inside a Python child.
|
|
2
|
+
#
|
|
3
|
+
# Run by the guard loader CoCheck writes under its home (PYTHONPATH names the guard, never this file, which an upgrade can remove);
|
|
4
|
+
# imported directly it also works. It does nothing unless COCHECK_WRITE_LOG names a directory and the session (COCHECK_TAG_SESSION)
|
|
5
|
+
# has had a call tagged. On the process's first write or program start it looks for the call's tag ("# cocheck-call:<call>:<agent>")
|
|
6
|
+
# in its ancestors' command lines, nearest first; with no tag it stops for good. It records writes only under the registered
|
|
7
|
+
# folders (roots.json), and records "spawn" when the process starts another program (os.system, subprocess, exec, spawn), since
|
|
8
|
+
# that program's writes are not seen. In a tagged session it also records "start" (with sys.executable) once it finds the tag, the
|
|
9
|
+
# proof that this process carried the hook. It never prints, never raises into the program, and chains to the user's own sitecustomize.
|
|
10
|
+
import os as _os
|
|
11
|
+
import sys as _sys
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _cocheck_install():
|
|
15
|
+
log_dir = _os.environ.get("COCHECK_WRITE_LOG")
|
|
16
|
+
session = _os.environ.get("COCHECK_TAG_SESSION", "")
|
|
17
|
+
if not log_dir or not _os.path.isabs(log_dir) or not hasattr(_sys, "addaudithook"):
|
|
18
|
+
return
|
|
19
|
+
if not session or "/" in session or session.startswith("."):
|
|
20
|
+
return
|
|
21
|
+
import re
|
|
22
|
+
import time
|
|
23
|
+
import _thread
|
|
24
|
+
import json
|
|
25
|
+
|
|
26
|
+
tag_re = re.compile(r"# cocheck-call:([A-Za-z0-9_-]{1,128}):([A-Za-z0-9_-]{1,128})")
|
|
27
|
+
write_flags = _os.O_WRONLY | _os.O_RDWR | _os.O_APPEND | _os.O_CREAT | _os.O_TRUNC
|
|
28
|
+
busy = set()
|
|
29
|
+
seen = set()
|
|
30
|
+
state = {"tag": None, "looked": False, "roots": None}
|
|
31
|
+
log_prefix = _os.path.join(log_dir, "")
|
|
32
|
+
hooked = re.compile(r"^(python(\d+(\.\d+)*)?|node)$")
|
|
33
|
+
|
|
34
|
+
def cmdline(pid):
|
|
35
|
+
# (ppid, command line) of a process, or None.
|
|
36
|
+
try:
|
|
37
|
+
with open("/proc/%d/cmdline" % pid, "rb") as f:
|
|
38
|
+
cmd = f.read().replace(b"\0", b" ").decode("utf-8", "replace")
|
|
39
|
+
with open("/proc/%d/stat" % pid, "rb") as f:
|
|
40
|
+
ppid = int(f.read().rsplit(b")", 1)[1].split()[1])
|
|
41
|
+
return ppid, cmd
|
|
42
|
+
except Exception:
|
|
43
|
+
pass
|
|
44
|
+
try:
|
|
45
|
+
import subprocess
|
|
46
|
+
out = subprocess.run(["/bin/ps", "-ww", "-o", "ppid=,command=", "-p", str(pid)],
|
|
47
|
+
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
|
48
|
+
timeout=2).stdout.decode("utf-8", "replace").strip()
|
|
49
|
+
if not out:
|
|
50
|
+
return None
|
|
51
|
+
ppid, _, cmd = out.partition(" ")
|
|
52
|
+
return int(ppid), cmd
|
|
53
|
+
except Exception:
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
shells = ("sh", "bash", "zsh", "dash", "ksh")
|
|
57
|
+
|
|
58
|
+
def is_c_shell(cmd):
|
|
59
|
+
words = cmd.split()
|
|
60
|
+
if not words or _os.path.basename(words[0]).lstrip("-") not in shells:
|
|
61
|
+
return False
|
|
62
|
+
return any(re.match(r"^-[A-Za-z]*c[A-Za-z]*$", w) for w in words[1:4])
|
|
63
|
+
|
|
64
|
+
def env_tag():
|
|
65
|
+
# The call's own shell put "<call>:<agent>" in the environment before the command ran; a child that outlives that shell
|
|
66
|
+
# (a forked pipeline stage whose shell aborted) inherits it, when no ancestor is left to read the tag from.
|
|
67
|
+
m = re.match(r"^([A-Za-z0-9_-]{1,128}):([A-Za-z0-9_-]{1,128})$", _os.environ.get("COCHECK_WRITE_CALL", ""))
|
|
68
|
+
return m.groups() if m else None
|
|
69
|
+
|
|
70
|
+
def find_tag():
|
|
71
|
+
pid = _os.getppid()
|
|
72
|
+
for _ in range(12):
|
|
73
|
+
if pid <= 1:
|
|
74
|
+
return env_tag() # the call's shell is gone: this process was left running by it
|
|
75
|
+
got = cmdline(pid)
|
|
76
|
+
if got is None:
|
|
77
|
+
return env_tag()
|
|
78
|
+
ppid, cmd = got
|
|
79
|
+
found = tag_re.findall(cmd)
|
|
80
|
+
if found:
|
|
81
|
+
return found[-1]
|
|
82
|
+
if is_c_shell(cmd):
|
|
83
|
+
return None # the nearest `<shell> -c` is the call's own shell: never look past it (a nested session's outer call)
|
|
84
|
+
pid = ppid
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
def look():
|
|
88
|
+
if not state["looked"]:
|
|
89
|
+
state["looked"] = True
|
|
90
|
+
if _os.path.exists(_os.path.join(log_dir, "active", session)):
|
|
91
|
+
state["tag"] = find_tag()
|
|
92
|
+
try:
|
|
93
|
+
with open(_os.path.join(log_dir, "roots.json"), "rb") as f:
|
|
94
|
+
state["roots"] = [r for r in json.loads(f.read().decode("utf-8")) if isinstance(r, str) and r.startswith("/")]
|
|
95
|
+
except Exception:
|
|
96
|
+
state["roots"] = []
|
|
97
|
+
return state["tag"]
|
|
98
|
+
|
|
99
|
+
def under_roots(path):
|
|
100
|
+
roots = state["roots"] or []
|
|
101
|
+
for cand in (path, None):
|
|
102
|
+
if cand is None:
|
|
103
|
+
try:
|
|
104
|
+
cand = _os.path.join(_os.path.realpath(_os.path.dirname(path)), _os.path.basename(path))
|
|
105
|
+
except Exception:
|
|
106
|
+
return False
|
|
107
|
+
for r in roots:
|
|
108
|
+
if cand == r or cand.startswith(r.rstrip("/") + "/"):
|
|
109
|
+
return True
|
|
110
|
+
return False
|
|
111
|
+
|
|
112
|
+
def record(op, path):
|
|
113
|
+
if op == "spawn" or op == "start":
|
|
114
|
+
if not isinstance(path, str):
|
|
115
|
+
path = _os.fsdecode(path) if isinstance(path, bytes) else "?"
|
|
116
|
+
key = (op, path)
|
|
117
|
+
else:
|
|
118
|
+
if isinstance(path, bytes):
|
|
119
|
+
path = _os.fsdecode(path)
|
|
120
|
+
if not isinstance(path, str) or path == "":
|
|
121
|
+
return
|
|
122
|
+
path = _os.path.abspath(path)
|
|
123
|
+
if path.startswith(log_prefix) or path.startswith("/dev/") or "__pycache__" in path:
|
|
124
|
+
return
|
|
125
|
+
key = (op, path)
|
|
126
|
+
if key in seen:
|
|
127
|
+
return
|
|
128
|
+
tag = look()
|
|
129
|
+
if tag is None:
|
|
130
|
+
return
|
|
131
|
+
if op != "spawn" and op != "start" and not under_roots(path):
|
|
132
|
+
return
|
|
133
|
+
seen.add(key)
|
|
134
|
+
rec = {"v": 1, "call": tag[0], "agent": tag[1], "pid": _os.getpid(), "ts": int(time.time() * 1000),
|
|
135
|
+
"op": op, "path": path, "via": "python"}
|
|
136
|
+
if op == "start":
|
|
137
|
+
rec["ppid"] = _os.getppid()
|
|
138
|
+
line = json.dumps(rec) + "\n"
|
|
139
|
+
name = _os.path.join(log_dir, "writes-%s.jsonl" % time.strftime("%Y-%m-%d", time.gmtime()))
|
|
140
|
+
try:
|
|
141
|
+
fd = _os.open(name, _os.O_WRONLY | _os.O_APPEND | _os.O_CREAT, 0o600)
|
|
142
|
+
except FileNotFoundError:
|
|
143
|
+
_os.makedirs(log_dir, 0o700, exist_ok=True)
|
|
144
|
+
fd = _os.open(name, _os.O_WRONLY | _os.O_APPEND | _os.O_CREAT, 0o600)
|
|
145
|
+
try:
|
|
146
|
+
_os.write(fd, line.encode("utf-8", "surrogateescape"))
|
|
147
|
+
finally:
|
|
148
|
+
_os.close(fd)
|
|
149
|
+
|
|
150
|
+
def spawned(exe):
|
|
151
|
+
# A Python or Node child carries its own hook; anything else (or a shell) writes where no hook sees.
|
|
152
|
+
name = _os.path.basename(_os.fsdecode(exe) if isinstance(exe, bytes) else str(exe))
|
|
153
|
+
if not hooked.match(name):
|
|
154
|
+
record("spawn", name)
|
|
155
|
+
|
|
156
|
+
def hook(event, args):
|
|
157
|
+
if state["looked"] and state["tag"] is None:
|
|
158
|
+
return
|
|
159
|
+
if event not in ("open", "os.rename", "os.remove", "os.truncate", "shutil.copyfile",
|
|
160
|
+
"subprocess.Popen", "os.system", "os.exec", "os.posix_spawn", "os.spawn", "os.startfile"):
|
|
161
|
+
return
|
|
162
|
+
me = _thread.get_ident()
|
|
163
|
+
if me in busy:
|
|
164
|
+
return
|
|
165
|
+
busy.add(me)
|
|
166
|
+
try:
|
|
167
|
+
if event == "open":
|
|
168
|
+
path, mode, flags = args[0], args[1], args[2]
|
|
169
|
+
if isinstance(path, int):
|
|
170
|
+
return
|
|
171
|
+
writes = (any(c in mode for c in "wax+") if isinstance(mode, str)
|
|
172
|
+
else isinstance(flags, int) and (flags & write_flags) != 0)
|
|
173
|
+
if writes:
|
|
174
|
+
record("write", path)
|
|
175
|
+
elif event == "os.rename":
|
|
176
|
+
record("remove", args[0])
|
|
177
|
+
record("write", args[1])
|
|
178
|
+
elif event == "os.remove":
|
|
179
|
+
record("remove", args[0])
|
|
180
|
+
elif event == "os.truncate":
|
|
181
|
+
if not isinstance(args[0], int):
|
|
182
|
+
record("write", args[0])
|
|
183
|
+
elif event == "shutil.copyfile":
|
|
184
|
+
record("write", args[1])
|
|
185
|
+
elif event == "subprocess.Popen":
|
|
186
|
+
exe, argv = args[0], args[1]
|
|
187
|
+
if exe is None:
|
|
188
|
+
if isinstance(argv, (str, bytes)):
|
|
189
|
+
exe = "sh"
|
|
190
|
+
elif argv:
|
|
191
|
+
exe = list(argv)[0]
|
|
192
|
+
spawned(exe if exe is not None else "?")
|
|
193
|
+
elif event == "os.system" or event == "os.startfile":
|
|
194
|
+
record("spawn", "sh")
|
|
195
|
+
elif event == "os.spawn":
|
|
196
|
+
spawned(args[1])
|
|
197
|
+
else:
|
|
198
|
+
spawned(args[0])
|
|
199
|
+
except Exception:
|
|
200
|
+
pass
|
|
201
|
+
finally:
|
|
202
|
+
busy.discard(me)
|
|
203
|
+
|
|
204
|
+
_sys.addaudithook(hook)
|
|
205
|
+
|
|
206
|
+
# Once the tag is found, a "start" record names the call and this interpreter, so "logged no write" is only ever trusted for a
|
|
207
|
+
# call whose children provably carried the hook (one that never loaded, or found no tag, leaves no start record).
|
|
208
|
+
if _os.path.exists(_os.path.join(log_dir, "active", session)):
|
|
209
|
+
me = _thread.get_ident()
|
|
210
|
+
busy.add(me)
|
|
211
|
+
try:
|
|
212
|
+
record("start", _sys.executable or "?")
|
|
213
|
+
except Exception:
|
|
214
|
+
pass
|
|
215
|
+
finally:
|
|
216
|
+
busy.discard(me)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
try:
|
|
220
|
+
_cocheck_install()
|
|
221
|
+
except Exception:
|
|
222
|
+
pass
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _cocheck_chain():
|
|
226
|
+
if globals().get("_COCHECK_GUARDED"):
|
|
227
|
+
return # the guard chains
|
|
228
|
+
# Runs the next sitecustomize on sys.path, the one this file shadows.
|
|
229
|
+
import importlib.machinery
|
|
230
|
+
import importlib.util
|
|
231
|
+
here = _os.path.dirname(_os.path.abspath(__file__))
|
|
232
|
+
rest = [p for p in _sys.path if _os.path.abspath(p or ".") != here]
|
|
233
|
+
spec = importlib.machinery.PathFinder.find_spec("sitecustomize", rest)
|
|
234
|
+
if spec is None or spec.loader is None or not spec.origin:
|
|
235
|
+
return
|
|
236
|
+
if _os.path.dirname(_os.path.abspath(spec.origin)) == here:
|
|
237
|
+
return
|
|
238
|
+
module = importlib.util.module_from_spec(spec)
|
|
239
|
+
spec.loader.exec_module(module)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
try:
|
|
243
|
+
_cocheck_chain()
|
|
244
|
+
except Exception:
|
|
245
|
+
pass
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// Whether a shell command names a file it may have written. Read when several calls were open over a write and nothing else tells
|
|
2
|
+
// them apart: the one call whose command names the file is credited (still inferred: the basis is `named`, never proof). Pure: no I/O.
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { braceExpand, isReadOnlyCommand } from "./write-scope.js";
|
|
5
|
+
/** A word with its brace expansion spelled out (`yahoo_{a,b}.json` names both files); a sequence or an over-long one is kept as written. */
|
|
6
|
+
const spelled = (w) => {
|
|
7
|
+
try {
|
|
8
|
+
return braceExpand(w);
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return [w];
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
/** The basename `base` (lower case) appears in `text` with no word character, dot or dash just before it. */
|
|
15
|
+
export function textNamesBase(text, base) {
|
|
16
|
+
if (base === "")
|
|
17
|
+
return false;
|
|
18
|
+
const t = text.toLowerCase();
|
|
19
|
+
for (let i = t.indexOf(base); i >= 0; i = t.indexOf(base, i + 1)) {
|
|
20
|
+
if (i === 0 || !/[\w.-]/.test(t[i - 1]))
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Whether the shell word `w` names `file`: its basename appears in the word at a name boundary, and any literal directories written
|
|
27
|
+
* before it match the file's own parent directories (so `lnk/a.json` does not name `raw/a.json`). Directories up to a `.`, `..`, `~`
|
|
28
|
+
* or a `$` variable are unknown and match anything.
|
|
29
|
+
*/
|
|
30
|
+
function wordNamesFile(w, file) {
|
|
31
|
+
const base = path.basename(file).toLowerCase();
|
|
32
|
+
const t = w.toLowerCase();
|
|
33
|
+
const parents = path.dirname(file).toLowerCase().split(/[\\/]+/).filter((x) => x !== "");
|
|
34
|
+
for (let i = t.indexOf(base); i >= 0; i = t.indexOf(base, i + 1)) {
|
|
35
|
+
if (i > 0 && /[\w.-]/.test(t[i - 1]))
|
|
36
|
+
continue;
|
|
37
|
+
const before = t.slice(0, i);
|
|
38
|
+
if (before !== "" && !before.endsWith("/") && !before.endsWith("\\"))
|
|
39
|
+
return true; // `--out=a.json`, `>a.json`: no directory written
|
|
40
|
+
const dir = before.slice(Math.max(...["=", ":", ">", "<", "(", "@"].map((c) => before.lastIndexOf(c))) + 1);
|
|
41
|
+
let segs = dir.split(/[\\/]+/).filter((x) => x !== "");
|
|
42
|
+
const cut = segs.findLastIndex((x) => x === "." || x === ".." || x.startsWith("~") || x.includes("$"));
|
|
43
|
+
segs = segs.slice(cut + 1);
|
|
44
|
+
if (segs.length <= parents.length && segs.every((x, k) => x === parents[parents.length - segs.length + k]))
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
const SEPARATORS = /\n|&&|\|\||;|\|/;
|
|
50
|
+
const WORD = /"([^"]*)"|'([^']*)'|(\S+)/g;
|
|
51
|
+
const words = (seg) => [...seg.matchAll(WORD)].map((m) => m[1] ?? m[2] ?? m[3]);
|
|
52
|
+
const bare = (w) => path.posix.basename(w).toLowerCase().replace(/\.(py|exe|bin)$/, "");
|
|
53
|
+
/** The program a simple command runs, skipping env assignments and a Python interpreter in front of a script. */
|
|
54
|
+
function program(ws) {
|
|
55
|
+
let i = 0;
|
|
56
|
+
while (i < ws.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(ws[i]))
|
|
57
|
+
i++;
|
|
58
|
+
if (i >= ws.length)
|
|
59
|
+
return undefined;
|
|
60
|
+
let name = bare(ws[i]);
|
|
61
|
+
if (/^python[\d.]*$/.test(name)) {
|
|
62
|
+
let j = i + 1;
|
|
63
|
+
while (j < ws.length && ws[j].startsWith("-"))
|
|
64
|
+
j++;
|
|
65
|
+
if (j < ws.length) {
|
|
66
|
+
name = bare(ws[j]);
|
|
67
|
+
i = j;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return { name, args: ws.slice(i + 1) };
|
|
71
|
+
}
|
|
72
|
+
// pdftoppm (poppler) options that take a value; every other `-x` word is a flag.
|
|
73
|
+
const PDFTOPPM_ARG = new Set(["f", "l", "r", "rx", "ry", "scale-to", "scale-to-x", "scale-to-y", "x", "y", "W", "H", "opw", "upw", "jpegopt", "tiffcompression", "freetype", "aa", "aaVector", "thinlinemode", "displayprofile", "defaultgrayprofile", "defaultrgbprofile", "defaultcmykprofile", "sep"]);
|
|
74
|
+
const PDFTOPPM_EXT = { png: "png", jpeg: "jpg", jpegcmyk: "jpg", tiff: "tif", mono: "pbm", gray: "pgm" };
|
|
75
|
+
/**
|
|
76
|
+
* pdftoppm `[options] <pdf> [<prefix>]`: the input it reads, and whether `base` is one of the pages it writes. Poppler names a page
|
|
77
|
+
* `<prefix>-<n>.<ext>` with `n` zero-padded to the digits of the document's last page (unknown here, so any padding), or
|
|
78
|
+
* `<prefix>.<ext>` with `-singlefile`; `-f`/`-l` bound `n` when they are literal numbers.
|
|
79
|
+
*/
|
|
80
|
+
function pdftoppm(args, base) {
|
|
81
|
+
const opts = new Map();
|
|
82
|
+
const pos = [];
|
|
83
|
+
for (let i = 0; i < args.length; i++) {
|
|
84
|
+
const a = args[i];
|
|
85
|
+
if (a.length > 1 && a.startsWith("-")) {
|
|
86
|
+
const o = a.replace(/^--?/, "");
|
|
87
|
+
if (PDFTOPPM_ARG.has(o))
|
|
88
|
+
opts.set(o, args[++i] ?? "");
|
|
89
|
+
else
|
|
90
|
+
opts.set(o, "");
|
|
91
|
+
}
|
|
92
|
+
else
|
|
93
|
+
pos.push(a);
|
|
94
|
+
}
|
|
95
|
+
const [input, prefix] = pos;
|
|
96
|
+
const reads = input === undefined ? [] : [input];
|
|
97
|
+
if (prefix === undefined || prefix === "-")
|
|
98
|
+
return { reads, writes: false };
|
|
99
|
+
const ext = Object.keys(PDFTOPPM_EXT).find((k) => opts.has(k));
|
|
100
|
+
const want = ext === undefined ? "ppm" : PDFTOPPM_EXT[ext];
|
|
101
|
+
const p = path.posix.basename(prefix).toLowerCase();
|
|
102
|
+
if (opts.has("singlefile"))
|
|
103
|
+
return { reads, writes: base === `${p}.${want}` };
|
|
104
|
+
if (!base.startsWith(`${p}-`) || !base.endsWith(`.${want}`))
|
|
105
|
+
return { reads, writes: false };
|
|
106
|
+
const num = base.slice(p.length + 1, base.length - want.length - 1);
|
|
107
|
+
if (!/^\d+$/.test(num))
|
|
108
|
+
return { reads, writes: false };
|
|
109
|
+
const n = Number(num);
|
|
110
|
+
const lit = (k) => (/^\d+$/.test(opts.get(k) ?? "") ? Number(opts.get(k)) : undefined);
|
|
111
|
+
const first = lit("f");
|
|
112
|
+
const last = lit("l");
|
|
113
|
+
return { reads, writes: n >= 1 && (first === undefined || n >= first) && (last === undefined || n <= last) };
|
|
114
|
+
}
|
|
115
|
+
/** soffice/libreoffice `--convert-to <ext>[:filter] [--outdir d] <inputs>`: the inputs it reads, and whether `base` is an input's stem with the new extension. */
|
|
116
|
+
function soffice(args, base) {
|
|
117
|
+
let to;
|
|
118
|
+
const inputs = [];
|
|
119
|
+
for (let i = 0; i < args.length; i++) {
|
|
120
|
+
const a = args[i];
|
|
121
|
+
if (a === "--convert-to" || a === "-convert-to")
|
|
122
|
+
to = (args[++i] ?? "").split(":")[0].toLowerCase();
|
|
123
|
+
else if (a === "--outdir" || a === "-outdir")
|
|
124
|
+
i++;
|
|
125
|
+
else if (!a.startsWith("-"))
|
|
126
|
+
inputs.push(a);
|
|
127
|
+
}
|
|
128
|
+
if (to === undefined || to === "")
|
|
129
|
+
return { reads: [], writes: false };
|
|
130
|
+
const writes = inputs.some((f) => {
|
|
131
|
+
const b = path.posix.basename(f).toLowerCase();
|
|
132
|
+
const dot = b.lastIndexOf(".");
|
|
133
|
+
return `${dot > 0 ? b.slice(0, dot) : b}.${to}` === base;
|
|
134
|
+
});
|
|
135
|
+
return { reads: inputs, writes };
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Whether `command` names `file` as something it may have written: a word of it holds the file's basename (with any literal directories
|
|
139
|
+
* before it matching the file's own), or a converter the command runs writes that name (pdftoppm pages, soffice --convert-to). Reads
|
|
140
|
+
* are not names: a part of the command made only of read-only forms (cat, head, ls, grep...) and a converter's own input are left out.
|
|
141
|
+
* Bound: the command is split on shell separators and whitespace by text, not parsed; a name inside a script the command runs, or built
|
|
142
|
+
* from a variable, is not seen; a basename in any other position still counts (a program that only reads it outside the forms above
|
|
143
|
+
* takes the credit).
|
|
144
|
+
*/
|
|
145
|
+
export function commandNamesFile(command, file) {
|
|
146
|
+
const base = path.basename(file).toLowerCase();
|
|
147
|
+
if (base === "" || command === "")
|
|
148
|
+
return false;
|
|
149
|
+
for (const seg of command.split(SEPARATORS)) {
|
|
150
|
+
if (seg.trim() === "" || isReadOnlyCommand(seg))
|
|
151
|
+
continue;
|
|
152
|
+
const ws = words(seg);
|
|
153
|
+
const prog = program(ws.filter((w) => !/^\d*[<>]/.test(w)));
|
|
154
|
+
const rule = prog?.name === "pdftoppm" ? pdftoppm : prog?.name === "soffice" || prog?.name === "libreoffice" ? soffice : undefined;
|
|
155
|
+
const { reads, writes } = rule === undefined ? { reads: [], writes: false } : rule(prog.args, base);
|
|
156
|
+
if (writes)
|
|
157
|
+
return true;
|
|
158
|
+
const readSet = new Set(reads);
|
|
159
|
+
if (ws.some((w) => !readSet.has(w) && spelled(w).some((x) => wordNamesFile(x, file))))
|
|
160
|
+
return true;
|
|
161
|
+
}
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// Proof by exact reconstruction. A host file-edit call reports what it did to a file; replaying exactly that on the file's recorded state
|
|
2
|
+
// before the call must give the recorded state after it (same hash). Pure: no host name, no I/O. Anything not replayable exactly gives `undefined`.
|
|
3
|
+
export const RECONSTRUCT_MAX_BYTES = 8 * 1024 * 1024;
|
|
4
|
+
/** Replaces as the Edit tools do: `old` must occur exactly once unless `all`; an empty `old` only fills an empty file. */
|
|
5
|
+
function applyEdits(text, edits) {
|
|
6
|
+
for (const e of edits) {
|
|
7
|
+
if (e.old === "") {
|
|
8
|
+
if (text !== "")
|
|
9
|
+
return undefined;
|
|
10
|
+
text = e.new;
|
|
11
|
+
continue;
|
|
12
|
+
}
|
|
13
|
+
const first = text.indexOf(e.old);
|
|
14
|
+
if (first < 0)
|
|
15
|
+
return undefined;
|
|
16
|
+
if (!e.all && text.indexOf(e.old, first + 1) >= 0)
|
|
17
|
+
return undefined;
|
|
18
|
+
text = e.all ? text.split(e.old).join(e.new) : text.slice(0, first) + e.new + text.slice(first + e.old.length);
|
|
19
|
+
}
|
|
20
|
+
return text;
|
|
21
|
+
}
|
|
22
|
+
/** Applies patch sections to `text` (LF text only): each hunk's context and removed lines must be found, in order, from where the last one ended. */
|
|
23
|
+
function applySections(text, sections) {
|
|
24
|
+
for (const sec of sections) {
|
|
25
|
+
if (sec.add) {
|
|
26
|
+
if (sec.lines.some((l) => !l.startsWith("+")))
|
|
27
|
+
return undefined;
|
|
28
|
+
text = sec.lines.map((l) => l.slice(1) + "\n").join("");
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
const lines = text === "" ? [] : text.split("\n");
|
|
32
|
+
if (lines.length > 0 && lines[lines.length - 1] === "")
|
|
33
|
+
lines.pop();
|
|
34
|
+
const hunks = [];
|
|
35
|
+
for (const l of sec.lines) {
|
|
36
|
+
if (l.startsWith("@@"))
|
|
37
|
+
hunks.push([]);
|
|
38
|
+
else {
|
|
39
|
+
if (hunks.length === 0)
|
|
40
|
+
hunks.push([]);
|
|
41
|
+
hunks[hunks.length - 1].push(l);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
let cursor = 0;
|
|
45
|
+
for (const h of hunks) {
|
|
46
|
+
const oldSeq = [];
|
|
47
|
+
const newSeq = [];
|
|
48
|
+
for (const l of h) {
|
|
49
|
+
const c = l[0];
|
|
50
|
+
if (l === "") {
|
|
51
|
+
oldSeq.push("");
|
|
52
|
+
newSeq.push("");
|
|
53
|
+
}
|
|
54
|
+
else if (c === " ") {
|
|
55
|
+
oldSeq.push(l.slice(1));
|
|
56
|
+
newSeq.push(l.slice(1));
|
|
57
|
+
}
|
|
58
|
+
else if (c === "-")
|
|
59
|
+
oldSeq.push(l.slice(1));
|
|
60
|
+
else if (c === "+")
|
|
61
|
+
newSeq.push(l.slice(1));
|
|
62
|
+
else
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
let at = lines.length;
|
|
66
|
+
if (oldSeq.length > 0) {
|
|
67
|
+
at = -1;
|
|
68
|
+
for (let i = cursor; i + oldSeq.length <= lines.length && at < 0; i++)
|
|
69
|
+
if (oldSeq.every((x, k) => lines[i + k] === x))
|
|
70
|
+
at = i;
|
|
71
|
+
if (at < 0)
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
lines.splice(at, oldSeq.length, ...newSeq);
|
|
75
|
+
cursor = at + newSeq.length;
|
|
76
|
+
}
|
|
77
|
+
text = lines.length === 0 ? "" : lines.join("\n") + "\n";
|
|
78
|
+
}
|
|
79
|
+
return text;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Every hash the file may have after the call, exact replay only. A patch writes LF lines; a Windows host may save the file with CRLF, so a
|
|
83
|
+
* patch replay gives the LF result and the same result with every line ending CRLF. A before-state that mixes endings or holds a lone CR gives
|
|
84
|
+
* nothing (the CRLF form needs every ending to be CRLF). Both forms are exact: the recorded hash must equal one of them whole.
|
|
85
|
+
*/
|
|
86
|
+
export function reconstructAll(rep, before, sha256) {
|
|
87
|
+
if (rep.sha !== undefined)
|
|
88
|
+
return [rep.sha];
|
|
89
|
+
if (rep.sections === undefined || before === undefined || before.length > RECONSTRUCT_MAX_BYTES || before.includes(0)) {
|
|
90
|
+
const one = reconstruct(rep, before, sha256);
|
|
91
|
+
return one === undefined ? [] : [one];
|
|
92
|
+
}
|
|
93
|
+
let src;
|
|
94
|
+
try {
|
|
95
|
+
src = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(before);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return [];
|
|
99
|
+
}
|
|
100
|
+
const crlf = src.includes("\r");
|
|
101
|
+
if (crlf && /\r(?!\n)|(?<!\r)\n/.test(src))
|
|
102
|
+
return [];
|
|
103
|
+
const out = rep.sections.some((x) => x.lines.some((l) => l.includes("\r"))) ? undefined : applySections(crlf ? src.replace(/\r\n/g, "\n") : src, rep.sections);
|
|
104
|
+
if (out === undefined)
|
|
105
|
+
return [];
|
|
106
|
+
return crlf ? [sha256(out.replace(/\n/g, "\r\n"))] : [sha256(out), sha256(out.replace(/\n/g, "\r\n"))];
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The hash the file must have after the call, if the call's report is replayed exactly on `before` (the recorded bytes just before the call: empty when
|
|
110
|
+
* the file did not exist, undefined when they are not available). `sha256` hashes text or bytes. undefined: cannot be reconstructed exactly
|
|
111
|
+
* (no before-state, binary, over the size cap, a patch that does not apply, an old string not found or ambiguous), so the change stays inferred.
|
|
112
|
+
*/
|
|
113
|
+
export function reconstruct(rep, before, sha256) {
|
|
114
|
+
if (rep.sha !== undefined)
|
|
115
|
+
return rep.sha;
|
|
116
|
+
if (before === undefined || before.length > RECONSTRUCT_MAX_BYTES || before.includes(0))
|
|
117
|
+
return undefined;
|
|
118
|
+
const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
119
|
+
let src;
|
|
120
|
+
try {
|
|
121
|
+
src = text.decode(before);
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
const out = rep.edits !== undefined ? applyEdits(src, rep.edits) : rep.sections !== undefined ? (src.includes("\r") ? undefined : applySections(src, rep.sections)) : undefined;
|
|
127
|
+
return out === undefined ? undefined : sha256(out);
|
|
128
|
+
}
|