@north-light/cli 0.3.750 → 0.3.752

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 (70) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/environments.d.ts +37 -0
  4. package/dist/api/routes.d.ts +2 -0
  5. package/dist/api/routes.js +1 -1
  6. package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
  7. package/dist/clients/attach/viewer.js +1 -1
  8. package/dist/core/canvas/schema-pg/037-grant-principals.sql +50 -0
  9. package/dist/core/canvas/schema-version.d.ts +1 -1
  10. package/dist/core/canvas/schema-version.js +1 -1
  11. package/dist/core/environments.js +1 -1
  12. package/dist/core/grants/local.js +1 -1
  13. package/dist/core/grants/mirror.d.ts +11 -3
  14. package/dist/core/grants/mirror.js +12 -12
  15. package/dist/core/grants/shadow.js +1 -1
  16. package/dist/core/grants/sync.js +1 -1
  17. package/dist/core/graph/objects.d.ts +3 -1
  18. package/dist/core/graph/objects.js +10 -10
  19. package/dist/core/ledger/payer.d.ts +4 -4
  20. package/dist/core/ledger/payer.js +1 -1
  21. package/dist/core/llm/app-rungs.js +1 -1
  22. package/dist/core/llm/run.d.ts +2 -2
  23. package/dist/core/llm/run.js +2 -2
  24. package/dist/core/profiles/manifest.d.ts +5 -0
  25. package/dist/core/profiles/manifest.js +1 -1
  26. package/dist/core/runtime/runner/blaxel/image-build.d.ts +10 -11
  27. package/dist/core/runtime/runner/blaxel/image-build.js +7 -6
  28. package/dist/core/runtime/start-check.js +1 -1
  29. package/dist/daemon/api/app-listener.js +12 -12
  30. package/dist/daemon/api/handlers/app-environments.d.ts +2 -0
  31. package/dist/daemon/api/handlers/app-environments.js +1 -0
  32. package/dist/daemon/api/handlers/git-credential.js +1 -1
  33. package/dist/daemon/api/handlers/runs.js +1 -1
  34. package/dist/daemon/api/operations.js +1 -1
  35. package/dist/daemon/api/principal.d.ts +11 -5
  36. package/dist/daemon/api/principal.js +1 -1
  37. package/dist/daemon/api/server.js +1 -1
  38. package/dist/daemon/crtrd.js +12 -12
  39. package/dist/daemon/reconcilers/recipe-image.d.ts +2 -0
  40. package/dist/daemon/reconcilers/recipe-image.js +5 -5
  41. package/docs/ci-runner.md +1 -1
  42. package/docs/sdk/release-notes.md +10 -0
  43. package/package.json +3 -3
  44. package/packages/crouter-api/dist/api/contract.js +1 -1
  45. package/packages/crouter-api/dist/api/routes.js +2 -0
  46. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  47. package/packages/crouter-api/dist/core/environments.js +3 -2
  48. package/packages/crouter-api/dist/core/grants/local.js +1 -1
  49. package/packages/crouter-api/dist/core/grants/mirror.js +35 -11
  50. package/packages/crouter-api/dist/core/grants/shadow.js +4 -2
  51. package/packages/crouter-api/dist/core/grants/sync.js +5 -4
  52. package/packages/crouter-api/dist/core/graph/objects.js +2 -2
  53. package/packages/crouter-api/dist/core/ledger/payer.js +8 -3
  54. package/packages/crouter-api/dist/core/llm/app-rungs.js +2 -2
  55. package/packages/crouter-api/dist/core/llm/run.js +3 -2
  56. package/packages/crouter-api/dist/core/profiles/manifest.js +1 -1
  57. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +42 -44
  58. package/packages/crouter-api/dist/core/runtime/start-check.js +2 -2
  59. package/packages/crouter-api/dist/daemon/api/handlers/git-credential.js +12 -2
  60. package/packages/crouter-api/dist/daemon/api/operations.js +4 -0
  61. package/packages/crouter-api/dist/daemon/api/principal.js +26 -7
  62. package/packages/crouter-api/dist/daemon/reconcilers/recipe-image.js +9 -1
  63. package/packages/crouter-api/package.json +1 -1
  64. package/packages/crouter-identity/dist/index.d.ts +4 -2
  65. package/packages/crouter-identity/dist/index.js +31 -12
  66. package/packages/crouter-identity/package.json +1 -1
  67. package/packages/crouter-plugin/dist/serve.js +4 -1
  68. package/packages/crouter-plugin/dist/verify.js +36 -8
  69. package/packages/crouter-plugin/package.json +3 -3
  70. package/runtime.lock.json +14 -14
