@north-light/cli 0.3.673 → 0.3.675

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 (45) hide show
  1. package/dist/clients/attach/session/connection.d.ts +2 -1
  2. package/dist/clients/attach/session/connection.js +1 -1
  3. package/dist/clients/attach/viewer.d.ts +11 -1
  4. package/dist/clients/attach/viewer.js +524 -524
  5. package/dist/commands/person-settings.d.ts +5 -0
  6. package/dist/commands/person-settings.js +1 -1
  7. package/dist/core/graph/reader.d.ts +2 -1
  8. package/dist/core/graph/reader.js +3 -3
  9. package/dist/core/graph/repo-sync/repos.d.ts +24 -3
  10. package/dist/core/graph/repo-sync/repos.js +4 -4
  11. package/dist/core/profiles/select.d.ts +3 -1
  12. package/dist/core/profiles/select.js +25 -25
  13. package/dist/core/runtime/bearings.d.ts +3 -3
  14. package/dist/core/runtime/bearings.js +6 -6
  15. package/dist/core/runtime/boot-root.d.ts +3 -3
  16. package/dist/core/runtime/boot-root.js +6 -4
  17. package/dist/core/runtime/deliver-live.js +1 -1
  18. package/dist/core/runtime/front-door.js +1 -1
  19. package/dist/core/runtime/starting-screen.d.ts +12 -0
  20. package/dist/core/runtime/starting-screen.js +9 -0
  21. package/dist/core/substrate/delivery/deliver.d.ts +1 -1
  22. package/dist/core/substrate/delivery/deliver.js +3 -3
  23. package/dist/core/substrate/delivery/plan.d.ts +4 -0
  24. package/dist/core/substrate/delivery/plan.js +2 -2
  25. package/dist/core/substrate/subject.d.ts +3 -1
  26. package/dist/core/substrate/subject.js +1 -1
  27. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  28. package/dist/daemon/api/handlers/delivery.js +1 -1
  29. package/package.json +3 -3
  30. package/packages/crouter-api/dist/clients/attach/session/connection.js +3 -2
  31. package/packages/crouter-api/dist/clients/attach/viewer.js +16 -7
  32. package/packages/crouter-api/dist/commands/person-settings.js +10 -3
  33. package/packages/crouter-api/dist/core/graph/reader.js +9 -4
  34. package/packages/crouter-api/dist/core/graph/repo-sync/repos.js +56 -13
  35. package/packages/crouter-api/dist/core/profiles/select.js +17 -7
  36. package/packages/crouter-api/dist/core/runtime/bearings.js +11 -12
  37. package/packages/crouter-api/dist/core/runtime/deliver-live.js +1 -1
  38. package/packages/crouter-api/dist/core/substrate/delivery/deliver.js +27 -6
  39. package/packages/crouter-api/dist/core/substrate/delivery/plan.js +2 -0
  40. package/packages/crouter-api/dist/core/substrate/subject.js +4 -4
  41. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +6 -4
  42. package/packages/crouter-api/package.json +1 -1
  43. package/packages/crouter-identity/package.json +1 -1
  44. package/packages/crouter-plugin/package.json +3 -3
  45. package/runtime.lock.json +14 -14
