@dsmm/dsmm 0.1.1 → 0.1.4

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 (95) hide show
  1. package/README.md +24 -13
  2. package/agent-presets/dsmm-builder/agent.cordis.yml +14 -12
  3. package/agent-presets/dsmm-builder/preset.yml +1 -1
  4. package/agent-presets/dsmm-clarifier/agent.cordis.yml +4 -2
  5. package/agent-presets/dsmm-clarifier/preset.yml +1 -1
  6. package/agent-presets/dsmm-code-search/agent.cordis.yml +4 -2
  7. package/agent-presets/dsmm-code-search/preset.yml +1 -1
  8. package/agent-presets/dsmm-creative/agent.cordis.yml +3 -1
  9. package/agent-presets/dsmm-creative/preset.yml +1 -1
  10. package/agent-presets/dsmm-doc-search/agent.cordis.yml +4 -2
  11. package/agent-presets/dsmm-doc-search/preset.yml +1 -1
  12. package/agent-presets/dsmm-media-reader/agent.cordis.yml +4 -2
  13. package/agent-presets/dsmm-media-reader/preset.yml +1 -1
  14. package/agent-presets/dsmm-oracle/agent.cordis.yml +3 -1
  15. package/agent-presets/dsmm-oracle/preset.yml +1 -1
  16. package/agent-presets/dsmm-oracle-2nd/agent.cordis.yml +3 -1
  17. package/agent-presets/dsmm-oracle-2nd/preset.yml +1 -1
  18. package/agent-presets/dsmm-orchestrator/agent.cordis.yml +15 -13
  19. package/agent-presets/dsmm-orchestrator/preset.yml +2 -2
  20. package/agent-presets/dsmm-plan-critic/agent.cordis.yml +4 -2
  21. package/agent-presets/dsmm-plan-critic/preset.yml +1 -1
  22. package/agent-presets/dsmm-planner/agent.cordis.yml +4 -2
  23. package/agent-presets/dsmm-planner/preset.yml +1 -1
  24. package/agent-presets/dsmm-reviewer/agent.cordis.yml +4 -2
  25. package/agent-presets/dsmm-reviewer/preset.yml +1 -1
  26. package/docs/agent-presets.md +15 -5
  27. package/docs/compatibility.md +64 -11
  28. package/docs/model-routing.md +10 -6
  29. package/docs/profiles.md +83 -0
  30. package/docs/releasing.md +58 -19
  31. package/docs/settings-status.md +13 -5
  32. package/lib/client/ProfilesSection.d.ts +11 -0
  33. package/lib/client/ProfilesSection.js +62 -0
  34. package/lib/client/controller.d.ts +77 -0
  35. package/lib/client/controller.js +198 -0
  36. package/lib/client/index.d.ts +11 -0
  37. package/lib/client/index.js +34 -0
  38. package/lib/client/locales.d.ts +56 -0
  39. package/lib/client/locales.js +48 -0
  40. package/lib/client/styles.d.ts +3 -0
  41. package/lib/client/styles.js +25 -0
  42. package/lib/client.js +1930 -0
  43. package/lib/commands.d.ts +3 -3
  44. package/lib/commands.js +4 -4
  45. package/lib/dsh-types.d.ts +4 -0
  46. package/lib/guards.d.ts +2 -2
  47. package/lib/guards.js +3 -2
  48. package/lib/index.d.ts +12 -4
  49. package/lib/index.js +72 -20
  50. package/lib/mode.d.ts +2 -2
  51. package/lib/mode.js +1 -1
  52. package/lib/model-routing.d.ts +2 -2
  53. package/lib/model-routing.js +17 -2
  54. package/lib/preset-registry.js +5 -3
  55. package/lib/profile-remote.d.ts +31 -0
  56. package/lib/profile-remote.js +106 -0
  57. package/lib/profile-rpc.d.ts +27 -0
  58. package/lib/profile-rpc.js +90 -0
  59. package/lib/profile-runtime.d.ts +44 -0
  60. package/lib/profile-runtime.js +159 -0
  61. package/lib/profile-store.d.ts +42 -0
  62. package/lib/profile-store.js +478 -0
  63. package/lib/profile-types.d.ts +40 -0
  64. package/lib/profile-types.js +2 -0
  65. package/lib/profiles.d.ts +26 -0
  66. package/lib/profiles.js +237 -0
  67. package/lib/prompts.d.ts +2 -2
  68. package/lib/prompts.js +4 -4
  69. package/lib/role-providers.d.ts +2 -2
  70. package/lib/role-providers.js +39 -6
  71. package/lib/role-routing.d.ts +2 -2
  72. package/lib/role-routing.js +4 -1
  73. package/lib/role-subagents.d.ts +2 -2
  74. package/lib/role-subagents.js +6 -4
  75. package/lib/roles.d.ts +4 -0
  76. package/lib/roles.js +43 -27
  77. package/lib/runtime-recovery.d.ts +2 -2
  78. package/lib/runtime-recovery.js +3 -3
  79. package/lib/session-metadata.d.ts +13 -0
  80. package/lib/session-metadata.js +34 -0
  81. package/lib/session-persistence.d.ts +35 -0
  82. package/lib/session-persistence.js +304 -0
  83. package/lib/settings.d.ts +8 -1
  84. package/lib/settings.js +4 -0
  85. package/lib/state.d.ts +1 -0
  86. package/lib/state.js +4 -0
  87. package/lib/status.js +6 -5
  88. package/locale/en.json +6 -0
  89. package/locale/zh.json +6 -0
  90. package/package.json +62 -15
  91. package/patches/agent-presets-root.example.cordis.patch.yml +6 -10
  92. package/prompts/deepseek-v4-pro.md +1 -1
  93. package/prompts/deepwork.md +3 -3
  94. package/scripts/repair-session-log.mjs +476 -0
  95. package/scripts/session-repair-native-verifier.mjs +367 -0
