@north-light/cli 0.3.755 → 0.3.757

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 (138) hide show
  1. package/dist/api/client.d.ts +1 -2
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/health.d.ts +0 -54
  6. package/dist/api/routes.d.ts +0 -1
  7. package/dist/api/routes.js +1 -1
  8. package/dist/build-root.d.ts +0 -3
  9. package/dist/build-root.js +1 -1
  10. package/dist/builtin-memory/internal/storage-tiers.md +3 -3
  11. package/dist/cli.js +8 -9
  12. package/dist/clients/attach/viewer.js +474 -474
  13. package/dist/commands/profile/new.js +1 -1
  14. package/dist/commands/profile/project.js +1 -1
  15. package/dist/commands/sys/branch.js +1 -1
  16. package/dist/commands/sys/daemon.js +1 -1
  17. package/dist/commands/sys.js +1 -1
  18. package/dist/core/bootstrap.js +1 -1
  19. package/dist/core/canvas/boot.d.ts +0 -25
  20. package/dist/core/canvas/boot.js +1 -1
  21. package/dist/core/canvas/executions.d.ts +0 -3
  22. package/dist/core/canvas/executions.js +1 -1
  23. package/dist/core/canvas/pid.d.ts +0 -10
  24. package/dist/core/canvas/pid.js +5 -5
  25. package/dist/core/directory/join.js +1 -1
  26. package/dist/core/grants/mirror.d.ts +0 -5
  27. package/dist/core/grants/mirror.js +6 -6
  28. package/dist/core/grants/sync.js +1 -1
  29. package/dist/core/human/page-schema.d.ts +1 -1
  30. package/dist/core/io.js +4 -4
  31. package/dist/core/layout.d.ts +0 -2
  32. package/dist/core/layout.js +2 -2
  33. package/dist/core/profiles/manifest.js +1 -1
  34. package/dist/core/profiles/project-dir.d.ts +3 -0
  35. package/dist/core/profiles/project-dir.js +1 -0
  36. package/dist/core/scoped-state/db.js +2 -2
  37. package/dist/daemon/api/handlers/daemon.js +1 -1
  38. package/dist/daemon/api/handlers/profiles.js +1 -1
  39. package/dist/daemon/api/map.d.ts +1 -6
  40. package/dist/daemon/api/map.js +2 -2
  41. package/dist/daemon/api/operations.js +1 -1
  42. package/dist/daemon/api/server.js +1 -1
  43. package/dist/daemon/control.d.ts +0 -8
  44. package/dist/daemon/crtrd.js +18 -20
  45. package/dist/daemon/manage.js +3 -3
  46. package/package.json +3 -3
  47. package/packages/crouter-api/dist/api/client.js +0 -3
  48. package/packages/crouter-api/dist/api/contract.js +1 -1
  49. package/packages/crouter-api/dist/api/routes.js +0 -1
  50. package/packages/crouter-api/dist/build-root.js +0 -9
  51. package/packages/crouter-api/dist/commands/profile/new.js +2 -2
  52. package/packages/crouter-api/dist/commands/profile/project.js +2 -1
  53. package/packages/crouter-api/dist/commands/sys/branch.js +1 -1
  54. package/packages/crouter-api/dist/commands/sys/daemon.js +1 -1
  55. package/packages/crouter-api/dist/commands/sys.js +1 -2
  56. package/packages/crouter-api/dist/core/canvas/executions.js +1 -17
  57. package/packages/crouter-api/dist/core/canvas/pid.js +0 -16
  58. package/packages/crouter-api/dist/core/directory/join.js +18 -1
  59. package/packages/crouter-api/dist/core/grants/mirror.js +0 -7
  60. package/packages/crouter-api/dist/core/grants/sync.js +2 -2
  61. package/packages/crouter-api/dist/core/io.js +0 -5
  62. package/packages/crouter-api/dist/core/layout.js +2 -19
  63. package/packages/crouter-api/dist/core/profiles/manifest.js +12 -18
  64. package/packages/crouter-api/dist/core/profiles/project-dir.js +20 -0
  65. package/packages/crouter-api/dist/daemon/api/map.js +0 -16
  66. package/packages/crouter-api/dist/daemon/api/operations.js +0 -1
  67. package/packages/crouter-api/dist/daemon/manage.js +1 -1
  68. package/packages/crouter-api/package.json +1 -1
  69. package/packages/crouter-identity/package.json +1 -1
  70. package/packages/crouter-plugin/package.json +3 -3
  71. package/runtime.lock.json +14 -14
  72. package/scripts/install-runtime.mjs +1 -30
  73. package/dist/commands/sys/migrate.d.ts +0 -1
  74. package/dist/commands/sys/migrate.js +0 -1
  75. package/dist/core/canvas/import-sqlite.d.ts +0 -46
  76. package/dist/core/canvas/import-sqlite.js +0 -19
  77. package/dist/core/canvas/migrations.d.ts +0 -16
  78. package/dist/core/canvas/migrations.js +0 -1073
  79. package/dist/core/feed/inbox-migrate.d.ts +0 -11
  80. package/dist/core/feed/inbox-migrate.js +0 -3
  81. package/dist/core/graph/bodies-boot-copy.d.ts +0 -28
  82. package/dist/core/graph/bodies-boot-copy.js +0 -1
  83. package/dist/core/layout-migrate/index.d.ts +0 -38
  84. package/dist/core/layout-migrate/index.js +0 -4
  85. package/dist/core/layout-migrate/loose-keys.d.ts +0 -2
  86. package/dist/core/layout-migrate/loose-keys.js +0 -1
  87. package/dist/core/layout-migrate/paths.d.ts +0 -30
  88. package/dist/core/layout-migrate/paths.js +0 -1
  89. package/dist/core/layout-migrate/stored-paths.d.ts +0 -9
  90. package/dist/core/layout-migrate/stored-paths.js +0 -11
  91. package/dist/core/layout-migrate/stores.d.ts +0 -30
  92. package/dist/core/layout-migrate/stores.js +0 -3
  93. package/dist/core/scoped-state/migrate.d.ts +0 -15
  94. package/dist/core/scoped-state/migrate.js +0 -3
  95. package/dist/daemon/boot-migrations.d.ts +0 -14
  96. package/dist/daemon/boot-migrations.js +0 -1
  97. package/dist/migrations/004-canvas-documents/apply.d.ts +0 -8
  98. package/dist/migrations/004-canvas-documents/apply.js +0 -1
  99. package/dist/migrations/004-canvas-documents/index.d.ts +0 -16
  100. package/dist/migrations/004-canvas-documents/index.js +0 -2
  101. package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +0 -16
  102. package/dist/migrations/004-canvas-documents/legacy/discover.js +0 -1
  103. package/dist/migrations/004-canvas-documents/legacy/history.d.ts +0 -5
  104. package/dist/migrations/004-canvas-documents/legacy/history.js +0 -2
  105. package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +0 -7
  106. package/dist/migrations/004-canvas-documents/legacy/nested.js +0 -1
  107. package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +0 -14
  108. package/dist/migrations/004-canvas-documents/legacy/parse.js +0 -1
  109. package/dist/migrations/004-canvas-documents/legacy/types.d.ts +0 -91
  110. package/dist/migrations/004-canvas-documents/legacy/types.js +0 -0
  111. package/dist/migrations/004-canvas-documents/legacy-edges.d.ts +0 -6
  112. package/dist/migrations/004-canvas-documents/legacy-edges.js +0 -18
  113. package/dist/migrations/004-canvas-documents/plan.d.ts +0 -102
  114. package/dist/migrations/004-canvas-documents/plan.js +0 -3
  115. package/dist/migrations/004-canvas-documents/pointers.d.ts +0 -23
  116. package/dist/migrations/004-canvas-documents/pointers.js +0 -4
  117. package/dist/migrations/activation.d.ts +0 -17
  118. package/dist/migrations/activation.js +0 -2
  119. package/packages/crouter-api/dist/commands/sys/migrate.js +0 -79
  120. package/packages/crouter-api/dist/core/layout-migrate/index.js +0 -523
  121. package/packages/crouter-api/dist/core/layout-migrate/paths.js +0 -118
  122. package/packages/crouter-api/dist/core/layout-migrate/stored-paths.js +0 -424
  123. package/packages/crouter-api/dist/core/layout-migrate/stores.js +0 -543
  124. package/packages/crouter-api/dist/core/locked-file.js +0 -121
  125. package/packages/crouter-api/dist/core/scoped-state/db.js +0 -271
  126. package/packages/crouter-api/dist/core/scoped-state/legacy-profiles.js +0 -65
  127. package/packages/crouter-api/dist/core/scoped-state/migrate.js +0 -332
  128. package/packages/crouter-api/dist/core/scoped-state/schema.js +0 -52
  129. package/packages/crouter-api/dist/migrations/004-canvas-documents/apply.js +0 -113
  130. package/packages/crouter-api/dist/migrations/004-canvas-documents/index.js +0 -89
  131. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/discover.js +0 -251
  132. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/history.js +0 -37
  133. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/nested.js +0 -37
  134. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/parse.js +0 -24
  135. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/types.js +0 -3
  136. package/packages/crouter-api/dist/migrations/004-canvas-documents/plan.js +0 -410
  137. package/packages/crouter-api/dist/migrations/004-canvas-documents/pointers.js +0 -95
  138. package/packages/crouter-api/dist/migrations/activation.js +0 -46
