@dsmm/dsmm 0.2.0 → 0.3.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 (285) hide show
  1. package/README.md +37 -67
  2. package/agent-presets/dsmm-builder/agent.cordis.yml +10 -2015
  3. package/agent-presets/dsmm-clarifier/agent.cordis.yml +24 -343
  4. package/agent-presets/dsmm-code-search/agent.cordis.yml +19 -6
  5. package/agent-presets/dsmm-coding/agent.cordis.yml +19 -438
  6. package/agent-presets/dsmm-complex/agent.cordis.yml +23 -1009
  7. package/agent-presets/dsmm-creative/agent.cordis.yml +25 -442
  8. package/agent-presets/dsmm-cross-cutting/agent.cordis.yml +29 -1013
  9. package/agent-presets/dsmm-deep/agent.cordis.yml +24 -1008
  10. package/agent-presets/dsmm-doc-search/agent.cordis.yml +19 -6
  11. package/agent-presets/dsmm-documenting/agent.cordis.yml +26 -439
  12. package/agent-presets/dsmm-frontend/agent.cordis.yml +21 -440
  13. package/agent-presets/dsmm-hard-reasoning/agent.cordis.yml +22 -441
  14. package/agent-presets/dsmm-media-reader/agent.cordis.yml +19 -6
  15. package/agent-presets/dsmm-normal-task/agent.cordis.yml +19 -438
  16. package/agent-presets/dsmm-oracle/agent.cordis.yml +25 -340
  17. package/agent-presets/dsmm-oracle-2nd/agent.cordis.yml +25 -340
  18. package/agent-presets/dsmm-orchestrator/agent.cordis.yml +29 -2025
  19. package/agent-presets/dsmm-plan-critic/agent.cordis.yml +24 -341
  20. package/agent-presets/dsmm-planner/agent.cordis.yml +14 -344
  21. package/agent-presets/dsmm-quick/agent.cordis.yml +19 -6
  22. package/agent-presets/dsmm-research/agent.cordis.yml +23 -8
  23. package/agent-presets/dsmm-reviewer/agent.cordis.yml +25 -340
  24. package/cordis.patch.yml +14 -0
  25. package/docs/agent-presets.md +36 -52
  26. package/docs/compatibility.md +47 -110
  27. package/docs/deferred-native-approval-risk.md +19 -0
  28. package/docs/design.md +2 -2
  29. package/docs/lsp.md +11 -21
  30. package/docs/migration-from-ocmm.md +2 -2
  31. package/docs/model-routing.md +84 -59
  32. package/docs/native-permissions.md +35 -0
  33. package/docs/profiles.md +40 -87
  34. package/docs/releasing.md +123 -2
  35. package/docs/roadmap.md +71 -17
  36. package/docs/settings-status.md +34 -169
  37. package/docs/skill-sync.md +52 -15
  38. package/lib/agent-registry.d.ts +36 -0
  39. package/lib/agent-registry.js +75 -0
  40. package/lib/child-admission-contract.d.ts +37 -0
  41. package/lib/child-admission-contract.js +2 -0
  42. package/lib/child-admission.d.ts +40 -0
  43. package/lib/child-admission.js +151 -0
  44. package/lib/child-capture.d.ts +85 -0
  45. package/lib/child-capture.js +205 -0
  46. package/lib/child-evidence.d.ts +17 -0
  47. package/lib/child-evidence.js +43 -0
  48. package/lib/client/ChildrenPanel.d.ts +43 -0
  49. package/lib/client/ChildrenPanel.js +82 -0
  50. package/lib/client/DeploymentPage.js +15 -8
  51. package/lib/client/EditableChoice.d.ts +17 -0
  52. package/lib/client/EditableChoice.js +49 -0
  53. package/lib/client/PermissionsPanel.d.ts +14 -0
  54. package/lib/client/PermissionsPanel.js +46 -0
  55. package/lib/client/ProfilesSection.js +30 -15
  56. package/lib/client/RoleAvailability.d.ts +7 -0
  57. package/lib/client/RoleAvailability.js +19 -0
  58. package/lib/client/SessionProfiles.js +27 -9
  59. package/lib/client/StructuredEditor.js +15 -7
  60. package/lib/client/children-controller.d.ts +98 -0
  61. package/lib/client/children-controller.js +296 -0
  62. package/lib/client/children-locales.d.ts +367 -0
  63. package/lib/client/children-locales.js +69 -0
  64. package/lib/client/controller.d.ts +6 -1
  65. package/lib/client/controller.js +14 -8
  66. package/lib/client/deployment-controller.js +1 -1
  67. package/lib/client/deployment-data.d.ts +2 -1
  68. package/lib/client/deployment-data.js +34 -5
  69. package/lib/client/deployment-locales.d.ts +4 -0
  70. package/lib/client/deployment-locales.js +11 -2
  71. package/lib/client/diagnostics.d.ts +14 -0
  72. package/lib/client/diagnostics.js +53 -0
  73. package/lib/client/index.d.ts +4 -0
  74. package/lib/client/index.js +96 -2
  75. package/lib/client/locales.d.ts +54 -0
  76. package/lib/client/locales.js +34 -16
  77. package/lib/client/permission-client.d.ts +16 -0
  78. package/lib/client/permission-client.js +38 -0
  79. package/lib/client/permission-controller.d.ts +62 -0
  80. package/lib/client/permission-controller.js +149 -0
  81. package/lib/client/permission-locales.d.ts +114 -0
  82. package/lib/client/permission-locales.js +75 -0
  83. package/lib/client/session-labels.js +4 -4
  84. package/lib/client/structured.js +19 -5
  85. package/lib/client/styles.d.ts +1 -1
  86. package/lib/client/styles.js +20 -0
  87. package/lib/client.js +5780 -1679
  88. package/lib/core-permission-authority.d.ts +18 -0
  89. package/lib/core-permission-authority.js +255 -0
  90. package/lib/core-permissions.d.ts +8 -0
  91. package/lib/core-permissions.js +33 -0
  92. package/lib/delivery-authority.d.ts +83 -0
  93. package/lib/delivery-authority.js +397 -0
  94. package/lib/deployment-config.d.ts +23 -0
  95. package/lib/deployment-config.js +61 -40
  96. package/lib/deployment-permission-rules.d.ts +55 -0
  97. package/lib/deployment-permission-rules.js +306 -0
  98. package/lib/dsh-types.d.ts +10 -4
  99. package/lib/guards.d.ts +1 -1
  100. package/lib/guards.js +29 -8
  101. package/lib/host-llm-startup.d.ts +41 -0
  102. package/lib/host-llm-startup.js +65 -0
  103. package/lib/host-llm.d.ts +92 -0
  104. package/lib/host-llm.js +325 -0
  105. package/lib/index.d.ts +15 -4
  106. package/lib/index.js +288 -48
  107. package/lib/live-pi-ai-owner.d.ts +18 -0
  108. package/lib/live-pi-ai-owner.js +144 -0
  109. package/lib/llm-runtime.d.ts +11 -0
  110. package/lib/llm-runtime.js +21 -0
  111. package/lib/managed-settings.d.ts +5 -0
  112. package/lib/managed-settings.js +14 -0
  113. package/lib/model-parameter-policy.d.ts +11 -0
  114. package/lib/model-parameter-policy.js +27 -0
  115. package/lib/model-routing.js +28 -17
  116. package/lib/modules.d.ts +13 -5
  117. package/lib/modules.js +17 -1
  118. package/lib/native-child-evidence.d.ts +40 -0
  119. package/lib/native-child-evidence.js +104 -0
  120. package/lib/native-pi-ai-wire.d.ts +37 -0
  121. package/lib/native-pi-ai-wire.js +261 -0
  122. package/lib/native-scope.js +1 -1
  123. package/lib/permission-bash.d.ts +6 -0
  124. package/lib/permission-bash.js +7 -0
  125. package/lib/permission-control.d.ts +73 -0
  126. package/lib/permission-control.js +205 -0
  127. package/lib/permission-controller.d.ts +68 -0
  128. package/lib/permission-controller.js +317 -0
  129. package/lib/permission-errors.d.ts +7 -0
  130. package/lib/permission-errors.js +21 -0
  131. package/lib/permission-fs-search.d.ts +5 -0
  132. package/lib/permission-fs-search.js +7 -0
  133. package/lib/permission-fs.d.ts +5 -0
  134. package/lib/permission-fs.js +7 -0
  135. package/lib/permission-native-access.d.ts +11 -0
  136. package/lib/permission-native-access.js +6 -0
  137. package/lib/permission-native-command.d.ts +10 -0
  138. package/lib/permission-native-command.js +93 -0
  139. package/lib/permission-native-rules.d.ts +75 -0
  140. package/lib/permission-native-rules.js +278 -0
  141. package/lib/permission-pwsh.d.ts +6 -0
  142. package/lib/permission-pwsh.js +7 -0
  143. package/lib/permission-remote.d.ts +26 -0
  144. package/lib/permission-remote.js +53 -0
  145. package/lib/permission-rpc.d.ts +29 -0
  146. package/lib/permission-rpc.js +152 -0
  147. package/lib/permission-rules.d.ts +115 -0
  148. package/lib/permission-rules.js +256 -0
  149. package/lib/permission-settings.d.ts +45 -0
  150. package/lib/permission-settings.js +48 -0
  151. package/lib/permission-shell.d.ts +38 -0
  152. package/lib/permission-shell.js +150 -0
  153. package/lib/permission-web.d.ts +5 -0
  154. package/lib/permission-web.js +7 -0
  155. package/lib/preset-registry.js +36 -25
  156. package/lib/profile-diagnostics.d.ts +45 -0
  157. package/lib/profile-diagnostics.js +148 -0
  158. package/lib/profile-locale.d.ts +3 -0
  159. package/lib/profile-locale.js +2 -0
  160. package/lib/profile-remote.d.ts +8 -0
  161. package/lib/profile-remote.js +163 -39
  162. package/lib/profile-rpc.d.ts +4 -3
  163. package/lib/profile-rpc.js +20 -16
  164. package/lib/profile-runtime.d.ts +40 -1
  165. package/lib/profile-runtime.js +368 -93
  166. package/lib/profile-store.d.ts +11 -0
  167. package/lib/profile-store.js +143 -11
  168. package/lib/profile-types.d.ts +70 -1
  169. package/lib/profile-types.js +1 -0
  170. package/lib/profiles.d.ts +16 -2
  171. package/lib/profiles.js +156 -79
  172. package/lib/prompt-content.js +1 -1
  173. package/lib/prompts.d.ts +37 -2
  174. package/lib/prompts.js +111 -9
  175. package/lib/recovery-policy.js +20 -7
  176. package/lib/role-control-remote.d.ts +38 -0
  177. package/lib/role-control-remote.js +211 -0
  178. package/lib/role-control-rpc.d.ts +51 -0
  179. package/lib/role-control-rpc.js +381 -0
  180. package/lib/role-control-types.d.ts +92 -0
  181. package/lib/role-control-types.js +8 -0
  182. package/lib/role-invocation.d.ts +47 -0
  183. package/lib/role-invocation.js +135 -0
  184. package/lib/role-llm-runtime.d.ts +17 -0
  185. package/lib/role-llm-runtime.js +62 -0
  186. package/lib/role-llm.d.ts +31 -0
  187. package/lib/role-llm.js +66 -0
  188. package/lib/role-policy.d.ts +46 -8
  189. package/lib/role-policy.js +421 -61
  190. package/lib/role-providers.d.ts +2 -2
  191. package/lib/role-providers.js +27 -72
  192. package/lib/role-routing.d.ts +11 -2
  193. package/lib/role-routing.js +42 -25
  194. package/lib/role-runs.d.ts +138 -0
  195. package/lib/role-runs.js +335 -0
  196. package/lib/role-subagents.d.ts +58 -3
  197. package/lib/role-subagents.js +179 -56
  198. package/lib/roles.d.ts +5 -6
  199. package/lib/roles.js +10 -39
  200. package/lib/route-json.d.ts +19 -0
  201. package/lib/route-json.js +129 -0
  202. package/lib/routing-policy.d.ts +2 -0
  203. package/lib/routing-policy.js +12 -2
  204. package/lib/runtime-integration.d.ts +81 -0
  205. package/lib/runtime-integration.js +702 -0
  206. package/lib/runtime-recovery.js +18 -8
  207. package/lib/session-persistence.d.ts +2 -1
  208. package/lib/session-persistence.js +1 -1
  209. package/lib/session-scope.js +4 -1
  210. package/lib/settings.d.ts +47 -13
  211. package/lib/settings.js +217 -82
  212. package/lib/skills.js +2 -2
  213. package/lib/status.d.ts +10 -1
  214. package/lib/status.js +11 -8
  215. package/lib/subagent-runtime.d.ts +57 -0
  216. package/lib/subagent-runtime.js +257 -0
  217. package/package.json +149 -89
  218. package/patches/subagent-runtime.yml +15 -0
  219. package/prompts/deepseek-flash.md +1 -1
  220. package/prompts/deepseek-v4-pro.md +2 -2
  221. package/prompts/deepwork.md +27 -18
  222. package/prompts/source/agents/clarifier.md +5 -3
  223. package/prompts/source/agents/orchestrator.md +18 -9
  224. package/prompts/source/agents/plan-critic.md +5 -1
  225. package/prompts/source/agents/planner.md +4 -2
  226. package/prompts/source/agents/reviewer.md +6 -0
  227. package/prompts/source/category/complex.md +4 -4
  228. package/prompts/source/category/creative.md +6 -4
  229. package/prompts/source/category/cross-cutting.md +10 -8
  230. package/prompts/source/category/deep.md +5 -3
  231. package/prompts/source/category/documenting.md +7 -1
  232. package/prompts/source/category/frontend.md +2 -2
  233. package/prompts/source/category/hard-reasoning.md +3 -3
  234. package/prompts/source/category/research.md +4 -2
  235. package/prompts/source/deepwork/claude-opus-5.md +2 -2
  236. package/prompts/source/deepwork/codex.md +1 -1
  237. package/prompts/source/deepwork/default.md +22 -15
  238. package/prompts/source/deepwork/gemini.md +23 -16
  239. package/prompts/source/deepwork/glm.md +21 -14
  240. package/prompts/source/deepwork/gpt.md +12 -6
  241. package/prompts/source/deepwork/planner.md +8 -5
  242. package/prompts/source/manifest.json +178 -63
  243. package/prompts/source/shared/dsh-host-contract.md +5 -3
  244. package/prompts/source/shared/locale.md +2 -2
  245. package/prompts/source/terminal/orchestrator.md +1 -1
  246. package/skills/ast-grep/SKILL.md +7 -4
  247. package/skills/brainstorming/SKILL.md +43 -22
  248. package/skills/coding-agent-sessions/SKILL.md +7 -4
  249. package/skills/coding-agent-sessions/scripts/agent_sessions/pi_family.py +46 -46
  250. package/skills/coding-agent-sessions/scripts/tests/test_pi_family_scanners.py +130 -130
  251. package/skills/debugging/SKILL.md +14 -9
  252. package/skills/debugging/references/methodology/00-setup.md +14 -62
  253. package/skills/debugging/references/methodology/02-investigate.md +4 -4
  254. package/skills/debugging/references/methodology/03-flaky-triage.md +3 -3
  255. package/skills/debugging/references/methodology/04-hard-reasoning-escalation.md +2 -14
  256. package/skills/debugging/references/methodology/06-fix.md +6 -6
  257. package/skills/debugging/references/methodology/08-qa.md +5 -5
  258. package/skills/debugging/references/methodology/09-cleanup.md +15 -153
  259. package/skills/debugging/references/methodology/partial-runtime-evidence.md +3 -16
  260. package/skills/debugging/references/runtimes/bundled-js-binary.md +1 -16
  261. package/skills/debugging/references/runtimes/native-binary.md +9 -54
  262. package/skills/debugging/references/runtimes/node.md +4 -15
  263. package/skills/debugging/references/runtimes/python.md +3 -15
  264. package/skills/debugging/references/runtimes/rust.md +2 -18
  265. package/skills/debugging/references/tools/dap.md +1 -1
  266. package/skills/debugging/references/tools/ghidra.md +4 -15
  267. package/skills/debugging/references/tools/playwright-cli.md +3 -15
  268. package/skills/debugging/references/tools/pwntools.md +4 -16
  269. package/skills/dispatching-parallel-agents/SKILL.md +18 -16
  270. package/skills/frontend/SKILL.md +7 -4
  271. package/skills/frontend/references/design/react-dev-tooling-skill.md +1 -1
  272. package/skills/git-master/SKILL.md +7 -4
  273. package/skills/init-deep/SKILL.md +7 -4
  274. package/skills/receiving-code-review/SKILL.md +17 -12
  275. package/skills/remove-ai-slops/SKILL.md +39 -38
  276. package/skills/requesting-code-review/SKILL.md +19 -17
  277. package/skills/requesting-code-review/code-reviewer.md +13 -1
  278. package/skills/subagent-driven-development/SKILL.md +29 -26
  279. package/skills/subagent-driven-development/implementer-prompt.md +29 -11
  280. package/skills/subagent-driven-development/spec-reviewer-prompt.md +6 -1
  281. package/skills/using-git-worktrees/SKILL.md +7 -4
  282. package/skills/writing-plans/SKILL.md +29 -24
  283. package/skills/writing-plans/plan-document-reviewer-prompt.md +10 -1
  284. package/scripts/repair-session-log.mjs +0 -476
  285. package/scripts/session-repair-native-verifier.mjs +0 -367