@@ -1,21 +1,21 @@
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 Ce}from"node:crypto";import{apiSocketPath as De,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 D}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 Cr}from"../core/profiles/relocate.js";import{getNode as Dr,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 Ct}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Dt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as At}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Lt,subscribeImageBuilt as $t}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Nt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Fe,capturePidCommand as Mt,captureTeardownSnapshot as Be,isPidAlive as Gt,isAnyPidAlive as He,killProcessTreePids as Ue}from"../core/canvas/pid.js";import{bindFleet as Ot,boundFleet as je}from"../core/runtime/fleet.js";import{bindDaemonControl as Ft,clearDaemonControl as Bt}from"./control.js";import{execDaemon as Ht,spawnDaemon as Ut}from"./manage.js";import{reconcileAndMigrateBoot as jt}from"../core/canvas/boot.js";import{resolveInstallId as zt}from"../core/canvas/install-id.js";import{setInstallId as qt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Wt,daemonOwnershipApplies as Kt,daemonOwnershipClaimed as Jt,releaseDaemonOwnership as ze}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Vt,closeAllDbs as ue,openDb as Yt,withCanvasWrite as he}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Qt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Xt,ensurePostgresHealthy as Zt,stopPostgres as en,withPostgresStartLock as rn}from"./postgres/index.js";import{brokerSignalBus as M}from"./broker-signals/bus.js";import{brokerSignalStreams as tn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as nn}from"./api/handlers/broker-ops.js";import{reconcilePackages as on}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as an}from"../core/scoped-state/migrate-app-installs.js";import{publish as sn,readBuiltinSnapshot as ln}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as cn,reapStaleSpares as dn}from"../core/runtime/warm-pool.js";import{DaemonFleet as pn}from"./fleet.js";import{copyNodeFilesToRows as mn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as fn}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 un}from"../core/events/source.js";import{activateCanvasImport as hn,MigrationBlockedError as wn,runForcedCanvasImport as vn}from"../migrations/activation.js";import{adoptInstallPerson as gn,convertLegacyScopedStore as yn,personStoresCopied as Sn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as _n}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as qe,installPreludeSnapshot as bn}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 na}from"../core/runtime/broker-ownership.js";function ge(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ge,"brokerCommandEpoch");const kn=5e3,Ke=150;async function Rn(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=Mt(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(D)?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()+kn;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(D)?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(Rn,"reapPriorEpochBrokers");const En=5e3;async function Pn(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[o]of c){const w=(await Dr(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(D)?await N({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const p=new Promise(o=>{setTimeout(o,En).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),p])));const g=[];for(const o of f)Gt(o.pid)&&(process.platform==="linux"&&E(D)?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(Pn,"teardownFleet");function Q(...e){Pe(vr(me()),{recursive:!0}),ur(me(),[process.pid,...e].join(`
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
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 In={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new st;at(e=>X.handleFatalFault(e,!1));const xn=new ct,Tn=new lt,Ye=new dt,Cn=new pt,Dn=new mt,An=new ft,Ln=new ut,$n=new St,Nn=new _t,Mn=new bt,Gn=new Rt,On=new kt,Fn=new Pt,Bn=new It,Hn=new xt,Un=new Tt,jn=new Ct,zn=new Dt,qn=new At,Wn=new Lt;async function Kn(e=Date.now(),c=In){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 xn.run(e,{rows:g,held:o}),await Tn.run(e);const y=await Ye.run(e,{rows:[...g,...w],fleet:f});await Cn.run(e,o),await qn.run(e,o),await Wn.run(e,{lifecycle:c}),await Dn.run(e,{lifecycle:c,held:o}),await An.run(e,{lifecycle:c}),await Ln.run(e,{lifecycle:c}),await $n.run(e,{lifecycle:c}),await Nn.run(e,{lifecycle:c,fleet:f,held:o}),Mn.run(e,{lifecycle:c}),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}),await _r(),zn.run(e,{fleet:f,lifecycle:c}),await jn.run(e,{rows:g}),X.warnIfSaturated({fleet:f,lifecycle:c,thresholds:p,frozen:y})}s(Kn,"superviseTick");async function Jn(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(Jn,"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 Vn=66e4;function Yn(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=De();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(Yn,"createProbeServer");const Qn="daemon is draining for shutdown and admits no new work";async function Xn(e){Pe(Ae(),{recursive:!0,mode:493}),process.platform==="linux"&&xe(Ae(),493);const c=De();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(Xn,"serveLayoutRefusal");async function Zn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(xr())return Xn(e);Ir();const c=s(r=>{process.stderr.write(`[crtrd] ${r}
5
- `)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,p=Kt(e.role);nn(Z(e.role));const g=s(async()=>p?await Wt(Ce(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Ce(16).toString("hex")}},"claimOwnership"),{database:o,ownership:w}=e.role!==void 0||f?{database:{url:await Vt()},ownership:await g()}:await rn(async()=>({database:await Xt({log:c,startLockHeld:!0}),ownership:await g()}));if(!w.claimed){if(w.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${w.incumbentPid??"?"})
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
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 Rn(y.token);for(const n of Cr())process.stderr.write(`[crtrd] ${n}
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
8
  `);for(const n of await Tr())process.stderr.write(`[crtrd] ${n}
9
- `);await Yt(),await Qt(o.url,c);const r=e.role===void 0&&!await Sn();let t=null;r&&(yn({kind:"user",root:We()}),t=_n(We())),e.role===void 0&&bn(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=ln()}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 sn(R,n,"release")));l=await he(async R=>await an(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 on(h)));if(n!==null){for(const h of n.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${h.message}
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
11
  `);for(const h of n.invalid)process.stderr.write(`[crtrd] package file is not a document: ${h.path}: ${h.error}
12
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
13
  `);for(const h of n.kinds.refused)process.stderr.write(`[crtrd] plugin "${h.plugin}" kind ${h.kind} not registered: ${h.message}
14
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 zt(),qt(_),e.role===void 0&&d!==null){if(await gn(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(D)&&(Pr(),await N({operation:"users.sync",users:await kr()})),p){await yt(y.token);const n=await mn();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,tn.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 Pn(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{Bt(),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 C()}catch(r){const t=r instanceof Error?r.stack??r.message:String(r);process.stderr.write(`[crtrd] handover cleanup failed:
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:
17
17
  ${t}
18
- `),process.exit(1)}try{process.platform==="linux"&&E(D)&&(await N({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Ht();const r=await Ut();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 C(){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(C,"requestCleanup");async function or(){S={phase:"initializing",message:Qn,blockerPaths:[]},I!==void 0&&!q&&(q=!0,await I.close({graceMs:Vn}))}s(or,"drainApi");async function _e(r){try{r==="SIGTERM"&&e.role==="api"&&await or(),await C(),await en({claimed:s(async()=>{try{return p&&await Jt()}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:
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
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(){C().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 Zt({log:c}),await Kn(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 vn({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(()=>{C().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 pn({epoch:r,enqueue:J}),Ot(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 jt(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 Nt();for(const a of fn){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 dn(),await cn()}),te=dr(),j=setInterval(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))},ee),ne=await $t(()=>{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(()=>Jn(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),un(),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;Ft({epoch:r,requestHandover:tr,registerDetached:k,startupBlock:Ze,admitStartup:ir,repairMigrations:ar}),Q(),I=H(e.role)?$r({tcp:e.tcp}):Yn(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 hn()}catch(a){if($=null,a instanceof wn)return S={phase:"blocked",message:a.message,blockerPaths:a.blockerPaths},C;throw a}process.platform==="linux"&&E(D)&&(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 C}catch(r){try{await C()}catch(t){throw new AggregateError([r,t],"daemon startup failed and cleanup also failed")}throw r}}s(Zn,"runDaemon");var ea=Zn;export{Vn as API_DRAIN_GRACE_MS,na as brokerCommandDeclaresCanvasHome,ge as brokerCommandEpoch,ea as default,Jn as exitedNodePass,Z as roleRunsLanes,H as roleServesRequests,Zn as runDaemon,Kn as superviseTick,Pn as teardownFleet};
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};
@@ -40,6 +40,8 @@ export interface RecipeImageDeps {
40
40
  deleteImage?: (name: string) => Promise<void>;
41
41
  now?: () => number;
42
42
  }
43
+ /** Deletes build folders a previous process left behind when it died mid-build; run once at startup. */
44
+ export declare function removeLeftoverBuildDirs(root?: string): void;
43
45
  export declare class RecipeImageReconciler {
44
46
  private readonly deps;
45
47
  constructor(deps?: RecipeImageDeps);
@@ -1,6 +1,6 @@
1
- var T=Object.defineProperty;var d=(o,e)=>T(o,"name",{value:e,configurable:!0});import{mkdtempSync as A}from"node:fs";import{tmpdir as h}from"node:os";import{join as R}from"node:path";import{hasUnseenWakeMail as O}from"../../core/canvas/deliveries.js";import{openDb as l,withCanvasWrite as U}from"../../core/canvas/db.js";import{emitEvent as g}from"../../core/events/emit.js";import{appendRunEvent as y}from"../../core/runs/events.js";import{blaxelConfigFromEnv as u}from"../../core/runtime/runner/blaxel/client.js";import{buildImage as I,deleteImage as W,environmentImageName as f,prepareBuildDir as C,removeBuildDir as j}from"../../core/runtime/runner/blaxel/image-build.js";import{mintInstallationToken as H}from"../api/handlers/git-credential.js";import{RECIPE_HAS_CONTENT_SQL as w,packagesTokenFor as k,recipeOf as x}from"../api/environment-of.js";import{brokerSignalBus as $}from"../broker-signals/bus.js";const E=3*6e4,N=10*6e4,p="EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL)",b=`NOT ${p}`,S=`(kind = 'blaxel' AND ${b} AND recipe_revision > COALESCE(image_revision, 0) AND ${w})`,L=`(kind = 'blaxel' AND ${p} AND (image_ref IS NOT NULL OR image_revision IS NOT NULL OR image_building_at IS NOT NULL))`;async function ie(o){const e=await(await l()).prepare(`SELECT ${w} AS has_content, image_revision, image_ref, image_error FROM environments WHERE object = ?`).get(o);if(e===void 0)throw new Error(`no environment ${o}`);return e.has_content?e.image_ref===null||e.image_revision===null?{state:"pending",error:e.image_error}:{state:"image",ref:e.image_ref,revision:Number(e.image_revision)}:{state:"base"}}d(ie,"resolveEnvironmentImage");async function te(o){return await $.subscribe(e=>{o(e)},{kinds:["environment_image"]})}d(te,"subscribeImageBuilt");async function F(o,e){const t=o.recipe.repositories.map(r=>r.github_full_name),i=t.length===0?null:await H(o.person,t),a=A(R(h(),"crtr-recipe-image-"));try{return await C({recipe:o.recipe,revision:o.revision,token:i?.token??null,packagesToken:await k(o.environmentId),dir:a}),await I(e,f(o.environmentId),a)}finally{j(a)}}d(F,"defaultBuild");class re{static{d(this,"RecipeImageReconciler")}deps;constructor(e={}){this.deps=e}async run(e,t){if(t.lifecycle.acceptsDetachedWork())try{const i=new Date(e).toISOString(),a=await l(),r=await a.prepare(`SELECT object FROM environments WHERE ${S} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(i);for(const{object:n}of r){const s=await this.claim(n,e,S,"recipe_revision");s!==null&&t.lifecycle.registerDetached(this.buildClaimed(n,Number(s.recipe_revision),s.lease).catch(_=>{g({level:"error",event:"recipe_image.failed",error:_})}))}const c=await a.prepare(`SELECT object FROM environments WHERE ${L} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(i);for(const{object:n}of c){const s=await this.claim(n,e,L,"object");s!==null&&t.lifecycle.registerDetached(this.withLease(n,s.lease,_=>this.deleteClaimed(n,_)).catch(_=>{g({level:"error",event:"recipe_image.delete_failed",error:_})}))}}catch(i){g({level:"error",event:"recipe_image.reconcile_failed",error:i})}}async claim(e,t,i,a){const r=new Date(t+E).toISOString(),c=await(await l()).prepare(`UPDATE environments SET image_building_at = ?
2
- WHERE object = ? AND ${i} AND (image_building_at IS NULL OR image_building_at <= ?)
3
- RETURNING ${a} AS recipe_revision`).get(r,e,new Date(t).toISOString());return c===void 0?null:{recipe_revision:c.recipe_revision,lease:r}}async withLease(e,t,i){const a=this.deps.now??Date.now;let r=t;const c=setInterval(()=>{const n=new Date(a()+E).toISOString();(async()=>{(await(await l()).prepare("UPDATE environments SET image_building_at = ? WHERE object = ? AND image_building_at = ?").run(n,e,r)).changes===1&&(r=n)})().catch(()=>{})},E/3);c.unref();try{await i(()=>r)}finally{clearInterval(c)}}async deleteClaimed(e,t){try{await(this.deps.deleteImage??(i=>W(u(),i)))(f(e))}catch(i){const a=i instanceof Error?i.message:String(i),r=new Date((this.deps.now??Date.now)()+N).toISOString();(await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(`deleting the image failed: ${a}`,r,e,t())).changes===1&&g({level:"error",event:"recipe_image.delete_failed",fields:{environment_id:e,error:a}});return}await(await l()).prepare("UPDATE environments SET image_ref = NULL, image_revision = NULL, image_error = NULL, image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,t())}async buildClaimed(e,t,i){const a=this.deps.now??Date.now;await this.withLease(e,i,async r=>{const c=await x(e);if(c===null||c.revision!==t){await(await l()).prepare("UPDATE environments SET image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,r());return}let n;try{const m=await(await l()).prepare("SELECT person FROM profiles WHERE environment_id = ? ORDER BY created_at LIMIT 1").get(e);if(m===void 0)throw new Error(`no profile runs in environment ${e}, so there is no person to take a GitHub token for`);const D={environmentId:e,revision:t,recipe:c,person:m.person};n=await(this.deps.build??(v=>F(v,u())))(D)}catch(m){await this.recordFailure(e,r(),m instanceof Error?m.message:String(m),a());return}const s=await l();(await s.prepare(`UPDATE environments SET image_revision = ?, image_ref = ?, image_error = NULL, image_building_at = NULL
4
- WHERE object = ? AND image_building_at = ? AND COALESCE(image_revision, 0) < ? AND ${b}`).run(t,n.ref,e,r(),t)).changes!==1&&await s.prepare(`UPDATE environments SET image_ref = ?, image_building_at = NULL WHERE object = ? AND ${p}`).run(n.ref,e)})}async recordFailure(e,t,i,a){const r=new Date(a+N).toISOString();if((await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(i,r,e,t)).changes===1){g({level:"error",event:"recipe_image.build_failed",fields:{environment_id:e,error:i}});for(const n of await M(e))try{await U(async s=>{await y(s,n.run_id,n.node_id,"environment.image_failed",{environment_id:e,error:i})})}catch(s){g({level:"error",event:"recipe_image.failure_event_failed",node_id:n.node_id,error:s})}}}}async function M(o){const e=await(await l()).prepare(`SELECT n.node_id, n.run_id FROM nodes n JOIN profiles p ON p.id = n.profile_id
1
+ var h=Object.defineProperty;var _=(r,e)=>h(r,"name",{value:e,configurable:!0});import{mkdtempSync as R,readdirSync as O,rmSync as y}from"node:fs";import{tmpdir as u}from"node:os";import{join as f}from"node:path";import{hasUnseenWakeMail as U}from"../../core/canvas/deliveries.js";import{openDb as l,withCanvasWrite as I}from"../../core/canvas/db.js";import{emitEvent as g}from"../../core/events/emit.js";import{appendRunEvent as W}from"../../core/runs/events.js";import{blaxelConfigFromEnv as w}from"../../core/runtime/runner/blaxel/client.js";import{buildImage as C,deleteImage as j,environmentImageName as b,prepareBuildDir as H,removeBuildDir as k}from"../../core/runtime/runner/blaxel/image-build.js";import{mintInstallationToken as x}from"../api/handlers/git-credential.js";import{RECIPE_HAS_CONTENT_SQL as N,packagesTokenFor as $,recipeOf as F}from"../api/environment-of.js";import{brokerSignalBus as M}from"../broker-signals/bus.js";const p=3*6e4,S=10*6e4,E="EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL)",D=`NOT ${E}`,L=`(kind = 'blaxel' AND ${D} AND recipe_revision > COALESCE(image_revision, 0) AND ${N})`,v=`(kind = 'blaxel' AND ${E} AND (image_ref IS NOT NULL OR image_revision IS NOT NULL OR image_building_at IS NOT NULL))`;async function re(r){const e=await(await l()).prepare(`SELECT ${N} AS has_content, image_revision, image_ref, image_error FROM environments WHERE object = ?`).get(r);if(e===void 0)throw new Error(`no environment ${r}`);return e.has_content?e.image_ref===null||e.image_revision===null?{state:"pending",error:e.image_error}:{state:"image",ref:e.image_ref,revision:Number(e.image_revision)}:{state:"base"}}_(re,"resolveEnvironmentImage");async function ae(r){return await M.subscribe(e=>{r(e)},{kinds:["environment_image"]})}_(ae,"subscribeImageBuilt");async function P(r,e){const i=r.recipe.repositories.map(a=>a.github_full_name),t=i.length===0?null:await x(r.person,i),n=R(f(u(),"crtr-recipe-image-"));try{return await H({recipe:r.recipe,revision:r.revision,token:t?.token??null,packagesToken:await $(r.environmentId),dir:n}),await C(e,b(r.environmentId),n)}finally{k(n)}}_(P,"defaultBuild");function ne(r=u()){for(const e of O(r))e.startsWith("crtr-recipe-image-")&&y(f(r,e),{recursive:!0,force:!0})}_(ne,"removeLeftoverBuildDirs");class oe{static{_(this,"RecipeImageReconciler")}deps;constructor(e={}){this.deps=e}async run(e,i){if(i.lifecycle.acceptsDetachedWork())try{const t=new Date(e).toISOString(),n=await l(),a=await n.prepare(`SELECT object FROM environments WHERE ${L} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(t);for(const{object:o}of a){const s=await this.claim(o,e,L,"recipe_revision");s!==null&&i.lifecycle.registerDetached(this.buildClaimed(o,Number(s.recipe_revision),s.lease).catch(m=>{g({level:"error",event:"recipe_image.failed",error:m})}))}const c=await n.prepare(`SELECT object FROM environments WHERE ${v} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(t);for(const{object:o}of c){const s=await this.claim(o,e,v,"object");s!==null&&i.lifecycle.registerDetached(this.withLease(o,s.lease,m=>this.deleteClaimed(o,m)).catch(m=>{g({level:"error",event:"recipe_image.delete_failed",error:m})}))}}catch(t){g({level:"error",event:"recipe_image.reconcile_failed",error:t})}}async claim(e,i,t,n){const a=new Date(i+p).toISOString(),c=await(await l()).prepare(`UPDATE environments SET image_building_at = ?
2
+ WHERE object = ? AND ${t} AND (image_building_at IS NULL OR image_building_at <= ?)
3
+ RETURNING ${n} AS recipe_revision`).get(a,e,new Date(i).toISOString());return c===void 0?null:{recipe_revision:c.recipe_revision,lease:a}}async withLease(e,i,t){const n=this.deps.now??Date.now;let a=i;const c=setInterval(()=>{const o=new Date(n()+p).toISOString();(async()=>{(await(await l()).prepare("UPDATE environments SET image_building_at = ? WHERE object = ? AND image_building_at = ?").run(o,e,a)).changes===1&&(a=o)})().catch(()=>{})},p/3);c.unref();try{await t(()=>a)}finally{clearInterval(c)}}async deleteClaimed(e,i){try{await(this.deps.deleteImage??(t=>j(w(),t)))(b(e))}catch(t){const n=t instanceof Error?t.message:String(t),a=new Date((this.deps.now??Date.now)()+S).toISOString();(await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(`deleting the image failed: ${n}`,a,e,i())).changes===1&&g({level:"error",event:"recipe_image.delete_failed",fields:{environment_id:e,error:n}});return}await(await l()).prepare("UPDATE environments SET image_ref = NULL, image_revision = NULL, image_error = NULL, image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,i())}async buildClaimed(e,i,t){const n=this.deps.now??Date.now;await this.withLease(e,t,async a=>{const c=await F(e);if(c===null||c.revision!==i){await(await l()).prepare("UPDATE environments SET image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,a());return}let o;try{const d=await(await l()).prepare("SELECT person FROM profiles WHERE environment_id = ? ORDER BY created_at LIMIT 1").get(e);if(d===void 0)throw new Error(`no profile runs in environment ${e}, so there is no person to take a GitHub token for`);await(await l()).prepare("UPDATE environments SET image_error = ? WHERE object = ? AND image_building_at = ?").run(`the build of revision ${i} started and its process exited before it finished`,e,a());const T={environmentId:e,revision:i,recipe:c,person:d.person};o=await(this.deps.build??(A=>P(A,w())))(T)}catch(d){await this.recordFailure(e,a(),d instanceof Error?d.message:String(d),n());return}const s=await l();(await s.prepare(`UPDATE environments SET image_revision = ?, image_ref = ?, image_error = NULL, image_building_at = NULL
4
+ WHERE object = ? AND image_building_at = ? AND COALESCE(image_revision, 0) < ? AND ${D}`).run(i,o.ref,e,a(),i)).changes!==1&&await s.prepare(`UPDATE environments SET image_ref = ?, image_building_at = NULL WHERE object = ? AND ${E}`).run(o.ref,e)})}async recordFailure(e,i,t,n){const a=new Date(n+S).toISOString();if((await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(t,a,e,i)).changes===1){g({level:"error",event:"recipe_image.build_failed",fields:{environment_id:e,error:t}});for(const o of await B(e))try{await I(async s=>{await W(s,o.run_id,o.node_id,"environment.image_failed",{environment_id:e,error:t})})}catch(s){g({level:"error",event:"recipe_image.failure_event_failed",node_id:o.node_id,error:s})}}}}async function B(r){const e=await(await l()).prepare(`SELECT n.node_id, n.run_id FROM nodes n JOIN profiles p ON p.id = n.profile_id
5
5
  WHERE p.environment_id = ? AND n.status IN ('active', 'idle') AND n.run_id IS NOT NULL
6
- AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.state != 'exited')`).all(o),t=[];for(const i of e)await O(i.node_id)&&t.push(i);return t}d(M,"nodesWaitingOnImage");export{p as ENVIRONMENT_DELETED_SQL,b as ENVIRONMENT_LIVE_SQL,S as IMAGE_BUILD_OWED_SQL,L as IMAGE_DELETE_OWED_SQL,E as LEASE_MS,N as RETRY_AFTER_FAILURE_MS,re as RecipeImageReconciler,M as nodesWaitingOnImage,ie as resolveEnvironmentImage,te as subscribeImageBuilt};
6
+ AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.state != 'exited')`).all(r),i=[];for(const t of e)await U(t.node_id)&&i.push(t);return i}_(B,"nodesWaitingOnImage");export{E as ENVIRONMENT_DELETED_SQL,D as ENVIRONMENT_LIVE_SQL,L as IMAGE_BUILD_OWED_SQL,v as IMAGE_DELETE_OWED_SQL,p as LEASE_MS,S as RETRY_AFTER_FAILURE_MS,oe as RecipeImageReconciler,B as nodesWaitingOnImage,ne as removeLeftoverBuildDirs,re as resolveEnvironmentImage,ae as subscribeImageBuilt};
package/docs/ci-runner.md CHANGED
@@ -85,7 +85,7 @@ Installing and upgrading: get a registration token (`gh api -X POST repos/Northl
85
85
 
86
86
  `publish.yml` starts with a `gate` job. It reads the pushed commit's **git tree** and looks for a workflow artifact named `tested-tree-<tree>`. `test.yml`'s final `tested` job creates that artifact only in mode `full`, after `build`, `checks` and every `linux` shard pass and every `macos` job (including `macos build-output`) passed (or was skipped because this is a pull request, where macOS never runs), on every such pull request run and on every run of Publish's own `tests` job. A tree released from a pull request's record therefore never ran its `laptopOnly` tests on macOS.
87
87
 
88
- - Rebase-merging a PR whose tested merge ref has the same tree as the resulting `main` commit → artifact found → `tests` is skipped and `publish` proceeds.
88
+ - Squash-merging a PR whose tested merge ref has the same tree as the resulting `main` commit → artifact found → `tests` is skipped and `publish` proceeds.
89
89
  - A direct push to `main`, or a merge after `main` moved (a different tree from the one the PR run tested) → no artifact → the full suite runs exactly as before. A release commit (`chore: release …`, pushed by Publish itself) changes the tree, so a PR not updated since before the latest release runs the suite once on merge; update the branch to avoid it.
90
90
  - The gate can only skip; if the lookup errors it runs the suite. `publish` runs only when `tests` passed, or was skipped *because* the gate found a record. A failed or cancelled suite never publishes.
91
91
  - Branch protection is not enabled on `main` and the gate does not depend on it: the proof is the tree, not a required check. Artifacts are kept 30 days; older trees are simply re-tested.
@@ -7,6 +7,16 @@ description: Behavior changes in @north-light/sdk that an app must act on, newes
7
7
 
8
8
  Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
9
9
 
10
+ ## 0.3.751
11
+
12
+ ### Call tokens may name any principal
13
+
14
+ The identity verifier accepts an `app:<id>` or `app:<id>/<path>` subject, and an app link with no grant when that app owns the subject's namespace (`chain[i].owner`). Strings that are not `user:`, `app:` or an app path are refused.
15
+
16
+ ### The daemon resolves owner tokens and exchanged person tokens
17
+
18
+ A token whose only link is an owner link now resolves to a caller holding the app's declared scopes and no grant (`grant` and `rev` are null). Operations that read or stream a grant (`grant.get`, `llm.*`) answer 403 `permission_error` to it. A grant-bearing `user:` link on an exchanged token resolves like an app link, with the person as the caller.
19
+
10
20
  ## 0.3.721
11
21
 
12
22
  ### `inferenceEndpoint` serves an app that pays for its own model calls (`billing: 'app'`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.750",
3
+ "version": "0.3.752",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -158,8 +158,8 @@
158
158
  },
159
159
  "license": "UNLICENSED",
160
160
  "dependencies": {
161
- "@north-light/identity": "0.3.750",
162
- "@north-light/plugin": "0.3.750",
161
+ "@north-light/identity": "0.3.752",
162
+ "@north-light/plugin": "0.3.752",
163
163
  "@earendil-works/chord": "1.5.2",
164
164
  "@earendil-works/pi-agent-core": "1.5.2",
165
165
  "@earendil-works/pi-ai": "1.5.2",
@@ -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.75';
15
+ export const CONTRACT_LEVEL = '1.76';
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`. */
@@ -188,6 +188,8 @@ export const routes = {
188
188
  appEnvVar: (variable) => `${V}/apps/self/env/${encodeURIComponent(variable)}`,
189
189
  profileEnv: (name) => `${V}/profiles/${name}/env`,
190
190
  profileEnvVar: (name, variable) => `${V}/profiles/${name}/env/${variable}`,
191
+ environments: () => `${V}/environments`,
192
+ environment: (name) => `${V}/environments/${name}`,
191
193
  profileEnvironment: (name) => `${V}/profiles/${name}/environment`,
192
194
  // Person settings
193
195
  settings: () => `${V}/settings`,
@@ -6,7 +6,7 @@
6
6
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
7
7
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
8
8
  * one below the live database's `schema_min_reader`. */
9
- export const CANVAS_SCHEMA_VERSION = 36;
9
+ export const CANVAS_SCHEMA_VERSION = 37;
10
10
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
11
11
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
12
12
  * it is put in a `search_path` connection option. */
@@ -11,9 +11,10 @@ import { setCloudProfileWriter } from './profiles/manifest.js';
11
11
  * across them, while the handle is unique per object type. Returns the environment's object id. */
12
12
  export async function createProfileBlaxelEnvironment(db, spec) {
13
13
  const app = await ownerForGrantee(db, spec.grantee);
14
- const profile = await ensureOwner(db, 'profile', 'profile', spec.profileId, spec.profileId, app);
14
+ const profile = await ensureOwner(db, 'profile', 'profile', spec.profileId, spec.profileId, app, { noActsFor: spec.person.startsWith('app:') });
15
15
  const object = await createObject(db, { type: 'environment', kind: 'blaxel', owner: profile.id, privacy: 'private', name: spec.profileId, preview: 'blaxel' });
16
- await writeActsFor(db, object.id, spec.person);
16
+ if (!spec.person.startsWith('app:'))
17
+ await writeActsFor(db, object.id, spec.person); // an app environment is kept for no person
17
18
  await db.prepare(`INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, payer, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?, ?)`).run(object.id, spec.memoryMb ?? 2048, spec.payer ?? null, new Date().toISOString());
18
19
  if (spec.recipe !== undefined)
19
20
  await writeEnvironmentRecipe(db, object.id, spec.recipe);
@@ -22,5 +22,5 @@ export async function installLocalTerminalGrant(installId, person) {
22
22
  await replaceGrants([{ id, runtime: installId, sub: person,
23
23
  grantee: 'app:terminal', rev: 1, scopes: TERMINAL_SCOPES,
24
24
  resolved_scopes: TERMINAL_SCOPES, spend_cap: null, expires_at: null,
25
- status: 'active', revoked_at: null, approved_at: now, payer: 'user', dependencies: {}, synced_at: now }], now, 'local');
25
+ status: 'active', revoked_at: null, approved_at: now, payer: person, dependencies: {}, synced_at: now }], now, 'local');
26
26
  }
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { parseScope } from '@north-light/identity';
2
+ import { parsePrincipal, parseScope } from '@north-light/identity';
3
3
  import { openDb, withCanvasWrite } from '../canvas/db.js';
4
4
  import { isUnsandboxedMachine } from '../runtime/unsandboxed.js';
5
5
  import { replaceWrittenBy, userSubject } from '../permissions/facts.js';
@@ -7,6 +7,21 @@ import { GROUP_TYPE, OBJECT_TYPE } from '../permissions/builtin.js';
7
7
  import { shadowCheck } from './shadow.js';
8
8
  const SETUP_STATES = ['not_started', 'pending', 'ready', 'failed', 'unavailable'];
9
9
  const STRENGTHS = ['ultra', 'strong', 'medium', 'light'];
10
+ /** The payer a mirrored grant carries, as a principal. The directory's older `'user'` (the grant's `sub`) and `'app'` (its `grantee`) read as those principals; anything else must parse as a principal. */
11
+ export function principalPayer(payer, sub, grantee) {
12
+ if (payer === undefined || payer === null || payer === 'user')
13
+ return sub;
14
+ if (payer === 'app')
15
+ return grantee;
16
+ if (typeof payer !== 'string' || parsePrincipal(payer) === null)
17
+ throw new TypeError('invalid grant payer');
18
+ return payer;
19
+ }
20
+ /** Whether the app's inference endpoint pays for this grant's model calls: its payer is an `app:` namespace root. */
21
+ export function endpointPays(grant) {
22
+ const payer = grant.payer === null ? null : parsePrincipal(grant.payer);
23
+ return payer !== null && payer.kind === 'app' && payer.path.length === 0;
24
+ }
10
25
  /** The fleet's runtime principal (`CRTR_RUNTIME`): a cloud role reads only its own runtime's grants, so a person's VM or laptop grants are never used. A Mac sets none. */
11
26
  export function runtimeScope() {
12
27
  const runtime = process.env['CRTR_RUNTIME'];
@@ -93,7 +108,7 @@ function record(row) {
93
108
  // A row whose computed columns lag its revision (a consent written but not yet computed) reads as no grant, never as the previous scopes.
94
109
  if (!computedFor(row.rev, row.computed_rev, row.scopes_json !== null, row.resolved_scopes_json !== null))
95
110
  throw new TypeError('grant columns are not computed for this revision');
96
- return { id: row.id, runtime: row.runtime, sub: row.sub, grantee: row.grantee,
111
+ return { id: row.id, runtime: row.runtime, sub: row.sub, grantee: row.grantee, grantee_prefix: row.grantee_prefix ?? null,
97
112
  rev: row.rev, scopes: entries(JSON.parse(row.scopes_json)),
98
113
  resolved_scopes: entries(JSON.parse(row.resolved_scopes_json)),
99
114
  spend_cap: row.spend_cap, expires_at: row.expires_at, status: row.status,
@@ -342,15 +357,22 @@ export async function grantStanding(grantId) {
342
357
  export async function grantIdsWhere(where) {
343
358
  return (await grantRows('id', where)).map((row) => row.id);
344
359
  }
345
- /** Who a grant's model calls are charged to: `app` only for a mirrored grant the directory marked app-paid, else the person. */
360
+ /** Who a grant's model calls are charged to: `app` only when the app's endpoint pays (`endpointPays`), else the person. */
346
361
  export async function payerOfGrant(grantId) {
347
- return (grantId ? (await grantRecord(grantId))?.payer : null) ?? 'user';
362
+ const grant = grantId ? await grantRecord(grantId) : null;
363
+ return grant !== null && endpointPays(grant) ? 'app' : 'user';
348
364
  }
349
365
  export async function activeGrant(grantId) {
350
366
  return active(await grantRow('*', 'id = ?', [grantId]));
351
367
  }
368
+ /** `sub`'s active grant to `grantee`: the exact row, else the wildcard row whose `grantee_prefix` is the longest prefix of `grantee`. The `'*'` sentinel never matches as an exact grantee. */
352
369
  export async function grantFor(grantee, sub) {
353
- return active(await grantRow('*', 'grantee = ? AND sub = ?', [grantee, sub]));
370
+ const exact = await grantRow('*', 'grantee = ? AND grantee_prefix IS NULL AND sub = ?', [grantee, sub]);
371
+ if (exact)
372
+ return active(exact);
373
+ const rows = await grantRows('*', 'sub = ? AND grantee_prefix IS NOT NULL AND starts_with(?, grantee_prefix)', [sub, grantee]);
374
+ rows.sort((a, b) => b.grantee_prefix.length - a.grantee_prefix.length);
375
+ return active(rows[0]);
354
376
  }
355
377
  /** The app's own active grant on this machine. Null for a mirror-only grant: an
356
378
  * unsandboxed machine runs no app, so a fanned-out hosted grant is never "the
@@ -430,6 +452,8 @@ export async function replaceGrants(grants, syncedAt, source, teams = []) {
430
452
  !Number.isInteger(grant.rev) || !['active', 'revoked', 'removed'].includes(grant.status)) {
431
453
  throw new TypeError('invalid grant sync response');
432
454
  }
455
+ if ((grant.grantee === '*') !== (grant.grantee_prefix != null))
456
+ throw new TypeError('invalid grant sync response');
433
457
  ids.add(grant.id);
434
458
  entries(grant.scopes);
435
459
  entries(grant.resolved_scopes);
@@ -443,22 +467,22 @@ export async function replaceGrants(grants, syncedAt, source, teams = []) {
443
467
  ? db.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${kept.map(() => '?').join(',')})`).run(...kept)
444
468
  : db.prepareUncached('DELETE FROM grants').run())).changes);
445
469
  const upsert = db.prepare(`INSERT INTO grants
446
- (id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
470
+ (id, runtime, sub, grantee, grantee_prefix, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
447
471
  status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
448
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
449
- ON CONFLICT (id) DO UPDATE SET runtime = excluded.runtime, sub = excluded.sub, grantee = excluded.grantee, rev = excluded.rev,
472
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
473
+ ON CONFLICT (id) DO UPDATE SET runtime = excluded.runtime, sub = excluded.sub, grantee = excluded.grantee, grantee_prefix = excluded.grantee_prefix, rev = excluded.rev,
450
474
  scopes_json = excluded.scopes_json, resolved_scopes_json = excluded.resolved_scopes_json, spend_cap = excluded.spend_cap,
451
475
  expires_at = excluded.expires_at, status = excluded.status, revoked_at = excluded.revoked_at, approved_at = excluded.approved_at,
452
476
  payer = excluded.payer, dependencies_json = excluded.dependencies_json, run_notice_url = excluded.run_notice_url,
453
477
  inference_endpoint_json = excluded.inference_endpoint_json, synced_at = excluded.synced_at, computed_rev = excluded.computed_rev
454
- WHERE (grants.runtime, grants.sub, grants.grantee, grants.rev, grants.scopes_json, grants.resolved_scopes_json, grants.spend_cap,
478
+ WHERE (grants.runtime, grants.sub, grants.grantee, grants.grantee_prefix, grants.rev, grants.scopes_json, grants.resolved_scopes_json, grants.spend_cap,
455
479
  grants.expires_at, grants.status, grants.revoked_at, grants.approved_at, grants.payer, grants.dependencies_json,
456
480
  grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
457
- IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
481
+ IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.grantee_prefix, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
458
482
  excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
459
483
  excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);
460
484
  for (const grant of grants) {
461
- changed += Number((await upsert.run(grant.id, grant.runtime, grant.sub, grant.grantee, grant.rev, JSON.stringify(grant.scopes), JSON.stringify(grant.resolved_scopes), grant.spend_cap, grant.expires_at, grant.status, grant.revoked_at, grant.approved_at, grant.payer, JSON.stringify(dependenciesOf(grant.dependencies)), grant.run_notice_url ?? null, grant.inference_endpoint ? JSON.stringify(grant.inference_endpoint) : null, grant.synced_at, grant.rev)).changes);
485
+ changed += Number((await upsert.run(grant.id, grant.runtime, grant.sub, grant.grantee, grant.grantee_prefix ?? null, grant.rev, JSON.stringify(grant.scopes), JSON.stringify(grant.resolved_scopes), grant.spend_cap, grant.expires_at, grant.status, grant.revoked_at, grant.approved_at, principalPayer(grant.payer, grant.sub, grant.grantee), JSON.stringify(dependenciesOf(grant.dependencies)), grant.run_notice_url ?? null, grant.inference_endpoint ? JSON.stringify(grant.inference_endpoint) : null, grant.synced_at, grant.rev)).changes);
462
486
  }
463
487
  await replaceWrittenBy(db, 'directory', GROUP_TYPE, 'member', teams.flatMap(({ team, members }) => members.map((member) => ({ resourceId: team, subject: userSubject(member) }))));
464
488
  await reconcileAppAdminFacts(db);
@@ -3,7 +3,7 @@
3
3
  import { directoryIssuer } from '../directory/issuer.js';
4
4
  import { outboundFetch } from '../events/outbound.js';
5
5
  import { warn } from '../output.js';
6
- import { canonicalJson } from './mirror.js';
6
+ import { canonicalJson, principalPayer } from './mirror.js';
7
7
  let ttlMs = 5_000;
8
8
  /** Test hook: how long a cached answer is used before its epochs are re-checked. */
9
9
  export function setShadowTtl(ms) { ttlMs = ms; }
@@ -67,7 +67,9 @@ async function compare(stored) {
67
67
  shadowCounts.lagging++;
68
68
  return;
69
69
  }
70
- const fields = COMPARED.filter((key) => canonicalJson(live[key] ?? null) !== canonicalJson(stored[key] ?? null));
70
+ // The directory may still send the older `'user'`/`'app'` payer; the mirror stores it as a principal.
71
+ const liveSide = { ...live, payer: principalPayer(live['payer'], stored.sub, stored.grantee) };
72
+ const fields = COMPARED.filter((key) => canonicalJson(liveSide[key] ?? null) !== canonicalJson(stored[key] ?? null));
71
73
  if (fields.length === 0) {
72
74
  shadowCounts.agree++;
73
75
  return;
@@ -7,7 +7,7 @@ import { reconcilePackages } from '../graph/package-reconcile.js';
7
7
  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
- import { dependenciesOf, inferenceEndpointOf, replaceGrants, teamsOf } from './mirror.js';
10
+ import { dependenciesOf, endpointPays, inferenceEndpointOf, principalPayer, replaceGrants, teamsOf } from './mirror.js';
11
11
  import { onGrantSync } from './on-sync.js';
12
12
  import { hostedEndpointOf, paymentSetupUrlOf, storeHostedEndpoint } from './hosted-endpoint.js';
13
13
  import { adoptInstallPerson } from '../scoped-state/migrate.js';
@@ -108,11 +108,12 @@ function responseGrant(value, client) {
108
108
  const approvedAt = revisions?.find((revision) => revision.rev === grant.rev)?.approved_at;
109
109
  if (typeof approvedAt !== 'string')
110
110
  throw new TypeError('grant revision has no approval time');
111
- // An absent or unrecognised payer is `user` (an older directory sends none); the endpoint rides only an app-paid grant.
112
- const payer = grant.payer === 'app' ? 'app' : 'user';
111
+ // The payer is a principal; an older directory's `'user'`/`'app'` (or none) maps to the grant's `sub`/`grantee`. The endpoint rides only a grant the app's endpoint pays for.
112
+ const payer = principalPayer(grant.payer, grant.sub, grant.grantee);
113
113
  return { ...grant, spend_cap: grant.spend_cap ?? null, expires_at: grant.expires_at ?? null,
114
+ grantee_prefix: typeof grant.grantee_prefix === 'string' ? grant.grantee_prefix : null,
114
115
  revoked_at: grant.revoked_at ?? null, approved_at: approvedAt, payer, dependencies: dependenciesOf(grant.dependencies),
115
- inference_endpoint: payer === 'app' ? inferenceEndpointOf(grant.inference_endpoint) : null,
116
+ inference_endpoint: endpointPays({ payer }) ? inferenceEndpointOf(grant.inference_endpoint) : null,
116
117
  run_notice_url: typeof grant.run_notice_url === 'string' && grant.run_notice_url !== '' ? grant.run_notice_url : null };
117
118
  }
118
119
  /** The person this pull serves: the bound one, else (a hosted first boot has none until its first snapshot commits) the one
@@ -26,7 +26,7 @@ export const ownerLockKey = (scheme, externalId, person = '') => `owner:${person
26
26
  * holding the same remote or path each get their own repo. Handles are unique per owner type: a handle already held
27
27
  * by a different identity of the same type throws `conflict` naming both; it is
28
28
  * never renamed silently. */
29
- export async function ensureOwner(db, type, scheme, externalId, handle, owner) {
29
+ export async function ensureOwner(db, type, scheme, externalId, handle, owner, options = {}) {
30
30
  if (!OWNER_TYPES.has(type))
31
31
  throw new Error(`ensureOwner: ${type} is not an owner type`);
32
32
  // An owner that exists needs no lock: taking one here would acquire it outside the order a peer ingest locked its keys in.
@@ -57,7 +57,7 @@ export async function ensureOwner(db, type, scheme, externalId, handle, owner) {
57
57
  await writeActsFor(db, created.id, userSubject(externalId).id);
58
58
  else if (type === 'repo')
59
59
  await writeActsFor(db, created.id, userSubject(person).id);
60
- else if (type === 'profile')
60
+ else if (type === 'profile' && options.noActsFor !== true)
61
61
  await writeActsFor(db, created.id, userSubject(await personIdAsync()).id);
62
62
  return created;
63
63
  }
@@ -1,5 +1,7 @@
1
1
  // Payer resolution (design-ledger, "Payer resolution"): one function. It reads the grant's payer and the credential route,
2
2
  // never a request header, so a caller cannot name its payer.
3
+ import { endpointPays } from '../grants/mirror.js';
4
+ import { isNamespaceOwner } from '../grants/owner.js';
3
5
  /** Who pays, and with what funding. A device call is not priced and never asks. */
4
6
  export function payerOf(call) {
5
7
  const paid = fundedBy(call);
@@ -10,9 +12,12 @@ function fundedBy(call) {
10
12
  case 'model':
11
13
  return call.route === 'endpoint' ? { payer: call.grantee, funding: 'endpoint' } : { payer: call.sub, funding: call.route };
12
14
  case 'tool':
13
- return call.tokenPayer.startsWith('app:') ? { payer: call.tokenPayer, funding: 'bill' } : { payer: call.sub, funding: 'bill' };
14
- case 'start':
15
+ return { payer: call.tokenPayer || call.sub, funding: 'bill' };
16
+ case 'start': {
15
17
  // Funding is chosen per candidate later; a start check ignores it.
16
- return call.grantPayer === 'app' ? { payer: call.grantee, funding: 'endpoint' } : { payer: call.sub, funding: 'bill' };
18
+ if (call.grantPayer)
19
+ return { payer: call.grantPayer, funding: endpointPays({ payer: call.grantPayer }) ? 'endpoint' : 'bill' };
20
+ return { payer: isNamespaceOwner(call.grantee, call.sub) ? call.grantee : call.sub, funding: 'bill' };
21
+ }
17
22
  }
18
23
  }
@@ -5,7 +5,7 @@ import { defaultModelLaddersConfig } from '../../types.js';
5
5
  import { MODEL_STRENGTHS, stripThinkingSuffix } from '../runtime/model-selection.js';
6
6
  import { modelTokenStrength } from '../runtime/launch.js';
7
7
  import { RunError } from '../runs/operations.js';
8
- import { grantRecord } from '../grants/mirror.js';
8
+ import { endpointPays, grantRecord } from '../grants/mirror.js';
9
9
  const STRENGTHS = MODEL_STRENGTHS;
10
10
  /** The endpoint's declared rungs, nearest to `strength` first (the stronger on a tie). */
11
11
  function rungsByDistance(endpoint, strength) {
@@ -55,7 +55,7 @@ export function appCandidates(endpoint, requested, exact = false) {
55
55
  * each rung's own level. */
56
56
  export async function appRungForGrant(grantId, requested, exact = false) {
57
57
  const grant = grantId ? await grantRecord(grantId) : null;
58
- if (grant?.payer !== 'app')
58
+ if (!grant || !endpointPays(grant))
59
59
  return null;
60
60
  if (!grant.inference_endpoint)
61
61
  throw new RunError(404, 'model_unavailable', `${grant.grantee} is app-paid but its grant carries no inference endpoint`);