@verax-ai/body 0.8.0 → 0.8.1

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/dist/cli.js CHANGED
@@ -18,7 +18,7 @@ import { runOperator } from "./operator-cli.js";
18
18
  import { runAnchor } from "./anchor-cli.js";
19
19
  import { runReconcile } from "./reconcile-cli.js";
20
20
  import { runVerify } from "./verify-cli.js";
21
- import { runUnlock } from "./unlock.js";
21
+ import { clearStaleLockAtStart, runUnlock } from "./unlock.js";
22
22
  import { runWitness } from "./witness.js";
23
23
  import { runWatch } from "./watch.js";
24
24
  import { runMemoryRehead } from "./memory-rehead-cli.js";
@@ -28,8 +28,9 @@ const HELP = `verax - the body an agent asks before it acts, and the ledger it a
28
28
  Usage: verax <command> [options]
29
29
 
30
30
  (no command) serve MCP over Streamable HTTP at /mcp on VERAX_BIND (default 127.0.0.1:8787)
31
- serve [--env-file <file>] [--log-file <file>]
31
+ serve [--env-file <file>] [--log-file <file>] [--clear-stale-lock]
32
32
  same as serving, after loading KEY=VALUE lines from that file.
33
+ --clear-stale-lock does what verax unlock --force does first, for a service manager's start.
33
34
  --log-file appends this process's stdout and stderr
34
35
  init --local <stateDir> [--force] [--days N] [--port N] [--operator-door <origin>]
35
36
  write a loopback key, one agent token, and verax.env
@@ -284,6 +285,10 @@ async function dispatchCli(argv, stdout, stderr, env) {
284
285
  return 78;
285
286
  }
286
287
  }
288
+ const stateDir = process.env.VERAX_STATE_DIR;
289
+ if (argv.includes("--clear-stale-lock") && stateDir) {
290
+ clearStaleLockAtStart(stateDir, (s) => stderr.write(s));
291
+ }
287
292
  await main();
288
293
  // main() returns once the server is listening. The open socket keeps the
289
294
  // process up; this promise stops the rest of the dispatcher from running.
package/dist/install.d.ts CHANGED
@@ -227,6 +227,7 @@ export type PlanOp = {
227
227
  op: "mkdir";
228
228
  path: string;
229
229
  mode?: number;
230
+ existingOk?: boolean;
230
231
  } | {
231
232
  op: "argv";
232
233
  argv: string[];
package/dist/install.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
- import { accessSync, chmodSync, closeSync, constants, copyFileSync, existsSync, fchmodSync, fchownSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
3
+ import { accessSync, chmodSync, closeSync, constants, copyFileSync, existsSync, fchmodSync, fchownSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, rmdirSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
4
4
  import { get } from "node:http";
5
5
  import { createServer as createNetServer } from "node:net";
6
6
  import path from "node:path";
@@ -1837,12 +1837,6 @@ function windowsAccountBody(create, tempDir) {
1837
1837
  "$plain = [Console]::In.ReadLine()",
1838
1838
  "if ([string]::IsNullOrEmpty($plain)) { exit 1 }",
1839
1839
  "$sec = ConvertTo-SecureString -String $plain -AsPlainText -Force",
1840
- user,
1841
- "$sid = (Get-LocalUser -Name 'verax-svc').SID.Value",
1842
- "[Console]::Out.WriteLine(('VERAX_SVC_SID:' + $sid))",
1843
- "Remove-LocalGroupMember -SID 'S-1-5-32-545' -Member $sid -ErrorAction SilentlyContinue",
1844
- "Enable-LocalUser -Name 'verax-svc'",
1845
- "$star = '*' + $sid",
1846
1840
  "$secedit = Join-Path $env:SystemRoot 'System32\\secedit.exe'",
1847
1841
  `$cfg = ${cfg}`,
1848
1842
  `$db = ${db}`,
@@ -1852,11 +1846,22 @@ function windowsAccountBody(create, tempDir) {
1852
1846
  "$flat = [regex]::Replace($raw, '\\\\[ \\t]*\\r?\\n', '')",
1853
1847
  "$prev = @()",
1854
1848
  "if ($flat -match 'SeBatchLogonRight\\s*=\\s*([^\\r\\n]*)') { $prev = @($Matches[1].Split(',') | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }) }",
1849
+ // secedit drops a holder it cannot resolve from the right it is applying, and some Windows
1850
+ // display languages export names they cannot read back. Refuse before the account, its
1851
+ // password or any right has changed: the scheduled task still holds the old password here.
1852
+ "foreach ($h in $prev) { $n = $h.TrimStart('*').Trim(); if ($n -notmatch '^(?i)S-1-') { try { [void](New-Object System.Security.Principal.NTAccount($n)).Translate([System.Security.Principal.SecurityIdentifier]) } catch { throw ('SeBatchLogonRight holder ' + $n + ' cannot be resolved; nothing was changed') } } }",
1853
+ user,
1854
+ "$sid = (Get-LocalUser -Name 'verax-svc').SID.Value",
1855
+ "[Console]::Out.WriteLine(('VERAX_SVC_SID:' + $sid))",
1856
+ "Remove-LocalGroupMember -SID 'S-1-5-32-545' -Member $sid -ErrorAction SilentlyContinue",
1857
+ "Enable-LocalUser -Name 'verax-svc'",
1858
+ "$star = '*' + $sid",
1855
1859
  "$want = [System.Collections.Generic.List[string]]::new()",
1856
1860
  "foreach ($h in $prev) { $want.Add($h) }",
1857
1861
  "if (-not ($want -contains $star)) { $want.Add($star) }",
1858
1862
  "$line = 'SeBatchLogonRight = ' + ($want -join ',')",
1859
- "if ($flat -match 'SeBatchLogonRight\\s*=') { $edited = [regex]::Replace($flat, 'SeBatchLogonRight\\s*=\\s*[^\\r\\n]*', $line, 1) } else { $edited = $flat.TrimEnd() + \"`r`n\" + $line + \"`r`n\" }",
1863
+ // The template names this right alone, so secedit cannot change any other right.
1864
+ "$edited = @('[Unicode]', 'Unicode=yes', '[Version]', 'signature=\"$CHICAGO$\"', 'Revision=1', '[Privilege Rights]', $line, '') -join \"`r`n\"",
1860
1865
  "[IO.File]::WriteAllText($cfg, $edited, [Text.Encoding]::Unicode)",
1861
1866
  psNative("& $secedit /configure /db $db /cfg $cfg /areas USER_RIGHTS | Out-Null", "secedit"),
1862
1867
  psNative("& $secedit /export /cfg $after /areas USER_RIGHTS | Out-Null", "secedit"),
@@ -1876,7 +1881,7 @@ function windowsAccountOps(password, create, tempDir) {
1876
1881
  return [powershellStdin(windowsAccountBody(create, tempDir), password, tempDir)];
1877
1882
  }
1878
1883
  function windowsTaskBody(nodeBin, cliBin, envFile, logFile) {
1879
- const argument = `"${cliBin}" serve --env-file "${envFile}" --log-file "${logFile}"`;
1884
+ const argument = `"${cliBin}" serve --env-file "${envFile}" --log-file "${logFile}" --clear-stale-lock`;
1880
1885
  return [
1881
1886
  psModuleImports([
1882
1887
  "ScheduledTasks",
@@ -1887,9 +1892,12 @@ function windowsTaskBody(nodeBin, cliBin, envFile, logFile) {
1887
1892
  "if ([string]::IsNullOrEmpty($plain)) { exit 1 }",
1888
1893
  `$action = New-ScheduledTaskAction -Execute ${psSingle(nodeBin)} -Argument ${psSingle(argument)}`,
1889
1894
  "$trigger = New-ScheduledTaskTrigger -AtStartup",
1890
- "$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1)",
1895
+ // -RestartCount does not cover a running process that dies. A start while one runs is ignored.
1896
+ "$watch = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 5)",
1897
+ // Without these the task is stopped after three days and on battery, and does not start on battery.
1898
+ "$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
1891
1899
  "$sid = (Get-LocalUser -Name 'verax-svc').SID.Value",
1892
- "Register-ScheduledTask -TaskName 'Verax Body' -Action $action -Trigger $trigger -User $sid -Password $plain -RunLevel Limited -Settings $settings -Force",
1900
+ "Register-ScheduledTask -TaskName 'Verax Body' -Action $action -Trigger @($trigger, $watch) -User $sid -Password $plain -RunLevel Limited -Settings $settings -Force",
1893
1901
  "Start-ScheduledTask -TaskName 'Verax Body'",
1894
1902
  ].join("; ");
1895
1903
  }
@@ -1908,6 +1916,8 @@ function directoryOwnerSidCommand(dir) {
1908
1916
  const literal = dir.replaceAll("'", "''");
1909
1917
  return psPrefixed(["Microsoft.PowerShell.Security"], `(Get-Acl -LiteralPath '${literal}').GetOwner([System.Security.Principal.SecurityIdentifier]).Value`);
1910
1918
  }
1919
+ /** Prints `missing` only for ERROR_FILE_NOT_FOUND (0x80070002). Access denied is 0x80070005 and stays an error. */
1920
+ const WINDOWS_TASK_LOOKUP_COMMAND = `$c = New-Object -ComObject Schedule.Service; $c.Connect(); try { [void]$c.GetFolder('\\').GetTask('${TASK_NAME}') } catch { if ($_.Exception.HResult -eq -2147024894) { [Console]::Out.Write('missing') } else { throw } }`;
1911
1921
  const WINDOWS_SERVICE_SID_COMMAND = psPrefixed(["Microsoft.PowerShell.LocalAccounts"], "(Get-LocalUser -Name 'verax-svc').SID.Value");
1912
1922
  function profileImagePathCommand(sid) {
1913
1923
  return psPrefixed(["Microsoft.PowerShell.Management"], `(Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\${sid}').ProfileImagePath`);
@@ -1929,6 +1939,7 @@ export function windowsPowerShellScripts() {
1929
1939
  { id: "directory-owner-sid", script: directoryOwnerSidCommand("C:\\ProgramData\\Verax") },
1930
1940
  { id: "file-owner", script: fileOwnerSidCommand("C:\\ProgramData\\Verax\\state\\keys\\record.private.pem") },
1931
1941
  { id: "service-sid", script: WINDOWS_SERVICE_SID_COMMAND },
1942
+ { id: "task-lookup", script: WINDOWS_TASK_LOOKUP_COMMAND },
1932
1943
  { id: "profile-image-path", script: profileImagePathCommand("S-1-5-21-1001") },
1933
1944
  { id: "account-create", script: powerShellScript(windowsAccountBody(true, temp)) },
1934
1945
  { id: "account-update", script: powerShellScript(windowsAccountBody(false, temp)) },
@@ -1942,7 +1953,7 @@ function xmlEscape(value) {
1942
1953
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1943
1954
  }
1944
1955
  function plistText(nodeBin, cliBin, envFile, errFile, logFile) {
1945
- const args = [nodeBin, cliBin, "serve", "--env-file", envFile, "--log-file", logFile].map((part) => ` <string>${xmlEscape(part)}</string>`);
1956
+ const args = [nodeBin, cliBin, "serve", "--env-file", envFile, "--log-file", logFile, "--clear-stale-lock"].map((part) => ` <string>${xmlEscape(part)}</string>`);
1946
1957
  return [
1947
1958
  '<?xml version="1.0" encoding="UTF-8"?>',
1948
1959
  '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
@@ -2076,7 +2087,7 @@ function unitText(nodeBin, cliBin, envFile, stateDir, logFile) {
2076
2087
  "[Service]",
2077
2088
  "Type=simple",
2078
2089
  "User=verax",
2079
- `ExecStart=${nodeBin} ${cliBin} serve --env-file ${envFile} --log-file ${logFile}`,
2090
+ `ExecStart=${nodeBin} ${cliBin} serve --env-file ${envFile} --log-file ${logFile} --clear-stale-lock`,
2080
2091
  "NoNewPrivileges=yes",
2081
2092
  "ProtectSystem=strict",
2082
2093
  `ReadWritePaths=${stateDir}`,
@@ -2356,7 +2367,7 @@ export function planInstall(platform, env, opts) {
2356
2367
  if (platform === "darwin") {
2357
2368
  ops.push({ op: "mkdir", path: fixed.darwinStateParent, mode: 0o755 }, { op: "argv", argv: toolArgv("chown", ["root:wheel", fixed.darwinStateParent], "darwin") }, { op: "argv", argv: toolArgv("chmod", ["0755", fixed.darwinStateParent], "darwin") });
2358
2369
  }
2359
- ops.push({ op: "mkdir", path: paths.stateDir, mode: 0o700 });
2370
+ ops.push({ op: "mkdir", path: paths.stateDir, mode: 0o700, ...(opts.force && opts.stateExists ? { existingOk: true } : {}) });
2360
2371
  if (platform === "win32") {
2361
2372
  const markerPath = path.win32.join(path.win32.dirname(paths.stateDir), "install.json");
2362
2373
  const marker = installMarkerText(opts, paths, { createdAccount: true });
@@ -2412,7 +2423,8 @@ export function planInstall(platform, env, opts) {
2412
2423
  }
2413
2424
  const tokenDir = path.win32.dirname(paths.tokenPath);
2414
2425
  const tokenRoot = path.win32.dirname(tokenDir);
2415
- ops.push({ op: "mkdir", path: tokenRoot, mode: 0o755 }, setOwner(tokenRoot), adminOnlyDirGrant(tokenRoot), resetInherit(tokenRoot), { op: "mkdir", path: tokenDir, mode: 0o755 }, setOwner(tokenDir), tokenUserDirGrant(tokenDir, tokenWho.principal), resetInherit(tokenDir));
2426
+ // Both sit under the locked Verax root and are locked again here. Uninstall leaves the root.
2427
+ ops.push({ op: "mkdir", path: tokenRoot, mode: 0o755, existingOk: true }, setOwner(tokenRoot), adminOnlyDirGrant(tokenRoot), resetInherit(tokenRoot), { op: "mkdir", path: tokenDir, mode: 0o755, existingOk: true }, setOwner(tokenDir), tokenUserDirGrant(tokenDir, tokenWho.principal), resetInherit(tokenDir));
2416
2428
  }
2417
2429
  else {
2418
2430
  const ids = invokingIdsOf(env, opts);
@@ -3750,7 +3762,7 @@ function removeEmptyDirs(dirs) {
3750
3762
  for (const dir of [...dirs].reverse()) {
3751
3763
  try {
3752
3764
  if (readdirSync(dir).length === 0)
3753
- rmSync(dir, { recursive: false, force: true });
3765
+ rmdirSync(dir);
3754
3766
  }
3755
3767
  catch {
3756
3768
  // Already gone, or not empty because a later step wrote there.
@@ -4198,7 +4210,7 @@ async function execute(plan, exec, io, platform, copyFile = copyFileSync, instal
4198
4210
  }
4199
4211
  if (step.op === "mkdir") {
4200
4212
  const existed = existsSync(step.path);
4201
- mkdirLeaf(step.path, step.mode ?? 0o755);
4213
+ mkdirLeaf(step.path, step.mode ?? 0o755, { existingOk: step.existingOk === true });
4202
4214
  if (!existed && step.path === plan.codeDir)
4203
4215
  created.codeDir = true;
4204
4216
  if (!existed && step.path === plan.stateDir)
@@ -4215,6 +4227,8 @@ async function execute(plan, exec, io, platform, copyFile = copyFileSync, instal
4215
4227
  io.stderr.write(applied.error.endsWith("\n") ? applied.error : `${applied.error}\n`);
4216
4228
  return finish(EX_CONFIG);
4217
4229
  }
4230
+ if (step.create)
4231
+ createdParents.push(step.path);
4218
4232
  continue;
4219
4233
  }
4220
4234
  if (step.op === "argv") {
@@ -4227,6 +4241,9 @@ async function execute(plan, exec, io, platform, copyFile = copyFileSync, instal
4227
4241
  if (powershellScriptStep(resolved, step.stdin)) {
4228
4242
  const failed = (ran.status ?? 1) !== 0 || stderrHasErrorMark(ran.stderr ?? "");
4229
4243
  if (failed && !step.optional) {
4244
+ // The script prints the SID only after New-LocalUser succeeded, so a later failure leaves the account.
4245
+ if (/VERAX_SVC_SID:S-1-/i.test(ran.stdout ?? ""))
4246
+ rememberCreatedAccount(created, resolved);
4230
4247
  if (step.rollbackDir)
4231
4248
  rmSync(step.rollbackDir, { recursive: true, force: true });
4232
4249
  const detail = redactSecrets(ran.stderr ?? "", step.argv, step.stdin).trim();
@@ -5583,16 +5600,26 @@ async function runInstallBody(argv, hooks = {}) {
5583
5600
  io.stderr.write(plan.message);
5584
5601
  return plan.code;
5585
5602
  }
5603
+ // Refused here, not at its mkdir: by then the account step has changed a password the task still holds.
5604
+ if (existsSync(plan.codeDir)) {
5605
+ io.stderr.write(`refusing: ${plan.codeDir} already exists. To upgrade, run verax uninstall --keep-state first\n`);
5606
+ return EX_CONFIG;
5607
+ }
5586
5608
  return execute(plan, exec, io, platform, hooks.copyFile ?? copyFileSync, plannedEnv, hooks.healthTimeoutMs, hooks.spawnUserToken);
5587
5609
  }
5588
- /** A non-zero tool result that means the install artifact is already gone. */
5610
+ /** A non-zero tool result that means the install artifact is already gone. `net` prints this number in every language. */
5589
5611
  function toolAlreadyAbsent(ran) {
5590
5612
  if ((ran.status ?? 1) === 0)
5591
5613
  return false;
5592
5614
  const text = `${ran.stdout ?? ""}\n${ran.stderr ?? ""}`.toLowerCase();
5593
5615
  if (text.trim() === "")
5594
5616
  return true;
5595
- return /cannot find the file specified|does not exist|could not be found|could not find|no such file|not found|not loaded|isn't loaded|is not loaded/.test(text);
5617
+ return /cannot find the file specified|does not exist|could not be found|could not find|no such file|not found|not loaded|isn't loaded|is not loaded|helpmsg 2221/.test(text);
5618
+ }
5619
+ /** schtasks says "not found" in the display language. The scheduler's own error number is the same in all of them. */
5620
+ function windowsTaskMissing(exec) {
5621
+ const ran = exec(toolArgv("powershell", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_TASK_LOOKUP_COMMAND], "win32"));
5622
+ return (ran.status ?? 1) === 0 && (ran.stdout ?? "").trim() === "missing";
5596
5623
  }
5597
5624
  /** userdel, groupdel, `net user /delete`, and `dscl -delete`. Empty output is not absence. */
5598
5625
  function isAccountDeleteArgv(argv) {
@@ -5826,11 +5853,14 @@ function executeUninstall(platform, plan, exec, io, opts) {
5826
5853
  if (platform === "win32") {
5827
5854
  const queryArgv = toolArgv("schtasks", ["/Query", "/TN", TASK_NAME], "win32");
5828
5855
  const query = exec(queryArgv);
5829
- if ((query.status ?? 1) !== 0 && !toolAlreadyAbsent(query)) {
5856
+ const absent = toolAlreadyAbsent(query) || (query.status === 1 && windowsTaskMissing(exec));
5857
+ if ((query.status ?? 1) !== 0 && !absent) {
5830
5858
  reportToolFailure(io, queryArgv, query);
5831
5859
  return query.status ?? 1;
5832
5860
  }
5833
5861
  const failed = note(query.status === 0, `scheduled task ${TASK_NAME}`, () => {
5862
+ // First, or the repeating trigger could start an instance between /End and /Delete, which /Delete leaves running.
5863
+ exec(toolArgv("schtasks", ["/Change", "/TN", TASK_NAME, "/DISABLE"], "win32"));
5834
5864
  const end = runUninstallTool(exec, io, toolArgv("schtasks", ["/End", "/TN", TASK_NAME], "win32"));
5835
5865
  if (end !== null)
5836
5866
  return end;
@@ -6112,7 +6142,7 @@ export async function runUninstall(argv, hooks = {}) {
6112
6142
  const userSid = platform === "win32" ? invokingSid(exec) : undefined;
6113
6143
  const plan = planUninstall(platform, plannedEnv, {
6114
6144
  keepState: parsed.keepState,
6115
- removeWinAccount: flags.createdAccount,
6145
+ removeWinAccount: flags.createdAccount && !parsed.keepState,
6116
6146
  removeDarwinUser: flags.createdUser,
6117
6147
  removeDarwinGroup: flags.createdGroup,
6118
6148
  removeLinuxUser: flags.createdUser,
@@ -6127,7 +6157,7 @@ export async function runUninstall(argv, hooks = {}) {
6127
6157
  }
6128
6158
  return executeUninstall(platform, plan, exec, io, {
6129
6159
  keepState: parsed.keepState,
6130
- removeWinAccount: flags.createdAccount,
6160
+ removeWinAccount: flags.createdAccount && !parsed.keepState,
6131
6161
  removeDarwinUser: flags.createdUser,
6132
6162
  removeDarwinGroup: flags.createdGroup,
6133
6163
  removeLinuxUser: flags.createdUser,
@@ -6184,21 +6214,29 @@ export function liveInstalledChecks(platform = process.platform, env = process.e
6184
6214
  const codeAcl = { stdout: textOf(codeDir), stderr: "" };
6185
6215
  const rootAcl = { stdout: textOf(rootDir), stderr: "" };
6186
6216
  const marker = path.win32.join(rootDir, "install.json");
6187
- return installedBoundaryChecks({
6188
- codeDir,
6189
- stateDir,
6190
- manifest,
6191
- hashOf: (rel) => hashUnder(codeDir, rel),
6192
- aclText: `${acl.stdout ?? ""}\n${acl.stderr ?? ""}`,
6193
- codeAclText: `${codeAcl.stdout ?? ""}\n${codeAcl.stderr ?? ""}`,
6194
- fileAcls,
6195
- winOwners: { state: ownerOf(stateDir), code: ownerOf(codeDir) },
6196
- rootDir,
6197
- rootAclText: `${rootAcl.stdout ?? ""}\n${rootAcl.stderr ?? ""}`,
6198
- markerPresent: ourMarker(marker),
6199
- installSource: markerSource(marker),
6200
- autostart: task.status === 0,
6201
- });
6217
+ // The SID the install recorded, so a replaced account with the same name is not trusted.
6218
+ const recordedSid = markerFlags(marker).accountSid;
6219
+ const liveSid = windowsServiceSid(exec);
6220
+ const svcSid = recordedSid ?? liveSid;
6221
+ const accountChecks = recordedSid !== undefined && liveSid !== recordedSid
6222
+ ? [{ id: "install-account", level: "fail", detail: `${VERAX_SVC} is ${liveSid ?? "missing or could not be read"}; the install recorded ${recordedSid}` }]
6223
+ : [];
6224
+ return [...accountChecks, ...installedBoundaryChecks({
6225
+ codeDir,
6226
+ stateDir,
6227
+ manifest,
6228
+ hashOf: (rel) => hashUnder(codeDir, rel),
6229
+ aclText: `${acl.stdout ?? ""}\n${acl.stderr ?? ""}`,
6230
+ codeAclText: `${codeAcl.stdout ?? ""}\n${codeAcl.stderr ?? ""}`,
6231
+ fileAcls,
6232
+ ...(svcSid ? { svcSid } : {}),
6233
+ winOwners: { state: ownerOf(stateDir), code: ownerOf(codeDir) },
6234
+ rootDir,
6235
+ rootAclText: `${rootAcl.stdout ?? ""}\n${rootAcl.stderr ?? ""}`,
6236
+ markerPresent: ourMarker(marker),
6237
+ installSource: markerSource(marker),
6238
+ autostart: task.status === 0,
6239
+ })];
6202
6240
  }
6203
6241
  if (platform === "darwin") {
6204
6242
  const statName = (flag, dir) => (exec(toolArgv("stat", ["-f", flag, dir], "darwin")).stdout ?? "").trim();
package/dist/unlock.d.ts CHANGED
@@ -12,4 +12,13 @@ export declare function readLockFile(path: string): LockRecord | null;
12
12
  export declare function runUnlock(stateDir: string, writeErr?: (s: string) => void, options?: {
13
13
  force?: boolean;
14
14
  unlink?: (path: string) => void;
15
+ afterJudge?: () => void;
16
+ beforeMove?: () => void;
15
17
  }): number;
18
+ /**
19
+ * For a service manager's start, where nobody is there to run `verax unlock`. Clears what
20
+ * `verax unlock --force` would clear, with the same record: the manager runs one instance, so a
21
+ * lock that does not move has no running owner, and on Windows a reboot can hand its pid to
22
+ * another process. A lock that moves stays, and the ledger refuses it as before.
23
+ */
24
+ export declare function clearStaleLockAtStart(stateDir: string, writeErr: (s: string) => void): void;
package/dist/unlock.js CHANGED
@@ -1,4 +1,5 @@
1
- import { appendFileSync, existsSync, readFileSync, unlinkSync } from "node:fs";
1
+ import { randomUUID } from "node:crypto";
2
+ import { appendFileSync, existsSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
2
3
  import { userInfo } from "node:os";
3
4
  import { join } from "node:path";
4
5
  import { lockBeatOf, lockState } from "@verax-ai/proxy";
@@ -53,12 +54,37 @@ function appendUnlockRow(stateDir, row) {
53
54
  encoding: "utf8",
54
55
  });
55
56
  }
57
+ function lockText(path) {
58
+ try {
59
+ return readFileSync(path, "utf8");
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ }
65
+ /** Puts a lock moved aside back, unless a newer one took its place. Its holder then finds the lock lost and stops. */
66
+ function restoreLock(claim, lockPath) {
67
+ const text = lockText(claim);
68
+ try {
69
+ if (text !== null)
70
+ writeFileSync(lockPath, text, { encoding: "utf8", flag: "wx", mode: 0o600 });
71
+ }
72
+ catch {
73
+ // A newer lock is in place.
74
+ }
75
+ rmSync(claim, { force: true });
76
+ }
56
77
  export function runUnlock(stateDir, writeErr = (s) => process.stderr.write(s), options = {}) {
57
78
  const lockPath = join(stateDir, "ledger.lock");
58
79
  if (!existsSync(lockPath)) {
59
80
  writeErr("no-lock\n");
60
81
  return 1;
61
82
  }
83
+ const judged = lockText(lockPath);
84
+ if (judged === null) {
85
+ writeErr(existsSync(lockPath) ? "lock-unreadable\n" : "no-lock\n");
86
+ return 1;
87
+ }
62
88
  const existing = readLockFile(lockPath);
63
89
  let forcedQuiet = false;
64
90
  if (!existing) {
@@ -106,26 +132,48 @@ export function runUnlock(stateDir, writeErr = (s) => process.stderr.write(s), o
106
132
  writeErr(`record-failed:${errnoCode(err)}\n`);
107
133
  return 1;
108
134
  }
109
- const unlink = options.unlink ?? unlinkSync;
110
- try {
111
- unlink(lockPath);
112
- }
113
- catch (err) {
114
- const code = errnoCode(err);
135
+ const refuse = (result, line, error) => {
115
136
  try {
116
- appendUnlockRow(stateDir, {
117
- atMs: Date.now(),
118
- ...base,
119
- result: "unlink-failed",
120
- error: code,
121
- });
137
+ appendUnlockRow(stateDir, { atMs: Date.now(), ...base, result, ...(error ? { error } : {}) });
122
138
  }
123
139
  catch (recordErr) {
124
140
  writeErr(`record-failed:${errnoCode(recordErr)}\n`);
125
141
  return 1;
126
142
  }
127
- writeErr(`unlink-failed:${code}\n`);
143
+ writeErr(line);
128
144
  return 1;
145
+ };
146
+ options.afterJudge?.();
147
+ // Judging can take five beats, and another start may have cleared this lock and taken its own
148
+ // meanwhile. A lock that already differs is not touched. Moved aside first, the lock is removed
149
+ // only if it is still the one that was judged.
150
+ if (!existsSync(lockPath))
151
+ return refuse("already-gone", "no-lock\n");
152
+ if (lockText(lockPath) !== judged)
153
+ return refuse("lock-changed", "lock-changed\n");
154
+ options.beforeMove?.();
155
+ const claim = `${lockPath}.${randomUUID()}`;
156
+ try {
157
+ renameSync(lockPath, claim);
158
+ }
159
+ catch (err) {
160
+ const code = errnoCode(err);
161
+ if (code === "ENOENT")
162
+ return refuse("already-gone", "no-lock\n");
163
+ return refuse("unlink-failed", `unlink-failed:${code}\n`, code);
164
+ }
165
+ if (lockText(claim) !== judged) {
166
+ restoreLock(claim, lockPath);
167
+ return refuse("lock-changed", "lock-changed\n");
168
+ }
169
+ const unlink = options.unlink ?? unlinkSync;
170
+ try {
171
+ unlink(claim);
172
+ }
173
+ catch (err) {
174
+ const code = errnoCode(err);
175
+ restoreLock(claim, lockPath);
176
+ return refuse("unlink-failed", `unlink-failed:${code}\n`, code);
129
177
  }
130
178
  try {
131
179
  appendUnlockRow(stateDir, { atMs: Date.now(), ...base, result: "removed" });
@@ -136,3 +184,13 @@ export function runUnlock(stateDir, writeErr = (s) => process.stderr.write(s), o
136
184
  }
137
185
  return 0;
138
186
  }
187
+ /**
188
+ * For a service manager's start, where nobody is there to run `verax unlock`. Clears what
189
+ * `verax unlock --force` would clear, with the same record: the manager runs one instance, so a
190
+ * lock that does not move has no running owner, and on Windows a reboot can hand its pid to
191
+ * another process. A lock that moves stays, and the ledger refuses it as before.
192
+ */
193
+ export function clearStaleLockAtStart(stateDir, writeErr) {
194
+ if (existsSync(join(stateDir, "ledger.lock")))
195
+ runUnlock(stateDir, writeErr, { force: true });
196
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verax-ai/body",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "engines": {
@@ -26,8 +26,8 @@
26
26
  "@cedulon/cose": "0.13.1",
27
27
  "@cedulon/effect-extract": "0.13.1",
28
28
  "@modelcontextprotocol/sdk": "^1.30.0",
29
- "@verax-ai/inventory": "^0.8.0",
30
- "@verax-ai/proxy": "^0.8.0",
29
+ "@verax-ai/inventory": "^0.8.1",
30
+ "@verax-ai/proxy": "^0.8.1",
31
31
  "jose": "^6.2.12"
32
32
  },
33
33
  "description": "VERAX body: an MCP server that decides, records and proves what an agent did.",