@@ -12,6 +12,10 @@ export interface DeliveryPayload {
12
12
  absoluteFile?: string;
13
13
  /** `file-read`: the read file's frontmatter; parsed from the file when omitted. */
14
14
  readFrontmatter?: Record<string, unknown>;
15
+ /** `file-read`: checkout root of each repo (by id) enclosing the file; computed from the file's disk when omitted. */
16
+ repoRoots?: ReadonlyMap<string, string>;
17
+ /** `file-read`: the file lives on another machine, so the planner must not realpath it or look at it on this disk. */
18
+ remotePath?: boolean;
15
19
  /** `document-read`: the document delivered or read; it never delivers to itself. */
16
20
  doc?: DeliveryDoc;
17
21
  /** `command` / `pre-command`: the command string. */
@@ -1,2 +1,2 @@
1
- var p=Object.defineProperty;var u=(e,r)=>p(e,"name",{value:r,configurable:!0});import{dirname as h}from"node:path";import{parseFrontmatterGeneric as w}from"../../frontmatter.js";import{readText as g,realpathOrSelf as R}from"../../fs-utils.js";import{checkoutChainOf as b}from"../../checkout-identities.js";import{readableRepos as k}from"../../graph/repo-sync/repos.js";import{minRung as O,rungAtLeast as F,rungRank as m}from"../schema.js";import{ruleConstraintsFit as v,ruleGate as y}from"./match.js";import{personIdAsync as N}from"../../canvas/person.js";function x(e){return e.doc.ownNode?"knowledge":e.doc.kind}u(x,"bootPartitionOf");async function H(e,r,n,i,t,a={}){const o=await A(e,t,a),d=(t==="document-read"&&a.doc!==void 0?i.filter(l=>l.object.id!==a.doc.object.id):i).map(l=>W(l,r,t,o));return j(t,d),{on:t,subject:r,reader:n,docs:d}}u(H,"planDelivery");async function A(e,r,n){if(r!=="file-read"||n.absoluteFile===void 0)return n;const i=R(n.absoluteFile);return{...n,absoluteFile:i,readFrontmatter:n.readFrontmatter??E(i),repoRoots:await S(e,i)}}u(A,"resolvePayload");function E(e){if(!/\.(md|mdx|markdown)$/i.test(e))return{};try{return w(g(e)).data??{}}catch{return{}}}u(E,"readFileFrontmatter");async function S(e,r){const n=new Map;let i;const t=u(async()=>i??=await N(),"personOf");for(const o of await b(e,h(r),t)){if(!o.ok)break;for(const s of(await k(e,await t(),o.scheme,o.externalId)).readable)n.has(s.id)||n.set(s.id,o.root)}const a=await e.prepare(`SELECT o.id, i.external_id AS path, i.person AS person FROM identities i JOIN objects o ON o.id = i.object
2
- WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all();for(const{id:o,path:s,person:d}of a)!n.has(o)&&r.startsWith(s.endsWith("/")?s:`${s}/`)&&d===await t()&&n.set(o,s);return n}u(S,"repoRootsOf");function W(e,r,n,i){const t=e.rules.filter(c=>c.on===n).map(c=>{const f=y(c,r);return{rule:c,gate:f,matched:f.pass&&v(c,e,n,i)}});let a=null;for(const{rule:c,matched:f}of t)f&&(a===null||m(c.deliver)>m(a.deliver))&&(a=c);const o=a?.deliver??"none",s=(n==="boot"||n==="workspace-open")&&!e.ownNode?e.limit:null,d=s===null?o:O(o,s),l=n==="boot"&&e.ownNode&&t.length===0?"name":d;return{doc:e,authoredRules:t,matchedRule:a,authoredRung:o,limit:s,cappedRung:d,ruleGate:t.length===0?null:a!==null?{pass:!0}:t.find(c=>!c.gate.pass)?.gate??{pass:!0},finalRung:l,winner:!1,shadowedBy:null}}u(W,"decide");function $(e,r){if(r==="boot"){const n=e.authoredRules.length>0&&e.authoredRules.every(i=>!i.gate.pass);return e.limit!=="none"&&!n}return F(e.finalRung,"name")}u($,"holdsName");function j(e,r){const n=e==="boot"||e==="workspace-open",i=new Map;for(const t of r){if(!$(t,e))continue;if(!n){t.winner=!0;continue}const a=e==="boot"?`${x(t)}:${t.doc.name}`:t.doc.name,o=i.get(a);o===void 0?(i.set(a,t),t.winner=!0):t.shadowedBy=o.doc}}u(j,"resolveWinners");export{x as bootPartitionOf,H as planDelivery};
1
+ var p=Object.defineProperty;var u=(e,r)=>p(e,"name",{value:r,configurable:!0});import{dirname as h}from"node:path";import{parseFrontmatterGeneric as w}from"../../frontmatter.js";import{readText as g,realpathOrSelf as R}from"../../fs-utils.js";import{checkoutChainOf as b}from"../../checkout-identities.js";import{readableRepos as k}from"../../graph/repo-sync/repos.js";import{minRung as O,rungAtLeast as F,rungRank as m}from"../schema.js";import{ruleConstraintsFit as v,ruleGate as N}from"./match.js";import{personIdAsync as x}from"../../canvas/person.js";function y(e){return e.doc.ownNode?"knowledge":e.doc.kind}u(y,"bootPartitionOf");async function H(e,r,t,i,n,a={}){const o=await A(e,n,a),d=(n==="document-read"&&a.doc!==void 0?i.filter(l=>l.object.id!==a.doc.object.id):i).map(l=>W(l,r,n,o));return j(n,d),{on:n,subject:r,reader:t,docs:d}}u(H,"planDelivery");async function A(e,r,t){if(r!=="file-read"||t.absoluteFile===void 0||t.remotePath)return t;const i=R(t.absoluteFile);return{...t,absoluteFile:i,readFrontmatter:t.readFrontmatter??E(i),repoRoots:await S(e,i)}}u(A,"resolvePayload");function E(e){if(!/\.(md|mdx|markdown)$/i.test(e))return{};try{return w(g(e)).data??{}}catch{return{}}}u(E,"readFileFrontmatter");async function S(e,r){const t=new Map;let i;const n=u(async()=>i??=await x(),"personOf");for(const o of await b(e,h(r),n)){if(!o.ok)break;for(const s of(await k(e,await n(),o.scheme,o.externalId)).readable)t.has(s.id)||t.set(s.id,o.root)}const a=await e.prepare(`SELECT o.id, i.external_id AS path, i.person AS person FROM identities i JOIN objects o ON o.id = i.object
2
+ WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all();for(const{id:o,path:s,person:d}of a)!t.has(o)&&r.startsWith(s.endsWith("/")?s:`${s}/`)&&d===await n()&&t.set(o,s);return t}u(S,"repoRootsOf");function W(e,r,t,i){const n=e.rules.filter(c=>c.on===t).map(c=>{const f=N(c,r);return{rule:c,gate:f,matched:f.pass&&v(c,e,t,i)}});let a=null;for(const{rule:c,matched:f}of n)f&&(a===null||m(c.deliver)>m(a.deliver))&&(a=c);const o=a?.deliver??"none",s=(t==="boot"||t==="workspace-open")&&!e.ownNode?e.limit:null,d=s===null?o:O(o,s),l=t==="boot"&&e.ownNode&&n.length===0?"name":d;return{doc:e,authoredRules:n,matchedRule:a,authoredRung:o,limit:s,cappedRung:d,ruleGate:n.length===0?null:a!==null?{pass:!0}:n.find(c=>!c.gate.pass)?.gate??{pass:!0},finalRung:l,winner:!1,shadowedBy:null}}u(W,"decide");function $(e,r){if(r==="boot"){const t=e.authoredRules.length>0&&e.authoredRules.every(i=>!i.gate.pass);return e.limit!=="none"&&!t}return F(e.finalRung,"name")}u($,"holdsName");function j(e,r){const t=e==="boot"||e==="workspace-open",i=new Map;for(const n of r){if(!$(n,e))continue;if(!t){n.winner=!0;continue}const a=e==="boot"?`${y(n)}:${n.doc.name}`:n.doc.name,o=i.get(a);o===void 0?(i.set(a,n),n.winner=!0):n.shadowedBy=o.doc}}u(j,"resolveWinners");export{y as bootPartitionOf,H as planDelivery};
@@ -6,7 +6,9 @@ export type { NodeConfigSubject } from './subject-fields.js';
6
6
  * walking the `parent` chain (canvas-db rows) until a row with no parent (the
7
7
  * root). The root is depth 0. Cycle-guarded (parents must not cycle, but never
8
8
  * loop forever) — mirrors `rootOfSpine` in runtime/placement.ts. */
9
- export declare function spineDepth(nodeId: string): Promise<number>;
9
+ export declare function spineDepth(nodeId: string, own?: {
10
+ parent?: string | null;
11
+ }): Promise<number>;
10
12
  /** Assemble the node-config subject for `nodeId` from its `NodeMeta` + the
11
13
  * derived fields. Returns `null` when the node has no canvas-db row (an
12
14
  * unknown id). Pure aside from the canvas-db + profile-manifest reads. */
@@ -1 +1 @@
1
- var n=Object.defineProperty;var a=(r,o)=>n(r,"name",{value:o,configurable:!0});import{getNode as c,getRow as s}from"../canvas/index.js";import{appForNode as l}from"../canvas/node-agent-paths.js";import{openDb as f}from"../canvas/db.js";import{checkoutsForCwd as m}from"../graph/repo-sync/repos.js";import{liveLookups as w,viewRepos as u}from"../graph/reader.js";import{effectiveScopes as d,scopeForCwd as b,profileNameFor as h}from"./subject-fields.js";import{effectiveScopes as _,scopeForCwd as L,profileNameFor as M}from"./subject-fields.js";async function k(r){let o=r;const e=new Set;let t=0;for(;!e.has(o);){e.add(o);const p=await s(o);if(p===null||p.parent==null)break;o=p.parent,t++}return t}a(k,"spineDepth");async function y(r,o){const e=await f(),t=await u(e,r,o,async(p,i)=>await m(e,p,i),w(e));return[...t.repos,...t.projectRepos]}a(y,"eligibleRepos");async function C(r,o){const e=await c(r);return e===null?null:{kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,hasManager:(e.parent??null)!==null,cwd:e.cwd,scope:b(e.cwd),orchestration:{depth:await k(r)},profile:h(e.profile_id),app:e.grantee??await l(r),scopes:d(e.scopes),repo:(o??await y(e.cwd,e.profile_id??null)).map(t=>t.name)}}a(C,"assembleNodeSubject");export{C as assembleNodeSubject,_ as effectiveScopes,M as profileNameFor,L as scopeForCwd,k as spineDepth};
1
+ var c=Object.defineProperty;var a=(o,r)=>c(o,"name",{value:r,configurable:!0});import{getNode as s,getRow as l}from"../canvas/index.js";import{appForNode as f}from"../canvas/node-agent-paths.js";import{openDb as m}from"../canvas/db.js";import{checkoutsForCwd as u}from"../graph/repo-sync/repos.js";import{liveLookups as w,viewRepos as d}from"../graph/reader.js";import{effectiveScopes as b,scopeForCwd as h,profileNameFor as k}from"./subject-fields.js";import{effectiveScopes as L,scopeForCwd as M,profileNameFor as q}from"./subject-fields.js";async function y(o,r){let e=o;const t=new Set;let p=0;for(;!t.has(e);){t.add(e);const i=e===o&&r!==void 0?r:await l(e);if(i===null||i.parent==null)break;e=i.parent,p++}return p}a(y,"spineDepth");async function F(o,r){const e=await m(),t=await d(e,o,r,async(p,i,n)=>await u(e,p,i,n),w(e));return[...t.repos,...t.projectRepos]}a(F,"eligibleRepos");async function j(o,r){const e=await s(o);return e===null?null:{kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,hasManager:(e.parent??null)!==null,cwd:e.cwd,scope:h(e.cwd),orchestration:{depth:await y(o,e)},profile:k(e.profile_id),app:e.grantee??await f(o),scopes:b(e.scopes),repo:(r??await F(e.cwd,e.profile_id??null)).map(t=>t.name)}}a(j,"assembleNodeSubject");export{j as assembleNodeSubject,L as effectiveScopes,q as profileNameFor,M as scopeForCwd,y as spineDepth};
@@ -1 +1 @@
1
- var z=Object.defineProperty;var s=(t,e)=>z(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as Q,findNodeBySessionFile as X,getNode as g,getNodes as Z,isWarmSpare as I,recordLaunch as q,recordRespawnAttempt as ee,recordSettledTurn as te,setPresence as x,subscriptionsOf as ne,updateNode as _,updateNodeTelemetry as ie}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S,recordExecutionIdle as re,recordExecutionPid as oe}from"../../../core/canvas/executions.js";import{bindSession as ae,readLiveSession as se,transferSession as ce}from"../../../core/canvas/sessions.js";import{isSafeNodeId as de}from"../../../core/canvas/paths.js";import{isPidAlive as le}from"../../../core/canvas/pid.js";import{editorLabel as P}from"../../../core/canvas/labels.js";import{assembleNodeSubject as ue}from"../../../core/substrate/subject.js";import{openDb as A,withCanvasWrite as f}from"../../../core/canvas/db.js";import{runningJobs as pe}from"../../../core/graph/jobs.js";import{notFound as R,usage as l}from"../../../core/errors.js";import{hasUnseenWakeMail as C,releaseExecutionMail as fe}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as me}from"../../../core/runtime/kickoff.js";import{readRoadmap as we}from"../../../core/runtime/roadmap.js";import{forkSourceNode as ye}from"../../../core/runtime/nodes.js";import{transition as k}from"../../../core/runtime/lifecycle.js";import{confirmViewer as F,probeViewer as T,tearDownNode as B}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as he}from"../viewer-presence.js";import{evaluateStop as be}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as N}from"../../../core/runtime/output-result.js";import{clearFault as y,readFault as _e,recordFault as ke}from"../../../core/canvas/recovery.js";import{updateModelRecipe as ve}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as ge}from"../../review/finish.js";import{emitEvent as L}from"../../../core/events/emit.js";import{consumePendingPark as xe,recordPendingParkActivity as Se}from"../../park-pending.js";import{shouldParkAfterSummary as Pe}from"../../park-activity.js";import{ownerOnly as Re}from"../router.js";import{situationalContextEnvelope as Oe}from"../../../core/runtime/situational-context.js";import{recoveryState as Ee,requireCurrentExecution as u}from"./broker-recovery.js";import{runAttachments as Ae}from"./node-records.js";import{readerForNode as Ce,warmNodeRepos as Fe}from"../../../core/graph/reader.js";import{checkoutsForCwd as Te}from"../../../core/graph/repo-sync/repos.js";import{deliver as O}from"../../../core/substrate/delivery/deliver.js";import{ensureRunObserver as Be}from"../../runs/observer.js";import{parseNodeTelemetryRecord as Ne,writeNodeTelemetryRecord as Le}from"./telemetry-record.js";import{mapAsync as De}from"../../../core/async-array.js";import{crtrVersion as D}from"../../../shared/crtr-version.js";import{buildPiArgv as Me}from"../../../core/runtime/launch.js";import{brokerLaunchJson as Ve}from"../../../core/runtime/host.js";import{CYCLE_APPLIED_ENV as $e,cycleCompatible as je}from"../../../core/runtime/launch-recipe.js";import{buildReviveKickoff as Ue,drainBearings as We}from"../../../core/runtime/kickoff.js";import{clearNodeLedger as He}from"../../../core/runtime/ledger.js";import{runNodeStartHooks as Je}from"../../../core/runtime/revive.js";import{consumeDeadlineOnWake as Ge}from"../../../core/feed/messages.js";import{encodeKickoffOrigin as Ye}from"../../../core/runtime/stamp/protocol.js";import{ApiError as Ke}from"../../../api/errors.js";function p(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw l(`${e} requires a JSON body`);return t}s(p,"objectBody");function M(t){const e=p(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw l("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw l("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw l("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw l("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw l("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw l("reviewBoundaryIds must be an array of strings");return e}s(M,"parseSessionBoundBody");function ze(t){const e=p(t,"broker settle");if(typeof e.stopReason!="string")throw l("stopReason must be a string");for(const n of["pushedFinal"])if(typeof e[n]!="boolean")throw l(`${n} must be a boolean`);return e}s(ze,"parseSettleBody");function Qe(t){const e=p(t,"broker cycle");if(typeof e.brokerVersion!="string"||e.brokerVersion==="")throw l("brokerVersion must be a non-empty string");return e}s(Qe,"parseCycleBody");function Xe(t){const e=p(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw l("outcome must be completed or failed");return e}s(Xe,"parseParkCompleteBody");function Ze(t){const e=p(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw l("expected_execution_id must be a non-empty string");const n=Ne(e);return{...n,expected_execution_id:e.expected_execution_id,updated_at:new Date(n.updated_at).toISOString()}}s(Ze,"parseTelemetryBody");function Ie(t){const e=p(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw l("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const r=n!==null&&typeof n=="object"?n:void 0;if(r===void 0||typeof r.family!="string"||r.family===""||!["ultra","strong","medium","light"].includes(r.strength))throw l("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw l("userSelected must be a boolean");return e}s(Ie,"parseModelCommitBody");async function m(t){const e=await g(t);if(e===null)throw R(`unknown node: ${t}`,{received:t});return e}s(m,"requireNode");async function v(t){return{node_id:t.node_id,grantee:t.grantee,name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}s(v,"extensionNode");async function V(t){const e=await m(t),n=[],r=new Set([t]);let i=e.parent??null;for(;i!==null&&i!==""&&!r.has(i);){r.add(i);const d=await g(i);if(d===null)break;n.unshift(await v(d)),i=d.parent??null}const a=await De((await Z((await ne(t)).map(d=>d.node_id))).filter(d=>d.kind!=="human").sort((d,h)=>d.status===h.status?0:d.status==="active"?-1:h.status==="active"?1:0),v),o=typeof e.fork_source_file=="string"?await ye(e.fork_source_file):null,c=await ue(t);if(c===null)throw R(`unknown node: ${t}`,{received:t});return{node:await v(e),warm_spare:await I(t),situational_card:await Oe(t),ancestors:n,children:a,fork_source:o===null?null:await v(o),subject:c,roadmap:await we(t)}}s(V,"extensionState");function E(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(E,"samePersona");function qe(t){const e=p(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw l("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw l("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(r=>typeof n[r]!="string"))throw l("recap expected must contain name, description, title, icon, and kind strings");return e}s(qe,"parseGeneratedNameBody");function et(t){const e=p(t,"broker persona-ack"),n=s(r=>{const i=e[r];if(typeof i!="object"||i===null||Array.isArray(i)||typeof i.kind!="string"||i.mode!=="base"&&i.mode!=="orchestrator"||i.lifecycle!=="terminal"&&i.lifecycle!=="resident")throw l(`${r} must be a persona state`);return i},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}s(et,"parsePersonaAckBody");async function $(t,e){const n=e.sessionFile===null?null:Q(e.sessionFile);return await f(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await m(t);if(await oe(e.executionId,t,e.pid)==="shutdown")return{action:"shutdown"};const a=i.review_binding?.review_id;if(a!==void 0&&!e.reviewBoundaryIds.includes(a))return{action:"shutdown"};if(e.reason==="new"&&i.parent==null)return{action:"relaunch_root"};if(e.reason!=="new"&&i.fork_from!=null&&i.pi_session_id==null&&n===null)return{action:"shutdown"};const o=n===null?null:await X(n);if(o!==null&&o.node_id!==t){if(le(o.pi_pid))return await ke(t,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${n}: it is owned by live node ${o.node_id}`}),{action:"shutdown"};const c=await se(o.node_id);if(c===null||await ce({fromNodeId:o.node_id,fromBindingId:c.bindingId,toNodeId:t,executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})!=="transferred")return{action:"shutdown"}}else if(await ae(t,{executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})==="shutdown")return{action:"shutdown"};return e.reason!=="new"&&(await me(t),i.intent==="refresh"&&await k(t,"revive")),{action:"none"}})}s($,"commitSessionBound");async function tt(t){return{status:200,body:await $(t.params.id,M(t.body))}}s(tt,"handleSessionBound");function nt(t){const e=M(t);if(e.bearings!=="fresh"&&e.bearings!=="inherited"&&e.bearings!=="present")throw l("bearings must be fresh, inherited or present");return e}s(nt,"parseCycleStartBody");async function it(t,e,n,r,i=!1){const a=e.warm_spare||r,o=!a&&n!=="present";return i||await Fe(await A(),t),await f(async c=>{const d=await Ce(c,t,async(Y,K)=>await Te(c,Y,K)),h=await O(c,d,{activity:"names"}),w=o?await O(c,d,{activity:"boot",...n==="inherited"?{inherited:!0}:{}}):void 0,b=a?void 0:await O(c,d,{activity:"system-prompt"});return{names:{refs:h.refs,names:h.names},...w===void 0?{}:{boot:{content:w.content,...w.inherited===!0?{inherited:!0}:{}}},...b===void 0?{}:{system_prompt:b.content}}})}s(it,"startupDelivery");async function j(t,e,n,r=!1){const i=await V(t),a=await it(t,i,e,n,r);if(a.boot!==void 0){const o={kind:i.node.kind,mode:i.node.mode,lifecycle:i.node.lifecycle},c=i.node.persona_ack,d=c===void 0?o:{kind:c.kind??i.node.kind,mode:c.mode,lifecycle:c.lifecycle};E(d,o)||await G(t,d,o)}return{state:i,delivery:a}}s(j,"renderStartData");async function ln(t){const{state:e,delivery:n}=await j(t,"fresh",!1,!0);return{action:"none",state:e,names:n.names,...n.boot===void 0?{}:{boot:n.boot},...n.system_prompt===void 0?{}:{system_prompt:n.system_prompt}}}s(ln,"renderCarriedStart");async function rt(t){const e=t.params.id,n=nt(t.body),r=await m(e),i=r.review_binding?.review_id,a=i!==void 0&&!n.reviewBoundaryIds.includes(i),o=a||r.cycle_pending===!0||r.intent==="refresh"||r.pi_session_id==null;if(o)await u(e,n.executionId);else{const{action:w}=await $(e,n);if(w!=="none")return{status:200,body:{action:w}}}const{state:c,delivery:d}=await j(e,n.bearings,a);return{status:200,body:{action:"none",...o?{bind_pending:!0}:{},state:c,...d,recovery:await Ee(e),attachments:(await Ae(e)).map(({path:w,sha256:b})=>({path:w,sha256:b})),structured_request:await N(e)}}}s(rt,"handleCycleStart");async function U(t,e){return e.live!==null||await he(t)||await C(t)}s(U,"isHeldAwake");async function W(t,e){return(await S(t))?.runner==="blaxel"&&!await U(t,e)&&(await pe(await A(),t)).length===0}s(W,"residentBlaxelCanIdle");function H(t){return t.inPlaceCycle===!0?{action:"new_cycle"}:{action:"shutdown"}}s(H,"refreshDirective");async function ot(t,e,n){const r=await g(t);if(r===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw R(`unknown node: ${t}`,{received:t})}if(await te(t,new Date().toISOString()),(e.stopReason==="stop"||e.stopReason==="length")&&await ee(t,{failures:0,notBefore:null}),e.stopReason==="quit"){let c=!1;return(r.status==="active"||r.status==="idle")&&r.intent===null&&(await k(t,"finish"),await y(t),await x(t,{pane:null,tmux_session:null,window:null}),c=!0),{directive:{action:"shutdown"},closePane:c}}if(e.stopReason!=="stop"&&e.stopReason!=="length")return await y(t,{link:"daemon\u2192node"}),r.intent==="refresh"?{directive:H(e),closePane:!1}:e.stopReason==="error"&&e.faultSettled===!0&&(await _e(t))?.retry.disposition==="fatal"&&await N(t)===null&&await W(t,n)?{directive:{action:"stay_resident"},closePane:!1}:{directive:{action:"stay_dormant"},closePane:!1};const i={pushedFinal:e.pushedFinal};if(i.pushedFinal||r.status==="done")return await y(t),await x(t,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(r.intent==="refresh")return await y(t),{directive:H(e),closePane:!1};const a=await be(t,i);if(await y(t),a.action==="reprompt")return{directive:{action:"reprompt",prompt:a.message},closePane:!1};if(a.reason==="finished")return{directive:await C(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const o=await U(t,n);return(await S(t))?.runner==="blaxel"?{directive:await W(t,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:a.reason!=="awaiting"&&a.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:o?{directive:{action:"stay_dormant"},closePane:!1}:(await k(t,"release"),{directive:{action:"shutdown"},closePane:!1})}s(ot,"settleBroker");async function at(t){const e=t.params.id,n=Qe(t.body);await u(e,n.expected_execution_id);const r=await m(e);if(r.intent!=="refresh")throw new Ke(409,"not_yielding",`${e} has no pending yield`);const i=await S(e),a=Me(r);return n.brokerVersion===D()&&(i.release===null||i.release===D())&&je(i.launchJson,await Ve(e,a,r.cwd))?{status:200,body:await st(e,r,i.executionId,a.env)}:{status:200,body:{action:"restart"}}}s(at,"handleCycle");async function st(t,e,n,r){e.cycles=(e.cycles??0)+1,await fe(t,n);const i=await We(e,n),a=await Ue(e,i);await He(t),await Je(t,e,!1),await Ge(t),await y(t,{preserveEpisode:!0}),await q(t,new Date().toISOString()),await _(t,{cycles:e.cycles,cycle_pending:!0});const o={};for(const c of $e)r[c]!==void 0&&(o[c]=r[c]);return o.CRTR_CYCLES=String(e.cycles),{action:"cycle",cycle:e.cycles,prompt:a,origin:Ye({type:"runtime",kind:"revive",cycle:e.cycles}),messageIds:e.run_id?i.unreadMessageIds??[]:[],env:o,...e.launch?.model!==void 0?{model:e.launch.model}:{},modelExact:e.launch?.modelExact===!0,editorLabel:P(e)}}s(st,"startCycleRecord");async function ct(t){const e=t.params.id,n=p(t.body,"broker idle");return await u(e,n.expected_execution_id),await re(n.expected_execution_id),{status:204}}s(ct,"handleIdle");async function dt(t){const e=t.params.id,n=ze(t.body);await u(e,n.expected_execution_id);const r=await T(e),{directive:i,closePane:a}=await f(async()=>await ot(e,n,await F(r)));return a&&await B(e),i.action!=="reprompt"&&ge(e).catch(o=>L({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:e,error:o})),{status:200,body:i}}s(dt,"handleSettle");async function lt(t){const e=t.params.id,n=Xe(t.body);await u(e,n.expected_execution_id);const r=await T(e),i=await f(async()=>{const a=await xe(e);if(a===void 0)return{action:"stay_dormant"};const o=await m(e);return await Pe(e,o,a,await F(r))?(await y(e),await k(e,"park"),await x(e,{pane:null,tmux_session:null,window:null}),L({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...de(e)?{node_id:e}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}});return i.action==="shutdown"&&await B(e),{status:200,body:i}}s(lt,"handleParkComplete");async function ut(t){const e=t.params.id;return await u(e,p(t.body,"broker park-activity").expected_execution_id),{status:200,body:await f(async()=>({activity:await Se(e)?"recorded":"none"}))}}s(ut,"handleParkActivity");async function pt(t){const e=t.params.id,n=Ze(t.body);return await u(e,n.expected_execution_id),await f(async()=>{await ie(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at}),Le(e,n)}),{status:204}}s(pt,"handleTelemetry");async function ft(t){const e=t.params.id,n=Ie(t.body);return await u(e,n.expected_execution_id),{status:200,body:{modelOverride:(await f(async()=>await ve(await m(e),n.spec,n.intent,n.userSelected))).model_override}}}s(ft,"handleModelCommit");let J=!0;function un(t){J=t}s(un,"setRequestsStartRunObservers");async function mt(t){const e=t.params.id,n=await m(e);return n.run_id&&J&&await Be(e,n.run_id),{status:200,body:await V(e)}}s(mt,"handleExtensionState");async function wt(t){const e=t.params.id,n=qe(t.body);return await u(e,n.expected_execution_id),{status:200,body:await f(async i=>{await i.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const a=await m(e);if(n.kind==="initial"){if((a.description??"").trim()!=="")return{applied:!1};const d=await _(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:P(d),description:d.description??"",title:d.title??"",icon:d.icon??""}}const o=n.expected;if(a.name!==o.name||(a.description??"")!==o.description||(a.title??"")!==o.title||(a.icon??"")!==o.icon||a.kind!==o.kind)return{applied:!1};const c=await _(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:P(c),description:c.description??"",title:c.title??"",icon:c.icon??""}})}}s(wt,"handleGeneratedName");async function yt(t){const e=t.params.id,n=et(t.body);return await u(e,n.expected_execution_id),{status:200,body:{applied:await G(e,n.from,n.to)}}}s(yt,"handlePersonaAck");async function G(t,e,n){return await f(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await m(t),a={kind:i.kind,mode:i.mode,lifecycle:i.lifecycle},o=i.persona_ack,c=o===void 0?a:{kind:o.kind??i.kind,mode:o.mode,lifecycle:o.lifecycle};return!E(a,n)||!E(c,e)?!1:(await _(t,{persona_ack:n}),!0)})}s(G,"applyPersonaAck");const pn=Re([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:tt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle-start",handler:rt},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:dt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle",handler:at},{method:"POST",pattern:"/v1/nodes/:id/broker/idle",handler:ct},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:lt},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:ut},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:pt},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:ft},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:mt},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:yt}]);export{pn as brokerOperationRoutes,v as extensionNode,ln as renderCarriedStart,j as renderStartData,un as setRequestsStartRunObservers};
1
+ var X=Object.defineProperty;var s=(t,e)=>X(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as Z,findNodeBySessionFile as I,getNode as g,getNodes as q,isWarmSpare as ee,recordLaunch as te,recordRespawnAttempt as ne,recordSettledTurn as ie,setPresence as x,subscriptionsOf as re,updateNode as _,updateNodeTelemetry as oe}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S,recordExecutionIdle as ae,recordExecutionPid as se}from"../../../core/canvas/executions.js";import{bindSession as ce,readLiveSession as de,transferSession as le}from"../../../core/canvas/sessions.js";import{isSafeNodeId as ue}from"../../../core/canvas/paths.js";import{isPidAlive as pe}from"../../../core/canvas/pid.js";import{editorLabel as P}from"../../../core/canvas/labels.js";import{assembleNodeSubject as fe}from"../../../core/substrate/subject.js";import{openDb as C,withCanvasWrite as f}from"../../../core/canvas/db.js";import{runningJobs as me}from"../../../core/graph/jobs.js";import{notFound as R,usage as l}from"../../../core/errors.js";import{hasUnseenWakeMail as F,releaseExecutionMail as we}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as ye}from"../../../core/runtime/kickoff.js";import{readRoadmap as he}from"../../../core/runtime/roadmap.js";import{forkSourceNode as be}from"../../../core/runtime/nodes.js";import{transition as k}from"../../../core/runtime/lifecycle.js";import{confirmViewer as T,probeViewer as B,tearDownNode as N}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as _e}from"../viewer-presence.js";import{evaluateStop as ke}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as L}from"../../../core/runtime/output-result.js";import{clearFault as h,readFault as ve,recordFault as ge}from"../../../core/canvas/recovery.js";import{updateModelRecipe as xe}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as Se}from"../../review/finish.js";import{emitEvent as D}from"../../../core/events/emit.js";import{consumePendingPark as Pe,recordPendingParkActivity as Re}from"../../park-pending.js";import{shouldParkAfterSummary as Oe}from"../../park-activity.js";import{ownerOnly as Ee}from"../router.js";import{situationalContextEnvelope as Ae}from"../../../core/runtime/situational-context.js";import{recoveryState as Ce,requireCurrentExecution as u}from"./broker-recovery.js";import{runAttachments as Fe}from"./node-records.js";import{readerForNode as Te,warmNodeRepos as Be}from"../../../core/graph/reader.js";import{checkoutsForCwd as Ne}from"../../../core/graph/repo-sync/repos.js";import{deliver as O}from"../../../core/substrate/delivery/deliver.js";import{nodeSubject as Le}from"../../../core/substrate/delivery/corpus.js";import{ensureRunObserver as De}from"../../runs/observer.js";import{parseNodeTelemetryRecord as Me,writeNodeTelemetryRecord as je}from"./telemetry-record.js";import{mapAsync as Ve}from"../../../core/async-array.js";import{crtrVersion as M}from"../../../shared/crtr-version.js";import{buildPiArgv as $e}from"../../../core/runtime/launch.js";import{brokerLaunchJson as Ue}from"../../../core/runtime/host.js";import{CYCLE_APPLIED_ENV as We,cycleCompatible as He}from"../../../core/runtime/launch-recipe.js";import{buildReviveKickoff as Je,drainBearings as Ge}from"../../../core/runtime/kickoff.js";import{clearNodeLedger as Ye}from"../../../core/runtime/ledger.js";import{runNodeStartHooks as Ke}from"../../../core/runtime/revive.js";import{consumeDeadlineOnWake as ze}from"../../../core/feed/messages.js";import{encodeKickoffOrigin as Qe}from"../../../core/runtime/stamp/protocol.js";import{ApiError as Xe}from"../../../api/errors.js";function p(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw l(`${e} requires a JSON body`);return t}s(p,"objectBody");function j(t){const e=p(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw l("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw l("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw l("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw l("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw l("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw l("reviewBoundaryIds must be an array of strings");return e}s(j,"parseSessionBoundBody");function Ze(t){const e=p(t,"broker settle");if(typeof e.stopReason!="string")throw l("stopReason must be a string");for(const n of["pushedFinal"])if(typeof e[n]!="boolean")throw l(`${n} must be a boolean`);return e}s(Ze,"parseSettleBody");function Ie(t){const e=p(t,"broker cycle");if(typeof e.brokerVersion!="string"||e.brokerVersion==="")throw l("brokerVersion must be a non-empty string");return e}s(Ie,"parseCycleBody");function qe(t){const e=p(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw l("outcome must be completed or failed");return e}s(qe,"parseParkCompleteBody");function et(t){const e=p(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw l("expected_execution_id must be a non-empty string");const n=Me(e);return{...n,expected_execution_id:e.expected_execution_id,updated_at:new Date(n.updated_at).toISOString()}}s(et,"parseTelemetryBody");function tt(t){const e=p(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw l("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const r=n!==null&&typeof n=="object"?n:void 0;if(r===void 0||typeof r.family!="string"||r.family===""||!["ultra","strong","medium","light"].includes(r.strength))throw l("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw l("userSelected must be a boolean");return e}s(tt,"parseModelCommitBody");async function m(t){const e=await g(t);if(e===null)throw R(`unknown node: ${t}`,{received:t});return e}s(m,"requireNode");async function v(t){return{node_id:t.node_id,grantee:t.grantee,name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}s(v,"extensionNode");async function V(t){const e=await m(t),n=[],r=new Set([t]);let i=e.parent??null;for(;i!==null&&i!==""&&!r.has(i);){r.add(i);const d=await g(i);if(d===null)break;n.unshift(await v(d)),i=d.parent??null}const a=await Ve((await q((await re(t)).map(d=>d.node_id))).filter(d=>d.kind!=="human").sort((d,w)=>d.status===w.status?0:d.status==="active"?-1:w.status==="active"?1:0),v),o=typeof e.fork_source_file=="string"?await be(e.fork_source_file):null,c=await fe(t);if(c===null)throw R(`unknown node: ${t}`,{received:t});return{node:await v(e),warm_spare:await ee(t),situational_card:await Ae(t),ancestors:n,children:a,fork_source:o===null?null:await v(o),subject:c,roadmap:await he(t)}}s(V,"extensionState");function E(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(E,"samePersona");function nt(t){const e=p(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw l("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw l("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(r=>typeof n[r]!="string"))throw l("recap expected must contain name, description, title, icon, and kind strings");return e}s(nt,"parseGeneratedNameBody");function it(t){const e=p(t,"broker persona-ack"),n=s(r=>{const i=e[r];if(typeof i!="object"||i===null||Array.isArray(i)||typeof i.kind!="string"||i.mode!=="base"&&i.mode!=="orchestrator"||i.lifecycle!=="terminal"&&i.lifecycle!=="resident")throw l(`${r} must be a persona state`);return i},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}s(it,"parsePersonaAckBody");async function $(t,e){const n=e.sessionFile===null?null:Z(e.sessionFile);return await f(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await m(t);if(await se(e.executionId,t,e.pid)==="shutdown")return{action:"shutdown"};const a=i.review_binding?.review_id;if(a!==void 0&&!e.reviewBoundaryIds.includes(a))return{action:"shutdown"};if(e.reason==="new"&&i.parent==null)return{action:"relaunch_root"};if(e.reason!=="new"&&i.fork_from!=null&&i.pi_session_id==null&&n===null)return{action:"shutdown"};const o=n===null?null:await I(n);if(o!==null&&o.node_id!==t){if(pe(o.pi_pid))return await ge(t,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${n}: it is owned by live node ${o.node_id}`}),{action:"shutdown"};const c=await de(o.node_id);if(c===null||await le({fromNodeId:o.node_id,fromBindingId:c.bindingId,toNodeId:t,executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})!=="transferred")return{action:"shutdown"}}else if(await ce(t,{executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})==="shutdown")return{action:"shutdown"};return e.reason!=="new"&&(await ye(t),i.intent==="refresh"&&await k(t,"revive")),{action:"none"}})}s($,"commitSessionBound");async function rt(t){return{status:200,body:await $(t.params.id,j(t.body))}}s(rt,"handleSessionBound");function ot(t){const e=j(t);if(e.bearings!=="fresh"&&e.bearings!=="inherited"&&e.bearings!=="present")throw l("bearings must be fresh, inherited or present");return e}s(ot,"parseCycleStartBody");async function at(t,e,n,r,i=!1){const a=e.warm_spare||r,o=!a&&n!=="present";return i||await Be(await C(),t),await f(async c=>{const d=await Te(c,t,async(K,z,Q)=>await Ne(c,K,z,Q)),w=await Le(c,d),y=await O(c,d,{activity:"names"},w),b=o?await O(c,d,{activity:"boot",...n==="inherited"?{inherited:!0}:{}},w):void 0,A=a?void 0:await O(c,d,{activity:"system-prompt"},w);return{names:{refs:y.refs,names:y.names},...b===void 0?{}:{boot:{content:b.content,...b.inherited===!0?{inherited:!0}:{}}},...A===void 0?{}:{system_prompt:A.content}}})}s(at,"startupDelivery");async function U(t,e,n,r=!1){const i=await V(t),a=await at(t,i,e,n,r);if(a.boot!==void 0){const o={kind:i.node.kind,mode:i.node.mode,lifecycle:i.node.lifecycle},c=i.node.persona_ack,d=c===void 0?o:{kind:c.kind??i.node.kind,mode:c.mode,lifecycle:c.lifecycle};E(d,o)||await Y(t,d,o)}return{state:i,delivery:a}}s(U,"renderStartData");async function mn(t){const{state:e,delivery:n}=await U(t,"fresh",!1,!0);return{action:"none",state:e,names:n.names,...n.boot===void 0?{}:{boot:n.boot},...n.system_prompt===void 0?{}:{system_prompt:n.system_prompt}}}s(mn,"renderCarriedStart");async function st(t){const e=t.params.id,n=ot(t.body),r=await m(e),i=r.review_binding?.review_id,a=i!==void 0&&!n.reviewBoundaryIds.includes(i),o=a||r.cycle_pending===!0||r.intent==="refresh"||r.pi_session_id==null;if(o)await u(e,n.executionId);else{const{action:y}=await $(e,n);if(y!=="none")return{status:200,body:{action:y}}}const{state:c,delivery:d}=await U(e,n.bearings,a);return{status:200,body:{action:"none",...o?{bind_pending:!0}:{},state:c,...d,recovery:await Ce(e),attachments:(await Fe(e)).map(({path:y,sha256:b})=>({path:y,sha256:b})),structured_request:await L(e)}}}s(st,"handleCycleStart");async function W(t,e){return e.live!==null||await _e(t)||await F(t)}s(W,"isHeldAwake");async function H(t,e){return(await S(t))?.runner==="blaxel"&&!await W(t,e)&&(await me(await C(),t)).length===0}s(H,"residentBlaxelCanIdle");function J(t){return t.inPlaceCycle===!0?{action:"new_cycle"}:{action:"shutdown"}}s(J,"refreshDirective");async function ct(t,e,n){const r=await g(t);if(r===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw R(`unknown node: ${t}`,{received:t})}if(await ie(t,new Date().toISOString()),(e.stopReason==="stop"||e.stopReason==="length")&&await ne(t,{failures:0,notBefore:null}),e.stopReason==="quit"){let c=!1;return(r.status==="active"||r.status==="idle")&&r.intent===null&&(await k(t,"finish"),await h(t),await x(t,{pane:null,tmux_session:null,window:null}),c=!0),{directive:{action:"shutdown"},closePane:c}}if(e.stopReason!=="stop"&&e.stopReason!=="length")return await h(t,{link:"daemon\u2192node"}),r.intent==="refresh"?{directive:J(e),closePane:!1}:e.stopReason==="error"&&e.faultSettled===!0&&(await ve(t))?.retry.disposition==="fatal"&&await L(t)===null&&await H(t,n)?{directive:{action:"stay_resident"},closePane:!1}:{directive:{action:"stay_dormant"},closePane:!1};const i={pushedFinal:e.pushedFinal};if(i.pushedFinal||r.status==="done")return await h(t),await x(t,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(r.intent==="refresh")return await h(t),{directive:J(e),closePane:!1};const a=await ke(t,i);if(await h(t),a.action==="reprompt")return{directive:{action:"reprompt",prompt:a.message},closePane:!1};if(a.reason==="finished")return{directive:await F(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const o=await W(t,n);return(await S(t))?.runner==="blaxel"?{directive:await H(t,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:a.reason!=="awaiting"&&a.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:o?{directive:{action:"stay_dormant"},closePane:!1}:(await k(t,"release"),{directive:{action:"shutdown"},closePane:!1})}s(ct,"settleBroker");async function dt(t){const e=t.params.id,n=Ie(t.body);await u(e,n.expected_execution_id);const r=await m(e);if(r.intent!=="refresh")throw new Xe(409,"not_yielding",`${e} has no pending yield`);const i=await S(e),a=$e(r);return n.brokerVersion===M()&&(i.release===null||i.release===M())&&He(i.launchJson,await Ue(e,a,r.cwd))?{status:200,body:await lt(e,r,i.executionId,a.env)}:{status:200,body:{action:"restart"}}}s(dt,"handleCycle");async function lt(t,e,n,r){e.cycles=(e.cycles??0)+1,await we(t,n);const i=await Ge(e,n),a=await Je(e,i);await Ye(t),await Ke(t,e,!1),await ze(t),await h(t,{preserveEpisode:!0}),await te(t,new Date().toISOString()),await _(t,{cycles:e.cycles,cycle_pending:!0});const o={};for(const c of We)r[c]!==void 0&&(o[c]=r[c]);return o.CRTR_CYCLES=String(e.cycles),{action:"cycle",cycle:e.cycles,prompt:a,origin:Qe({type:"runtime",kind:"revive",cycle:e.cycles}),messageIds:e.run_id?i.unreadMessageIds??[]:[],env:o,...e.launch?.model!==void 0?{model:e.launch.model}:{},modelExact:e.launch?.modelExact===!0,editorLabel:P(e)}}s(lt,"startCycleRecord");async function ut(t){const e=t.params.id,n=p(t.body,"broker idle");return await u(e,n.expected_execution_id),await ae(n.expected_execution_id),{status:204}}s(ut,"handleIdle");async function pt(t){const e=t.params.id,n=Ze(t.body);await u(e,n.expected_execution_id);const r=await B(e),{directive:i,closePane:a}=await f(async()=>await ct(e,n,await T(r)));return a&&await N(e),i.action!=="reprompt"&&Se(e).catch(o=>D({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:e,error:o})),{status:200,body:i}}s(pt,"handleSettle");async function ft(t){const e=t.params.id,n=qe(t.body);await u(e,n.expected_execution_id);const r=await B(e),i=await f(async()=>{const a=await Pe(e);if(a===void 0)return{action:"stay_dormant"};const o=await m(e);return await Oe(e,o,a,await T(r))?(await h(e),await k(e,"park"),await x(e,{pane:null,tmux_session:null,window:null}),D({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...ue(e)?{node_id:e}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}});return i.action==="shutdown"&&await N(e),{status:200,body:i}}s(ft,"handleParkComplete");async function mt(t){const e=t.params.id;return await u(e,p(t.body,"broker park-activity").expected_execution_id),{status:200,body:await f(async()=>({activity:await Re(e)?"recorded":"none"}))}}s(mt,"handleParkActivity");async function wt(t){const e=t.params.id,n=et(t.body);return await u(e,n.expected_execution_id),await f(async()=>{await oe(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at}),je(e,n)}),{status:204}}s(wt,"handleTelemetry");async function yt(t){const e=t.params.id,n=tt(t.body);return await u(e,n.expected_execution_id),{status:200,body:{modelOverride:(await f(async()=>await xe(await m(e),n.spec,n.intent,n.userSelected))).model_override}}}s(yt,"handleModelCommit");let G=!0;function wn(t){G=t}s(wn,"setRequestsStartRunObservers");async function ht(t){const e=t.params.id,n=await m(e);return n.run_id&&G&&await De(e,n.run_id),{status:200,body:await V(e)}}s(ht,"handleExtensionState");async function bt(t){const e=t.params.id,n=nt(t.body);return await u(e,n.expected_execution_id),{status:200,body:await f(async i=>{await i.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const a=await m(e);if(n.kind==="initial"){if((a.description??"").trim()!=="")return{applied:!1};const d=await _(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:P(d),description:d.description??"",title:d.title??"",icon:d.icon??""}}const o=n.expected;if(a.name!==o.name||(a.description??"")!==o.description||(a.title??"")!==o.title||(a.icon??"")!==o.icon||a.kind!==o.kind)return{applied:!1};const c=await _(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:P(c),description:c.description??"",title:c.title??"",icon:c.icon??""}})}}s(bt,"handleGeneratedName");async function _t(t){const e=t.params.id,n=it(t.body);return await u(e,n.expected_execution_id),{status:200,body:{applied:await Y(e,n.from,n.to)}}}s(_t,"handlePersonaAck");async function Y(t,e,n){return await f(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await m(t),a={kind:i.kind,mode:i.mode,lifecycle:i.lifecycle},o=i.persona_ack,c=o===void 0?a:{kind:o.kind??i.kind,mode:o.mode,lifecycle:o.lifecycle};return!E(a,n)||!E(c,e)?!1:(await _(t,{persona_ack:n}),!0)})}s(Y,"applyPersonaAck");const yn=Ee([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:rt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle-start",handler:st},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:pt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle",handler:dt},{method:"POST",pattern:"/v1/nodes/:id/broker/idle",handler:ut},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:ft},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:mt},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:yt},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:ht},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:bt},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:_t}]);export{yn as brokerOperationRoutes,v as extensionNode,mn as renderCarriedStart,U as renderStartData,wn as setRequestsStartRunObservers};
@@ -1 +1 @@
1
- var _=Object.defineProperty;var d=(e,n)=>_(e,"name",{value:n,configurable:!0});import{ApiError as r}from"../../../api/errors.js";import{dirname as k}from"node:path";import{openDb as N,withCanvasWrite as l}from"../../../core/canvas/db.js";import{readerForNode as h,warmNodeDirs as m,warmNodeRepos as q}from"../../../core/graph/reader.js";import{checkoutsForCwd as p}from"../../../core/graph/repo-sync/repos.js";import{DRY_RUN_ONLY as A,deliver as D,hypotheticalFrom as R,hypotheticalReader as C,inspect as y}from"../../../core/substrate/delivery/deliver.js";import{actsAsPerson as O,mayOnNode as S}from"../router.js";import{requireCurrentExecution as P}from"./broker-recovery.js";const T=["boot","system-prompt","compact","persona","file-read","command","pre-command","slash-command","names",...A];function b(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new r(400,"usage","delivery requires a JSON body");const n=e;if(!T.includes(n.activity))throw new r(400,"usage",`invalid delivery activity: ${String(n.activity)}`);if(n.subject!==void 0&&typeof n.subject!="string")throw new r(400,"usage","delivery subject must be a string");return n}d(b,"parse");async function g(e,n,i){const t=e.principal;if(t.class==="person"&&t.sub!==void 0){if(i!==void 0)throw new r(403,"permission_error","a hypothetical delivery dry run is not available to a person bearer; name a node you can read");if(n===void 0||!await S(t,"read",n))throw new r(404,"not_found","node not found");return}E(e)}d(g,"requireDryRunCaller");function E(e){if(!O(e.principal)&&e.principal.class!=="broker")throw new r(403,"permission_error","a delivery dry run is available to a person or a node only")}d(E,"requirePerson");function F(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new r(400,"usage","hypothetical must be an object");const n=d((o,s)=>{if(o!==void 0){if(typeof o!="string"||o==="")throw new r(400,"usage",`hypothetical.${s} must be a non-empty string`);return o}},"str"),i=n(e.cwd,"cwd");if(i!==void 0&&!i.startsWith("/"))throw new r(400,"usage","hypothetical.cwd must be an absolute path");if(e.mode!==void 0&&e.mode!=="base"&&e.mode!=="orchestrator")throw new r(400,"usage","hypothetical.mode must be base or orchestrator");if(e.lifecycle!==void 0&&e.lifecycle!=="terminal"&&e.lifecycle!=="resident")throw new r(400,"usage","hypothetical.lifecycle must be terminal or resident");if(e.has_manager!==void 0&&typeof e.has_manager!="boolean")throw new r(400,"usage","hypothetical.has_manager must be a boolean");if(e.depth!==void 0&&(!Number.isInteger(e.depth)||e.depth<0))throw new r(400,"usage","hypothetical.depth must be a non-negative integer");const t={};i!==void 0&&(t.cwd=i),e.profile!==void 0&&(t.profile=e.profile===null?null:n(e.profile,"profile"));const u=n(e.grantee,"grantee");u!==void 0&&(t.grantee=u);const a=n(e.kind,"kind");return a!==void 0&&(t.kind=a),e.mode!==void 0&&(t.mode=e.mode),e.lifecycle!==void 0&&(t.lifecycle=e.lifecycle),e.has_manager!==void 0&&(t.hasManager=e.has_manager),e.depth!==void 0&&(t.depth=e.depth),t}d(F,"hypotheticalOf");async function w(e,n,i){const t=await N();e!==void 0&&await q(t,e),n&&await m(t,e,[n]),i!==void 0&&i.startsWith("/")&&await m(t,e,[k(i)])}d(w,"warmDeliveryCwds");async function W(e){const n=b(e.body);if(n.node!==void 0&&typeof n.node!="string")throw new r(400,"usage","node must be a node id");await g(e,n.node,n.hypothetical);const i={activity:n.activity,...n.subject!==void 0?{subject:n.subject}:{}};await w(n.node,n.hypothetical?.cwd,n.activity==="file-read"?n.subject:void 0);const{result:t,plan:u}=await l(async a=>{if(n.hypothetical===void 0){if(n.node===void 0)throw new r(400,"usage","a delivery dry run names a node, a hypothetical node, or both");return await y(a,await h(a,n.node,async(v,j)=>await p(a,v,j)),i,n.subject_override)}const o=F(n.hypothetical),s=n.node!==void 0?await R(n.node,o):{...o,cwd:o.cwd??""};if(s.cwd==="")throw new r(400,"usage","a hypothetical node needs a cwd");const{reader:c,subject:f}=await C(a,s);return await y(a,c,i,n.subject_override,f)},{rollback:!0});return{status:200,body:{...t,plan:u}}}d(W,"handleDryRun");async function I(e){const n=e.params.id,i=b(e.body),t={activity:i.activity,...i.subject!==void 0?{subject:i.subject}:{},...i.inherited===!0?{inherited:!0}:{}};if(i.dry_run===!0){await g(e,n,void 0),await w(n,void 0,i.activity==="file-read"?i.subject:void 0);const{result:a,plan:o}=await l(async s=>await y(s,await h(s,n,async(c,f)=>await p(s,c,f)),t,i.subject_override),{rollback:!0});return{status:200,body:{...a,plan:o}}}if(e.principal.class==="broker"&&e.principal.node!==n)throw new r(403,"permission_error","delivery is performed by the node's own broker");return await P(n,i.expected_execution_id),await w(n,void 0,i.activity==="file-read"?i.subject:void 0),{status:200,body:await l(async a=>await D(a,await h(a,n,async(o,s)=>await p(a,o,s)),t))}}d(I,"handleDelivery");const G=[{method:"POST",pattern:"/v1/nodes/:id/delivery",handler:I},{method:"POST",pattern:"/v1/delivery/dry-run",handler:W}];export{G as deliveryRoutes};
1
+ var k=Object.defineProperty;var d=(e,n)=>k(e,"name",{value:n,configurable:!0});import{ApiError as r}from"../../../api/errors.js";import{dirname as N}from"node:path";import{openDb as q,withCanvasWrite as h}from"../../../core/canvas/db.js";import{readerForNode as p,warmNodeDirs as b,warmNodeRepos as A}from"../../../core/graph/reader.js";import{checkoutsForCwd as y}from"../../../core/graph/repo-sync/repos.js";import{DRY_RUN_ONLY as D,deliver as R,hypotheticalFrom as C,hypotheticalReader as O,inspect as w}from"../../../core/substrate/delivery/deliver.js";import{actsAsPerson as S,mayOnNode as P}from"../router.js";import{requireCurrentExecution as T}from"./broker-recovery.js";const E=["boot","system-prompt","compact","persona","file-read","command","pre-command","slash-command","names",...D];function g(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new r(400,"usage","delivery requires a JSON body");const n=e;if(!E.includes(n.activity))throw new r(400,"usage",`invalid delivery activity: ${String(n.activity)}`);if(n.subject!==void 0&&typeof n.subject!="string")throw new r(400,"usage","delivery subject must be a string");return n}d(g,"parse");async function v(e,n,i){const t=e.principal;if(t.class==="person"&&t.sub!==void 0){if(i!==void 0)throw new r(403,"permission_error","a hypothetical delivery dry run is not available to a person bearer; name a node you can read");if(n===void 0||!await P(t,"read",n))throw new r(404,"not_found","node not found");return}F(e)}d(v,"requireDryRunCaller");function F(e){if(!S(e.principal)&&e.principal.class!=="broker")throw new r(403,"permission_error","a delivery dry run is available to a person or a node only")}d(F,"requirePerson");function W(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new r(400,"usage","hypothetical must be an object");const n=d((o,s)=>{if(o!==void 0){if(typeof o!="string"||o==="")throw new r(400,"usage",`hypothetical.${s} must be a non-empty string`);return o}},"str"),i=n(e.cwd,"cwd");if(i!==void 0&&!i.startsWith("/"))throw new r(400,"usage","hypothetical.cwd must be an absolute path");if(e.mode!==void 0&&e.mode!=="base"&&e.mode!=="orchestrator")throw new r(400,"usage","hypothetical.mode must be base or orchestrator");if(e.lifecycle!==void 0&&e.lifecycle!=="terminal"&&e.lifecycle!=="resident")throw new r(400,"usage","hypothetical.lifecycle must be terminal or resident");if(e.has_manager!==void 0&&typeof e.has_manager!="boolean")throw new r(400,"usage","hypothetical.has_manager must be a boolean");if(e.depth!==void 0&&(!Number.isInteger(e.depth)||e.depth<0))throw new r(400,"usage","hypothetical.depth must be a non-negative integer");const t={};i!==void 0&&(t.cwd=i),e.profile!==void 0&&(t.profile=e.profile===null?null:n(e.profile,"profile"));const u=n(e.grantee,"grantee");u!==void 0&&(t.grantee=u);const a=n(e.kind,"kind");return a!==void 0&&(t.kind=a),e.mode!==void 0&&(t.mode=e.mode),e.lifecycle!==void 0&&(t.lifecycle=e.lifecycle),e.has_manager!==void 0&&(t.hasManager=e.has_manager),e.depth!==void 0&&(t.depth=e.depth),t}d(W,"hypotheticalOf");async function m(e,n,i){const t=await q();e!==void 0&&await A(t,e),n&&await b(t,e,[n]),i!==void 0&&i.startsWith("/")&&await b(t,e,[N(i)])}d(m,"warmDeliveryCwds");async function I(e){const n=g(e.body);if(n.node!==void 0&&typeof n.node!="string")throw new r(400,"usage","node must be a node id");await v(e,n.node,n.hypothetical);const i={activity:n.activity,...n.subject!==void 0?{subject:n.subject}:{}};await m(n.node,n.hypothetical?.cwd,n.activity==="file-read"?n.subject:void 0);const{result:t,plan:u}=await h(async a=>{if(n.hypothetical===void 0){if(n.node===void 0)throw new r(400,"usage","a delivery dry run names a node, a hypothetical node, or both");return await w(a,await p(a,n.node,async(l,j,_)=>await y(a,l,j,_)),i,n.subject_override)}const o=W(n.hypothetical),s=n.node!==void 0?await C(n.node,o):{...o,cwd:o.cwd??""};if(s.cwd==="")throw new r(400,"usage","a hypothetical node needs a cwd");const{reader:c,subject:f}=await O(a,s);return await w(a,c,i,n.subject_override,f)},{rollback:!0});return{status:200,body:{...t,plan:u}}}d(I,"handleDryRun");async function Y(e){const n=e.params.id,i=g(e.body),t={activity:i.activity,...i.subject!==void 0?{subject:i.subject}:{},...i.inherited===!0?{inherited:!0}:{}};if(i.dry_run===!0){await v(e,n,void 0),await m(n,void 0,i.activity==="file-read"?i.subject:void 0);const{result:a,plan:o}=await h(async s=>await w(s,await p(s,n,async(c,f,l)=>await y(s,c,f,l)),t,i.subject_override),{rollback:!0});return{status:200,body:{...a,plan:o}}}if(e.principal.class==="broker"&&e.principal.node!==n)throw new r(403,"permission_error","delivery is performed by the node's own broker");return await T(n,i.expected_execution_id),await m(n,void 0,i.activity==="file-read"?i.subject:void 0),{status:200,body:await h(async a=>await R(a,await p(a,n,async(o,s,c)=>await y(a,o,s,c)),t))}}d(Y,"handleDelivery");const H=[{method:"POST",pattern:"/v1/nodes/:id/delivery",handler:Y},{method:"POST",pattern:"/v1/delivery/dry-run",handler:I}];export{H as deliveryRoutes};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.673",
3
+ "version": "0.3.675",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -156,8 +156,8 @@
156
156
  },
157
157
  "license": "UNLICENSED",
158
158
  "dependencies": {
159
- "@north-light/identity": "0.3.673",
160
- "@north-light/plugin": "0.3.673",
159
+ "@north-light/identity": "0.3.675",
160
+ "@north-light/plugin": "0.3.675",
161
161
  "@earendil-works/chord": "1.5.2",
162
162
  "@earendil-works/pi-agent-core": "1.5.2",
163
163
  "@earendil-works/pi-ai": "1.5.2",
@@ -63,7 +63,7 @@ export async function preWaitForViewSocket(nodeId) {
63
63
  /** Resolve the target, revive the node if it is dormant (server-side), and dial
64
64
  * the broker. Rejects with a plain `InputError` — no terminal has been taken
65
65
  * over at this point, so a failure here is an ordinary non-zero CLI exit. */
66
- export async function connectToNode(nodeId, canvasName, wakeParked = true) {
66
+ export async function connectToNode(nodeId, canvasName, wakeParked = true, known) {
67
67
  // An imported Mac has no local canvas API: its canvas and its brokers' viewer channels are reached through the cloud control plane,
68
68
  // so attach without `--canvas` dials the cloud with the person's sign-in. It is still the person's own attach, not a `--canvas` view:
69
69
  // `remote` stays false, so the viewer claims the controller role like any local attach.
@@ -95,7 +95,8 @@ export async function connectToNode(nodeId, canvasName, wakeParked = true) {
95
95
  transport = new RelayTransport(nodeId, resolveRemoteCanvasTarget(canvasName));
96
96
  }
97
97
  else {
98
- const localMeta = await canvasSource.getNode(nodeId);
98
+ // A caller that just created the node already holds its detail: no second read.
99
+ const localMeta = known ?? await canvasSource.getNode(nodeId);
99
100
  if (localMeta === null) {
100
101
  throw new InputError({
101
102
  error: 'not_found',
@@ -57,7 +57,7 @@ import { loadProfileManifest } from '../../core/profiles/manifest.js';
57
57
  import { watchInboxActivity } from '../../core/human/root.js';
58
58
  import { byNewestFirst, inboxRowFromDTO } from '../inbox/dto-adapt.js';
59
59
  import { cliClient } from '../../commands/api-client.js';
60
- import { loadPersonSettingsViaApi } from '../../commands/person-settings.js';
60
+ import { installPersonSettingsDto, loadPersonSettingsViaApi } from '../../commands/person-settings.js';
61
61
  import { buildBannerInfo } from './session/banner.js';
62
62
  import { backgroundBashHint, detachBindingHint, detachHint, inboxOpenHint, refreshAttachBindingSnapshot } from './session/bindings.js';
63
63
  import { connectToNode, resolveHelloRole } from './session/connection.js';
@@ -82,10 +82,17 @@ function quoteIfNeeded(word) {
82
82
  * always restoring the terminal first. `canvasName`, when set, attaches over
83
83
  * a relayed WebSocket to that `remoteCanvas.targets.<name>` instead of the
84
84
  * local unix socket — see the `--canvas` flag on `attachToLeaf`. */
85
- export async function runAttach(nodeId, observer, canvasName, wakeParked = true) {
86
- // The viewer is its own esbuild bundle with its own copy of the settings cache: read the person's settings before anything
87
- // calls readConfig (theme, keybindings, ChatView's field initializers all do).
88
- await loadPersonSettingsViaApi();
85
+ export async function runAttach(nodeId, observer, canvasName, wakeParked = true,
86
+ /** What a caller that just created the node already holds: the node's detail, the person's settings answer, and whether to play the first-prompt animation. */
87
+ held,
88
+ /** Called synchronously just before the viewer takes the terminal. */
89
+ onConnected) {
90
+ // The viewer is its own esbuild bundle with its own copy of the settings cache: install the person's settings before anything
91
+ // calls readConfig (theme, keybindings, ChatView's field initializers all do). A caller that holds them hands them over.
92
+ if (held === undefined)
93
+ await loadPersonSettingsViaApi();
94
+ else
95
+ installPersonSettingsDto(held.settings);
89
96
  // 1. Get onto the broker before anything paints (session/connection.ts):
90
97
  // resolve local-vs-relay, revive the node server-side if it is dormant,
91
98
  // and win the connect race. A failure here is still a plain CLI error.
@@ -94,7 +101,7 @@ export async function runAttach(nodeId, observer, canvasName, wakeParked = true)
94
101
  // read, native slash command, pane tag and lifecycle action gates on it,
95
102
  // and no collaborator may re-derive it.
96
103
  mark('viewer.connect_start', { node: nodeId });
97
- const connection = await connectToNode(nodeId, canvasName, wakeParked);
104
+ const connection = await connectToNode(nodeId, canvasName, wakeParked, held?.node);
98
105
  mark(connection.initialSnapshot === undefined ? 'viewer.socket_connected' : 'viewer.offline_snapshot_ready');
99
106
  const { remote, canvasSource, meta, socket } = connection;
100
107
  const role = resolveHelloRole(observer);
@@ -172,7 +179,7 @@ export async function runAttach(nodeId, observer, canvasName, wakeParked = true)
172
179
  });
173
180
  containers.header.addChild(strip.component);
174
181
  const userConfig = readConfig('user');
175
- const initialWhip = process.env['CRTR_ATTACH_INITIAL_WHIP'] === '1';
182
+ const initialWhip = held?.initialWhip ?? process.env['CRTR_ATTACH_INITIAL_WHIP'] === '1';
176
183
  delete process.env['CRTR_ATTACH_INITIAL_WHIP'];
177
184
  const startupReviewId = takeStartupReviewId();
178
185
  const startupTicketId = process.env['CRTR_ATTACH_OPEN_TICKET'];
@@ -678,6 +685,8 @@ export async function runAttach(nodeId, observer, canvasName, wakeParked = true)
678
685
  // 6. Lay out, paint, start, then handshake — starting before the handshake
679
686
  // means the welcome's applySnapshot renders into a live TUI.
680
687
  layout.mount();
688
+ // Synchronous with tui.start(): the caller's screen gives the terminal back and the viewer takes it in the same tick, with no cooked-mode gap.
689
+ onConnected?.();
681
690
  tui.start();
682
691
  if (connection.initialSnapshot !== undefined) {
683
692
  // Seed the same state/transcript owners a broker welcome feeds. No socket
@@ -1,12 +1,19 @@
1
1
  // A CLI or viewer process holds no database: it reads the person's settings snapshot from crtrd once, then every settings write
2
2
  // goes back as `PUT /v1/settings` ops (core/scoped-state/person-store.ts holds the one write algorithm).
3
3
  import { ApiError } from '../api/index.js';
4
- import { setPersonId } from '../core/canvas/person-state.js';
5
- import { installPersonSnapshot, setSettingsReloader, setSettingsTransport, SettingsRevisionConflictError } from '../core/scoped-state/person-store.js';
4
+ import { personId, setPersonId } from '../core/canvas/person-state.js';
5
+ import { currentSnapshot, installPersonSnapshot, setSettingsReloader, setSettingsTransport, SettingsRevisionConflictError } from '../core/scoped-state/person-store.js';
6
6
  import { cliClient } from './api-client.js';
7
7
  const fromDto = (dto) => dto.snapshot;
8
+ /** This process's live settings (every write it has made included), for handing to a viewer bundle that holds its own cache. */
9
+ export function loadedPersonSettings() {
10
+ return { person: personId(), snapshot: currentSnapshot() };
11
+ }
8
12
  export async function loadPersonSettingsViaApi() {
9
- const loaded = await cliClient().getSettings();
13
+ installPersonSettingsDto(await cliClient().getSettings());
14
+ }
15
+ /** Install a settings answer already in hand (no request) and wire this process's reload and write transports. */
16
+ export function installPersonSettingsDto(loaded) {
10
17
  setPersonId(loaded.person);
11
18
  installPersonSnapshot(loaded.person, fromDto(loaded));
12
19
  setSettingsReloader(async () => fromDto(await cliClient().getSettings()));
@@ -16,13 +16,18 @@ import { warmCheckoutDirs } from '../checkout-identities.js';
16
16
  import { fillProfileProjectRepo } from '../profiles/manifest.js';
17
17
  import { emitEvent } from '../events/emit.js';
18
18
  import { isCloudRole } from '../canvas/person-state.js';
19
- import { mayRead, reposForCwd, warmCheckoutIdentities } from './repo-sync/repos.js';
19
+ import { loadReadAccess, mayRead, prefetchRepoReads, reposForCwd, warmCheckoutIdentities } from './repo-sync/repos.js';
20
20
  /** A node's view of repos: for the checkouts enclosing its cwd, every repo object of their remotes the person may read (own first, then oldest), then
21
21
  * the repos its profile names (an entry's `repo`, and the checkouts of its `path`), in manifest order, each repo once. A repo entry needs no folder or
22
22
  * git; one the person may not read adds nothing. A project path that no longer exists, is not in a repo, or has no work tree contributes nothing. */
23
23
  export async function viewRepos(db, cwd, profileId, reposFn, lookups, person) {
24
24
  const projects = profileId === null ? [] : lookups.projects(profileId);
25
- const checkouts = await reposFn(cwd, person);
25
+ // One load of the permission inputs serves the cwd and every project entry.
26
+ const who = projects.length === 0 ? undefined : person ?? await personIdAsync();
27
+ const access = who === undefined ? undefined : await loadReadAccess(db, who);
28
+ if (access !== undefined && who !== undefined)
29
+ await prefetchRepoReads(db, who, [cwd, ...projects.flatMap((p) => p.path !== undefined && (isCloudRole() || existsSync(p.path)) ? [p.path] : [])], access);
30
+ const checkouts = await reposFn(cwd, person, access);
26
31
  const seen = new Set(checkouts.map((c) => c.repo.id));
27
32
  const projectRepos = [];
28
33
  const projectCheckouts = [];
@@ -30,7 +35,7 @@ export async function viewRepos(db, cwd, profileId, reposFn, lookups, person) {
30
35
  if (project.repo !== undefined && !seen.has(project.repo)) {
31
36
  const repo = await lookups.object(project.repo);
32
37
  if (repo !== null && repo.type === 'repo' && repo.deleted_at === null
33
- && await mayRead(db, person ?? await personIdAsync(), repo.id)) {
38
+ && await mayRead(db, who ?? person ?? await personIdAsync(), repo.id, access)) {
34
39
  seen.add(repo.id);
35
40
  projectRepos.push(repo);
36
41
  }
@@ -40,7 +45,7 @@ export async function viewRepos(db, cwd, profileId, reposFn, lookups, person) {
40
45
  continue;
41
46
  let found;
42
47
  try {
43
- found = await reposFn(project.path, person);
48
+ found = await reposFn(project.path, person, access);
44
49
  }
45
50
  catch (e) {
46
51
  if (e instanceof CrtrError && e.code === 'git-lookup-failed')
@@ -33,23 +33,65 @@ export async function ensureRepo(db, id, handle) {
33
33
  free = `${wanted}-${n}`;
34
34
  return await ensureOwner(db, 'repo', id.scheme, id.externalId, free);
35
35
  }
36
+ export async function loadReadAccess(db, person) {
37
+ return { defs: await loadDefinitions(db), subjects: await subjectSet(db, person.replace(/^user:/, '')) };
38
+ }
36
39
  /** Whether `person` may read the object `id` by permission facts alone (no ceiling): the gate for a repo a profile names. */
37
- export async function mayRead(db, person, id) {
38
- const read = compilePermission(await loadDefinitions(db), await subjectSet(db, person.replace(/^user:/, '')), OBJECT_TYPE, 'read', f `${id}::text`);
40
+ export async function mayRead(db, person, id, access) {
41
+ const { defs, subjects } = access ?? await loadReadAccess(db, person);
42
+ const read = compilePermission(defs, subjects, OBJECT_TYPE, 'read', f `${id}::text`);
39
43
  const row = await db.prepareUncached(`SELECT ${read.sql} AS ok`).get(...read.params);
40
44
  return row?.ok === true;
41
45
  }
42
46
  /** The repo objects of one remote identity, any person's, that `person` may read (permission facts only, no ceiling), the person's own first and
43
47
  * then by age, oldest first. `heldByPerson` says whether the person has an identity row for it at all, readable or not. */
44
- export async function readableRepos(db, person, scheme, externalId) {
45
- const read = compilePermission(await loadDefinitions(db), await subjectSet(db, person.replace(/^user:/, '')), OBJECT_TYPE, 'read', raw('o.id'));
46
- const rows = await db.prepareUncached(`SELECT o.*, i.person AS holder, ${read.sql} AS ok FROM identities i JOIN objects o ON o.id = i.object
47
- WHERE o.type = 'repo' AND o.deleted_at IS NULL AND i.scheme = ? AND i.external_id = ?`).all(...read.params, scheme, externalId);
48
+ export async function readableRepos(db, person, scheme, externalId, access) {
49
+ const key = `${scheme}\0${externalId}`;
50
+ const prefetched = access?.readable?.get(key);
51
+ if (prefetched !== undefined)
52
+ return { readable: [...prefetched.readable], heldByPerson: prefetched.heldByPerson };
53
+ return (await readableReposFor(db, person, [{ scheme, externalId }], access)).get(key);
54
+ }
55
+ /** `readableRepos` for several identities in one read. */
56
+ async function readableReposFor(db, person, ids, access) {
57
+ const { defs, subjects } = access ?? await loadReadAccess(db, person);
58
+ const read = compilePermission(defs, subjects, OBJECT_TYPE, 'read', raw('o.id'));
59
+ const rows = ids.length === 0 ? [] : await db.prepareUncached(`SELECT o.*, i.person AS holder, i.scheme AS id_scheme, i.external_id AS id_external, ${read.sql} AS ok FROM identities i JOIN objects o ON o.id = i.object
60
+ WHERE o.type = 'repo' AND o.deleted_at IS NULL AND (i.scheme, i.external_id) IN (SELECT * FROM unnest(?::text[], ?::text[]))`)
61
+ .all(...read.params, ids.map((i) => i.scheme), ids.map((i) => i.externalId));
48
62
  const mine = `user:${person.replace(/^user:/, '')}`;
49
63
  const own = (r) => r.holder === mine && r.owner === null;
50
- const readable = rows.filter((r) => r.ok).sort((a, b) => Number(own(b)) - Number(own(a)) || a.created_at.localeCompare(b.created_at) || a.seq - b.seq)
51
- .map(({ holder: _holder, ok: _ok, ...repo }) => repo);
52
- return { readable, heldByPerson: rows.some((r) => r.holder === mine) };
64
+ const out = new Map();
65
+ for (const id of ids) {
66
+ const mineRows = rows.filter((r) => r.id_scheme === id.scheme && r.id_external === id.externalId);
67
+ const readable = mineRows.filter((r) => r.ok).sort((a, b) => Number(own(b)) - Number(own(a)) || a.created_at.localeCompare(b.created_at) || a.seq - b.seq)
68
+ .map(({ holder: _holder, ok: _ok, id_scheme: _s, id_external: _e, ...repo }) => repo);
69
+ out.set(`${id.scheme}\0${id.externalId}`, { readable, heldByPerson: mineRows.some((r) => r.holder === mine) });
70
+ }
71
+ return out;
72
+ }
73
+ const localPathRepos = async (db) => await db.prepare(`SELECT o.*, i.external_id AS path, i.person AS person FROM identities i JOIN objects o ON o.id = i.object
74
+ WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all();
75
+ /** For a request that resolves many directories for one person: read once what each `checkoutsForCwd` would read per directory (the readable
76
+ * repos of every git identity in `dirs`, and the local-path repos) and store it on `access`. */
77
+ export async function prefetchRepoReads(db, person, dirs, access) {
78
+ const ids = new Map();
79
+ for (const cwd of dirs) {
80
+ let chain;
81
+ try {
82
+ chain = await checkoutChainOf(db, realpathOrSelf(resolve(cwd)), async () => person);
83
+ }
84
+ catch (e) {
85
+ if (e instanceof CrtrError && e.code === 'git-lookup-failed')
86
+ continue; // the loop reports it
87
+ throw e;
88
+ }
89
+ for (const id of chain)
90
+ if (id.ok)
91
+ ids.set(`${id.scheme}\0${id.externalId}`, { scheme: id.scheme, externalId: id.externalId });
92
+ }
93
+ access.readable = await readableReposFor(db, person, [...ids.values()], access);
94
+ access.localPaths = await localPathRepos(db);
53
95
  }
54
96
  /** Repos enclosing `cwd`, nearest first: every enclosing git checkout (created
55
97
  * on first sight) and every existing local-path repo whose path is `cwd` or
@@ -65,23 +107,24 @@ export async function warmCheckoutIdentities(cwd) {
65
107
  /** `reposForCwd` with the directory each repo is checked out at. Each git checkout yields every repo object of its remote that `person` (default: the
66
108
  * request's person) may read: their own first, then the others oldest first. A personal repo object is created only when the person holds none for the
67
109
  * remote; one they hold but may no longer read (a group they left) contributes nothing. */
68
- export async function checkoutsForCwd(db, cwd, person) {
110
+ export async function checkoutsForCwd(db, cwd, person, access) {
69
111
  const dir = realpathOrSelf(resolve(cwd));
70
112
  const found = [];
113
+ let loaded = access;
71
114
  for (const id of await checkoutChainOf(db, dir, async () => person ?? await personIdAsync())) {
72
115
  if (!id.ok) {
73
116
  throw new CrtrError('git-lookup-failed', `cannot identify the repo at ${id.dir}: ${id.reason}`, ExitCode.GENERAL, { dir: id.dir });
74
117
  }
75
118
  const who = person ?? await personIdAsync();
76
- const { readable, heldByPerson } = await readableRepos(db, who, id.scheme, id.externalId);
119
+ loaded ??= await loadReadAccess(db, who);
120
+ const { readable, heldByPerson } = await readableRepos(db, who, id.scheme, id.externalId, loaded);
77
121
  if (readable.length === 0 && !heldByPerson)
78
122
  readable.push(await ensureRepo(db, id));
79
123
  for (const repo of readable)
80
124
  found.push({ root: id.root, repo });
81
125
  }
82
126
  // Every person's local-path repos are read, and the request's person is asked for only when one of them encloses `dir`: a folder in no repo needs no person.
83
- const paths = await db.prepare(`SELECT o.*, i.external_id AS path, i.person AS person FROM identities i JOIN objects o ON o.id = i.object
84
- WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all();
127
+ const paths = access?.localPaths ?? await localPathRepos(db);
85
128
  const enclosing = paths.filter(({ path }) => dir === path || dir.startsWith(path.endsWith(sep) ? path : path + sep));
86
129
  const holder = enclosing.length > 0 ? person ?? await personIdAsync() : '';
87
130
  for (const { path, person: owner, ...repo } of enclosing) {
@@ -10,7 +10,9 @@
10
10
  import { projectPaths } from '../../api/dto/profiles.js';
11
11
  import { spawnSync } from 'node:child_process';
12
12
  import { existsSync, realpathSync } from 'node:fs';
13
- import { basename, resolve as resolvePath, sep } from 'node:path';
13
+ import { basename, join, resolve as resolvePath, sep } from 'node:path';
14
+ import { appendRotatingRecord } from '../log.js';
15
+ import { crtrHome } from '../canvas/paths.js';
14
16
  import { createInterface } from 'node:readline/promises';
15
17
  import { emitKeypressEvents } from 'node:readline';
16
18
  import { listProfiles, loadProfileManifest, resolveProfileOperand, updateProfileLastUsed, createProfile, addProfileProject, ensureRootProfile, ROOT_PROFILE_ID, } from './manifest.js';
@@ -669,7 +671,15 @@ async function promptPickProfileOrCreate(candidates, cwd, exact, pinnedId, bindi
669
671
  * the root profile. Non-interactive (no TTY):
670
672
  * default to the root profile and print the recovery instruction to STDERR —
671
673
  * never stdout, which the caller may be piping. */
672
- export async function selectProfileForCwd(cwd, explicitProfile, forcePicker = false) {
674
+ export async function selectProfileForCwd(cwd, explicitProfile, forcePicker = false,
675
+ /** The front door's startup does not hold the start on the last-used write (a timestamp nothing in this start reads back); crtrd's callers wait for it. */
676
+ waitForLastUsed = true) {
677
+ const touch = async (profileId) => {
678
+ if (waitForLastUsed)
679
+ await updateProfileLastUsed(profileId);
680
+ else
681
+ updateProfileLastUsed(profileId).catch((error) => appendRotatingRecord(join(crtrHome(), 'attach-invariants.log'), `${new Date().toISOString()} profile.last_used ${profileId} ${String(error).replaceAll(/[\r\n]/g, ' ')}`));
682
+ };
673
683
  const resolvedCwd = resolveCwd(cwd);
674
684
  const bindings = resolveUserKeybindings();
675
685
  if (explicitProfile !== undefined && explicitProfile !== null && explicitProfile !== '') {
@@ -679,7 +689,7 @@ export async function selectProfileForCwd(cwd, explicitProfile, forcePicker = fa
679
689
  if (!profileCoversCwd(entry, resolvedCwd) && isInteractive()) {
680
690
  await promptAddDirToProfile(entry, resolvedCwd);
681
691
  }
682
- await updateProfileLastUsed(entry.profileId);
692
+ await touch(entry.profileId);
683
693
  return entry.profileId;
684
694
  }
685
695
  // Looped for the one gate that changes the world before it answers: `v` opens
@@ -700,14 +710,14 @@ export async function selectProfileForCwd(cwd, explicitProfile, forcePicker = fa
700
710
  // hint, so a boot-time breadcrumb here would just be redundant.
701
711
  // `crtr --pick-profile` (forcePicker) re-opens the menu to re-pin/unpin.
702
712
  if (pinned !== null && !forcePicker) {
703
- await updateProfileLastUsed(pinned.profileId);
713
+ await touch(pinned.profileId);
704
714
  return pinned.profileId;
705
715
  }
706
716
  // Exactly one profile's project dir IS cwd — unambiguous project root, use it
707
717
  // silently, never a prompt. (Several exact claims fall through to the menu.)
708
718
  // Suppressed under forcePicker so `--pick-profile` can pin even a lone owner.
709
719
  if (!forcePicker && pinned === null && exact.length === 1) {
710
- await updateProfileLastUsed(exact[0].profileId);
720
+ await touch(exact[0].profileId);
711
721
  return exact[0].profileId;
712
722
  }
713
723
  // Non-interactive: cannot prompt. Prefer an exact claimant, else any covering
@@ -716,7 +726,7 @@ export async function selectProfileForCwd(cwd, explicitProfile, forcePicker = fa
716
726
  const pool = exact.length > 0 ? exact : covering;
717
727
  if (pool.length > 0) {
718
728
  const winner = pickMostRecent(pool);
719
- await updateProfileLastUsed(winner.profileId);
729
+ await touch(winner.profileId);
720
730
  return winner.profileId;
721
731
  }
722
732
  const root = await ensureRootProfile();
@@ -734,7 +744,7 @@ export async function selectProfileForCwd(cwd, explicitProfile, forcePicker = fa
734
744
  : await promptCreateOrRoot(resolvedCwd, bindings);
735
745
  if (chosen === MANAGED)
736
746
  continue;
737
- await updateProfileLastUsed(chosen);
747
+ await touch(chosen);
738
748
  return chosen;
739
749
  }
740
750
  }
@@ -29,8 +29,8 @@ export { buildProjectContextBlock, contextDirNote, orchestratorContextNote };
29
29
  * `assembleNodeSubject`'s profile resolution). This absolute-path disclosure
30
30
  * is intentional (spec-approved): the agent must know its full purview, not a
31
31
  * redacted count. */
32
- export async function profileNote(nodeId) {
33
- const meta = await getNode(nodeId);
32
+ export async function profileNote(nodeId, known) {
33
+ const meta = known !== undefined ? known : await getNode(nodeId);
34
34
  if (meta === null)
35
35
  return '';
36
36
  return profileNoteShared(meta.cwd, meta.profile_id);
@@ -41,10 +41,10 @@ export async function profileNote(nodeId) {
41
41
  // Not the full subtree — just the load-bearing spine up and one level down.
42
42
  /** Ancestry trunk from the root DOWN to (but excluding) `nodeId`, climbing the
43
43
  * spine `parent` edge. Cycle-guarded. Root first. */
44
- async function ancestorTrunk(nodeId) {
44
+ async function ancestorTrunk(nodeId, own) {
45
45
  const trunk = [];
46
46
  const seen = new Set([nodeId]);
47
- let cur = (await getNode(nodeId))?.parent ?? null;
47
+ let cur = own.parent ?? null;
48
48
  while (cur !== null && cur !== '' && !seen.has(cur)) {
49
49
  seen.add(cur);
50
50
  const m = await getNode(cur);
@@ -67,18 +67,17 @@ async function childNodes(nodeId) {
67
67
  /** The graph mini-map: the ancestry trunk (root first), then this node marked
68
68
  * `● you`, then its immediate children. Returns '' for a lone root with no
69
69
  * children (nothing to map). Exported for testing. */
70
- export async function buildGraphMap(nodeId) {
71
- const meta = await getNode(nodeId);
70
+ export async function buildGraphMap(nodeId, known) {
71
+ const meta = known !== undefined ? known : await getNode(nodeId);
72
72
  if (meta === null)
73
73
  return '';
74
- const trunk = await ancestorTrunk(nodeId);
74
+ const trunk = await ancestorTrunk(nodeId, meta);
75
75
  const children = await childNodes(nodeId);
76
76
  return renderGraphMap(nodeId, meta.kind, meta.mode, trunk, children);
77
77
  }
78
78
  /** The identity assertion injected at session start. A fork names its source
79
79
  * while treating the copied first-person narrative as reference. */
80
- async function buildIdentityAssertion(nodeId) {
81
- const meta = await getNode(nodeId);
80
+ async function buildIdentityAssertion(nodeId, meta) {
82
81
  const forkFrom = meta?.fork_from;
83
82
  // A known node id carries its human label. Paths and session ids remain
84
83
  // opaque provenance rather than being passed to the node-id lookup.
@@ -163,13 +162,13 @@ function managedWorktreeNote(node) {
163
162
  * documents owned by the directory's repo (its `<repo>/index` is the workspace front door). */
164
163
  async function bearingsShell(nodeId, knowledge, workspaceContext) {
165
164
  const node = await getNode(nodeId);
166
- const bearings = ['<crtr-bearings>', await buildIdentityAssertion(nodeId)];
167
- const map = await buildGraphMap(nodeId);
165
+ const bearings = ['<crtr-bearings>', await buildIdentityAssertion(nodeId, node)];
166
+ const map = await buildGraphMap(nodeId, node);
168
167
  if (map !== '')
169
168
  bearings.push('', '## Your place in the canvas', map);
170
169
  bearings.push('', '## Your documents and context directory', contextDirNote(nodeId, node?.grantee));
171
170
  // Profile purview — omitted entirely when there is no project purview (see profileNote).
172
- const profileSection = await profileNote(nodeId);
171
+ const profileSection = await profileNote(nodeId, node);
173
172
  if (profileSection !== '')
174
173
  bearings.push('', profileSection);
175
174
  const worktree = managedWorktreeNote(node);