@@ -1,21 +1,19 @@
1
- var lr=Object.defineProperty;var s=(e,c)=>lr(e,"name",{value:c,configurable:!0});import{applyBootSettings as cr}from"./boot-settings.js";import{startBrokerMemoryCap as dr}from"./broker-memory-cap.js";import{startPeerOutbox as pr}from"./peer/outbox.js";import{reportMachineStatus as mr}from"../core/peer/directory.js";import{createPeerRelay as fr}from"./peer/relay-service.js";import{writeFileSync as ur,readFileSync as hr,rmSync as wr,mkdirSync as Pe,existsSync as E,unlinkSync as Ie,chmodSync as xe}from"node:fs";import{createServer as Y}from"node:http";import{dirname as vr}from"node:path";import{envCrtrdTcp as Te}from"../shared/env.js";import{openCanvasConversationStore as gr,serveCanvasConversationStore as yr}from"../core/canvas/sessions.js";import{installConversationStore as Sr}from"../core/conversation-store/index.js";import{pollRunObservers as _r}from"./runs/observer.js";import{randomBytes as De}from"node:crypto";import{apiSocketPath as Ce,crtrHome as br}from"../core/canvas/paths.js";import{activeAppUsers as kr}from"../core/spaces/users.js";import{ensureAppSpace as Rr,ensureUserFiles as Er}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as C}from"../launcher/spec.js";import{launcherRequest as N}from"../launcher/client.js";import{installLauncherEventSink as Pr}from"./launcher-events.js";import{initializeEmptyLayout as Ir,layoutNeedsMigration as xr,socketDir as Ae}from"../core/layout.js";import{migrateLooseKeys as Tr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Dr}from"../core/profiles/relocate.js";import{getNode as Cr,getRow as Ar,listNodesForSupervision as Le,listParkedResidentsWithWakeMail as Lr,setFrozen as $e}from"../core/canvas/index.js";import{createApiServer as $r,closeServer as Ne}from"./api/server.js";import{Router as Nr}from"./api/router.js";import{healthRoutes as Mr}from"./api/handlers/health.js";import{createAppListener as Gr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Or}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Fr}from"../core/canvas/person-state.js";import{markCloudRole as Br,resolvePerson as Hr,retireLocalPerson as Ur,setPersonId as jr}from"../core/canvas/person.js";import{backfillNodeApps as Me,runPermissionsBoot as zr}from"../core/permissions/boot.js";import{startRunNotices as qr}from"./run-notices.js";import{startGrantEffects as Wr}from"./reconcilers/grant-effects.js";import{syncPackages as Kr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Jr}from"../core/model-auth/activations.js";import{createGrantSync as Vr,GRANT_SYNC_INTERVAL_S as Ge}from"../core/grants/sync.js";import{sweepSandboxes as Yr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Qr}from"./cron/run-socket.js";import{hasSyncedGrants as Xr}from"../core/grants/mirror.js";import{readConfig as Oe}from"../core/config.js";import{reconcileUndeliveredTickets as Zr}from"./human/sweep.js";import{resetHandedOffDeliveries as et}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as rt}from"../core/canvas/daemon-actions.js";import{sweepReviews as tt}from"./review/sweep.js";import{pidfilePath as me}from"./pidfile.js";import{rendererWarning as nt}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as ot}from"./supervise-cadence.js";import{createResumeDetector as it}from"./resume-detector.js";import{setFatalFaultAnnouncer as at}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as st}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as lt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as ct}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as dt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as pt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as mt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ft}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as ut}from"./reconcilers/action-lane.js";import{endLiveExecution as ht,hasObservedExit as wt,latestExecutionForNode as vt,migrateLegacyExecutionIdentities as gt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as yt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as St}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as _t}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as bt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as kt}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as Rt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Et}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as Pt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as It}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as xt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as fe}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Tt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Dt}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Ct}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as At}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Lt,removeLeftoverBuildDirs as $t,subscribeImageBuilt as Nt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Mt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Fe,capturePidCommand as Gt,captureTeardownSnapshot as Be,isPidAlive as Ot,isAnyPidAlive as He,killProcessTreePids as Ue}from"../core/canvas/pid.js";import{bindFleet as Ft,boundFleet as je}from"../core/runtime/fleet.js";import{bindDaemonControl as Bt,clearDaemonControl as Ht}from"./control.js";import{execDaemon as Ut,spawnDaemon as jt}from"./manage.js";import{reconcileAndMigrateBoot as zt}from"../core/canvas/boot.js";import{resolveInstallId as qt}from"../core/canvas/install-id.js";import{setInstallId as Wt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Kt,daemonOwnershipApplies as Jt,daemonOwnershipClaimed as Vt,releaseDaemonOwnership as ze}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Yt,closeAllDbs as ue,openDb as Qt,withCanvasWrite as he}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Xt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Zt,ensurePostgresHealthy as en,stopPostgres as rn,withPostgresStartLock as tn}from"./postgres/index.js";import{brokerSignalBus as M}from"./broker-signals/bus.js";import{brokerSignalStreams as nn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as on}from"./api/handlers/broker-ops.js";import{reconcilePackages as an}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as sn}from"../core/scoped-state/migrate-app-installs.js";import{publish as ln,readBuiltinSnapshot as cn}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as dn,reapStaleSpares as pn}from"../core/runtime/warm-pool.js";import{DaemonFleet as mn}from"./fleet.js";import{copyNodeFilesToRows as fn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as un}from"./boot-migrations.js";import{emitEvent as m}from"../core/events/emit.js";import{operationIdContext as b}from"../core/events/operation-id.js";import{bindDaemonEventSource as hn}from"../core/events/source.js";import{activateCanvasImport as wn,MigrationBlockedError as vn,runForcedCanvasImport as gn}from"../migrations/activation.js";import{adoptInstallPerson as yn,convertLegacyScopedStore as Sn,personStoresCopied as _n}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as bn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as qe,installPreludeSnapshot as kn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as we}from"../core/scoped-state/person-rows.js";import{userScopeRoot as We}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ve}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as oa}from"../core/runtime/broker-ownership.js";function ge(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ge,"brokerCommandEpoch");const Rn=5e3,Ke=150;async function En(e){const c=Fe();if(c===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=br(),p=[];for(const[i,l]of c.processes){const v=l.command;if(l.zombie||!v.includes("broker-cli.js")||!ve(v,f)||ge(v)===e)continue;const _=v.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||p.push({pid:i,nodeId:_})}let g=0;const o=[];for(const i of p){const l=Gt(i.pid);if(l===null||!l.includes("broker-cli.js")||!ve(l,f)||ge(l)===e||l.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const v=Be(i.pid,null);if(!v.reused){try{process.platform==="linux"&&E(C)?await N({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:v})}}const w=Date.now()+Rn;for(;Date.now()<w&&o.some(i=>He(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ke));let y=0;for(const i of o){const l=i.snap.tree.length>0?i.snap.tree:[i.pid];He(l)&&(process.platform==="linux"&&E(C)?await N({operation:"stop",pid:i.pid}):Ue(l,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Ke));const d=Fe();if(d===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[i,l]of d.processes){const v=l.command;l.zombie||!v.includes("broker-cli.js")||ve(v,f)&&ge(v)!==e&&u.push(i)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);m({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:p.length,sigtermed:g,sigkilled:y}})}s(En,"reapPriorEpochBrokers");const Pn=5e3;async function In(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[o]of c){const w=(await Cr(o))?.status;(w==="active"||w==="idle")&&await $e(o,new Date().toISOString())}const f=c.map(([,o])=>({pid:o.pid,snap:Be(o.pid,null),exited:o.handle.exited}));for(const o of f)if(!o.snap.reused)try{process.platform==="linux"&&E(C)?await N({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const p=new Promise(o=>{setTimeout(o,Pn).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),p])));const g=[];for(const o of f)Ot(o.pid)&&(process.platform==="linux"&&E(C)?await N({operation:"stop",pid:o.pid}):Ue(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),g.push(o));await Promise.all(g.map(o=>o.exited));for(const[o]of c)await ht(o,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(In,"teardownFleet");function Q(...e){Pe(vr(me()),{recursive:!0}),ur(me(),[process.pid,...e].join(`
2
- `),"utf8")}s(Q,"writePidfile");function Je(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Je,"isMissingPathError");function Ve(e){const c=me();let f;try{f=hr(c,"utf8")}catch(p){if(Je(p))return;throw p}if(f.split(`
3
- `,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{wr(c)}catch(p){if(Je(p))return;throw p}}s(Ve,"removeOwnedPidfileMirror");const xn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new st;at(e=>X.handleFatalFault(e,!1));const Tn=new ct,Dn=new lt,Ye=new dt,Cn=new pt,An=new mt,Ln=new ft,$n=new ut,Nn=new St,Mn=new _t,Gn=new bt,On=new Rt,Fn=new kt,Bn=new Pt,Hn=new It,Un=new xt,jn=new Tt,zn=new Dt,qn=new Ct,Wn=new At;$t();const Kn=new Lt;async function Jn(e=Date.now(),c=xn){const f=je(),p=await X.runFleetPreamble(f);let g,o,w;try{o=await fe();const d=(await Le()).filter(i=>!o.has(i.node_id));g=d.filter(i=>i.status==="active"||i.status==="idle"),w=d.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const u=new Set(w.map(i=>i.node_id));w.push(...(await Lr()).filter(i=>!u.has(i.node_id)&&!o.has(i.node_id)))}catch(d){m({level:"error",event:"canvas.node_list.failed",error:d});return}await X.run(e,{rows:g,fleet:f,lifecycle:c,held:o}),await Tn.run(e,{rows:g,held:o}),await Dn.run(e);const y=await Ye.run(e,{rows:[...g,...w],fleet:f});await Cn.run(e,o),await Wn.run(e,o),await Kn.run(e,{lifecycle:c}),await An.run(e,{lifecycle:c,held:o}),await Ln.run(e,{lifecycle:c}),await $n.run(e,{lifecycle:c}),await Nn.run(e,{lifecycle:c}),await Mn.run(e,{lifecycle:c,fleet:f,held:o}),Gn.run(e,{lifecycle:c}),On.run(e,{lifecycle:c}),Fn.run(e,{lifecycle:c}),Bn.run(e,{lifecycle:c}),Hn.run(e,{lifecycle:c}),Un.run(e,{lifecycle:c}),jn.run(e,{lifecycle:c}),await _r(),qn.run(e,{fleet:f,lifecycle:c}),await zn.run(e,{rows:g}),X.warnIfSaturated({fleet:f,lifecycle:c,thresholds:p,frozen:y})}s(Jn,"superviseTick");async function Vn(e,c=Date.now()){if((await fe()).has(e))return;const f=await vt(e);if(f===null||!wt(f))return;const p=await Ar(e);p===null||p.kind==="human"||await Ye.runNode(c,p,je())}s(Vn,"exitedNodePass");function Z(e){return e===void 0||e==="reconcile"||e==="all"}s(Z,"roleRunsLanes");function H(e){return e===void 0||e==="api"||e==="all"}s(H,"roleServesRequests");const Yn=66e4;function Qn(e){const c=new Nr().registerAll(Mr(()=>null).filter(l=>l.pattern==="/healthz")),f=s((l,v)=>{const _=(l.url??"/").split("?")[0];if((l.method??"GET").toUpperCase()==="GET"&&_==="/healthz"){c.handle(l,v,null,{class:"person"});return}v.writeHead(404,{"content-type":"application/json; charset=utf-8"}),v.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),p=Ce();E(p)&&Ie(p);const g=Y(f),o=new Promise((l,v)=>{g.once("error",v),g.listen(p,()=>{g.off("error",v),xe(p,384),l()})});let w,y=null,d=o;const u=e.tcp??Te()??Oe("user").api.tcp;if(u!==void 0&&u!==""){const l=/^(.*):(\d+)$/.exec(u.trim());if(l===null||Number(l[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${u}`);const v=Y(f);v.on("error",_=>m({event:"api.server.failed",level:"error",error:_})),d=o.then(()=>new Promise(_=>{v.once("error",()=>_()),v.listen(Number(l[2]),l[1]===""?"0.0.0.0":l[1],()=>{const P=v.address();y=`${P.address}:${P.port}`,_()})})),w=v}let i=!1;return{ready:d,tcpAddress:s(()=>y,"tcpAddress"),async close(l={}){if(!i){i=!0,await Promise.all([Ne(g,new Set,l.graceMs),w===void 0?Promise.resolve():Ne(w,new Set,l.graceMs)]);try{E(p)&&Ie(p)}catch{}}}}}s(Qn,"createProbeServer");const Xn="daemon is draining for shutdown and admits no new work";async function Zn(e){Pe(Ae(),{recursive:!0,mode:493}),process.platform==="linux"&&xe(Ae(),493);const c=Ce();if(E(c))throw new Error(`layout refusal cannot bind occupied socket: ${c}`);const f=Y((d,u)=>{if(d.method==="GET"&&d.url==="/healthz"){u.writeHead(200,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}u.writeHead(503,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((d,u)=>{f.once("error",u),f.listen(c,()=>{f.off("error",u),d()})});let p;const g=e.tcp??Te();if(g){const d=/^(.*):(\d+)$/.exec(g);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${g}`);const u=Y(f.listeners("request")[0]);await new Promise((i,l)=>{u.once("error",l),u.listen(Number(d[2]),d[1],()=>{u.off("error",l),i()})}),p=u}Q();let o;const w=s(()=>(o??=(async()=>{f.closeAllConnections(),p?.closeAllConnections(),await Promise.all([f,p].filter(d=>d!==void 0).map(d=>new Promise((u,i)=>d.close(l=>l?i(l):u())))),Ve(process.pid),process.off("SIGINT",y),process.off("SIGTERM",y)})(),o),"cleanup"),y=s(()=>{w().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
4
- `),process.exit(1)})},"onSignal");return process.on("SIGINT",y),process.on("SIGTERM",y),w}s(Zn,"serveLayoutRefusal");async function eo(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(xr())return Zn(e);Ir();const c=s(r=>{process.stderr.write(`[crtrd] ${r}
5
- `)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,p=Jt(e.role);on(Z(e.role));const g=s(async()=>p?await Kt(De(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:De(16).toString("hex")}},"claimOwnership"),{database:o,ownership:w}=e.role!==void 0||f?{database:{url:await Yt()},ownership:await g()}:await tn(async()=>({database:await Zt({log:c,startLockHeld:!0}),ownership:await g()}));if(!w.claimed){if(w.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${w.incumbentPid??"?"})
6
- `);else{const r=[w.incumbentPid!==void 0?`pid ${w.incumbentPid}`:void 0,w.verdict!==void 0?`verdict ${w.verdict}`:void 0].filter(a=>a!==void 0),t=r.length>0?` (${r.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${w.reason}${t}
7
- `),w.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(w.reason==="own_identity_indeterminate"||w.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const y=w.claim;let d=null,u=null,i=null,l=null,v,_="";try{p&&await En(y.token);for(const n of Dr())process.stderr.write(`[crtrd] ${n}
8
- `);for(const n of await Tr())process.stderr.write(`[crtrd] ${n}
9
- `);await Qt(),await Xt(o.url,c);const r=e.role===void 0&&!await _n();let t=null;r&&(Sn({kind:"user",root:We()}),t=bn(We())),e.role===void 0&&kn(t??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await M.listen(o.url);const a=s(n=>{we(n).catch(h=>m({level:"error",event:"daemon.settings.reload_failed",error:h}))},"reloadPerson");if(v=await M.subscribe(n=>{qe().includes(n)&&a(n)},{kinds:["settings"],onListenStart:s(()=>{for(const n of qe())a(n)},"onListenStart")}),e.role!==void 0&&Br(),e.role==="all"&&Fr(),e.role!==void 0){let n;try{n=cn()}catch(R){m({level:"error",event:"daemon.packages.snapshot_failed",error:R})}const h=await he(async R=>(await Me(R),n===void 0?void 0:await ln(R,n,"release")));l=await he(async R=>await sn(R));for(const R of h?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${R.path}: ${R.error}
10
- `)}else{d=await Hr(),d!==null&&(jr(d.id),await we(d.id));const n=await he(async h=>(await Me(h),d===null?null:await an(h)));if(n!==null){for(const h of n.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${h.message}
11
- `);for(const h of n.invalid)process.stderr.write(`[crtrd] package file is not a document: ${h.path}: ${h.error}
12
- `);for(const h of n.quarantined)process.stderr.write(`[crtrd] plugin "${h.name}" has a damaged ${h.file} (${h.reason}); ${h.movedTo!==void 0?`moved to ${h.movedTo}`:"left in place and skipped"}
13
- `);for(const h of n.kinds.refused)process.stderr.write(`[crtrd] plugin "${h.plugin}" kind ${h.kind} not registered: ${h.message}
14
- `);for(const h of n.kinds.invalid)process.stderr.write(`[crtrd] plugin "${h.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${h.error}
15
- `)}}if(_=await qt(),Wt(_),e.role===void 0&&d!==null){if(await yn(d.id),process.platform==="darwin"){const{readConfig:n,updateConfig:h}=await import("../core/config.js");if(n("user").paths?.user_files===void 0){const{homedir:R}=await import("node:os");await h("user",Ee=>{Ee.paths??={},Ee.paths.user_files??=R()})}}u=await Ur(),u.joinedFrom!==null&&await we(u.person),await cr(),i=await zr()}if(process.platform==="linux"&&E(C)&&(Pr(),await N({operation:"users.sync",users:await kr()})),p){await yt(y.token);const n=await fn();Object.values(n).some(h=>h>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(n)}
16
- `)}}catch(r){await M.close();try{if(p){const{released:t}=await ze(y);if(!t)throw new Error("daemon ownership claim was not released")}await ue()}catch(t){throw new AggregateError([r,t],"daemon startup failed and cleanup also failed")}throw r}let P=!0,ee,U=Promise.resolve(),re=!1,j,te,ne,oe,ie,A;const z=new Set;let ae=!1,ye=!1,x,I,q=!1,W,L,G,O,F,se,le,ce,de;const Qe=it();let T,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",Xe=null;function Ze(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(Ze,"startupBlock");function k(r){z.add(r),r.finally(()=>{z.delete(r)}).catch(()=>{})}s(k,"registerDetached");const er={acceptsDetachedWork:s(()=>P,"acceptsDetachedWork"),registerDetached:k};async function rr(){try{P=!1,nn.close(),ne?.(),ne=void 0,oe?.(),v?.(),oe=void 0,ie?.(),ie=void 0,ce?.(),ce=void 0,await M.close(),j!==void 0&&(clearInterval(j),j=void 0),te?.(),te=void 0,G!==void 0&&(clearInterval(G),G=void 0),O!==void 0&&(clearInterval(O),O=void 0),de?.(),de=void 0;let r;do r=U,await r;while(r!==U);for(;z.size>0;)await Promise.allSettled([...z]);if(A!==void 0&&(p&&await In(A),await A.exitsSettled(),A.dispose()),I!==void 0&&!q&&(q=!0,await I.close()),se?.(),se=void 0,le?.(),le=void 0,F!==void 0){const t=F;F=void 0,await t.stop()}if(L!==void 0){const t=L;L=void 0,await t.close()}if(W!==void 0){const t=W;W=void 0,await t.close()}if(ae||(Ve(process.pid),ae=!0),ae&&!ye){if(p){const{released:t}=await ze(y);if(!t)throw new Error("daemon ownership claim was not released")}ye=!0,await ue()}}finally{Ht(),process.off("SIGINT",be),process.off("SIGTERM",ke),process.off("exit",Re)}}s(rr,"cleanupAttempt");const K=1e3;let Se=!1;function tr(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return Se?{graceMs:K}:(Se=!0,b.fresh(()=>{m({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{nr()},K),{graceMs:K})}s(tr,"requestHandover");async function nr(){try{await D()}catch(r){const t=r instanceof Error?r.stack??r.message:String(r);process.stderr.write(`[crtrd] handover cleanup failed:
1
+ var Qe=Object.defineProperty;var a=(e,d)=>Qe(e,"name",{value:d,configurable:!0});import{applyBootSettings as Xe}from"./boot-settings.js";import{startBrokerMemoryCap as Ze}from"./broker-memory-cap.js";import{startPeerOutbox as er}from"./peer/outbox.js";import{reportMachineStatus as rr}from"../core/peer/directory.js";import{createPeerRelay as tr}from"./peer/relay-service.js";import{writeFileSync as nr,readFileSync as or,rmSync as ir,mkdirSync as ar,existsSync as R,unlinkSync as ke,chmodSync as sr}from"node:fs";import{createServer as be}from"node:http";import{dirname as dr}from"node:path";import{envCrtrdTcp as lr}from"../shared/env.js";import{openCanvasConversationStore as cr,serveCanvasConversationStore as pr}from"../core/canvas/sessions.js";import{installConversationStore as mr}from"../core/conversation-store/index.js";import{pollRunObservers as fr}from"./runs/observer.js";import{randomBytes as Re}from"node:crypto";import{apiSocketPath as ur,crtrHome as wr}from"../core/canvas/paths.js";import{activeAppUsers as hr}from"../core/spaces/users.js";import{ensureAppSpace as vr,ensureUserFiles as gr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as I}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Sr}from"./launcher-events.js";import{initializeEmptyLayout as _r}from"../core/layout.js";import{relocateProfileFolders as yr}from"../core/profiles/relocate.js";import{getNode as kr,getRow as br,listNodesForSupervision as Ee,listParkedResidentsWithWakeMail as Rr,setFrozen as Pe}from"../core/canvas/index.js";import{createApiServer as Er,closeServer as xe}from"./api/server.js";import{Router as Pr}from"./api/router.js";import{healthRoutes as xr}from"./api/handlers/health.js";import{createAppListener as Dr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Ir}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Tr}from"../core/canvas/person-state.js";import{markCloudRole as Cr,resolvePerson as Ar,retireLocalPerson as Lr,setPersonId as $r}from"../core/canvas/person.js";import{backfillNodeApps as De,runPermissionsBoot as Nr}from"../core/permissions/boot.js";import{startRunNotices as Mr}from"./run-notices.js";import{startGrantEffects as Or}from"./reconcilers/grant-effects.js";import{syncPackages as Gr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Fr}from"../core/model-auth/activations.js";import{createGrantSync as Br,GRANT_SYNC_INTERVAL_S as Ie}from"../core/grants/sync.js";import{sweepSandboxes as jr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Ur}from"./cron/run-socket.js";import{hasSyncedGrants as Hr}from"../core/grants/mirror.js";import{readConfig as Te}from"../core/config.js";import{reconcileUndeliveredTickets as zr}from"./human/sweep.js";import{resetHandedOffDeliveries as Wr}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as qr}from"../core/canvas/daemon-actions.js";import{sweepReviews as Kr}from"./review/sweep.js";import{pidfilePath as de}from"./pidfile.js";import{rendererWarning as Vr}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as Yr}from"./supervise-cadence.js";import{createResumeDetector as Jr}from"./resume-detector.js";import{setFatalFaultAnnouncer as Qr}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as Xr}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as Zr}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as et}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as rt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as tt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as nt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ot}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as it}from"./reconcilers/action-lane.js";import{endLiveExecution as at,hasObservedExit as st,latestExecutionForNode as dt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as lt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as ct}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as pt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as mt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as ft}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as ut}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as wt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as ht}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as vt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as gt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as le}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as St}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as _t}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as yt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as kt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as bt,removeLeftoverBuildDirs as Rt,subscribeImageBuilt as Et}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Pt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Ce,capturePidCommand as xt,captureTeardownSnapshot as Ae,isPidAlive as Dt,isAnyPidAlive as Le,killProcessTreePids as $e}from"../core/canvas/pid.js";import{bindFleet as It,boundFleet as Ne}from"../core/runtime/fleet.js";import{bindDaemonControl as Tt,clearDaemonControl as Ct}from"./control.js";import{execDaemon as At,spawnDaemon as Lt}from"./manage.js";import{reconcileBootLiveness as $t}from"../core/canvas/boot.js";import{resolveInstallId as Nt}from"../core/canvas/install-id.js";import{setInstallId as Mt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Ot,daemonOwnershipApplies as Gt,daemonOwnershipClaimed as Ft,releaseDaemonOwnership as Me}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Bt,closeAllDbs as ce,openDb as jt,withCanvasWrite as pe}from"../core/canvas/db.js";import{ensurePostgres as Ut,ensurePostgresHealthy as Ht,stopPostgres as zt,withPostgresStartLock as Wt}from"./postgres/index.js";import{brokerSignalBus as L}from"./broker-signals/bus.js";import{brokerSignalStreams as qt}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as Kt}from"./api/handlers/broker-ops.js";import{reconcilePackages as Vt}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as Yt}from"../core/scoped-state/migrate-app-installs.js";import{publish as Jt,readBuiltinSnapshot as Qt}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as Xt,reapStaleSpares as Zt}from"../core/runtime/warm-pool.js";import{DaemonFleet as en}from"./fleet.js";import{copyNodeFilesToRows as rn}from"../core/runtime/first-boot-rows.js";import{emitEvent as l}from"../core/events/emit.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{bindDaemonEventSource as tn}from"../core/events/source.js";import{heldPersons as Oe,installPreludeSnapshot as nn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as V}from"../core/scoped-state/person-rows.js";import{brokerCommandDeclaresCanvasHome as me}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as Ai}from"../core/runtime/broker-ownership.js";function fe(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}a(fe,"brokerCommandEpoch");const on=5e3,Ge=150;async function an(e){const d=Ce();if(d===null)throw l({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const m=wr(),c=[];for(const[i,s]of d.processes){const u=s.command;if(s.zombie||!u.includes("broker-cli.js")||!me(u,m)||fe(u)===e)continue;const _=u.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||c.push({pid:i,nodeId:_})}let h=0;const o=[];for(const i of c){const s=xt(i.pid);if(s===null||!s.includes("broker-cli.js")||!me(s,m)||fe(s)===e||s.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const u=Ae(i.pid,null);if(!u.reused){try{process.platform==="linux"&&R(I)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}h++,o.push({pid:i.pid,snap:u})}}const f=Date.now()+on;for(;Date.now()<f&&o.some(i=>Le(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ge));let S=0;for(const i of o){const s=i.snap.tree.length>0?i.snap.tree:[i.pid];Le(s)&&(process.platform==="linux"&&R(I)?await A({operation:"stop",pid:i.pid}):$e(s,"SIGKILL",i.snap.identities),S++)}S>0&&await new Promise(i=>setTimeout(i,Ge));const w=Ce();if(w===null)throw l({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const v=[];for(const[i,s]of w.processes){const u=s.command;s.zombie||!u.includes("broker-cli.js")||me(u,m)&&fe(u)!==e&&v.push(i)}if(v.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${v.join(", ")}`);l({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:c.length,sigtermed:h,sigkilled:S}})}a(an,"reapPriorEpochBrokers");const sn=5e3;async function dn(e){const d=Array.from(e.entries());if(d.length===0)return;for(const[o]of d){const f=(await kr(o))?.status;(f==="active"||f==="idle")&&await Pe(o,new Date().toISOString())}const m=d.map(([,o])=>({pid:o.pid,snap:Ae(o.pid,null),exited:o.handle.exited}));for(const o of m)if(!o.snap.reused)try{process.platform==="linux"&&R(I)?await A({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const c=new Promise(o=>{setTimeout(o,sn).unref()});await Promise.allSettled(m.map(o=>Promise.race([o.exited.then(()=>{}),c])));const h=[];for(const o of m)Dt(o.pid)&&(process.platform==="linux"&&R(I)?await A({operation:"stop",pid:o.pid}):$e(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),h.push(o));await Promise.all(h.map(o=>o.exited));for(const[o]of d)await at(o,{reason:"daemon-teardown"});l({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:m.length,sigkilled:h.length}})}a(dn,"teardownFleet");function ue(...e){ar(dr(de()),{recursive:!0}),nr(de(),[process.pid,...e].join(`
2
+ `),"utf8")}a(ue,"writePidfile");function Fe(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}a(Fe,"isMissingPathError");function ln(e){const d=de();let m;try{m=or(d,"utf8")}catch(c){if(Fe(c))return;throw c}if(m.split(`
3
+ `,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{ir(d)}catch(c){if(Fe(c))return;throw c}}a(ln,"removeOwnedPidfileMirror");const cn={acceptsDetachedWork:a(()=>!0,"acceptsDetachedWork"),registerDetached:a(e=>{e.catch(()=>{})},"registerDetached")},Y=new Xr;Qr(e=>Y.handleFatalFault(e,!1));const pn=new et,mn=new Zr,Be=new rt,fn=new tt,un=new nt,wn=new ot,hn=new it,vn=new ct,gn=new pt,Sn=new mt,_n=new ut,yn=new ft,kn=new ht,bn=new vt,Rn=new gt,En=new St,Pn=new _t,xn=new yt,Dn=new kt;Rt();const In=new bt;async function Tn(e=Date.now(),d=cn){const m=Ne(),c=await Y.runFleetPreamble(m);let h,o,f;try{o=await le();const w=(await Ee()).filter(i=>!o.has(i.node_id));h=w.filter(i=>i.status==="active"||i.status==="idle"),f=w.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const v=new Set(f.map(i=>i.node_id));f.push(...(await Rr()).filter(i=>!v.has(i.node_id)&&!o.has(i.node_id)))}catch(w){l({level:"error",event:"canvas.node_list.failed",error:w});return}await Y.run(e,{rows:h,fleet:m,lifecycle:d,held:o}),await pn.run(e,{rows:h,held:o}),await mn.run(e);const S=await Be.run(e,{rows:[...h,...f],fleet:m});await fn.run(e,o),await Dn.run(e,o),await In.run(e,{lifecycle:d}),await un.run(e,{lifecycle:d,held:o}),await wn.run(e,{lifecycle:d}),await hn.run(e,{lifecycle:d}),await vn.run(e,{lifecycle:d}),await gn.run(e,{lifecycle:d,fleet:m,held:o}),Sn.run(e,{lifecycle:d}),_n.run(e,{lifecycle:d}),yn.run(e,{lifecycle:d}),kn.run(e,{lifecycle:d}),bn.run(e,{lifecycle:d}),Rn.run(e,{lifecycle:d}),En.run(e,{lifecycle:d}),await fr(),xn.run(e,{fleet:m,lifecycle:d}),await Pn.run(e,{rows:h}),Y.warnIfSaturated({fleet:m,lifecycle:d,thresholds:c,frozen:S})}a(Tn,"superviseTick");async function Cn(e,d=Date.now()){if((await le()).has(e))return;const m=await dt(e);if(m===null||!st(m))return;const c=await br(e);c===null||c.kind==="human"||await Be.runNode(d,c,Ne())}a(Cn,"exitedNodePass");function J(e){return e===void 0||e==="reconcile"||e==="all"}a(J,"roleRunsLanes");function F(e){return e===void 0||e==="api"||e==="all"}a(F,"roleServesRequests");const An=66e4;function Ln(e){const d=new Pr().registerAll(xr(()=>null).filter(s=>s.pattern==="/healthz")),m=a((s,u)=>{const _=(s.url??"/").split("?")[0];if((s.method??"GET").toUpperCase()==="GET"&&_==="/healthz"){d.handle(s,u,null,{class:"person"});return}u.writeHead(404,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),c=ur();R(c)&&ke(c);const h=be(m),o=new Promise((s,u)=>{h.once("error",u),h.listen(c,()=>{h.off("error",u),sr(c,384),s()})});let f,S=null,w=o;const v=e.tcp??lr()??Te("user").api.tcp;if(v!==void 0&&v!==""){const s=/^(.*):(\d+)$/.exec(v.trim());if(s===null||Number(s[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${v}`);const u=be(m);u.on("error",_=>l({event:"api.server.failed",level:"error",error:_})),w=o.then(()=>new Promise(_=>{u.once("error",()=>_()),u.listen(Number(s[2]),s[1]===""?"0.0.0.0":s[1],()=>{const b=u.address();S=`${b.address}:${b.port}`,_()})})),f=u}let i=!1;return{ready:w,tcpAddress:a(()=>S,"tcpAddress"),async close(s={}){if(!i){i=!0,await Promise.all([xe(h,new Set,s.graceMs),f===void 0?Promise.resolve():xe(f,new Set,s.graceMs)]);try{R(c)&&ke(c)}catch{}}}}}a(Ln,"createProbeServer");const $n="daemon is draining for shutdown and admits no new work";async function Nn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();_r();const d=a(n=>{process.stderr.write(`[crtrd] ${n}
4
+ `)},"logPostgres"),m=!!process.env.CRTR_TEST_PG_URL,c=Gt(e.role);Kt(J(e.role));const h=a(async()=>c?await Ot(Re(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Re(16).toString("hex")}},"claimOwnership"),{database:o,ownership:f}=e.role!==void 0||m?{database:{url:await Bt()},ownership:await h()}:await Wt(async()=>({database:await Ut({log:d,startLockHeld:!0}),ownership:await h()}));if(!f.claimed){if(f.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${f.incumbentPid??"?"})
5
+ `);else{const n=[f.incumbentPid!==void 0?`pid ${f.incumbentPid}`:void 0,f.verdict!==void 0?`verdict ${f.verdict}`:void 0].filter(t=>t!==void 0),r=n.length>0?` (${n.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${f.reason}${r}
6
+ `),f.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(f.reason==="own_identity_indeterminate"||f.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const S=f.claim;let w=null,v=null,i=null,s=null,u,_="";try{c&&await an(S.token);for(const r of yr())process.stderr.write(`[crtrd] ${r}
7
+ `);await jt(),e.role===void 0&&nn({profiles:[],defaults:{},settings:{},state:{},apps:{}}),await L.listen(o.url);const n=a(r=>{V(r).catch(t=>l({level:"error",event:"daemon.settings.reload_failed",error:t}))},"reloadPerson");if(u=await L.subscribe(r=>{Oe().includes(r)&&n(r)},{kinds:["settings"],onListenStart:a(()=>{for(const r of Oe())n(r)},"onListenStart")}),e.role!==void 0&&Cr(),e.role==="all"&&Tr(),e.role!==void 0){let r;try{r=Qt()}catch(p){l({level:"error",event:"daemon.packages.snapshot_failed",error:p})}const t=await pe(async p=>(await De(p),r===void 0?void 0:await Jt(p,r,"release")));s=await pe(async p=>await Yt(p));for(const p of t?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${p.path}: ${p.error}
8
+ `)}else{w=await Ar(),w!==null&&($r(w.id),await V(w.id));const r=await pe(async t=>(await De(t),w===null?null:await Vt(t)));if(r!==null){for(const t of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${t.message}
9
+ `);for(const t of r.invalid)process.stderr.write(`[crtrd] package file is not a document: ${t.path}: ${t.error}
10
+ `);for(const t of r.quarantined)process.stderr.write(`[crtrd] plugin "${t.name}" has a damaged ${t.file} (${t.reason}); ${t.movedTo!==void 0?`moved to ${t.movedTo}`:"left in place and skipped"}
11
+ `);for(const t of r.kinds.refused)process.stderr.write(`[crtrd] plugin "${t.plugin}" kind ${t.kind} not registered: ${t.message}
12
+ `);for(const t of r.kinds.invalid)process.stderr.write(`[crtrd] plugin "${t.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${t.error}
13
+ `)}}if(_=await Nt(),Mt(_),e.role===void 0&&w!==null){if(await V(w.id),process.platform==="darwin"){const{readConfig:r,updateConfig:t}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:p}=await import("node:os");await t("user",P=>{P.paths??={},P.paths.user_files??=p()})}}v=await Lr(),v.joinedFrom!==null&&await V(v.person),await Xe(),i=await Nr()}if(process.platform==="linux"&&R(I)&&(Sr(),await A({operation:"users.sync",users:await hr()})),c){await lt(S.token);const r=await rn();Object.values(r).some(t=>t>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
14
+ `)}}catch(n){await L.close();try{if(c){const{released:r}=await Me(S);if(!r)throw new Error("daemon ownership claim was not released")}await ce()}catch(r){throw new AggregateError([n,r],"daemon startup failed and cleanup also failed")}throw n}let b=!0,Q,B=Promise.resolve(),X=!1,j,Z,ee,re,te,T;const U=new Set;let ne=!1,we=!1,x,E,H=!1,z,C,$,N,M,oe,ie,ae,se;const je=Jr();let D,g={phase:"initializing",message:"daemon startup is running and normal services are unavailable",blockerPaths:[]},Ue=null;function He(){return g.phase==="ready"?null:{phase:g.phase,message:g.message,blockerPaths:g.blockerPaths}}a(He,"startupBlock");function k(n){U.add(n),n.finally(()=>{U.delete(n)}).catch(()=>{})}a(k,"registerDetached");const ze={acceptsDetachedWork:a(()=>b,"acceptsDetachedWork"),registerDetached:k};async function We(){try{b=!1,qt.close(),ee?.(),ee=void 0,re?.(),u?.(),re=void 0,te?.(),te=void 0,ae?.(),ae=void 0,await L.close(),j!==void 0&&(clearInterval(j),j=void 0),Z?.(),Z=void 0,$!==void 0&&(clearInterval($),$=void 0),N!==void 0&&(clearInterval(N),N=void 0),se?.(),se=void 0;let n;do n=B,await n;while(n!==B);for(;U.size>0;)await Promise.allSettled([...U]);if(T!==void 0&&(c&&await dn(T),await T.exitsSettled(),T.dispose()),E!==void 0&&!H&&(H=!0,await E.close()),oe?.(),oe=void 0,ie?.(),ie=void 0,M!==void 0){const r=M;M=void 0,await r.stop()}if(C!==void 0){const r=C;C=void 0,await r.close()}if(z!==void 0){const r=z;z=void 0,await r.close()}if(ne||(ln(process.pid),ne=!0),ne&&!we){if(c){const{released:r}=await Me(S);if(!r)throw new Error("daemon ownership claim was not released")}we=!0,await ce()}}finally{Ct(),process.off("SIGINT",ge),process.off("SIGTERM",Se),process.off("exit",_e)}}a(We,"cleanupAttempt");const W=1e3;let he=!1;function qe(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return he?{graceMs:W}:(he=!0,y.fresh(()=>{l({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:W}})}),setTimeout(()=>{Ke()},W),{graceMs:W})}a(qe,"requestHandover");async function Ke(){try{await O()}catch(n){const r=n instanceof Error?n.stack??n.message:String(n);process.stderr.write(`[crtrd] handover cleanup failed:
15
+ ${r}
16
+ `),process.exit(1)}try{process.platform==="linux"&&R(I)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await At();const n=await Lt();y.fresh(()=>{l({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:n.pid??n.existing_pid??null,spawned:n.started}})})}catch(n){y.fresh(()=>{l({level:"error",event:"daemon.handover.successor_failed",error:n})});const r=n instanceof Error?n.message:String(n);process.stderr.write(`[crtrd] handover successor failed to start: ${r}
17
+ `),process.exit(1)}process.exit(0)}a(Ke,"performHandover");function O(){if(x!==void 0)return x;const n=We();return x=n,n.then(()=>{x===n&&(x=void 0)},()=>{x===n&&(x=void 0)}),n}a(O,"requestCleanup");async function Ve(){g={phase:"initializing",message:$n,blockerPaths:[]},E!==void 0&&!H&&(H=!0,await E.close({graceMs:An}))}a(Ve,"drainApi");async function ve(n){try{n==="SIGTERM"&&e.role==="api"&&await Ve(),await O(),await zt({claimed:a(async()=>{try{return c&&await Ft()}finally{await ce()}},"claimed")}),process.exit(0)}catch(r){process.exitCode=1;const t=r instanceof Error?r.stack??`${r.name}: ${r.message}`:String(r);process.stderr.write(`[crtrd] ${n} cleanup failed:
17
18
  ${t}
18
- `),process.exit(1)}try{process.platform==="linux"&&E(C)&&(await N({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Ut();const r=await jt();b.fresh(()=>{m({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:r.pid??r.existing_pid??null,spawned:r.started}})})}catch(r){b.fresh(()=>{m({level:"error",event:"daemon.handover.successor_failed",error:r})});const t=r instanceof Error?r.message:String(r);process.stderr.write(`[crtrd] handover successor failed to start: ${t}
19
- `),process.exit(1)}process.exit(0)}s(nr,"performHandover");function D(){if(x!==void 0)return x;const r=rr();return x=r,r.then(()=>{x===r&&(x=void 0)},()=>{x===r&&(x=void 0)}),r}s(D,"requestCleanup");async function or(){S={phase:"initializing",message:Xn,blockerPaths:[]},I!==void 0&&!q&&(q=!0,await I.close({graceMs:Yn}))}s(or,"drainApi");async function _e(r){try{r==="SIGTERM"&&e.role==="api"&&await or(),await D(),await rn({claimed:s(async()=>{try{return p&&await Vt()}finally{await ue()}},"claimed")}),process.exit(0)}catch(t){process.exitCode=1;const a=t instanceof Error?t.stack??`${t.name}: ${t.message}`:String(t);process.stderr.write(`[crtrd] ${r} cleanup failed:
20
- ${a}
21
- `),process.exit(1)}}s(_e,"handleSignal");function be(){_e("SIGINT")}s(be,"onSigint");function ke(){_e("SIGTERM")}s(ke,"onSigterm");function Re(){D().catch(()=>{})}s(Re,"onExit");async function J(r){P&&(U=U.then(r).then(()=>{},t=>{b.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:t})})}))}s(J,"enqueue");async function V(){!P||re||(Qe.check()&&T&&(m({level:"info",event:"daemon.resume.detected"}),k(T().catch(()=>{}))),re=!0,await J(async()=>{if(re=!1,!!P)try{f||await en({log:c}),await Jn(Date.now(),er)}catch(r){b.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:r})})}}))}s(V,"enqueueTick");let B=null;async function ir(){if(B!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${B instanceof Error?B.message:String(B)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const r=S.phase==="prepared";try{return await pe(),S={phase:"ready",message:"",blockerPaths:[]},r?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(t){throw B=t,{status:500,code:"admission_failed",message:`daemon admission failed: ${t instanceof Error?t.message:String(t)}`}}}s(ir,"admitStartup");async function ar(r){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const t=await gn({dryRun:r.dryRun});if(r.dryRun||t.pending||S.phase!=="blocked")return{result:t,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:t,resumed:!1};try{return await pe(),S={phase:"ready",message:"",blockerPaths:[]},{result:t,resumed:!0}}catch(a){const n=a instanceof Error?a.message:String(a);return setTimeout(()=>{D().catch(()=>{})},1e3),{result:t,resumed:!1,resumeError:n}}}finally{$=null}}s(ar,"repairMigrations");async function sr(){ee=e.intervalMs??ot;const r=y.token;A=new mn({epoch:r,enqueue:J}),Ft(A),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},b.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:ee}})});const t=_;if(b.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:t}})}),b.fresh(()=>{let a;try{a=nt()}catch{return}a!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:a.slice(0,2048)}})}),Et(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile|all): it names the directory this deployment mints tokens against");if(e.role==="all"&&!process.env.CRTR_DATABASE_URL&&!process.env.CRTR_TEST_PG_URL)throw new Error("CRTR_DATABASE_URL must be set on --role all: it names the Postgres this process serves");if(e.role!==void 0&&Or(),!Z(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await b.fresh(async()=>{await tt(),await Zr();const a=e.role!==void 0;await et(Date.now(),a),await rt(Date.now(),a)}),e.role===void 0&&await b.fresh(async()=>{const{reconcile:a,migrated:n}=await zt(gt);a.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:a.cleared.length,same_boot_proven:a.sameBootProven}}),n.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:n.length}})}),await b.fresh(async()=>{const a=await fe();for(const n of await Le())a.has(n.node_id)||n.status!=="active"||n.pi_pid!=null||n.frozen_at!=null||n.respawn_not_before!=null||(await $e(n.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:n.node_id}))}),await b.fresh(async()=>{await Mt();for(const a of un){const n=await a.apply();n.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:a.id,...n.summary}})}}),k(Qr()),T){const a=s(()=>{k(T().catch(()=>{})),k(mr().then(n=>F?.observe(n)).then(()=>{},n=>{m({level:"warn",event:"daemon.peer.status_failed",error:n})}))},"refresh");k(Yr().then(({completion:n})=>n).catch(n=>{m({level:"error",event:"daemon.grants.sweep_failed",error:n})})),a(),G=setInterval(a,Ge*1e3),G.unref(),de=pr({joined:!0,register:k})}await J(async()=>{await pn(),await dn()}),te=dr(),j=setInterval(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))},ee),ne=await Nt(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))}),oe=await M.subscribe(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))},{kinds:["spend_limits"]}),ie=await M.subscribe(a=>{J(()=>b.fresh(()=>Vn(a)))},{kinds:["execution_exit"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:a})=>a(()=>!P,n=>m({level:"warn",event:"daemon.move.settle_failed",error:n}))).catch(a=>m({level:"warn",event:"daemon.move.settle_failed",error:a}))}s(sr,"completeStartup");function pe(){return Xe??=sr().catch(r=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},r})}s(pe,"resumeStartup");try{process.on("SIGINT",be),process.on("SIGTERM",ke),process.on("exit",Re),hn(),d!==null&&m({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),l!==null&&!l.alreadyDone&&m({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),i!==null&&m({level:"info",event:"daemon.permissions.boot",fields:{...i}}),u!==null&&m({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),H(e.role)?W=await yr():Sr(gr());const r=y.token;Bt({epoch:r,requestHandover:tr,registerDetached:k,startupBlock:Ze,admitStartup:ir,repairMigrations:ar}),Q(),I=H(e.role)?$r({tcp:e.tcp}):Qn(e),await I.ready,Q(I.tcpAddress()??"");const t=Oe("user").runtime;if(t?.issuer&&(T=Vr(t.issuer,k),t.unsandboxed===!0&&(F=fr({syncGrants:T}))),e.role==="api"||e.role==="all"){const a=s(()=>k(import("../core/providers/bundles.js").then(h=>h.syncProviderBundles()).catch(h=>{m({level:"error",event:"daemon.providers.bundle_sync_failed",error:h})})),"bundleTick"),n=s(()=>{k(Kr().catch(h=>{m({level:"error",event:"daemon.packages.sync_failed",error:h})})),a()},"packageTick");n(),O=setInterval(n,Ge*1e3),O.unref()}if(H(e.role)&&(se=await qr()),Z(e.role)&&(le=Jr()),ce=await Wr({serves:H(e.role),runsLanes:Z(e.role)}),t?.unsandboxed===!0&&t.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),H(e.role)&&t!==void 0&&t.listener!==void 0&&t.unsandboxed!==!0&&(L=await Gr(t,async()=>await Xr(t.issuer.replace(/\/$/,"")),T),await L.ready,Q(I.tcpAddress()??"",`${t.listener.address}:${L.port()}`)),e.role===void 0)try{await wn()}catch(a){if($=null,a instanceof vn)return S={phase:"blocked",message:a.message,blockerPaths:a.blockerPaths},D;throw a}process.platform==="linux"&&E(C)&&(Er(),await Rr("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await pe(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return D}catch(r){try{await D()}catch(t){throw new AggregateError([r,t],"daemon startup failed and cleanup also failed")}throw r}}s(eo,"runDaemon");var ra=eo;export{Yn as API_DRAIN_GRACE_MS,oa as brokerCommandDeclaresCanvasHome,ge as brokerCommandEpoch,ra as default,Vn as exitedNodePass,Z as roleRunsLanes,H as roleServesRequests,eo as runDaemon,Jn as superviseTick,In as teardownFleet};
19
+ `),process.exit(1)}}a(ve,"handleSignal");function ge(){ve("SIGINT")}a(ge,"onSigint");function Se(){ve("SIGTERM")}a(Se,"onSigterm");function _e(){O().catch(()=>{})}a(_e,"onExit");async function q(n){b&&(B=B.then(n).then(()=>{},r=>{y.fresh(()=>{l({level:"error",event:"daemon.lane_job.failed",error:r})})}))}a(q,"enqueue");async function K(){!b||X||(je.check()&&D&&(l({level:"info",event:"daemon.resume.detected"}),k(D().catch(()=>{}))),X=!0,await q(async()=>{if(X=!1,!!b)try{m||await Ht({log:d}),await Tn(Date.now(),ze)}catch(n){y.fresh(()=>{l({level:"error",event:"daemon.tick.failed",error:n})})}}))}a(K,"enqueueTick");let G=null;async function Ye(){if(G!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${G instanceof Error?G.message:String(G)}`};if(g.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(g.phase!=="prepared"&&g.phase!=="recovering")throw{status:409,code:"not_prepared",message:g.message};const n=g.phase==="prepared";try{return await ye(),g={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(r){throw G=r,{status:500,code:"admission_failed",message:`daemon admission failed: ${r instanceof Error?r.message:String(r)}`}}}a(Ye,"admitStartup");async function Je(){Q=e.intervalMs??Yr;const n=S.token;T=new en({epoch:n,enqueue:q}),It(T),g={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},y.fresh(()=>{l({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:Q}})});const r=_;if(y.fresh(()=>{l({level:"info",event:"daemon.install_id.resolved",fields:{install_id:r}})}),y.fresh(()=>{let t;try{t=Vr()}catch{return}t!==null&&l({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),wt(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile|all): it names the directory this deployment mints tokens against");if(e.role==="all"&&!process.env.CRTR_DATABASE_URL&&!process.env.CRTR_TEST_PG_URL)throw new Error("CRTR_DATABASE_URL must be set on --role all: it names the Postgres this process serves");if(e.role!==void 0&&Ir(),!J(e.role)){g={phase:"ready",message:"",blockerPaths:[]};return}if(await y.fresh(async()=>{await Kr(),await zr();const t=e.role!==void 0;await Wr(Date.now(),t),await qr(Date.now(),t)}),e.role===void 0&&await y.fresh(async()=>{const t=await $t();t.changed&&l({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}})}),await y.fresh(async()=>{const t=await le();for(const p of await Ee())t.has(p.node_id)||p.status!=="active"||p.pi_pid!=null||p.frozen_at!=null||p.respawn_not_before!=null||(await Pe(p.node_id,new Date().toISOString()),l({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:p.node_id}))}),await y.fresh(async()=>{await Pt()}),k(Ur()),D){const t=a(()=>{k(D().catch(()=>{})),k(rr().then(p=>M?.observe(p)).then(()=>{},p=>{l({level:"warn",event:"daemon.peer.status_failed",error:p})}))},"refresh");k(jr().then(({completion:p})=>p).catch(p=>{l({level:"error",event:"daemon.grants.sweep_failed",error:p})})),t(),$=setInterval(t,Ie*1e3),$.unref(),se=er({joined:!0,register:k})}await q(async()=>{await Zt(),await Xt()}),Z=Ze(),j=setInterval(()=>{K().catch(t=>l({level:"error",event:"daemon.tick.failed",error:t}))},Q),ee=await Et(()=>{K().catch(t=>l({level:"error",event:"daemon.tick.failed",error:t}))}),re=await L.subscribe(()=>{K().catch(t=>l({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),te=await L.subscribe(t=>{q(()=>y.fresh(()=>Cn(t)))},{kinds:["execution_exit"]}),await K(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!b,p=>l({level:"warn",event:"daemon.move.settle_failed",error:p}))).catch(t=>l({level:"warn",event:"daemon.move.settle_failed",error:t}))}a(Je,"completeStartup");function ye(){return Ue??=Je().catch(n=>{throw g={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}a(ye,"resumeStartup");try{process.on("SIGINT",ge),process.on("SIGTERM",Se),process.on("exit",_e),tn(),w!==null&&l({level:"info",event:"daemon.person.resolved",fields:{person_id:w.id,source:w.source}}),s!==null&&!s.alreadyDone&&l({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:s.moved,discarded:s.discarded,people:s.people}}),i!==null&&l({level:"info",event:"daemon.permissions.boot",fields:{...i}}),v!==null&&l({level:"info",event:"daemon.person.retired",fields:{person_id:v.person,joined_from:v.joinedFrom,retired:v.retired,columns:v.columns}}),F(e.role)?z=await pr():mr(cr());const n=S.token;Tt({epoch:n,requestHandover:qe,registerDetached:k,startupBlock:He,admitStartup:Ye}),ue(),E=F(e.role)?Er({tcp:e.tcp}):Ln(e),await E.ready,ue(E.tcpAddress()??"");const r=Te("user").runtime;if(r?.issuer&&(D=Br(r.issuer,k),r.unsandboxed===!0&&(M=tr({syncGrants:D}))),e.role==="api"||e.role==="all"){const t=a(()=>k(import("../core/providers/bundles.js").then(P=>P.syncProviderBundles()).catch(P=>{l({level:"error",event:"daemon.providers.bundle_sync_failed",error:P})})),"bundleTick"),p=a(()=>{k(Gr().catch(P=>{l({level:"error",event:"daemon.packages.sync_failed",error:P})})),t()},"packageTick");p(),N=setInterval(p,Ie*1e3),N.unref()}return F(e.role)&&(oe=await Mr()),J(e.role)&&(ie=Fr()),ae=await Or({serves:F(e.role),runsLanes:J(e.role)}),r?.unsandboxed===!0&&r.listener!==void 0&&l({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),F(e.role)&&r!==void 0&&r.listener!==void 0&&r.unsandboxed!==!0&&(C=await Dr(r,async()=>await Hr(r.issuer.replace(/\/$/,"")),D),await C.ready,ue(E.tcpAddress()??"",`${r.listener.address}:${C.port()}`)),process.platform==="linux"&&R(I)&&(gr(),await vr("app:terminal")),e.prepare?g={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await ye(),g={phase:"ready",message:"",blockerPaths:[]}),O}catch(n){try{await O()}catch(r){throw new AggregateError([n,r],"daemon startup failed and cleanup also failed")}throw n}}a(Nn,"runDaemon");var Ii=Nn;export{An as API_DRAIN_GRACE_MS,Ai as brokerCommandDeclaresCanvasHome,fe as brokerCommandEpoch,Ii as default,Cn as exitedNodePass,J as roleRunsLanes,F as roleServesRequests,Nn as runDaemon,Tn as superviseTick,dn as teardownFleet};
@@ -1,3 +1,3 @@
1
- var J=Object.defineProperty;var o=(t,e)=>J(t,"name",{value:e,configurable:!0});import{spawn as K,execFileSync as q}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as x,join as T}from"node:path";import{fileURLToPath as Z,pathToFileURL as N}from"node:url";import{existsSync as F,lstatSync as tt,mkdirSync as et,openSync as H,closeSync as G,fstatSync as W,readSync as rt}from"node:fs";import{apiSocketPath as nt,crtrHome as S}from"../core/canvas/paths.js";import{listProcessTable as ot}from"../core/canvas/pid.js";import{bindDaemonEventSource as at,eventSource as it}from"../core/events/source.js";import{hostExecPath as I}from"../core/runtime/branded-host.js";import{isDaemonRunning as st,readPidfile as w,isPidAlive as R}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as V}from"./startup-policy.js";import{computerIsUnset as ct,readMachineConfig as ut}from"./machine-link/config.js";import{exclusiveLockOwnerPid as lt}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as _t}from"../core/canvas/paths.js";import{envNoDaemonAutostart as dt}from"../shared/env.js";import{waitForDaemonAvailability as pt}from"../api/index.js";import{localClient as Rt}from"../api/node-transport.js";const ft=["TMUX","TMUX_PANE","NODE_OPTIONS"],mt=new Set(["CRTR_HOME","CRTR_RUNTIME_HOME","CRTR_PIDFILE","CRTR_RUNTIME","CRTR_INSTALL_ID","CRTR_LOG","CRTR_DEBUG","CRTR_DEBUG_PID_LIVENESS","CRTR_TIMING","CRTR_TIMING_PROC","CRTR_NO_DAEMON_AUTOSTART","CRTR_NO_AUTO_UPDATE","CRTR_NO_AUTO_INIT","CRTR_NO_EXPORTS","CRTR_LAYOUT_REFUSE","CRTR_POSTGRES_HOME","CRTR_DATABASE_URL","CRTR_DATABASE_SCHEMA","CRTR_DATABASE_POOL_MAX","CRTR_SCHEMA_DATABASE_URL","CRTR_DOCUMENT_PORT","CRTR_LAUNCHER_SOCKET","CRTR_API_ADDRESS","CRTR_DIRECTORY_URL","CRTR_PUBLIC_API_URL","CRTR_CANVAS_URL","CRTR_CANVAS_CLIENT_ID","CRTR_CANVAS_JWK_FILE","CRTR_SECRETS_KEY","CRTR_IMPORT_SERVICE_TOKEN","CRTR_PACKAGES_TOKEN","CRTR_FEEDBACK_ENDPOINT","CRTR_FEEDBACK_TOKEN","CRTR_SUPPORT_REPO","CRTR_BRANDED_HOST","CRTR_CODESIGN_IDENTITY","CRTR_PLUGIN_REVALIDATE_TTL_MS","CRTR_IMPORT_BLOB_WORKERS","CRTR_MAX_LIVE_BROKERS","CRTR_WARN_LIVE_BROKERS","CRTR_BROKER_RSS_CAP_MB","CRTR_UNATTENDED_PARK_MS","CRTR_WARM_POOL","CRTR_STREAM_WATCHDOG_MS","CRTR_CONVERSATION_COMMIT_DEADLINE_MS","CRTR_NAME_MODEL","CRTR_MODEL_PROVIDER","CRTR_BROKER_SIGNAL_LONG_PROOF"]),ht=["CRTR_DB_","CRTR_BOOT_","CRTR_R2_","CRTR_LEDGER_","CRTR_BASH_","CRTR_WATCHER_","CRTR_RECAP_","CRTR_MODEL_AUTH_","CRTR_TEST_","CRTR_FAULT_"];function Et(t){return ft.includes(t)?!1:t.startsWith("CRTR_")?mt.has(t)||ht.some(e=>t.startsWith(e)):!0}o(Et,"daemonKeepsEnv");function y(){const t={};for(const[e,r]of Object.entries(process.env))Et(e)&&(t[e]=r);return t}o(y,"sanitizedDaemonEnv");function Tt(){for(let t=x(Z(import.meta.url));;t=x(t)){if(F(T(t,"bin","runtime-generation-manifest.mjs")))return t;if(x(t)===t)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(Tt,"generationRoot");async function g(){const t=Tt(),e=N(T(t,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(e);try{tt(T(r(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",N(Q(import.meta.url).resolve("tsx/esm")).href,T(t,"src","daemon","crtrd-cli.ts")]}const n=N(T(t,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),s=a("daemon");if(!s.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${s.error}`);return[s.runtime.entryPath]}o(g,"resolveDaemonLaunch");function wt(t,e){return t.includes(` --canvas-home ${e} `)||t.endsWith(` --canvas-home ${e}`)}o(wt,"daemonCommandDeclaresCanvasHome");function Dt(){const t=ot();if(t===null)return[];const e=S(),r=[];for(const{pid:n,command:a}of t)a.includes("daemon/crtrd")&&wt(a,e)&&n!==process.pid&&r.push(n);return r}o(Dt,"findDaemonPids");function St(t){const e=Dt().filter(n=>n!==t);for(const n of e)try{process.kill(n,"SIGTERM")}catch{}if(e.length===0)return e;const r=Date.now()+2e3;for(;Date.now()<r&&e.some(n=>R(n));)q("sleep",["0.1"]);for(const n of e)if(R(n))try{process.kill(n,"SIGKILL")}catch{}return e}o(St,"sweepStrayDaemons");async function Zt(){const t=process.execve;if(t===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const e=I(),r=await g();return t(e,[e,...r,"--canvas-home",S()],y())}o(Zt,"execDaemon");async function P(t){const e=await g(),r=K(I(),[...e,...t],{stdio:["ignore","pipe","pipe"],env:y()});let n="",a="";r.stdout.setEncoding("utf8").on("data",c=>{n+=c}),r.stderr.setEncoding("utf8").on("data",c=>{a+=c});const s=await new Promise((c,d)=>{r.once("error",d),r.once("close",f=>c(f))});if(s!==0)throw new Error(a.trim()||`the ${t[0]} process exited with code ${s}`);const u=n.trim().split(`
2
- `).at(-1)??"";return JSON.parse(u)}o(P,"runDaemonEntry");function te(t,e){return P(["import-dump",t,e])}o(te,"runDaemonImportDump");function ee(t){return P(["import-dump",t,"bodies"])}o(ee,"runDaemonBodiesDump");function re(){return P(["import-dump","","install-id"])}o(re,"runDaemonInstallId");const j=2e4,L=10,v=1e3;async function b(t=v){const e=Math.min(t,v);return Rt({autostart:!1,timeoutMs:e,socketPath:nt()}).probeHealthz(e)}o(b,"probeDaemonHealth");function At(t){const e=t instanceof Error?t.message:String(t);if(typeof t!="object"||t===null)return e;const r=t.code,n=t.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!e.includes(a)?`${e}: ${a}`:e}o(At,"probeErrorMessage");async function X(t=v){const e=await b(t);if(e.startup_phase==="blocked"){const r=w()??process.pid;throw new C(r,e.startup_blocked??"daemon startup is blocked")}if(!e.ok)throw new Error(e.startup_blocked??"crtrd health check reported not ready")}o(X,"probeDaemonServing");async function ne(){try{return await X(),!0}catch{return!1}}o(ne,"isDaemonServing");function U(t){return new Promise(e=>{setTimeout(e,t)})}o(U,"sleepMs");class k extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(e,r){super(r===""?e:`${e}
3
- ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(e){super(e instanceof Error?e.message:String(e),{cause:e}),this.name="DaemonLaunchError"}}class C extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(e,r){super(`daemon ${e} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class B extends Error{static{o(this,"DaemonNotPreparedError")}constructor(e,r){super(r===void 0?`daemon ${e} is serving but did not report the prepared startup phase`:`daemon ${e} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function Ct(t,e=V,r={},n="ready"){const a=r.readPidfile??w,s=r.isPidAlive??R,u=r.childExited,c=r.isDaemonServing,d=r.probeDaemonServing??(async h=>{if(c!==void 0){if(await c())return;throw new Error("crtrd health check reported not ready")}await X(h)}),f=r.probeDaemonHealth??b,D=r.sleepMs??U,i=r.now??Date.now;let p=null,l=null;return await pt({windowMs:e,pollIntervalMs:L,now:i,sleep:D,retry:o(h=>h!==l,"retry"),probe:o(async h=>{const m=a();if(m===null||!s(m)){const _=u?.();throw _!=null&&(_.signal!==null?l=new k(`daemon ${t} exited before becoming ready (by ${_.signal})`,r.childStderrTail?.()??""):_.code!==0&&(l=new k(`daemon ${t} exited before becoming ready (with exit code ${_.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${t} has no live pidfile owner`)}if(n==="ready"){try{await d(h)}catch(_){throw _ instanceof C&&(l=_),_}p=m;return}const E=await f(h);if(E.startup_phase==="prepared"){p=m;return}throw E.startup_phase==="blocked"?(l=new C(m,E.startup_blocked??"on-disk migration is blocked"),l):E.startup_phase==="ready"?(l=new B(m,E.startup_phase),l):new Error(`daemon ${m} is ${E.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),p===t?null:p}o(Ct,"verifyDaemonStartup");async function Ot(t,e=j,r={}){const n=r.readPidfile??w,a=r.isPidAlive??R,s=r.sleepMs??U,u=r.now??Date.now,c=u()+e;for(;u()<=c;){if(!a(t)&&n()!==t)return;await s(L)}throw new Error(`daemon ${t} did not exit and release its pidfile within ${e}ms`)}o(Ot,"waitForDaemonExit");const Mt=2e3,xt=5e3;async function z(t,e=j,r={}){const n=r.isPidAlive??R,a=r.sleepMs??U,s=r.now??Date.now;try{process.kill(t,"SIGTERM")}catch{}try{return await Ot(t,e,r),"terminated"}catch{}try{process.kill(t,"SIGKILL")}catch{}const u=s()+Mt;for(;s()<=u;){if(!n(t))return"killed";await a(L)}throw new Error(`daemon ${t} survived both SIGTERM and SIGKILL`)}o(z,"stopDaemonProcess");async function oe(){const t=w(),e=t!==null&&R(t),r=e&&await z(t)==="killed",n=St(null);return{stopped:e||n.length>0,...e?{pid:t}:{},strays_killed:n,force_killed:r}}o(oe,"stopAllDaemons");function Nt(t,e,r=2048){let n;try{n=H(t,"r");const{size:a}=W(n),s=Math.max(e,a-r),u=a-s;if(u<=0)return"";const c=Buffer.alloc(u);return rt(n,c,0,u,s),c.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{G(n)}catch{}}}o(Nt,"readLogTailFrom");async function It(t={}){if(process.platform==="linux"&&F("/run/crtr/launcher.sock")&&!R(w()??-1)&&ut()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const e=t.targetPhase??"ready",r=w();if(r!==null&&R(r))try{const i=await b();if(e==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new B(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof B)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:At(i)}}et(S(),{recursive:!0});const n=await g().catch(i=>{throw new Y(i)}),a=T(S(),"crtrd.err"),s=H(a,"a"),u=(()=>{try{return W(s).size}catch{return 0}})();it()===void 0&&at();const c=K(I(),[...n,"--canvas-home",S(),...e==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:y()});G(s);const d=c.pid;if(d===void 0)throw new Error("daemon spawn did not return a pid");let f=null;c.once("exit",(i,p)=>{f={code:i,signal:p}}),c.unref();let D;try{D=await Ct(d,V,{childExited:o(()=>f,"childExited"),childStderrTail:o(()=>Nt(a,u),"childStderrTail")},e)}catch(i){const p=lt(_t())===d;if(f===null&&!p&&!(i instanceof C))try{await z(d,xt)}catch{}throw i}return D!==null?{started:!1,existing_pid:D,startup_phase:e}:{started:!0,pid:d,startup_phase:e}}o(It,"spawnDaemon");function yt(){return dt()||process.argv.includes("--no-autostart")}o(yt,"autostartDisabled");const gt=5e3,Pt=6e4;let $=!1,A,O=0,M=0;function Lt(t){return Math.min(gt*2**(t-1),Pt)}o(Lt,"autostartBackoffMs");function vt(){A=void 0,O=0,M=0}o(vt,"resetDaemonAutostart");function ae(){return A}o(ae,"daemonAutostartStartupFailure");function ie(t={}){const e=t.isDaemonRunning??st,r=t.spawnDaemon??It,n=t.now??Date.now;if(!yt()&&!(!t.spawnDaemon&&ct())&&!$&&!(n()<M)){if(e()){vt();return}A=void 0,$=!0,r().then(()=>{A=void 0,O=0,M=0},a=>{(a instanceof k||a instanceof Y)&&(A=a.message),O+=1,M=n()+Lt(O)}).finally(()=>{$=!1})}}o(ie,"ensureDaemon");export{ft as DAEMON_ENV_STRIP_KEYS,k as DaemonExitedBeforeReadyError,Y as DaemonLaunchError,B as DaemonNotPreparedError,C as DaemonStartupBlockedError,yt as autostartDisabled,ae as daemonAutostartStartupFailure,wt as daemonCommandDeclaresCanvasHome,Et as daemonKeepsEnv,ie as ensureDaemon,Zt as execDaemon,Dt as findDaemonPids,ne as isDaemonServing,b as probeDaemonHealth,X as probeDaemonServing,At as probeErrorMessage,vt as resetDaemonAutostart,ee as runDaemonBodiesDump,te as runDaemonImportDump,re as runDaemonInstallId,y as sanitizedDaemonEnv,It as spawnDaemon,oe as stopAllDaemons,z as stopDaemonProcess,St as sweepStrayDaemons,Ct as verifyDaemonStartup,Ot as waitForDaemonExit};
1
+ var J=Object.defineProperty;var o=(t,e)=>J(t,"name",{value:e,configurable:!0});import{spawn as K,execFileSync as q}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as x,join as T}from"node:path";import{fileURLToPath as Z,pathToFileURL as N}from"node:url";import{existsSync as F,lstatSync as tt,mkdirSync as et,openSync as H,closeSync as G,fstatSync as W,readSync as rt}from"node:fs";import{apiSocketPath as nt,crtrHome as S}from"../core/canvas/paths.js";import{listProcessTable as ot}from"../core/canvas/pid.js";import{bindDaemonEventSource as at,eventSource as it}from"../core/events/source.js";import{hostExecPath as I}from"../core/runtime/branded-host.js";import{isDaemonRunning as st,readPidfile as w,isPidAlive as R}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as V}from"./startup-policy.js";import{computerIsUnset as ct,readMachineConfig as ut}from"./machine-link/config.js";import{exclusiveLockOwnerPid as lt}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as dt}from"../core/canvas/paths.js";import{envNoDaemonAutostart as _t}from"../shared/env.js";import{waitForDaemonAvailability as pt}from"../api/index.js";import{localClient as Rt}from"../api/node-transport.js";const ft=["TMUX","TMUX_PANE","NODE_OPTIONS"],mt=new Set(["CRTR_HOME","CRTR_RUNTIME_HOME","CRTR_PIDFILE","CRTR_RUNTIME","CRTR_INSTALL_ID","CRTR_LOG","CRTR_DEBUG","CRTR_DEBUG_PID_LIVENESS","CRTR_TIMING","CRTR_TIMING_PROC","CRTR_NO_DAEMON_AUTOSTART","CRTR_NO_AUTO_UPDATE","CRTR_NO_AUTO_INIT","CRTR_NO_EXPORTS","CRTR_POSTGRES_HOME","CRTR_DATABASE_URL","CRTR_DATABASE_SCHEMA","CRTR_DATABASE_POOL_MAX","CRTR_SCHEMA_DATABASE_URL","CRTR_DOCUMENT_PORT","CRTR_LAUNCHER_SOCKET","CRTR_API_ADDRESS","CRTR_DIRECTORY_URL","CRTR_PUBLIC_API_URL","CRTR_CANVAS_URL","CRTR_CANVAS_CLIENT_ID","CRTR_CANVAS_JWK_FILE","CRTR_SECRETS_KEY","CRTR_IMPORT_SERVICE_TOKEN","CRTR_PACKAGES_TOKEN","CRTR_FEEDBACK_ENDPOINT","CRTR_FEEDBACK_TOKEN","CRTR_SUPPORT_REPO","CRTR_BRANDED_HOST","CRTR_CODESIGN_IDENTITY","CRTR_PLUGIN_REVALIDATE_TTL_MS","CRTR_IMPORT_BLOB_WORKERS","CRTR_MAX_LIVE_BROKERS","CRTR_WARN_LIVE_BROKERS","CRTR_BROKER_RSS_CAP_MB","CRTR_UNATTENDED_PARK_MS","CRTR_WARM_POOL","CRTR_STREAM_WATCHDOG_MS","CRTR_CONVERSATION_COMMIT_DEADLINE_MS","CRTR_NAME_MODEL","CRTR_MODEL_PROVIDER","CRTR_BROKER_SIGNAL_LONG_PROOF"]),ht=["CRTR_DB_","CRTR_BOOT_","CRTR_R2_","CRTR_LEDGER_","CRTR_BASH_","CRTR_WATCHER_","CRTR_RECAP_","CRTR_MODEL_AUTH_","CRTR_TEST_","CRTR_FAULT_"];function Et(t){return ft.includes(t)?!1:t.startsWith("CRTR_")?mt.has(t)||ht.some(e=>t.startsWith(e)):!0}o(Et,"daemonKeepsEnv");function y(){const t={};for(const[e,r]of Object.entries(process.env))Et(e)&&(t[e]=r);return t}o(y,"sanitizedDaemonEnv");function Tt(){for(let t=x(Z(import.meta.url));;t=x(t)){if(F(T(t,"bin","runtime-generation-manifest.mjs")))return t;if(x(t)===t)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(Tt,"generationRoot");async function g(){const t=Tt(),e=N(T(t,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(e);try{tt(T(r(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",N(Q(import.meta.url).resolve("tsx/esm")).href,T(t,"src","daemon","crtrd-cli.ts")]}const n=N(T(t,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),s=a("daemon");if(!s.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${s.error}`);return[s.runtime.entryPath]}o(g,"resolveDaemonLaunch");function wt(t,e){return t.includes(` --canvas-home ${e} `)||t.endsWith(` --canvas-home ${e}`)}o(wt,"daemonCommandDeclaresCanvasHome");function Dt(){const t=ot();if(t===null)return[];const e=S(),r=[];for(const{pid:n,command:a}of t)a.includes("daemon/crtrd")&&wt(a,e)&&n!==process.pid&&r.push(n);return r}o(Dt,"findDaemonPids");function St(t){const e=Dt().filter(n=>n!==t);for(const n of e)try{process.kill(n,"SIGTERM")}catch{}if(e.length===0)return e;const r=Date.now()+2e3;for(;Date.now()<r&&e.some(n=>R(n));)q("sleep",["0.1"]);for(const n of e)if(R(n))try{process.kill(n,"SIGKILL")}catch{}return e}o(St,"sweepStrayDaemons");async function Zt(){const t=process.execve;if(t===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const e=I(),r=await g();return t(e,[e,...r,"--canvas-home",S()],y())}o(Zt,"execDaemon");async function P(t){const e=await g(),r=K(I(),[...e,...t],{stdio:["ignore","pipe","pipe"],env:y()});let n="",a="";r.stdout.setEncoding("utf8").on("data",c=>{n+=c}),r.stderr.setEncoding("utf8").on("data",c=>{a+=c});const s=await new Promise((c,_)=>{r.once("error",_),r.once("close",f=>c(f))});if(s!==0)throw new Error(a.trim()||`the ${t[0]} process exited with code ${s}`);const u=n.trim().split(`
2
+ `).at(-1)??"";return JSON.parse(u)}o(P,"runDaemonEntry");function te(t,e){return P(["import-dump",t,e])}o(te,"runDaemonImportDump");function ee(t){return P(["import-dump",t,"bodies"])}o(ee,"runDaemonBodiesDump");function re(){return P(["import-dump","","install-id"])}o(re,"runDaemonInstallId");const j=2e4,L=10,v=1e3;async function b(t=v){const e=Math.min(t,v);return Rt({autostart:!1,timeoutMs:e,socketPath:nt()}).probeHealthz(e)}o(b,"probeDaemonHealth");function At(t){const e=t instanceof Error?t.message:String(t);if(typeof t!="object"||t===null)return e;const r=t.code,n=t.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!e.includes(a)?`${e}: ${a}`:e}o(At,"probeErrorMessage");async function X(t=v){const e=await b(t);if(e.startup_phase==="blocked"){const r=w()??process.pid;throw new C(r,e.startup_blocked??"daemon startup is blocked")}if(!e.ok)throw new Error(e.startup_blocked??"crtrd health check reported not ready")}o(X,"probeDaemonServing");async function ne(){try{return await X(),!0}catch{return!1}}o(ne,"isDaemonServing");function k(t){return new Promise(e=>{setTimeout(e,t)})}o(k,"sleepMs");class U extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(e,r){super(r===""?e:`${e}
3
+ ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class z extends Error{static{o(this,"DaemonLaunchError")}constructor(e){super(e instanceof Error?e.message:String(e),{cause:e}),this.name="DaemonLaunchError"}}class C extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(e,r){super(`daemon ${e} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class B extends Error{static{o(this,"DaemonNotPreparedError")}constructor(e,r){super(r===void 0?`daemon ${e} is serving but did not report the prepared startup phase`:`daemon ${e} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function Ct(t,e=V,r={},n="ready"){const a=r.readPidfile??w,s=r.isPidAlive??R,u=r.childExited,c=r.isDaemonServing,_=r.probeDaemonServing??(async h=>{if(c!==void 0){if(await c())return;throw new Error("crtrd health check reported not ready")}await X(h)}),f=r.probeDaemonHealth??b,D=r.sleepMs??k,i=r.now??Date.now;let p=null,l=null;return await pt({windowMs:e,pollIntervalMs:L,now:i,sleep:D,retry:o(h=>h!==l,"retry"),probe:o(async h=>{const m=a();if(m===null||!s(m)){const d=u?.();throw d!=null&&(d.signal!==null?l=new U(`daemon ${t} exited before becoming ready (by ${d.signal})`,r.childStderrTail?.()??""):d.code!==0&&(l=new U(`daemon ${t} exited before becoming ready (with exit code ${d.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${t} has no live pidfile owner`)}if(n==="ready"){try{await _(h)}catch(d){throw d instanceof C&&(l=d),d}p=m;return}const E=await f(h);if(E.startup_phase==="prepared"){p=m;return}throw E.startup_phase==="blocked"?(l=new C(m,E.startup_blocked??"on-disk migration is blocked"),l):E.startup_phase==="ready"?(l=new B(m,E.startup_phase),l):new Error(`daemon ${m} is ${E.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),p===t?null:p}o(Ct,"verifyDaemonStartup");async function Ot(t,e=j,r={}){const n=r.readPidfile??w,a=r.isPidAlive??R,s=r.sleepMs??k,u=r.now??Date.now,c=u()+e;for(;u()<=c;){if(!a(t)&&n()!==t)return;await s(L)}throw new Error(`daemon ${t} did not exit and release its pidfile within ${e}ms`)}o(Ot,"waitForDaemonExit");const Mt=2e3,xt=5e3;async function Y(t,e=j,r={}){const n=r.isPidAlive??R,a=r.sleepMs??k,s=r.now??Date.now;try{process.kill(t,"SIGTERM")}catch{}try{return await Ot(t,e,r),"terminated"}catch{}try{process.kill(t,"SIGKILL")}catch{}const u=s()+Mt;for(;s()<=u;){if(!n(t))return"killed";await a(L)}throw new Error(`daemon ${t} survived both SIGTERM and SIGKILL`)}o(Y,"stopDaemonProcess");async function oe(){const t=w(),e=t!==null&&R(t),r=e&&await Y(t)==="killed",n=St(null);return{stopped:e||n.length>0,...e?{pid:t}:{},strays_killed:n,force_killed:r}}o(oe,"stopAllDaemons");function Nt(t,e,r=2048){let n;try{n=H(t,"r");const{size:a}=W(n),s=Math.max(e,a-r),u=a-s;if(u<=0)return"";const c=Buffer.alloc(u);return rt(n,c,0,u,s),c.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{G(n)}catch{}}}o(Nt,"readLogTailFrom");async function It(t={}){if(process.platform==="linux"&&F("/run/crtr/launcher.sock")&&!R(w()??-1)&&ut()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const e=t.targetPhase??"ready",r=w();if(r!==null&&R(r))try{const i=await b();if(e==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new B(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof B)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:At(i)}}et(S(),{recursive:!0});const n=await g().catch(i=>{throw new z(i)}),a=T(S(),"crtrd.err"),s=H(a,"a"),u=(()=>{try{return W(s).size}catch{return 0}})();it()===void 0&&at();const c=K(I(),[...n,"--canvas-home",S(),...e==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:y()});G(s);const _=c.pid;if(_===void 0)throw new Error("daemon spawn did not return a pid");let f=null;c.once("exit",(i,p)=>{f={code:i,signal:p}}),c.unref();let D;try{D=await Ct(_,V,{childExited:o(()=>f,"childExited"),childStderrTail:o(()=>Nt(a,u),"childStderrTail")},e)}catch(i){const p=lt(dt())===_;if(f===null&&!p&&!(i instanceof C))try{await Y(_,xt)}catch{}throw i}return D!==null?{started:!1,existing_pid:D,startup_phase:e}:{started:!0,pid:_,startup_phase:e}}o(It,"spawnDaemon");function yt(){return _t()||process.argv.includes("--no-autostart")}o(yt,"autostartDisabled");const gt=5e3,Pt=6e4;let $=!1,A,O=0,M=0;function Lt(t){return Math.min(gt*2**(t-1),Pt)}o(Lt,"autostartBackoffMs");function vt(){A=void 0,O=0,M=0}o(vt,"resetDaemonAutostart");function ae(){return A}o(ae,"daemonAutostartStartupFailure");function ie(t={}){const e=t.isDaemonRunning??st,r=t.spawnDaemon??It,n=t.now??Date.now;if(!yt()&&!(!t.spawnDaemon&&ct())&&!$&&!(n()<M)){if(e()){vt();return}A=void 0,$=!0,r().then(()=>{A=void 0,O=0,M=0},a=>{(a instanceof U||a instanceof z)&&(A=a.message),O+=1,M=n()+Lt(O)}).finally(()=>{$=!1})}}o(ie,"ensureDaemon");export{ft as DAEMON_ENV_STRIP_KEYS,U as DaemonExitedBeforeReadyError,z as DaemonLaunchError,B as DaemonNotPreparedError,C as DaemonStartupBlockedError,yt as autostartDisabled,ae as daemonAutostartStartupFailure,wt as daemonCommandDeclaresCanvasHome,Et as daemonKeepsEnv,ie as ensureDaemon,Zt as execDaemon,Dt as findDaemonPids,ne as isDaemonServing,b as probeDaemonHealth,X as probeDaemonServing,At as probeErrorMessage,vt as resetDaemonAutostart,ee as runDaemonBodiesDump,te as runDaemonImportDump,re as runDaemonInstallId,y as sanitizedDaemonEnv,It as spawnDaemon,oe as stopAllDaemons,Y as stopDaemonProcess,St as sweepStrayDaemons,Ct as verifyDaemonStartup,Ot as waitForDaemonExit};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.755",
3
+ "version": "0.3.757",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -157,8 +157,8 @@
157
157
  },
158
158
  "license": "UNLICENSED",
159
159
  "dependencies": {
160
- "@north-light/identity": "0.3.755",
161
- "@north-light/plugin": "0.3.755",
160
+ "@north-light/identity": "0.3.757",
161
+ "@north-light/plugin": "0.3.757",
162
162
  "@earendil-works/chord": "1.5.2",
163
163
  "@earendil-works/pi-agent-core": "1.5.2",
164
164
  "@earendil-works/pi-ai": "1.5.2",
@@ -151,9 +151,6 @@ export class CrtrClient {
151
151
  admitDaemon() {
152
152
  return this.request('POST', routes.daemonAdmit());
153
153
  }
154
- migrateState(req) {
155
- return this.request('POST', routes.daemonMigrate(), req);
156
- }
157
154
  // Nodes
158
155
  appendNodeLog(id, req) {
159
156
  return this.request('POST', routes.nodeLog(this.nodePath(id)), req);
@@ -12,7 +12,7 @@
12
12
  //
13
13
  // PURITY (spec §3.1): Node built-ins + `src/api/*` only.
14
14
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
15
- export const CONTRACT_LEVEL = '1.77';
15
+ export const CONTRACT_LEVEL = '1.78';
16
16
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
17
17
  export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
18
18
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -21,7 +21,6 @@ export const routes = {
21
21
  status: () => `${V}/status`,
22
22
  due: () => `${V}/due`,
23
23
  daemonRestart: () => `${V}/daemon/restart`,
24
- daemonMigrate: () => `${V}/daemon/migrate`,
25
24
  daemonDrain: () => `${V}/daemon/drain`,
26
25
  daemonAdmit: () => `${V}/daemon/admit`,
27
26
  // Nodes — collection + item
@@ -290,20 +290,11 @@ export function isPkgInstallInvocation(argv) {
290
290
  }
291
291
  export function isSignInInvocation(argv) { return isSysInvocation(argv, 'signin') || isSysInvocation(argv, 'signout'); }
292
292
  export function isJoinInvocation(argv) { return isSysInvocation(argv, 'join'); }
293
- export function isLayoutMigrationInvocation(argv) { return isSysInvocation(argv, 'migrate'); }
294
293
  /** Assemble the canonical daemon-control definitions without loading settings or plugin discovery. This path exists so `crtr sys daemon restart` can start the new generation that converts pre-SQL user state. */
295
294
  export async function resolveDaemonControlRoot() {
296
295
  const { registerDaemonControlSys } = await import('./commands/sys/daemon.js');
297
296
  return defineRoot({ tagline: TAGLINE, globals: GLOBALS, subtrees: [registerDaemonControlSys()] });
298
297
  }
299
- /** Migration runs offline before command plugins can read or initialize scoped state. */
300
- export async function resolveLayoutMigrationRoot() {
301
- const [{ defineSysBranch }, { sysMigrateLeaf }] = await Promise.all([
302
- import('./commands/sys/branch.js'),
303
- import('./commands/sys/migrate.js'),
304
- ]);
305
- return defineRoot({ tagline: TAGLINE, globals: GLOBALS, subtrees: [defineSysBranch([sysMigrateLeaf])] });
306
- }
307
298
  /** Build a root that contains only the subtree `first` dispatches into.
308
299
  * Returns the FULL root when `first` is not a recognized subtree — bare `crtr`,
309
300
  * `-h`/`--help`, `--version`, and any unknown leading token all need the
@@ -1,6 +1,6 @@
1
1
  import { defineLeaf } from '../../core/command.js';
2
2
  import { usage } from '../../core/errors.js';
3
- import { resolve } from 'node:path';
3
+ import { resolveExistingProjectDir } from '../../core/profiles/project-dir.js';
4
4
  import { cliClient } from '../api-client.js';
5
5
  import { resolveMetaPairs } from './meta.js';
6
6
  export const newLeaf = defineLeaf({
@@ -87,7 +87,7 @@ export const newLeaf = defineLeaf({
87
87
  throw usage('provide `--name <name>` to create a profile, or `--root` to provision the stable root profile.');
88
88
  return newProfileOutput(await cliClient().createProfile({
89
89
  name,
90
- ...(project !== undefined ? { projects: [{ path: resolve(project) }] } : {}),
90
+ ...(project !== undefined ? { projects: [{ path: resolveExistingProjectDir(project) }] } : {}),
91
91
  ...(repos.length > 0 ? { repositories: repos } : {}),
92
92
  ...(defaultKind !== undefined ? { default_kind: defaultKind } : {}),
93
93
  ...(Object.keys(metadata).length > 0 ? { metadata } : {}),
@@ -1,6 +1,7 @@
1
1
  // `crtr profile project` manages purview relationships and per-owner automatic delivery limits.
2
2
  import { defineLeaf, defineBranch } from '../../core/command.js';
3
3
  import { resolve } from 'node:path';
4
+ import { resolveExistingProjectDir } from '../../core/profiles/project-dir.js';
4
5
  import { usage } from '../../core/errors.js';
5
6
  import { cliClient } from '../api-client.js';
6
7
  import { resolveProfileViaDaemon } from './daemon-profiles.js';
@@ -48,7 +49,7 @@ const addLeaf = defineLeaf({
48
49
  if ((dir === undefined) === (repo === undefined))
49
50
  throw usage('pass exactly one of --dir and --repo', { next: 'Use --dir <directory> for a folder or --repo <handle> for a repo with no folder.' });
50
51
  const updated = await cliClient().updateProfile(id, {
51
- add_project: dir !== undefined ? { path: resolve(dir) } : { repo: repo },
52
+ add_project: dir !== undefined ? { path: resolveExistingProjectDir(dir) } : { repo: repo },
52
53
  });
53
54
  return { profile_id: updated.id, projects: updated.projects };
54
55
  },
@@ -1,7 +1,7 @@
1
1
  import { defineBranch } from '../../core/command.js';
2
2
  const SYS_ROOT_ENTRY = {
3
3
  concept: 'crtr configuration, diagnostics, and self-management',
4
- desc: 'settings, config, connect, setup, tutorial, doctor, context, sync, migrate, join, update, version, feedback, logs, retry-delivery, support, limits, daemon',
4
+ desc: 'settings, config, connect, setup, tutorial, doctor, context, sync, join, update, version, feedback, logs, retry-delivery, support, limits, daemon',
5
5
  useWhen: 'managing the crtr installation, inspecting diagnostics, operating the crtrd supervisor process, or registering a hosted runtime with its directory before first boot',
6
6
  };
7
7
  const SYS_HELP = {
@@ -78,7 +78,7 @@ async function awaitDaemonPhase(phase, timeoutMs) {
78
78
  message: health.startup_blocked ?? 'daemon startup is blocked',
79
79
  received: health.startup_phase,
80
80
  field: 'phase',
81
- next: 'Repair the reported blocker paths with `crtr sys migrate`, then retry the await.',
81
+ next: 'Fix the reported blocker, then retry the await.',
82
82
  });
83
83
  }
84
84
  if (health.startup_phase === phase)
@@ -17,7 +17,6 @@ import { tutorialBranch } from './sys/tutorial/branch.js';
17
17
  import { supportBranch } from './sys/support.js';
18
18
  import { contextBranch } from './sys/context.js';
19
19
  import { sysSyncBranch } from './sys/sync.js';
20
- import { sysMigrateLeaf } from './sys/migrate.js';
21
20
  import { sysJoinLeaf } from './sys/join.js';
22
21
  import { sysImportBranch } from './sys/import/start.js';
23
22
  import { sysMachineBranch } from './sys/machine/rotate.js';
@@ -25,5 +24,5 @@ import { sysDesktopBranch } from './sys/desktop.js';
25
24
  import { sysSigninLeaf, sysSignoutLeaf } from './sys/signin.js';
26
25
  import { sysUpdateLeaf, sysVersionLeaf } from './sys/update.js';
27
26
  export function registerSys() {
28
- return defineSysBranch([sysSettingsLeaf, configBranch, sysEnvBranch, sysSetupLeaf, tutorialBranch, sysDoctorLeaf, contextBranch, sysFeedbackLeaf, sysLogsLeaf, sysWorktreesLeaf, sysRetryDeliveryLeaf, sysSpacesLeaf, sysLimitsBranch, sysSpendBranch, supportBranch, sysUpdateLeaf, sysVersionLeaf, sysMigrateLeaf, sysJoinLeaf, sysSyncBranch, sysImportBranch, sysMachineBranch, sysSigninLeaf, sysSignoutLeaf, sysDesktopBranch, daemonBranch]);
27
+ return defineSysBranch([sysSettingsLeaf, configBranch, sysEnvBranch, sysSetupLeaf, tutorialBranch, sysDoctorLeaf, contextBranch, sysFeedbackLeaf, sysLogsLeaf, sysWorktreesLeaf, sysRetryDeliveryLeaf, sysSpacesLeaf, sysLimitsBranch, sysSpendBranch, supportBranch, sysUpdateLeaf, sysVersionLeaf, sysJoinLeaf, sysSyncBranch, sysImportBranch, sysMachineBranch, sysSigninLeaf, sysSignoutLeaf, sysDesktopBranch, daemonBranch]);
29
28
  }
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { openDb, withCanvasWrite } from './db.js';
3
- import { capturePidIdentities, captureLivenessSnapshot, identitiesMatch, recordedPidLiveness, isBootScopedIdentity, isLegacyTicksIdentity } from './pid.js';
3
+ import { capturePidIdentities, captureLivenessSnapshot, recordedPidLiveness } from './pid.js';
4
4
  import { existsSync, readFileSync } from 'node:fs';
5
5
  import { LAUNCHER_SOCKET } from '../../launcher/spec.js';
6
6
  import { revokeNodeTokens } from './node-tokens.js';
@@ -187,22 +187,6 @@ export async function endLiveExecution(nodeId, input) {
187
187
  return Number(ended.changes) === 1;
188
188
  });
189
189
  }
190
- export async function migrateLegacyExecutionIdentities(captureIdentity = (pid) => capturePidIdentities([pid])?.get(pid)) {
191
- const db = await openDb();
192
- const rows = await db.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all();
193
- const update = db.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'");
194
- const migrated = [];
195
- for (const row of rows) {
196
- if (!isLegacyTicksIdentity(row.process_identity))
197
- continue;
198
- const current = captureIdentity(row.pid);
199
- if (current === undefined || !isBootScopedIdentity(current) || !identitiesMatch(current, row.process_identity))
200
- continue;
201
- if ((await update.run(current, row.execution_id, row.pid, row.process_identity)).changes > 0)
202
- migrated.push(row.execution_id);
203
- }
204
- return { migrated };
205
- }
206
190
  /** Records a stop request on the node's live execution; the first request's time and reason stand. */
207
191
  export async function requestExecutionStop(nodeId, input) {
208
192
  const updated = await (await openDb()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(now(), input.afterTurn ? 1 : 0, input.reason, nodeId);
@@ -304,22 +304,6 @@ export function makeBootIdCache(read, now = Date.now, negativeTtlMs = BOOT_ID_NE
304
304
  };
305
305
  }
306
306
  const bootIdBase = makeBootIdCache(readKernelBootId);
307
- /** Is `identity` a LEGACY (pre-boot-scoped) baseline — a `<lstart>#<ticks>` row
308
- * whose base is NOT a boot_id UUID but which DOES carry ticks? These are the
309
- * rows the one-time startup migration re-records once this platform can
310
- * compose boot-scoped identities (see `migrateLegacyPidIdentities`). */
311
- export function isLegacyTicksIdentity(identity) {
312
- const { base, ticks } = splitIdentity(identity);
313
- return ticks !== undefined && !BOOT_ID_RE.test(base);
314
- }
315
- /** Is `identity` a NEW-format boot-scoped baseline — `<bootId>#<ticks>` with a
316
- * real boot_id UUID base AND ticks? The startup migration only re-records a
317
- * legacy row when the pid's CURRENT identity comes out in this shape (i.e. the
318
- * platform now composes new-format), never otherwise. */
319
- export function isBootScopedIdentity(identity) {
320
- const { base, ticks } = splitIdentity(identity);
321
- return ticks !== undefined && BOOT_ID_RE.test(base);
322
- }
323
307
  /** Compose the stable, BOOT-SCOPED process-identity fingerprint used
324
308
  * everywhere in this module. ALWAYS used to build an identity string, never a
325
309
  * raw field directly, so every identity captured anywhere (launch-time
@@ -3,13 +3,13 @@
3
3
  // It writes no settings (the daemon applies them at its start); the private key never leaves this computer.
4
4
  import { createHash, generateKeyPairSync, randomUUID } from 'node:crypto';
5
5
  import { existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs';
6
+ import { request } from 'node:http';
6
7
  import { hostname } from 'node:os';
7
8
  import { join } from 'node:path';
8
9
  import { InputError } from '../io.js';
9
10
  import { network } from '../errors.js';
10
11
  import { secretsDir } from '../layout.js';
11
12
  import { apiSocketPath } from '../canvas/paths.js';
12
- import { daemonAnswers } from '../layout-migrate/index.js';
13
13
  import { atomicWriteJson, readJsonIfExists } from '../fs-utils.js';
14
14
  import { launcherPresent } from '../grants/sandboxes.js';
15
15
  import { crtrVersion } from '../../shared/crtr-version.js';
@@ -151,6 +151,23 @@ async function registerAndStore(directory, credential, name, retry) {
151
151
  }
152
152
  return { ...joined, registered };
153
153
  }
154
+ /** True when a daemon answers /healthz on the socket (a blocked daemon still answers and owns its files). */
155
+ function daemonAnswers(socketPath) {
156
+ return new Promise(resolve => {
157
+ const req = request({ socketPath, path: '/healthz', method: 'GET', timeout: 1000 }, res => {
158
+ res.resume();
159
+ resolve(true);
160
+ });
161
+ req.on('timeout', () => req.destroy(new Error('daemon probe timed out')));
162
+ req.on('error', error => {
163
+ if (error.code === 'ENOENT' || error.code === 'ECONNREFUSED')
164
+ resolve(false);
165
+ else
166
+ resolve(true); // Uncertain probe: do not touch an owned volume.
167
+ });
168
+ req.end();
169
+ });
170
+ }
154
171
  /** A hosted runtime's first boot: register with the provisioning enrollment token before any daemon exists. Refuses `daemon_running` when one answers. */
155
172
  export async function joinDirectory(directory, token, name = hostname()) {
156
173
  const socket = apiSocketPath();
@@ -417,13 +417,6 @@ export async function dropLocalGrantMirror(db) {
417
417
  await db.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run();
418
418
  return Number((await db.prepare('DELETE FROM grants').run()).changes);
419
419
  }
420
- /** Mark rows a build older than C-D2 wrote as computed for their revision. That build computed every column locally in the same
421
- * write but never set `computed_rev`, so its rows are complete; left NULL they read as no grant until the next successful
422
- * sync rewrites them, and the terminal grant then refuses every launch (NL-550). A directory-written row with lagging
423
- * columns has NULL scopes, so it is never matched. Returns the rows changed. */
424
- export async function backfillComputedRev() {
425
- return await withCanvasWrite(async (db) => Number((await db.prepare('UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL').run()).changes));
426
- }
427
420
  /** The `teams` a grant sync answer carried; absent (an unjoined install, an older directory) reads as none. Team
428
421
  * membership is advisory next to the grants the same answer carries, so an entry that is not a directory team
429
422
  * (`team:<id>`, e.g. a canvas group row echoed back) is dropped rather than failing the sync. */
@@ -8,9 +8,9 @@ import { isUnsandboxedMachine } from '../runtime/unsandboxed.js';
8
8
  import { emitEvent } from '../events/emit.js';
9
9
  import { describeOutboundFailure, outboundFetch, outboundJson, outboundRefusal } from '../events/outbound.js';
10
10
  import { dependenciesOf, endpointPays, inferenceEndpointOf, principalPayer, replaceGrants, teamsOf } from './mirror.js';
11
+ import { loadPersonSettings } from '../scoped-state/person-rows.js';
11
12
  import { onGrantSync } from './on-sync.js';
12
13
  import { hostedEndpointOf, paymentSetupUrlOf, storeHostedEndpoint } from './hosted-endpoint.js';
13
- import { adoptInstallPerson } from '../scoped-state/migrate.js';
14
14
  import { PersonOutsideRequestError, PersonUnresolvedError, personId, resolvePerson, retireLocalPerson, setPersonId } from '../canvas/person.js';
15
15
  export const GRANT_SYNC_INTERVAL_S = 300;
16
16
  /** A `private_key_jwt` client assertion for `endpoint` (the directory's token endpoint), signed by the runtime client key. */
@@ -135,7 +135,7 @@ async function pullPerson() {
135
135
  /** Bind a person resolved on a hosted first boot and run the boot one-shot. */
136
136
  async function bindLatePerson(resolved) {
137
137
  setPersonId(resolved.id);
138
- await adoptInstallPerson(resolved.id);
138
+ await loadPersonSettings(resolved.id);
139
139
  const result = await retireLocalPerson();
140
140
  // The boot reconcile was skipped while the person was unresolved.
141
141
  await withCanvasWrite(async (db) => await reconcilePackages(db));
@@ -300,11 +300,6 @@ export function apiErrorToCliError(err, next, options = {}) {
300
300
  next: 'crtrd is now on the new generation — retry the command.',
301
301
  });
302
302
  }
303
- if (err.code === 'layout_migration_required') {
304
- return new CrtrError('layout_migration_required', err.message, ExitCode.NETWORK, {
305
- next: 'Run `crtr sys migrate` while the runtime is offline, then restart it.',
306
- });
307
- }
308
303
  if (err.code === 'daemon_unavailable') {
309
304
  return new CrtrError('daemon_unavailable', err.message, ExitCode.NETWORK, {
310
305
  next: 'Start it with `crtr sys daemon start`, then retry.',