@@ -1,476 +0,0 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { constants as fsConstants } from "node:fs";
3
- import { lstat, open, realpath, rename } from "node:fs/promises";
4
- import { basename, dirname, isAbsolute, parse, relative, resolve, sep } from "node:path";
5
- import { fileURLToPath, pathToFileURL } from "node:url";
6
- import { isDeepStrictEqual } from "node:util";
7
- import { constants, zstdCompressSync, zstdDecompressSync } from "node:zlib";
8
- import { KNOWN_SESSION_EVENT_TYPES, SESSION_FORMAT_VERSION } from "@deepseek-ai/dsh-session";
9
- import { annotateDsmmEvent } from "../lib/session-metadata.js";
10
-
11
- const MAX_BYTES = 256 * 1024 * 1024;
12
- const MARKER = Buffer.from(',"ignorable":true');
13
- const ZSTD_MAGIC = 0xfd2fb528;
14
- const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
15
- const checksumOptions = { params: { [constants.ZSTD_c_checksumFlag]: 1 } };
16
- const sha256 = value => createHash("sha256").update(value).digest("hex");
17
-
18
- /** Safe diagnostics deliberately omit parser, native, filesystem, and record payloads. */
19
- export class SessionLogRepairError extends Error {
20
- constructor(code, recovery = {}) {
21
- super(`Session-log repair refused: ${code}`);
22
- this.name = "SessionLogRepairError";
23
- this.code = code;
24
- this.recovery = Object.freeze({ ...recovery });
25
- }
26
- }
27
-
28
- const refuse = code => { throw new SessionLogRepairError(code); };
29
- const safeFailure = (error, code) => error instanceof SessionLogRepairError ? error : new SessionLogRepairError(code);
30
- const safeInteger = value => Number.isSafeInteger(value) && value >= 0 && !Object.is(value, -0);
31
-
32
- /** Spec-only frame boundaries; decoding and checksum validation use public node:zlib. */
33
- export function scanZstdFrames(bytes) {
34
- if (!Buffer.isBuffer(bytes) || bytes.length === 0) refuse("INVALID_INPUT");
35
- const frames = [];
36
- let cursor = 0;
37
- const requireBytes = count => {
38
- if (count > bytes.length - cursor) refuse("TORN_FRAME");
39
- };
40
- while (cursor < bytes.length) {
41
- const start = cursor;
42
- requireBytes(5);
43
- if (bytes.readUInt32LE(cursor) !== ZSTD_MAGIC) refuse("CORRUPT_FRAME");
44
- const descriptor = bytes[cursor + 4];
45
- cursor += 5;
46
- if ((descriptor & 0x18) !== 0) refuse("CORRUPT_FRAME");
47
- if ((descriptor & 0x04) === 0) refuse("UNCHECKSUMMED_FRAME");
48
- const singleSegment = (descriptor & 0x20) !== 0;
49
- const dictionaryFlag = descriptor & 0x03;
50
- const contentFlag = descriptor >>> 6;
51
- const dictionarySize = [0, 1, 2, 4][dictionaryFlag];
52
- const contentSize = contentFlag === 0 ? (singleSegment ? 1 : 0) : [0, 2, 4, 8][contentFlag];
53
- requireBytes((singleSegment ? 0 : 1) + dictionarySize + contentSize);
54
- cursor += (singleSegment ? 0 : 1) + dictionarySize + contentSize;
55
- let last = false;
56
- while (!last) {
57
- requireBytes(3);
58
- const block = bytes.readUIntLE(cursor, 3);
59
- cursor += 3;
60
- last = (block & 1) !== 0;
61
- const kind = (block >>> 1) & 3;
62
- const size = block >>> 3;
63
- if (kind === 3 || size > 128 * 1024) refuse("CORRUPT_FRAME");
64
- const physicalSize = kind === 1 ? 1 : size;
65
- requireBytes(physicalSize);
66
- cursor += physicalSize;
67
- }
68
- requireBytes(4);
69
- cursor += 4;
70
- frames.push({ start, end: cursor });
71
- }
72
- return frames;
73
- }
74
-
75
- function parseRow(bytes) {
76
- let text;
77
- let value;
78
- try {
79
- text = decoder.decode(bytes);
80
- value = JSON.parse(text);
81
- } catch {
82
- refuse("INVALID_JSON");
83
- }
84
- if (typeof value !== "object" || value === null || Array.isArray(value)) refuse("INVALID_RECORD");
85
- // JSON.parse alone would erase duplicate keys. Tokenize already-valid JSON to refuse them.
86
- const tokens = /"(?:\\[\s\S]|[^"\\])*"|[{}\[\]:,]|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/gu;
87
- const stack = [];
88
- for (const match of text.matchAll(tokens)) {
89
- const token = match[0];
90
- const top = stack.at(-1);
91
- if (token === "{") stack.push({ keys: new Set(), keyExpected: true });
92
- else if (token === "[") stack.push({});
93
- else if (token === "}" || token === "]") stack.pop();
94
- else if (token === "," && top?.keys) top.keyExpected = true;
95
- else if (token.startsWith('"') && top?.keys && top.keyExpected) {
96
- const key = JSON.parse(token);
97
- if (top.keys.has(key)) refuse("INVALID_JSON");
98
- top.keys.add(key);
99
- top.keyExpected = false;
100
- }
101
- }
102
- const pending = [value];
103
- while (pending.length) {
104
- const entry = pending.pop();
105
- if (typeof entry === "string" && !entry.isWellFormed()) refuse("INVALID_JSON");
106
- if (typeof entry === "number" && (!Number.isFinite(entry) || Object.is(entry, -0))) refuse("INVALID_JSON");
107
- if (typeof entry === "object" && entry !== null) {
108
- for (const [key, child] of Object.entries(entry)) {
109
- if (!key.isWellFormed()) refuse("INVALID_JSON");
110
- pending.push(child);
111
- }
112
- }
113
- }
114
- return value;
115
- }
116
-
117
- function readRows(plaintext) {
118
- const rows = [];
119
- let offset = 0;
120
- while (offset < plaintext.length) {
121
- const end = plaintext.indexOf(10, offset);
122
- if (end < 0) refuse("TORN_RECORD");
123
- rows.push({ value: parseRow(plaintext.subarray(offset, end)), start: offset, end });
124
- offset = end + 1;
125
- }
126
- if (rows.length === 0) refuse("INVALID_RECORD");
127
- return rows;
128
- }
129
-
130
- /** Returned rows/bytes are private in-memory verification inputs, never console output. */
131
- export function auditSessionLog(bytes, { encoding = "zstd", maxBytes = MAX_BYTES } = {}) {
132
- if (!Buffer.isBuffer(bytes) || bytes.length === 0 || !safeInteger(maxBytes) || maxBytes < 1 || bytes.length > maxBytes) refuse("INPUT_LIMIT");
133
- if (encoding !== "zstd" && encoding !== "none") refuse("INVALID_ENCODING");
134
- const frames = encoding === "zstd" ? scanZstdFrames(bytes) : [{ start: 0, end: bytes.length }];
135
- const decoded = [];
136
- let decodedSize = 0;
137
- for (const frame of frames) {
138
- let plaintext;
139
- try {
140
- plaintext = encoding === "zstd" ? zstdDecompressSync(bytes.subarray(frame.start, frame.end), {
141
- maxOutputLength: maxBytes - decodedSize,
142
- params: { [constants.ZSTD_d_windowLogMax]: Math.max(10, Math.ceil(Math.log2(maxBytes))) }
143
- }) : bytes;
144
- } catch {
145
- refuse("CORRUPT_FRAME");
146
- }
147
- if (plaintext.length > maxBytes - decodedSize) refuse("INPUT_LIMIT");
148
- decoded.push({ ...frame, plaintext, plainStart: decodedSize, insertions: [] });
149
- decodedSize += plaintext.length;
150
- }
151
- const plaintext = Buffer.concat(decoded.map(frame => frame.plaintext));
152
- const sourceRows = readRows(plaintext);
153
- const header = sourceRows[0].value;
154
- if (header.type !== "session" || header.version !== SESSION_FORMAT_VERSION || typeof header.id !== "string" || !header.id
155
- || !safeInteger(header.createdAt) || typeof header.isSeeded !== "boolean" || !safeInteger(header.delegationDepth)) refuse("UNSUPPORTED_HEADER");
156
- const events = [];
157
- let changedEventCount = 0;
158
- for (let index = 1; index < sourceRows.length; index += 1) {
159
- const row = sourceRows[index];
160
- const event = row.value;
161
- if (typeof event.type !== "string" || !event.type || !safeInteger(event.seq) || event.seq !== index - 1 || !safeInteger(event.time)
162
- || !Object.hasOwn(event, "data") || Object.hasOwn(event, "ignorable") && event.ignorable !== true) refuse("INVALID_EVENT");
163
- let annotated;
164
- try {
165
- annotated = annotateDsmmEvent(event);
166
- } catch {
167
- refuse("INVALID_DSMM_METADATA");
168
- }
169
- if (!KNOWN_SESSION_EVENT_TYPES.has(event.type) && annotated.ignorable !== true) refuse("UNSUPPORTED_EVENT");
170
- events.push(annotated);
171
- if (annotated === event) continue;
172
- changedEventCount += 1;
173
- let insertion = row.end - 1;
174
- while (insertion >= row.start && [9, 13, 32].includes(plaintext[insertion])) insertion -= 1;
175
- if (plaintext[insertion] !== 125) refuse("INVALID_RECORD");
176
- const frame = decoded.find(part => insertion >= part.plainStart && insertion < part.plainStart + part.plaintext.length);
177
- if (!frame) refuse("INVALID_RECORD");
178
- frame.insertions.push(insertion - frame.plainStart);
179
- }
180
- let changedFrameCount = 0;
181
- const candidateFrames = decoded.map(frame => {
182
- if (frame.insertions.length === 0) return bytes.subarray(frame.start, frame.end);
183
- changedFrameCount += 1;
184
- const parts = [];
185
- let start = 0;
186
- for (const insertion of frame.insertions) {
187
- parts.push(frame.plaintext.subarray(start, insertion), MARKER);
188
- start = insertion;
189
- }
190
- parts.push(frame.plaintext.subarray(start));
191
- const value = Buffer.concat(parts);
192
- return encoding === "zstd" ? zstdCompressSync(value, checksumOptions) : value;
193
- });
194
- const candidateBytes = Buffer.concat(candidateFrames);
195
- // Independently decode candidate rows and prove complete structural equality except markers.
196
- const candidatePlaintext = encoding === "zstd"
197
- ? Buffer.concat(scanZstdFrames(candidateBytes).map(frame => zstdDecompressSync(candidateBytes.subarray(frame.start, frame.end), { maxOutputLength: maxBytes })))
198
- : candidateBytes;
199
- const rows = readRows(candidatePlaintext).map(row => row.value);
200
- if (!isDeepStrictEqual(rows, [header, ...events])) refuse("RECORD_EQUALITY_FAILED");
201
- return { header, rows, events, candidateBytes, encoding, changedEventCount, changedFrameCount,
202
- frameCount: frames.length, inputSha256: sha256(bytes), candidateSha256: sha256(candidateBytes) };
203
- }
204
-
205
- function validAbsolutePath(value) {
206
- if (typeof value !== "string" || !value.isWellFormed() || !isAbsolute(value) || /[\0*?]/u.test(value)) refuse("UNSAFE_PATH");
207
- const pieces = value.slice(parse(value).root.length).split(/[\\/]/u);
208
- if (pieces.some(piece => piece === "." || piece === ".." || process.platform === "win32" && (piece.includes(":") || /[. ]$/u.test(piece)))) refuse("UNSAFE_PATH");
209
- return resolve(value);
210
- }
211
-
212
- function within(root, path) {
213
- const difference = relative(root, path);
214
- return difference !== "" && !isAbsolute(difference) && difference !== ".." && !difference.startsWith(`..${sep}`);
215
- }
216
-
217
- async function assertPath(filePath, allowedRoot) {
218
- if (!within(allowedRoot, filePath)) refuse("UNSAFE_PATH");
219
- for (let current = filePath; ; current = dirname(current)) {
220
- const value = await lstat(current, { bigint: true });
221
- if (value.isSymbolicLink() || current !== filePath && !value.isDirectory()) refuse("UNSAFE_PATH");
222
- if (current === filePath && (!value.isFile() || value.nlink !== 1n)) refuse("UNSAFE_PATH");
223
- if (current === dirname(current)) break;
224
- }
225
- // Equality by relative path tolerates Windows casing/short names, but no redirected parent.
226
- const canonical = await realpath(filePath);
227
- const rootCanonical = await realpath(allowedRoot);
228
- if (!within(rootCanonical, canonical)) refuse("UNSAFE_PATH");
229
- }
230
-
231
- const revision = value => [value.dev, value.ino, value.size, value.mtimeNs, value.ctimeNs].join(":");
232
- const identity = value => [value.dev, value.ino].join(":");
233
-
234
- async function snapshot(filePath, allowedRoot, maxBytes) {
235
- await assertPath(filePath, allowedRoot);
236
- const handle = await open(filePath, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
237
- try {
238
- const before = await handle.stat({ bigint: true });
239
- if (!before.isFile() || before.nlink !== 1n) refuse("UNSAFE_PATH");
240
- if (before.size > BigInt(maxBytes)) refuse("INPUT_LIMIT");
241
- const chunks = [];
242
- let position = 0;
243
- for (;;) {
244
- const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes - position + 1));
245
- const { bytesRead } = await handle.read(chunk, 0, chunk.length, position);
246
- if (bytesRead === 0) break;
247
- position += bytesRead;
248
- if (position > maxBytes) refuse("INPUT_LIMIT");
249
- chunks.push(chunk.subarray(0, bytesRead));
250
- }
251
- const bytes = Buffer.concat(chunks);
252
- const after = await handle.stat({ bigint: true });
253
- const pathStat = await lstat(filePath, { bigint: true });
254
- if (revision(before) !== revision(after) || identity(after) !== identity(pathStat) || pathStat.nlink !== 1n || pathStat.isSymbolicLink()) refuse("SOURCE_CHANGED");
255
- return { bytes, sha256: sha256(bytes), revision: revision(after), identity: identity(after) };
256
- } finally {
257
- await handle.close();
258
- }
259
- }
260
-
261
- async function assertSnapshot(filePath, allowedRoot, maxBytes, expected, code) {
262
- const current = await snapshot(filePath, allowedRoot, maxBytes);
263
- if (current.sha256 !== expected.sha256 || current.revision !== expected.revision || current.identity !== expected.identity) refuse(code);
264
- return current;
265
- }
266
-
267
- async function createPrivateFile(filePath, bytes, allowedRoot, maxBytes) {
268
- // Recheck the existing parent immediately before exclusive artifact creation.
269
- const parent = dirname(filePath);
270
- if (parent !== allowedRoot && !within(allowedRoot, parent)) refuse("UNSAFE_PATH");
271
- for (let current = parent; ; current = dirname(current)) {
272
- const value = await lstat(current);
273
- if (!value.isDirectory() || value.isSymbolicLink()) refuse("UNSAFE_PATH");
274
- if (current === dirname(current)) break;
275
- }
276
- const canonicalParent = await realpath(parent);
277
- const canonicalRoot = await realpath(allowedRoot);
278
- if (relative(canonicalRoot, canonicalParent) !== "" && !within(canonicalRoot, canonicalParent)) refuse("UNSAFE_PATH");
279
- const handle = await open(filePath, "wx", 0o600);
280
- try {
281
- if (process.platform !== "win32") await handle.chmod(0o600);
282
- await handle.writeFile(bytes);
283
- await handle.sync();
284
- } finally {
285
- await handle.close();
286
- }
287
- const created = await snapshot(filePath, allowedRoot, maxBytes);
288
- if (created.sha256 !== sha256(bytes)) refuse("ARTIFACT_VERIFY_FAILED");
289
- if (process.platform !== "win32" && ((await lstat(filePath)).mode & 0o777) !== 0o600) refuse("PRIVATE_ARTIFACT_REQUIRED");
290
- await syncDirectory(dirname(filePath));
291
- return created;
292
- }
293
-
294
- async function syncDirectory(directory) {
295
- if (process.platform === "win32") return; // Windows replacement has no unlink fallback.
296
- const handle = await open(directory, "r");
297
- try { await handle.sync(); } finally { await handle.close(); }
298
- }
299
-
300
- async function assertLease(lease) {
301
- try {
302
- if (!lease || typeof lease.release !== "function" || typeof lease.assertQuiescent !== "function"
303
- || typeof lease.assertPrivateDirectory !== "function" || await lease.assertQuiescent() !== true
304
- || await lease.assertPrivateDirectory() !== true) refuse("QUIESCENCE_REQUIRED");
305
- } catch (error) {
306
- throw safeFailure(error, "QUIESCENCE_REQUIRED");
307
- }
308
- }
309
-
310
- async function verifyNative(verifyCandidate, candidatePath, sourcePath, originalPath, audit, expectedSha256) {
311
- try {
312
- const result = await verifyCandidate({ candidatePath, sourcePath, originalPath, header: structuredClone(audit.header),
313
- rows: structuredClone(audit.rows), events: structuredClone(audit.events), encoding: audit.encoding,
314
- expectedSha256, candidateSha256: audit.candidateSha256 });
315
- if (result?.publicRead !== true || result?.restored !== true || result?.historyEqual !== true) refuse("NATIVE_VERIFY_FAILED");
316
- } catch {
317
- refuse("NATIVE_VERIFY_FAILED");
318
- }
319
- }
320
-
321
- function receipt(audit, outcome, recovery = {}) {
322
- return Object.freeze({ outcome, originalSha256: audit.inputSha256, candidateSha256: audit.candidateSha256,
323
- changedEventCount: audit.changedEventCount, changedFrameCount: audit.changedFrameCount,
324
- frameCount: audit.frameCount, eventCount: audit.events.length, encoding: audit.encoding, ...recovery });
325
- }
326
-
327
- /**
328
- * Apply requires trusted, actually held native writer exclusion, carrier-quiescence,
329
- * same-directory privacy, and public native read/restore/history verification.
330
- * Those callbacks are operator integration, not model-controlled boolean claims.
331
- */
332
- export async function repairSessionLog({ filePath: suppliedPath, allowedRoot: suppliedRoot, expectedSha256,
333
- apply = false, acquireExclusiveWriterLease, verifyCandidate, maxBytes = MAX_BYTES } = {}) {
334
- let lease;
335
- let result;
336
- let failure;
337
- const recovery = {};
338
- try {
339
- const filePath = validAbsolutePath(suppliedPath);
340
- const allowedRoot = validAbsolutePath(suppliedRoot);
341
- if (!/^[a-f0-9]{64}$/u.test(expectedSha256 ?? "")) refuse("EXPECTED_DIGEST_REQUIRED");
342
- if (apply !== true && apply !== false || !safeInteger(maxBytes) || maxBytes < 1) refuse("INVALID_OPTIONS");
343
- if (apply && (typeof acquireExclusiveWriterLease !== "function" || typeof verifyCandidate !== "function")) refuse("VERIFICATION_REQUIRED");
344
- await assertPath(filePath, allowedRoot);
345
- if (apply) {
346
- try { lease = await acquireExclusiveWriterLease({ filePath, sourcePath: filePath, allowedRoot, expectedSha256 }); }
347
- catch { refuse("WRITER_LEASE_REQUIRED"); }
348
- await assertLease(lease);
349
- }
350
- const source = await snapshot(filePath, allowedRoot, maxBytes);
351
- if (source.sha256 !== expectedSha256) refuse("DIGEST_MISMATCH");
352
- const encoding = filePath.endsWith(".jsonl.zstd") ? "zstd" : filePath.endsWith(".jsonl") ? "none" : undefined;
353
- if (!encoding) refuse("INVALID_ENCODING");
354
- const audit = auditSessionLog(source.bytes, { encoding, maxBytes });
355
- if (!apply) result = receipt(audit, "DRY_RUN");
356
- else if (audit.changedEventCount === 0) {
357
- await verifyNative(verifyCandidate, filePath, filePath, filePath, audit, expectedSha256);
358
- await assertLease(lease);
359
- await assertSnapshot(filePath, allowedRoot, maxBytes, source, "SOURCE_CHANGED");
360
- result = receipt(audit, "ALREADY_COMPATIBLE");
361
- }
362
- else {
363
- const directory = dirname(filePath);
364
- const prefix = `${basename(filePath)}.dsmm-${randomUUID()}`;
365
- const backupPath = resolve(directory, `${prefix}.backup`);
366
- const candidatePath = resolve(directory, `${prefix}.candidate`);
367
- recovery.backupPath = backupPath;
368
- recovery.candidatePath = candidatePath;
369
- await assertLease(lease);
370
- const backup = await createPrivateFile(backupPath, source.bytes, allowedRoot, maxBytes);
371
- await assertLease(lease);
372
- const candidate = await createPrivateFile(candidatePath, audit.candidateBytes, allowedRoot, maxBytes);
373
- await verifyNative(verifyCandidate, candidatePath, filePath, backupPath, audit, expectedSha256);
374
- await assertLease(lease);
375
- await assertSnapshot(backupPath, allowedRoot, maxBytes, backup, "BACKUP_CHANGED");
376
- await assertSnapshot(candidatePath, allowedRoot, maxBytes, candidate, "CANDIDATE_CHANGED");
377
- await assertSnapshot(filePath, allowedRoot, maxBytes, source, "SOURCE_CHANGED");
378
- try { await rename(candidatePath, filePath); }
379
- catch { throw new SessionLogRepairError("ATOMIC_REPLACE_FAILED", recovery); }
380
- recovery.activeChanged = true;
381
- try {
382
- await syncDirectory(directory);
383
- const active = await snapshot(filePath, allowedRoot, maxBytes);
384
- if (active.sha256 !== audit.candidateSha256 || active.identity !== candidate.identity) refuse("POST_VERIFY_FAILED");
385
- await assertSnapshot(backupPath, allowedRoot, maxBytes, backup, "BACKUP_CHANGED");
386
- await verifyNative(verifyCandidate, filePath, filePath, backupPath, audit, expectedSha256);
387
- await assertLease(lease);
388
- await assertSnapshot(backupPath, allowedRoot, maxBytes, backup, "BACKUP_CHANGED");
389
- await assertSnapshot(filePath, allowedRoot, maxBytes, active, "SOURCE_CHANGED");
390
- result = receipt(audit, "REPAIRED", { backupPath });
391
- } catch {
392
- // Restore only our exact candidate; never overwrite an intervening edit.
393
- try {
394
- await assertLease(lease);
395
- const active = await snapshot(filePath, allowedRoot, maxBytes);
396
- if (active.sha256 !== audit.candidateSha256 || active.identity !== candidate.identity) refuse("ROLLBACK_UNSAFE");
397
- await assertSnapshot(backupPath, allowedRoot, maxBytes, backup, "BACKUP_CHANGED");
398
- const failedCandidatePath = resolve(directory, `${prefix}.failed.candidate`);
399
- const rollbackPath = resolve(directory, `${prefix}.rollback.candidate`);
400
- await createPrivateFile(failedCandidatePath, audit.candidateBytes, allowedRoot, maxBytes);
401
- recovery.candidatePath = failedCandidatePath;
402
- await createPrivateFile(rollbackPath, source.bytes, allowedRoot, maxBytes);
403
- await assertLease(lease);
404
- await assertSnapshot(filePath, allowedRoot, maxBytes, active, "ROLLBACK_UNSAFE");
405
- await rename(rollbackPath, filePath);
406
- await syncDirectory(directory);
407
- if ((await snapshot(filePath, allowedRoot, maxBytes)).sha256 !== expectedSha256) refuse("ROLLBACK_VERIFY_FAILED");
408
- recovery.activeChanged = false;
409
- } catch (error) {
410
- throw new SessionLogRepairError(safeFailure(error, "ROLLBACK_FAILED").code, recovery);
411
- }
412
- throw new SessionLogRepairError("POST_VERIFY_FAILED_ROLLED_BACK", recovery);
413
- }
414
- }
415
- } catch (error) {
416
- const safe = safeFailure(error, "IO_FAILED");
417
- failure = new SessionLogRepairError(safe.code, { ...recovery, ...safe.recovery });
418
- } finally {
419
- if (lease && typeof lease.release === "function") {
420
- try { await lease.release(); }
421
- catch {
422
- failure = new SessionLogRepairError("WRITER_LEASE_RELEASE_FAILED", { ...recovery, priorFailureCode: failure?.code });
423
- }
424
- }
425
- }
426
- if (failure) throw failure;
427
- return result;
428
- }
429
-
430
- export function parseRepairArguments(args) {
431
- const values = {};
432
- const names = { "--file": "filePath", "--sha256": "expectedSha256", "--root": "allowedRoot", "--verifier": "verifier",
433
- "--native-runtime-manifest": "nativeManifestPath", "--carrier-executable": "carrierExecutablePath" };
434
- for (let index = 0; index < args.length; index += 1) {
435
- const token = args[index];
436
- const key = names[token] ?? (token === "--apply" ? "apply" : token === "--assert-quiescent" ? "assertQuiescent" : undefined);
437
- if (!key || Object.hasOwn(values, key)) refuse("INVALID_ARGUMENTS");
438
- values[key] = key === "apply" || key === "assertQuiescent" ? true : args[++index];
439
- if (values[key] === undefined || typeof values[key] === "string" && values[key].startsWith("--")) refuse("INVALID_ARGUMENTS");
440
- }
441
- if (values.apply && (!values.assertQuiescent || !values.verifier)) refuse("VERIFICATION_REQUIRED");
442
- if (!values.apply && (values.verifier || values.assertQuiescent || values.nativeManifestPath || values.carrierExecutablePath)) refuse("INVALID_ARGUMENTS");
443
- if (Boolean(values.nativeManifestPath) !== Boolean(values.carrierExecutablePath)) refuse("INVALID_ARGUMENTS");
444
- return values;
445
- }
446
-
447
- async function main() {
448
- try {
449
- const { verifier, assertQuiescent: _assertion, nativeManifestPath, carrierExecutablePath, ...options } = parseRepairArguments(process.argv.slice(2));
450
- let callbacks = {};
451
- if (verifier) {
452
- const path = validAbsolutePath(verifier);
453
- if (!(await lstat(path)).isFile() || (await lstat(path)).isSymbolicLink()) refuse("UNSAFE_VERIFIER");
454
- try { callbacks = await import(pathToFileURL(path).href); }
455
- catch { refuse("VERIFIER_LOAD_FAILED"); }
456
- if (nativeManifestPath || carrierExecutablePath) {
457
- if (typeof callbacks.createNativeSessionRepairVerifier !== "function") refuse("VERIFIER_FACTORY_REQUIRED");
458
- try {
459
- callbacks = await callbacks.createNativeSessionRepairVerifier({
460
- nativeManifestPath: validAbsolutePath(nativeManifestPath), carrierExecutablePath: validAbsolutePath(carrierExecutablePath) });
461
- } catch (error) {
462
- throw safeFailure(error, "VERIFIER_SETUP_FAILED");
463
- }
464
- }
465
- }
466
- const result = await repairSessionLog({ ...options,
467
- acquireExclusiveWriterLease: callbacks.acquireExclusiveWriterLease, verifyCandidate: callbacks.verifyCandidate });
468
- process.stdout.write(`${JSON.stringify(result)}\n`);
469
- } catch (error) {
470
- const safe = safeFailure(error, "IO_FAILED");
471
- process.stderr.write(`${JSON.stringify({ outcome: "REFUSED", code: safe.code, recovery: safe.recovery })}\n`);
472
- process.exitCode = 1;
473
- }
474
- }
475
-
476
- if (process.argv[1] && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url))) await main();