@@ -0,0 +1,367 @@
1
+ import { createHash } from "node:crypto";
2
+ import { spawn } from "node:child_process";
3
+ import { constants as fsConstants } from "node:fs";
4
+ import { chmod, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rm } from "node:fs/promises";
5
+ import { createRequire } from "node:module";
6
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
+ import { pathToFileURL } from "node:url";
8
+ import { isDeepStrictEqual } from "node:util";
9
+ import { auditSessionLog } from "./repair-session-log.mjs";
10
+
11
+ const PINNED_VERSION = "0.2.0-rc.2";
12
+ const MAX_BYTES = 256 * 1024 * 1024;
13
+ const digest = bytes => createHash("sha256").update(bytes).digest("hex");
14
+ const pathKey = path => process.platform === "win32" ? resolve(path).toLowerCase() : resolve(path);
15
+
16
+ /** Diagnostics never retain native/parser errors, paths, or message payloads. */
17
+ export class NativeSessionVerificationError extends Error {
18
+ constructor(code) {
19
+ super(`Native session verification refused: ${code}`);
20
+ this.name = "NativeSessionVerificationError";
21
+ this.code = code;
22
+ }
23
+ }
24
+ const refuse = code => { throw new NativeSessionVerificationError(code); };
25
+ const safeError = (error, code) => error instanceof NativeSessionVerificationError ? error : new NativeSessionVerificationError(code);
26
+
27
+ const SEMAPHORE_SCRIPT = `
28
+ $ErrorActionPreference = 'Stop'
29
+ $sem = $null
30
+ $held = $false
31
+ try {
32
+ $sem = [System.Threading.Semaphore]::new(1, 1, $env:DSMM_REPAIR_SEMAPHORE)
33
+ $held = $sem.WaitOne(0)
34
+ if (-not $held) { [Console]::Out.WriteLine('BUSY'); exit 3 }
35
+ [Console]::Out.WriteLine('HELD')
36
+ [Console]::Out.Flush()
37
+ $null = [Console]::In.ReadLine()
38
+ } catch { [Console]::Out.WriteLine('FAILED'); exit 4 }
39
+ finally {
40
+ if ($held) { $null = $sem.Release() }
41
+ if ($null -ne $sem) { $sem.Dispose() }
42
+ }
43
+ `;
44
+
45
+ const QUIESCENCE_SCRIPT = `
46
+ $ErrorActionPreference = 'Stop'
47
+ try {
48
+ $p = $env:DSMM_REPAIR_PARAMETERS | ConvertFrom-Json
49
+ $busy = $false
50
+ foreach ($entry in (Get-CimInstance -ClassName Win32_Process -Property Name,ExecutablePath)) {
51
+ if ($p.names -contains $entry.Name.ToLowerInvariant()) { $busy = $true; break }
52
+ if ($p.executable -and $entry.ExecutablePath -and $entry.ExecutablePath.ToLowerInvariant() -eq $p.executable) { $busy = $true; break }
53
+ }
54
+ if ($busy) { [Console]::Out.WriteLine('NO') } else { [Console]::Out.WriteLine('YES') }
55
+ } catch { [Console]::Out.WriteLine('FAILED'); exit 4 }
56
+ `;
57
+
58
+ const PRIVACY_SCRIPT = `
59
+ $ErrorActionPreference = 'Stop'
60
+ try {
61
+ $p = $env:DSMM_REPAIR_PARAMETERS | ConvertFrom-Json
62
+ $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
63
+ $trusted = @($identity, 'S-1-5-18', 'S-1-5-32-544')
64
+ $source = [System.IO.File]::GetAccessControl($p.source)
65
+ $directory = [System.IO.Directory]::GetAccessControl($p.directory)
66
+ foreach ($acl in @($source, $directory)) {
67
+ $descriptor = [System.Security.AccessControl.RawSecurityDescriptor]::new($acl.GetSecurityDescriptorBinaryForm(), 0)
68
+ if ($null -eq $descriptor.DiscretionaryAcl) { [Console]::Out.WriteLine('NO'); exit 0 }
69
+ }
70
+ $owner = $directory.GetOwner([System.Security.Principal.SecurityIdentifier]).Value
71
+ if ($trusted -notcontains $owner) { [Console]::Out.WriteLine('NO'); exit 0 }
72
+ $sourceRights = @{}
73
+ foreach ($rule in $source.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) {
74
+ if ($rule.AccessControlType -eq 'Deny') { [Console]::Out.WriteLine('NO'); exit 0 }
75
+ if ($rule.AccessControlType -eq 'Allow') {
76
+ $sid = $rule.IdentityReference.Value
77
+ $sourceRights[$sid] = ([long]$sourceRights[$sid]) -bor ([long]$rule.FileSystemRights)
78
+ }
79
+ }
80
+ foreach ($rule in $directory.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) {
81
+ if ($rule.AccessControlType -ne 'Allow') { continue }
82
+ $sid = $rule.IdentityReference.Value
83
+ if ($sid -eq 'S-1-3-0') { $sid = $identity }
84
+ if ($trusted -contains $sid) { continue }
85
+ $rights = [long]$rule.FileSystemRights
86
+ if (-not $sourceRights.ContainsKey($sid) -or (($rights -band $sourceRights[$sid]) -ne $rights)) { [Console]::Out.WriteLine('NO'); exit 0 }
87
+ }
88
+ [Console]::Out.WriteLine('YES')
89
+ } catch { [Console]::Out.WriteLine('FAILED'); exit 4 }
90
+ `;
91
+
92
+ const PRIVATE_ROOT_SCRIPT = `
93
+ $ErrorActionPreference = 'Stop'
94
+ try {
95
+ $p = $env:DSMM_REPAIR_PARAMETERS | ConvertFrom-Json
96
+ $acl = [System.Security.AccessControl.DirectorySecurity]::new()
97
+ $acl.SetAccessRuleProtection($true, $false)
98
+ $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
99
+ $acl.SetOwner($user)
100
+ foreach ($sid in @($user, [System.Security.Principal.SecurityIdentifier]::new('S-1-5-18'), [System.Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'))) {
101
+ $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
102
+ $acl.AddAccessRule($rule)
103
+ }
104
+ [System.IO.Directory]::SetAccessControl($p.directory, $acl)
105
+ [Console]::Out.WriteLine('YES')
106
+ } catch { [Console]::Out.WriteLine('FAILED'); exit 4 }
107
+ `;
108
+
109
+ function powershell(script, parameters = {}) {
110
+ const executable = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
111
+ return spawn(executable, ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], {
112
+ windowsHide: true, stdio: ["pipe", "pipe", "ignore"],
113
+ env: { ...process.env, DSMM_REPAIR_PARAMETERS: JSON.stringify(parameters), DSMM_REPAIR_SEMAPHORE: parameters.semaphore ?? "" }
114
+ });
115
+ }
116
+
117
+ function probeWindows(script, parameters, code) {
118
+ return new Promise((resolveProbe, reject) => {
119
+ const child = powershell(script, parameters);
120
+ let output = "";
121
+ const timer = setTimeout(() => { child.kill(); reject(new NativeSessionVerificationError(code)); }, 15000);
122
+ child.stdout.on("data", chunk => {
123
+ output += chunk.toString("utf8");
124
+ if (output.length > 64) child.kill();
125
+ });
126
+ child.once("error", () => { clearTimeout(timer); reject(new NativeSessionVerificationError(code)); });
127
+ child.once("exit", exitCode => {
128
+ clearTimeout(timer);
129
+ if (exitCode === 0 && output.trim() === "YES") resolveProbe(true);
130
+ else reject(new NativeSessionVerificationError(code));
131
+ });
132
+ child.stdin.end();
133
+ });
134
+ }
135
+
136
+ async function acquireWindowsLease(lockPath) {
137
+ const semaphore = `Local\\dsh-session-lock-${digest(resolve(lockPath).toLowerCase())}`;
138
+ const child = powershell(SEMAPHORE_SCRIPT, { semaphore });
139
+ let exited = false;
140
+ const completion = new Promise(resolveExit => { child.once("close", () => { exited = true; resolveExit(); }); });
141
+ try {
142
+ await new Promise((resolveHeld, reject) => {
143
+ let output = "";
144
+ const timer = setTimeout(() => { child.kill(); reject(new NativeSessionVerificationError("LEASE_UNAVAILABLE")); }, 15000);
145
+ const finish = error => { clearTimeout(timer); child.stdout.removeListener("data", onData); error ? reject(error) : resolveHeld(); };
146
+ const onData = chunk => {
147
+ output += chunk.toString("utf8");
148
+ if (!output.includes("\n") && output.length < 64) return;
149
+ finish(output.trim() === "HELD" ? undefined : new NativeSessionVerificationError(output.trim() === "BUSY" ? "WRITER_ACTIVE" : "LEASE_UNAVAILABLE"));
150
+ };
151
+ child.stdout.on("data", onData);
152
+ child.once("error", () => finish(new NativeSessionVerificationError("LEASE_UNAVAILABLE")));
153
+ child.once("exit", () => finish(new NativeSessionVerificationError("LEASE_UNAVAILABLE")));
154
+ });
155
+ } catch (error) {
156
+ child.stdin.destroy();
157
+ child.kill();
158
+ await completion;
159
+ throw safeError(error, "LEASE_UNAVAILABLE");
160
+ }
161
+ return {
162
+ async assertHeld() { if (exited || child.exitCode !== null || child.killed) refuse("LEASE_LOST"); },
163
+ async release() {
164
+ if (exited || child.exitCode !== null || child.killed) refuse("LEASE_LOST");
165
+ child.stdin.end("RELEASE\n");
166
+ const timer = setTimeout(() => child.kill(), 5000);
167
+ await completion;
168
+ clearTimeout(timer);
169
+ if (child.exitCode !== 0) refuse("LEASE_RELEASE_FAILED");
170
+ }
171
+ };
172
+ }
173
+
174
+ async function assertPlainPath(filePath, allowedRoot) {
175
+ if (typeof filePath !== "string" || !isAbsolute(filePath) || /[\0*?]/u.test(filePath)) refuse("UNSAFE_PATH");
176
+ const path = resolve(filePath);
177
+ if (allowedRoot !== undefined) {
178
+ if (typeof allowedRoot !== "string" || !isAbsolute(allowedRoot)) refuse("UNSAFE_PATH");
179
+ const within = relative(resolve(allowedRoot), path);
180
+ if (!within || within === ".." || within.startsWith(`..${sep}`) || isAbsolute(within)) refuse("UNSAFE_PATH");
181
+ }
182
+ const entry = await lstat(path);
183
+ const directory = await lstat(dirname(path));
184
+ if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1 || !directory.isDirectory() || directory.isSymbolicLink()
185
+ || pathKey(await realpath(path)) !== pathKey(path)) refuse("UNSAFE_PATH");
186
+ return path;
187
+ }
188
+
189
+ async function snapshot(filePath) {
190
+ const path = await assertPlainPath(filePath);
191
+ const handle = await open(path, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
192
+ try {
193
+ const before = await handle.stat({ bigint: true });
194
+ if (before.size > BigInt(MAX_BYTES)) refuse("INPUT_LIMIT");
195
+ const bytes = await handle.readFile();
196
+ const after = await handle.stat({ bigint: true });
197
+ const current = await lstat(path, { bigint: true });
198
+ if (before.ino !== after.ino || before.dev !== after.dev || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs
199
+ || current.ino !== before.ino || current.dev !== before.dev || current.nlink !== 1n || current.isSymbolicLink()
200
+ || current.size !== before.size || current.mtimeNs !== before.mtimeNs || current.ctimeNs !== before.ctimeNs) refuse("SOURCE_CHANGED");
201
+ return bytes;
202
+ } finally { await handle.close(); }
203
+ }
204
+
205
+ async function acquirePosixLease(lockPath, nativeRequire) {
206
+ const { tryLockExclusive } = await import(pathToFileURL(nativeRequire.resolve("@deepseek-ai/node-addon-system/flock")).href);
207
+ const entry = await lstat(lockPath).catch(error => { if (error.code === "ENOENT") return undefined; throw error; });
208
+ if (entry && (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1)) refuse("UNSAFE_LOCK");
209
+ const handle = await open(lockPath, fsConstants.O_RDWR | fsConstants.O_CREAT | (fsConstants.O_NOFOLLOW ?? 0), 0o600);
210
+ try {
211
+ await tryLockExclusive(handle.fd);
212
+ const held = await handle.stat({ bigint: true });
213
+ const assertHeld = async () => {
214
+ const current = await lstat(lockPath, { bigint: true });
215
+ if (!current.isFile() || current.isSymbolicLink() || current.nlink !== 1n || current.ino !== held.ino || current.dev !== held.dev) refuse("LEASE_LOST");
216
+ };
217
+ await assertHeld();
218
+ return { assertHeld, async release() { try { await assertHeld(); } finally { await handle.close(); } } };
219
+ } catch (error) {
220
+ await handle.close();
221
+ if (error?.code === "EAGAIN" || error?.code === "EWOULDBLOCK") refuse("WRITER_ACTIVE");
222
+ throw safeError(error, "LEASE_UNAVAILABLE");
223
+ }
224
+ }
225
+
226
+ async function assertPrivateDirectory(sourcePath) {
227
+ if (process.platform === "win32") return probeWindows(PRIVACY_SCRIPT, { source: sourcePath, directory: dirname(sourcePath) }, "DIRECTORY_NOT_PRIVATE");
228
+ const source = await lstat(sourcePath);
229
+ const directory = await lstat(dirname(sourcePath));
230
+ if (directory.uid !== process.getuid() || (directory.mode & 0o077 & ~(source.mode & 0o077)) !== 0) refuse("DIRECTORY_NOT_PRIVATE");
231
+ return true;
232
+ }
233
+
234
+ function encodeSegment(value) {
235
+ if (typeof value !== "string" || !value || value === "." || value === "..") refuse("INVALID_HEADER");
236
+ let encoded = "";
237
+ for (let index = 0; index < value.length; index++) {
238
+ const character = value[index];
239
+ encoded += character !== "~" && /^[A-Za-z0-9._-]$/u.test(character) ? character : `~${value.charCodeAt(index).toString(16).toUpperCase().padStart(4, "0")}`;
240
+ }
241
+ return encoded;
242
+ }
243
+
244
+ function projectKey(cwd) {
245
+ if (cwd === undefined) return "_no-cwd";
246
+ if (typeof cwd !== "string" || !cwd) refuse("INVALID_HEADER");
247
+ const readable = cwd.replace(/[\\/:]+/gu, "-").split("").map(character => character !== "~" && /^[A-Za-z0-9._-]$/u.test(character) ? character : `~${character.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}`).join("");
248
+ return `--${(readable.replace(/^-+/u, "") || "root").slice(0, 251)}--`;
249
+ }
250
+
251
+ /** Trusted operator callbacks. No native private modules, startup, authentication, or global stores are used. */
252
+ export async function createNativeSessionRepairVerifier({ nativeManifestPath, nativeRequire, carrierExecutablePath, carrierProcessNames = ["DeepSeek Harness.exe", "DeepSeekHarness.exe", "dsh.exe", "deepseek-harness", "DeepSeek Harness", "dsh"] } = {}) {
253
+ try {
254
+ if (nativeManifestPath !== undefined) {
255
+ if (nativeRequire !== undefined || !isAbsolute(nativeManifestPath)) refuse("INVALID_NATIVE_RUNTIME");
256
+ const manifest = JSON.parse(await readFile(nativeManifestPath, "utf8"));
257
+ if (manifest.name !== "@deepseek-ai/dsh" || manifest.version !== PINNED_VERSION) refuse("INCOMPATIBLE_NATIVE_RUNTIME");
258
+ nativeRequire = createRequire(nativeManifestPath);
259
+ }
260
+ nativeRequire ??= createRequire(new URL("../package.json", import.meta.url));
261
+ if (typeof nativeRequire?.resolve !== "function") refuse("INVALID_NATIVE_RUNTIME");
262
+ for (const name of ["@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session"]) {
263
+ const manifest = JSON.parse(await readFile(nativeRequire.resolve(`${name}/package.json`), "utf8"));
264
+ if (manifest.version !== PINNED_VERSION) refuse("INCOMPATIBLE_NATIVE_RUNTIME");
265
+ }
266
+ const jsonlRequire = createRequire(nativeRequire.resolve("@deepseek-ai/dsh-session-persistence-jsonl/package.json"));
267
+ const [{ Context }, { default: JsonlSessionPersistence }, { Session, SessionId }, { currentSessionMessageProjections }] = await Promise.all([
268
+ import(pathToFileURL(nativeRequire.resolve("@deepseek-ai/cordis")).href),
269
+ import(pathToFileURL(nativeRequire.resolve("@deepseek-ai/dsh-session-persistence-jsonl")).href),
270
+ import(pathToFileURL(nativeRequire.resolve("@deepseek-ai/dsh-session")).href),
271
+ import(pathToFileURL(jsonlRequire.resolve("@deepseek-ai/dsh-session-format-catalog/message-projections")).href)
272
+ ]);
273
+ if (!Array.isArray(carrierProcessNames) || carrierProcessNames.some(name => typeof name !== "string" || !name)
274
+ || carrierExecutablePath !== undefined && (typeof carrierExecutablePath !== "string" || !isAbsolute(carrierExecutablePath))) refuse("INVALID_CARRIER_IDENTITY");
275
+ const names = [...new Set(["DeepSeek Harness.exe", "DeepSeekHarness.exe", "dsh.exe", "deepseek-harness", "DeepSeek Harness", "dsh", ...carrierProcessNames].map(name => name.toLowerCase()))];
276
+ const executable = carrierExecutablePath === undefined ? undefined : pathKey(carrierExecutablePath);
277
+ const leases = new Map();
278
+ const assertQuiescent = async () => {
279
+ if (process.platform === "win32") return probeWindows(QUIESCENCE_SCRIPT, { names, executable }, "CARRIER_ACTIVE");
280
+ if (process.platform !== "linux") refuse("QUIESCENCE_UNSUPPORTED");
281
+ for (const name of await readdir("/proc")) {
282
+ if (!/^\d+$/u.test(name)) continue;
283
+ let command;
284
+ let path;
285
+ try {
286
+ command = (await readFile(`/proc/${name}/comm`, "utf8")).trim().toLowerCase();
287
+ if (executable) path = await readlink(`/proc/${name}/exe`);
288
+ } catch (error) { if (error.code === "ENOENT" || error.code === "ESRCH") continue; throw error; }
289
+ if (names.includes(command) || executable && pathKey(path) === executable) refuse("CARRIER_ACTIVE");
290
+ }
291
+ return true;
292
+ };
293
+ return Object.freeze({
294
+ async acquireExclusiveWriterLease({ filePath, sourcePath = filePath, allowedRoot, expectedSha256 } = {}) {
295
+ let held;
296
+ try {
297
+ const path = await assertPlainPath(sourcePath, allowedRoot);
298
+ if (filePath !== undefined && pathKey(filePath) !== pathKey(path) || !/^[a-f0-9]{64}$/u.test(expectedSha256)) refuse("INVALID_INPUT");
299
+ if (leases.has(pathKey(path))) refuse("WRITER_ACTIVE");
300
+ held = process.platform === "win32" ? await acquireWindowsLease(join(dirname(path), "session.lock")) : await acquirePosixLease(join(dirname(path), "session.lock"), jsonlRequire);
301
+ if (digest(await snapshot(path)) !== expectedSha256) refuse("SOURCE_CHANGED");
302
+ let released = false;
303
+ const assertHeld = async () => { if (released) refuse("LEASE_LOST"); await held.assertHeld(); };
304
+ const lease = Object.freeze({
305
+ async assertQuiescent() { try { await assertHeld(); await assertQuiescent(); await assertHeld(); return true; } catch (error) { throw safeError(error, "QUIESCENCE_UNVERIFIED"); } },
306
+ async assertPrivateDirectory() { try { await assertHeld(); await assertPrivateDirectory(path); await assertHeld(); return true; } catch (error) { throw safeError(error, "DIRECTORY_NOT_PRIVATE"); } },
307
+ async release() { if (released) return; released = true; leases.delete(pathKey(path)); try { await held.release(); } catch (error) { throw safeError(error, "LEASE_RELEASE_FAILED"); } }
308
+ });
309
+ leases.set(pathKey(path), { lease, expectedSha256 });
310
+ return lease;
311
+ } catch (error) { await held?.release(); throw safeError(error, "LEASE_UNAVAILABLE"); }
312
+ },
313
+ async verifyCandidate({ candidatePath, originalPath, sourcePath, header, rows, events, expectedSha256, candidateSha256, encoding } = {}) {
314
+ let validationRoot;
315
+ let ctx;
316
+ let reader;
317
+ try {
318
+ const entry = typeof sourcePath === "string" ? leases.get(pathKey(sourcePath)) : undefined;
319
+ if (!entry || entry.expectedSha256 !== expectedSha256) refuse("LEASE_REQUIRED");
320
+ await entry.lease.assertQuiescent();
321
+ await entry.lease.assertPrivateDirectory();
322
+ if (![candidatePath, originalPath].every(path => typeof path === "string" && pathKey(dirname(path)) === pathKey(dirname(sourcePath)))) refuse("UNSAFE_PATH");
323
+ const original = await snapshot(originalPath);
324
+ const candidate = await snapshot(candidatePath);
325
+ if (digest(original) !== expectedSha256 || digest(candidate) !== candidateSha256) refuse("SOURCE_CHANGED");
326
+ const audit = auditSessionLog(original, { encoding });
327
+ const candidateAudit = auditSessionLog(candidate, { encoding });
328
+ if (!isDeepStrictEqual(audit.rows, rows) || !isDeepStrictEqual(audit.header, header) || !isDeepStrictEqual(audit.events, events)
329
+ || !isDeepStrictEqual(candidateAudit.rows, rows) || candidateAudit.changedEventCount !== 0 || audit.candidateSha256 !== candidateSha256) refuse("RECORD_EQUALITY_FAILED");
330
+ validationRoot = await mkdtemp(join(dirname(sourcePath), ".dsmm-native-verify-"));
331
+ if (process.platform === "win32") await probeWindows(PRIVATE_ROOT_SCRIPT, { directory: validationRoot }, "DIRECTORY_NOT_PRIVATE");
332
+ else await chmod(validationRoot, 0o700);
333
+ const path = join(validationRoot, projectKey(header.cwd), encodeSegment(header.id), `session.v${header.version}.jsonl${encoding === "zstd" ? ".zstd" : ""}`);
334
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
335
+ const target = await open(path, "wx", 0o600);
336
+ try { await target.writeFile(candidate); await target.sync(); } finally { await target.close(); }
337
+ ctx = new Context();
338
+ await ctx.plugin(JsonlSessionPersistence, { root: validationRoot, compression: encoding }).await();
339
+ reader = await ctx.sessionPersistence.open(SessionId(header.id), "read");
340
+ const read = await reader.read();
341
+ if (read.events.length !== events.length) refuse("NATIVE_PREFIX_MISMATCH");
342
+ for (const event of read.events) if (event.type === "deepwork/mode" || event.type === "dsmm/role-policy") {
343
+ if (!isDeepStrictEqual(event, events[event.seq])) refuse("NATIVE_METADATA_MISMATCH");
344
+ }
345
+ const restored = Session.fromRestore(reader.id, read.events, reader.header, reader.inheritedEventCount, read.eventState, currentSessionMessageProjections);
346
+ const baseline = structuredClone(read.events).map(event => {
347
+ if ((event.type === "deepwork/mode" || event.type === "dsmm/role-policy") && event.ignorable === true) delete event.ignorable;
348
+ return event;
349
+ });
350
+ const reference = Session.fromRestore(reader.id, baseline, structuredClone(reader.header), reader.inheritedEventCount, "detached", currentSessionMessageProjections);
351
+ if (!isDeepStrictEqual(restored.surface.nodes, reference.surface.nodes) || !isDeepStrictEqual(restored.deriveMessages(), reference.deriveMessages())) refuse("HISTORY_CHANGED");
352
+ if (digest(await snapshot(candidatePath)) !== candidateSha256 || digest(await snapshot(originalPath)) !== expectedSha256) refuse("SOURCE_CHANGED");
353
+ await entry.lease.assertQuiescent();
354
+ await entry.lease.assertPrivateDirectory();
355
+ return Object.freeze({ publicRead: true, restored: true, historyEqual: true });
356
+ } catch (error) { throw safeError(error, "NATIVE_VERIFICATION_FAILED"); }
357
+ finally {
358
+ try { try { await reader?.close(); } finally { await ctx?.fiber.dispose(); } }
359
+ catch { refuse("NATIVE_DISPOSAL_FAILED"); }
360
+ finally { if (validationRoot) await rm(validationRoot, { recursive: true, force: true }).catch(() => refuse("VALIDATION_CLEANUP_FAILED")); }
361
+ }
362
+ }
363
+ });
364
+ } catch (error) { throw safeError(error, "NATIVE_RUNTIME_UNAVAILABLE"); }
365
+ }
366
+
367
+ export default createNativeSessionRepairVerifier;