@north-light/cli 0.3.620 → 0.3.622

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.
@@ -1 +1 @@
1
- var h=Object.defineProperty;var s=(e,o)=>h(e,"name",{value:o,configurable:!0});import{defineLeaf as m}from"../../core/command.js";import{usage as d}from"../../core/errors.js";import{DOC_UNSET_FIELDS as u}from"../../api/dto/docs.js";import{cliClient as f}from"../api-client.js";import{parseReplaceBlocks as p}from"./replace-blocks.js";import{FIELD_FLAGS as t,REF_CONSTRAINT as y,fieldsFromInput as b,rethrowDocError as w,renderLinkReport as v,ruleParam as g}from"./shared.js";const q=m({name:"edit",description:"revise a document you have read",whenToUse:"a document you read needs a change to its body or fields",help:{name:"doc edit",summary:"revise a document you have read",guide:"The edit is made from the revision you last read (`crtr canvas read`); pass no revision. If someone edited it after your read, the edit is refused and nothing is overwritten. For a partial edit, pipe one or more literal blocks on stdin with --blocks: <<<<<<< SEARCH, old text, =======, new text, >>>>>>> REPLACE (markers on their own lines). Each SEARCH must match exactly once; empty REPLACE deletes text. Alternatively pipe a whole new body without --blocks, or use --replace JSON for scripts. Choose one mode. Pipe text straight in with a quoted heredoc (`<<'EOF'`); an unquoted one lets the shell expand `$` and backticks in the text, and the mangled text is what gets saved. A field flag replaces that field; omitted fields stay as they are. A change to fields alone (preview, summary, privacy, rules, why-it-exists, \u2026) takes effect at once and records a new revision with the body unchanged, attributed to you with the rationale, so `crtr doc history` lists it and the revision number advances. A caller that read the document earlier needs a fresh read before its next body edit.",params:[{kind:"positional",name:"ref",required:!0,constraint:y},{kind:"flag",name:"rationale",type:"string",required:!0,constraint:"Why this revision is made; recorded on the revision, never in the body. A fields-only edit records its revision with the same body."},{kind:"stdin",name:"body",required:!1,constraint:"Whole new body by default; with --blocks, exact SEARCH/REPLACE blocks."},{kind:"flag",name:"blocks",type:"bool",required:!1,constraint:"Interpret stdin as one or more whole-line <<<<<<< SEARCH / ======= / >>>>>>> REPLACE blocks; empty SEARCH is invalid, empty REPLACE deletes."},{kind:"flag",name:"replace",type:"string",required:!1,constraint:'JSON list `[{"old": "\u2026", "new": "\u2026"}]` of exact-text replacements; each `old` must match exactly once in the body you read.'},{kind:"flag",name:"verbatim",type:"bool",required:!1,constraint:"The body is the person's own text relayed unchanged; recorded on the revision."},t.preview("New one-line preview."),t.summary,t.privacy("`public` or `private`. A private document is kept from apps without a private-read scope; the owner and anyone it is shared with still read it."),g("Replaces the whole rule list."),t.whyItExists,t.unlisted("Sets unlisted; remove it with `--unset unlisted`."),t.lintIgnore,t.extension,{kind:"flag",name:"unset",type:"enum",choices:[...u],required:!1,repeatable:!0,constraint:"Clear one optional field."}],output:[{name:"revision",type:"number",required:!0,constraint:"The new revision number; a fields-only edit advances it too."},{name:"unresolved_links",type:"string[]",required:!1,constraint:"`[[links]]` in the new body that name no document yet."},{name:"remote_links",type:"string[]",required:!1,constraint:"`[[links]]` whose first segment is no owner on this runtime: on another runtime, or misspelled."}],outputKind:"object",effects:["Commits a new revision based on your last read and pushes the edit to the document's watchers."]},run:s(async e=>{const o=e.ref;let n=typeof e.body=="string"&&e.body!==""?e.body:void 0,i;if(e.blocks===!0){if(e.replace!==void 0)throw d("choose --blocks or --replace, not both",{field:"blocks"});i=p(n??""),n=void 0}if(typeof e.replace=="string"){if(n!==void 0)throw d("give a stdin body or --replace, not both",{field:"replace",next:"Drop one of them and rerun."});try{const r=JSON.parse(e.replace);if(!Array.isArray(r)||r.length===0||r.some(a=>typeof a!="object"||a===null||typeof a.old!="string"||typeof a.new!="string"))throw new Error;i=r}catch{throw d('--replace must be a non-empty JSON list of {"old": string, "new": string}',{field:"replace",next:"Fix the JSON and rerun."})}}const l=e.unset===void 0?[]:[].concat(e.unset),c={rationale:e.rationale,...n!==void 0?{body:n}:{},...i!==void 0?{replace:i}:{},...e.verbatim===!0?{verbatim:!0}:{},...b(e),...l.length>0?{unset:l}:{}};try{return{...await f().docs.edit(o,c)}}catch(r){w(r,o)}},"run"),render:s(e=>`<edited name="${String(e.name)}" revision=${String(e.revision)}>${v(e)}`,"render")});export{q as editLeaf};
1
+ var h=Object.defineProperty;var s=(e,o)=>h(e,"name",{value:o,configurable:!0});import{defineLeaf as m}from"../../core/command.js";import{usage as d}from"../../core/errors.js";import{DOC_UNSET_FIELDS as u}from"../../api/dto/docs.js";import{cliClient as f}from"../api-client.js";import{parseReplaceBlocks as y}from"./replace-blocks.js";import{FIELD_FLAGS as t,PREVIEW_TEXT as p,REF_CONSTRAINT as b,UNREACHED_CONSTRAINT as w,fieldsFromInput as v,rethrowDocError as g,renderLinkReport as E,ruleParam as k}from"./shared.js";const L=m({name:"edit",description:"revise a document you have read",whenToUse:"a document you read needs a change to its body or fields",help:{name:"doc edit",summary:"revise a document you have read",guide:"The edit is made from the revision you last read (`crtr canvas read`); pass no revision. If someone edited it after your read, the edit is refused and nothing is overwritten. For a partial edit, pipe one or more literal blocks on stdin with --blocks: <<<<<<< SEARCH, old text, =======, new text, >>>>>>> REPLACE (markers on their own lines). Each SEARCH must match exactly once; empty REPLACE deletes text. Alternatively pipe a whole new body without --blocks, or use --replace JSON for scripts. Choose one mode. Pipe text straight in with a quoted heredoc (`<<'EOF'`); an unquoted one lets the shell expand `$` and backticks in the text, and the mangled text is what gets saved. A field flag replaces that field; omitted fields stay as they are. A change to fields alone (preview, summary, privacy, rules, why-it-exists, \u2026) takes effect at once and records a new revision with the body unchanged, attributed to you with the rationale, so `crtr doc history` lists it and the revision number advances. A caller that read the document earlier needs a fresh read before its next body edit.",params:[{kind:"positional",name:"ref",required:!0,constraint:b},{kind:"flag",name:"rationale",type:"string",required:!0,constraint:"Why this revision is made; recorded on the revision, never in the body. A fields-only edit records its revision with the same body."},{kind:"stdin",name:"body",required:!1,constraint:"Whole new body by default; with --blocks, exact SEARCH/REPLACE blocks."},{kind:"flag",name:"blocks",type:"bool",required:!1,constraint:"Interpret stdin as one or more whole-line <<<<<<< SEARCH / ======= / >>>>>>> REPLACE blocks; empty SEARCH is invalid, empty REPLACE deletes."},{kind:"flag",name:"replace",type:"string",required:!1,constraint:'JSON list `[{"old": "\u2026", "new": "\u2026"}]` of exact-text replacements; each `old` must match exactly once in the body you read.'},{kind:"flag",name:"verbatim",type:"bool",required:!1,constraint:"The body is the person's own text relayed unchanged; recorded on the revision."},t.preview(`New preview. ${p}`),t.summary,t.privacy("`public` or `private`. A private document is kept from apps without a private-read scope; the owner and anyone it is shared with still read it."),k("A delivery rule; `--unset rules` removes every rule."),t.whyItExists,t.unlisted("Sets unlisted; remove it with `--unset unlisted`."),t.lintIgnore,t.extension,{kind:"flag",name:"unset",type:"enum",choices:[...u],required:!1,repeatable:!0,constraint:"Clear one optional field."}],output:[{name:"revision",type:"number",required:!0,constraint:"The new revision number; a fields-only edit advances it too."},{name:"unresolved_links",type:"string[]",required:!1,constraint:"`[[links]]` in the new body that name no document yet."},{name:"remote_links",type:"string[]",required:!1,constraint:"`[[links]]` whose first segment is no owner on this runtime: on another runtime, or misspelled."},{name:"unreached",type:"bool",required:!1,constraint:w}],outputKind:"object",effects:["Commits a new revision based on your last read and pushes the edit to the document's watchers."]},run:s(async e=>{const o=e.ref;let n=typeof e.body=="string"&&e.body!==""?e.body:void 0,i;if(e.blocks===!0){if(e.replace!==void 0)throw d("choose --blocks or --replace, not both",{field:"blocks"});i=y(n??""),n=void 0}if(typeof e.replace=="string"){if(n!==void 0)throw d("give a stdin body or --replace, not both",{field:"replace",next:"Drop one of them and rerun."});try{const r=JSON.parse(e.replace);if(!Array.isArray(r)||r.length===0||r.some(a=>typeof a!="object"||a===null||typeof a.old!="string"||typeof a.new!="string"))throw new Error;i=r}catch{throw d('--replace must be a non-empty JSON list of {"old": string, "new": string}',{field:"replace",next:"Fix the JSON and rerun."})}}const l=e.unset===void 0?[]:[].concat(e.unset),c={rationale:e.rationale,...n!==void 0?{body:n}:{},...i!==void 0?{replace:i}:{},...e.verbatim===!0?{verbatim:!0}:{},...v(e),...l.length>0?{unset:l}:{}};try{return{...await f().docs.edit(o,c)}}catch(r){g(r,o)}},"run"),render:s(e=>`<edited name="${String(e.name)}" revision=${String(e.revision)}>${E(e)}`,"render")});export{L as editLeaf};
@@ -1,2 +1,2 @@
1
- var o=Object.defineProperty;var t=(n,e)=>o(n,"name",{value:e,configurable:!0});import{defineLeaf as i}from"../../core/command.js";import{cliClient as s,rethrowAsCliError as a}from"../api-client.js";import{ownerFromInput as c}from"./shared.js";const p=i({name:"lint",description:"check documents for authoring problems",whenToUse:"checking the documents you can change for bodies too long for their delivery, badly shaped previews, or links to nothing",help:{name:"doc lint",summary:"check documents for authoring problems",guide:'Checks the documents you can change: body length against how the document is delivered; the "When \u2026, read this because \u2026" preview shape where a rule delivers at preview; `[[links]]` that name no document; more than one workspace-open content document per repo your profile manages. A document skips a check named in its lint-ignore field.',params:[{kind:"flag",name:"owner",type:"string",required:!1,constraint:"Check only this owner's documents: node | user | profile | profile:<name> | app | repo | repo:<handle>."}],output:[{name:"findings",type:"object[]",required:!0,constraint:"Each {name, severity, rule, message}; empty when clean."}],outputKind:"object",effects:["None."]},run:t(async n=>{try{return{...await s().docs.lint({...c(n),cwd:process.cwd()})}}catch(e){a(e)}},"run"),render:t(n=>{const{findings:e}=n;return e.length===0?"No findings.":e.map(r=>`<finding name="${r.name}" severity="${r.severity}" rule="${r.rule}">${r.message}</finding>`).join(`
2
- `)+"\nFix each with `crtr doc edit`, or add the rule to the document's lint-ignore field when it does not apply."},"render")});export{p as lintLeaf};
1
+ var r=Object.defineProperty;var t=(n,e)=>r(n,"name",{value:e,configurable:!0});import{defineLeaf as i}from"../../core/command.js";import{cliClient as a,rethrowAsCliError as s}from"../api-client.js";import{ownerFromInput as d}from"./shared.js";const m=i({name:"lint",description:"check documents for authoring problems",whenToUse:"checking the documents you can change for bodies too long for their delivery, badly shaped previews, or links to nothing",help:{name:"doc lint",summary:"check documents for authoring problems",guide:'Checks the documents you can change: body length against how the document is delivered; the "When \u2026, read this because \u2026" preview shape where a rule delivers at preview; `[[links]]` that name no document; a document not owned by a node that no rule delivers and no document with a rule links to (`unreached`); more than one workspace-open content document per repo your profile manages. A document skips a check named in its lint-ignore field.',params:[{kind:"flag",name:"owner",type:"string",required:!1,constraint:"Check only this owner's documents: node | user | profile | profile:<name> | app | repo | repo:<handle>."}],output:[{name:"findings",type:"object[]",required:!0,constraint:"Each {name, severity, rule, message}; empty when clean."}],outputKind:"object",effects:["None."]},run:t(async n=>{try{return{...await a().docs.lint({...d(n),cwd:process.cwd()})}}catch(e){s(e)}},"run"),render:t(n=>{const{findings:e}=n;return e.length===0?"No findings.":e.map(o=>`<finding name="${o.name}" severity="${o.severity}" rule="${o.rule}">${o.message}</finding>`).join(`
2
+ `)+"\nFix each with `crtr doc edit`, or add the rule to the document's lint-ignore field when it does not apply."},"render")});export{m as lintLeaf};
@@ -4,6 +4,8 @@ export declare const REF_CONSTRAINT = "A document name (with or without [[ ]]) o
4
4
  export declare const OWNER_VALUES = "node | user | profile | profile:<name> | app | repo | repo:<handle>";
5
5
  export declare function ownerParam(constraint: string): FlagParam;
6
6
  export declare function ruleParam(constraint: string): FlagParam;
7
+ /** The `--preview` contract on write and edit: for most readers the line is all they see. */
8
+ export declare const PREVIEW_TEXT: string;
7
9
  export declare const FIELD_FLAGS: {
8
10
  preview: (constraint: string) => FlagParam;
9
11
  kind: FlagParam;
@@ -21,5 +23,6 @@ export declare function ownerFromInput(input: Record<string, unknown>): {
21
23
  };
22
24
  /** Rethrow an API failure with the next step its code implies for `ref`. */
23
25
  export declare function rethrowDocError(err: unknown, ref: string): never;
26
+ export declare const UNREACHED_CONSTRAINT = "Present and true when the document is owned by someone other than a node, has no rule, and no document with a rule links to it: no agent will be routed to it. Give it a --rule with `crtr doc edit`, link it from a document that loads, or accept it with `--lint-ignore unreached`.";
24
27
  /** The link lines under a write or edit result. */
25
28
  export declare function renderLinkReport(r: Record<string, unknown>): string;
@@ -1,2 +1,2 @@
1
- var f=Object.defineProperty;var o=(e,t)=>f(e,"name",{value:t,configurable:!0});import{usage as m}from"../../core/errors.js";import{ApiError as w}from"../../api/errors.js";import{rethrowAsCliError as h}from"../api-client.js";import{RULE_ON as g,RULE_DELIVER as v,DOC_KINDS as y}from"../../api/dto/docs.js";import{PRIVACY_LEVELS_DTO as b}from"../../api/dto/objects.js";const q="A document name (with or without [[ ]]) or a raw object id.",p="node | user | profile | profile:<name> | app | repo | repo:<handle>";function O(e){return{kind:"flag",name:"owner",type:"string",required:!1,constraint:e,focusedHelp:{whenToUse:"Omit it for a document only this node and the nodes it points at need: the writing node owns it and it is deleted with the node, unless a kept document links to it. Give another owner when the document must outlive this node or reach other nodes by itself. A document worth another owner carries reusable current truth: a non-obvious procedure, a gotcha, a lasting preference, a convention across repos. Task notes, conversation summaries and facts the repo already records stay with the node or are not written. Before writing one, search for a document that already covers it (`crtr canvas search`) and revise that one with `crtr doc edit` instead of adding a near copy. When one document grows long, keep the most important content in it and move separate subjects into documents named under it (`topic/part`), each pointed at with a `[[link]]`. Choose the narrowest owner that still reaches the next agent who needs it.",value:`One of ${p}. \`node\` \u2014 the writing node; only this node loads it by rule, other nodes read it when pointed at it; deleted with the node. \`profile\` \u2014 the node's profile, or \`profile:<name>\`; loads for nodes running in that profile; stays on this runtime. \`app\` \u2014 the app that runs the node; kept until deleted; readable by that app's nodes. \`repo\` \u2014 the repo the node works in (from its working directory), or \`repo:<handle>\` for another repo whose checkout the node's file permissions let it write (such as a project of its profile); every clone and worktree of the repo shares it, and it syncs to collaborators over the repo's \`refs/crtr/docs\`. A repo owns only public documents: a private document that should load in one repo is owned by \`user\` and carries a rule with \`if: {"repo": "<handle>"}\`. \`user\` \u2014 you, the person; loads for every node by its rules; readable by apps by privacy level. Default: the writing node; a person's own run (not a node) defaults to \`user\`. The owner becomes the start of the document's full name (\`<owner-handle>/<name>\`); \`crtr doc move --owner\` changes it later and keeps the id and every link.`,effects:["Decides who may read and change the document, where it syncs, and what deleting takes it with."]}}}o(O,"ownerParam");const k="`if` is a condition on the receiving node. Fields: `kind`, `mode`, `lifecycle`, `cwd`, `repo` (the handle of a repo the node is eligible for: those enclosing its cwd and those of its profile's projects; use `cwd` for where it works), `profile`, `depth`. A field map is ANDed across fields; dotted fields resolve nested values. A scalar matches by equality (a list value matches when any element is equal); a list matcher matches by membership or overlap; an object matcher takes `eq`, `ne`, `in`, `nin`, `exists`, `contains`, `containsAll`, `containsAny`, `matches`, `imatches`, `gt`, `gte`, `lt`, `lte`. `all`, `any` and `not` combine conditions; field matchers beside them are ANDed in. An empty condition always matches; an unknown operator never matches. `match_frontmatter` uses the same language against the read file's YAML frontmatter.";function S(e){return{kind:"flag",name:"rule",type:"string",required:!1,repeatable:!0,constraint:e,focusedHelp:{whenToUse:"Omit it for most documents: a document with no rule is read when a node is pointed at it (`[[name]]`), finds it with `crtr canvas search`, or sees it in a listing. Add a rule only when the document must load on its own because of what a node is doing; every rule costs context in every node it fires on. Prefer the narrowest trigger: a `file-read` rule with a real glob over `boot` for knowledge about specific code; `boot` for knowledge about a person or process with no file boundary. When the whole document is one sentence, deliver `content` \u2014 a preview line would be longer than the document.",value:`One JSON object per occurrence: \`{"on": \u2026, "match"?: [globs], "match_frontmatter"?: {\u2026}, "if"?: {\u2026}, "deliver": \u2026}\`. \`on\` is the node's activity: ${g.join(" | ")}. \`boot\` \u2014 every session start of the node. \`workspace-open\` \u2014 the node's first message when it works in the document's repo. \`file-read\` \u2014 the node reads the content of a file whose absolute path or basename matches a \`match\` glob, or whose frontmatter matches \`match_frontmatter\`; through the Read tool, or a bash segment of \`cat\`, \`sed\` (not \`-i\`), \`head\`, \`tail\` (not \`-f\`), \`nl\` or \`awk\` on a literal path (resolved after the command's own \`cd\`s; \`rg\`, \`grep\`, \`find\`, \`ls\`, \`wc\`, \`stat\` are searches, not reads, and never fire it). \`document-read\` \u2014 another document whose name matches is delivered at content, including an explicit read. \`command\` \u2014 a shell segment of a bash command matches (segments split on \`&&\`, \`||\`, \`;\`, \`|\` and newlines outside quotes, leading \`VAR=value\` dropped; \`*\` spans whole whitespace-separated tokens, \`?\` one character, quoted text is opaque). \`pre-command\` \u2014 as \`command\`, but runs before the command: when the node has not read the document, the command does not run and the document is returned instead; the node re-issues the command. \`slash-command\` \u2014 the document is a \`/<name>\` slash command whose body is the injected prompt. \`match\` is required on \`file-read\` (unless \`match_frontmatter\` is given), \`document-read\`, \`command\` and \`pre-command\`, and not allowed on \`boot\`, \`workspace-open\` and \`slash-command\`. `+k+` \`deliver\` is ${v.join(" | ")}: the bare name, the preview line, or the whole body. The flag set replaces the document's whole rule list; on \`crtr doc edit\`, \`--unset rules\` removes every rule.`,effects:["When several rules deliver one document to a node, the highest delivery wins: content over preview over name; content already in the node's context is not delivered again.","A document delivered at content is a read: it records the node as a watcher, so the node is pushed later edits.","The profile's delivery limit per owner caps what `boot` and `workspace-open` rules deliver for that owner.",'A rule that delivers at `preview` requires the preview in the shape "When <situation in the reader\'s work>, read this because <what the reader gains>"; `crtr doc lint` checks it. There the line alone decides whether a node that did not ask for the document opens it.']}}}o(S,"ruleParam");const N={preview:o(e=>({kind:"flag",name:"preview",type:"string",required:!1,constraint:e}),"preview"),kind:{kind:"flag",name:"kind",type:"enum",choices:[...y],required:!1,constraint:"knowledge is consulted for facts or procedures; preference directs behavior. Default knowledge."},summary:{kind:"flag",name:"summary",type:"string",required:!1,constraint:"A very short version of the content, shown in `crtr canvas list`."},privacy:o(e=>({kind:"flag",name:"privacy",type:"enum",choices:[...b],required:!1,constraint:e}),"privacy"),whyItExists:{kind:"flag",name:"why-it-exists",type:"string",required:!1,constraint:"The observed failure this document exists to prevent; shown only with `crtr canvas read --fields`."},unlisted:o(e=>({kind:"flag",name:"unlisted",type:"bool",required:!1,constraint:e}),"unlisted"),lintIgnore:{kind:"flag",name:"lint-ignore",type:"string",required:!1,repeatable:!0,constraint:"A `crtr doc lint` rule name to skip for this document."},extension:{kind:"flag",name:"extension",type:"string",required:!1,repeatable:!0,constraint:"One declared plugin field as `<plugin>.<field>=<json value>`."}};function c(e){return e===void 0?[]:Array.isArray(e)?e.map(String):[String(e)]}o(c,"list");function T(e){const t=[],n={};for(const[r,a]of[["preview","preview"],["kind","kind"],["summary","summary"],["privacy","privacy"],["whyItExists","why_it_exists"]])typeof e[r]=="string"&&(n[a]=e[r]);typeof n.preview=="string"&&/[\r\n]/.test(n.preview)&&t.push("--preview must be one line"),e.unlisted===!0&&(n.unlisted=!0);const i=c(e.lintIgnore);i.length>0&&(n.lint_ignore=i);const s=c(e.rule);if(s.length>0){const r=[];s.forEach((a,u)=>{try{const d=JSON.parse(a);typeof d!="object"||d===null||Array.isArray(d)?t.push(`--rule #${u+1} must be a JSON object`):r.push(d)}catch{t.push(`--rule #${u+1} is not valid JSON: ${a}`)}}),n.rules=r}const l={};for(const r of c(e.extension)){const a=/^([^.=]+)\.([^=]+)=(.*)$/s.exec(r);if(!a){t.push(`--extension ${r} is not <plugin>.<field>=<json value>`);continue}try{(l[a[1]]??={})[a[2]]=JSON.parse(a[3])}catch{t.push(`--extension ${r}: the value after = is not valid JSON`)}}if(Object.keys(l).length>0&&(n.extensions=l),t.length>0)throw m(t.join("; "),{next:"Fix every value above and rerun; `--rule -h` gives the rule grammar."});return n}o(T,"fieldsFromInput");function R(e){const t=e.owner;if(t===void 0)return{};const n=String(t);if(!/^(node|user|profile|app|repo)$|^(profile|repo):.+$/.test(n))throw m(`invalid --owner ${n}`,{field:"owner",next:`Pass one of ${p}.`});return{owner:n}}o(R,"ownerFromInput");function D(e,t){e instanceof w&&(e.code==="read_first"&&h(e,`Read it first with \`crtr canvas read ${t}\`, then rerun the edit.`),e.code==="stale_revision"&&h(e,`Someone edited it after your read. Read it again with \`crtr canvas read ${t}\`, make your change on the current text, and rerun the edit.`)),h(e)}o(D,"rethrowDocError");function I(e){const t=[],n=e.unresolved_links,i=e.remote_links;return n?.length&&t.push(`Unresolved links (no document by these names yet): ${n.map(s=>`[[${s}]]`).join(", ")}`),i?.length&&t.push(`Not on this runtime: ${i.map(s=>`[[${s}]]`).join(", ")} \u2014 each may be on another runtime, or the name may be misspelled.`),t.map(s=>`
2
- ${s}`).join("")}o(I,"renderLinkReport");export{N as FIELD_FLAGS,p as OWNER_VALUES,q as REF_CONSTRAINT,T as fieldsFromInput,R as ownerFromInput,O as ownerParam,I as renderLinkReport,D as rethrowDocError,S as ruleParam};
1
+ var w=Object.defineProperty;var o=(e,t)=>w(e,"name",{value:t,configurable:!0});import{usage as m}from"../../core/errors.js";import{ApiError as y}from"../../api/errors.js";import{rethrowAsCliError as l}from"../api-client.js";import{RULE_ON as g,RULE_DELIVER as v,DOC_KINDS as b}from"../../api/dto/docs.js";import{PRIVACY_LEVELS_DTO as k}from"../../api/dto/objects.js";const j="A document name (with or without [[ ]]) or a raw object id.",p="node | user | profile | profile:<name> | app | repo | repo:<handle>";function O(e){return{kind:"flag",name:"owner",type:"string",required:!1,constraint:e,focusedHelp:{whenToUse:"Omit it for a document only this node and the nodes it points at need: the writing node owns it and it is deleted with the node, unless a kept document links to it. Give another owner when the document must outlive this node or reach other nodes by itself. A document worth another owner carries reusable current truth: a non-obvious procedure, a gotcha, a lasting preference, a convention across repos. Task notes, conversation summaries and facts the repo already records stay with the node or are not written. Before writing one, search for a document that already covers it (`crtr canvas search`) and revise that one with `crtr doc edit` instead of adding a near copy. When one document grows long, keep the most important content in it and move separate subjects into documents named under it (`topic/part`), each pointed at with a `[[link]]`. Choose the narrowest owner that still reaches the next agent who needs it.",value:`One of ${p}. \`node\` \u2014 the writing node; only this node loads it by rule, other nodes read it when pointed at it; deleted with the node. \`profile\` \u2014 the node's profile, or \`profile:<name>\`; loads for nodes running in that profile; stays on this runtime. \`app\` \u2014 the app that runs the node; kept until deleted; readable by that app's nodes. \`repo\` \u2014 the repo the node works in (from its working directory), or \`repo:<handle>\` for another repo whose checkout the node's file permissions let it write (such as a project of its profile); every clone and worktree of the repo shares it, and it syncs to collaborators over the repo's \`refs/crtr/docs\`. A repo owns only public documents: a private document that should load in one repo is owned by \`user\` and carries a rule with \`if: {"repo": "<handle>"}\`. \`user\` \u2014 you, the person; loads for every node by its rules; readable by apps by privacy level. Default: the writing node; a person's own run (not a node) defaults to \`user\`. The owner becomes the start of the document's full name (\`<owner-handle>/<name>\`); \`crtr doc move --owner\` changes it later and keeps the id and every link.`,effects:["Decides who may read and change the document, where it syncs, and what deleting takes it with."]}}}o(O,"ownerParam");const x="`if` is a condition on the receiving node. Fields: `kind`, `mode`, `lifecycle`, `cwd`, `repo` (the handle of a repo the node is eligible for: those enclosing its cwd and those of its profile's projects; use `cwd` for where it works), `profile`, `depth`. A field map is ANDed across fields; dotted fields resolve nested values. A scalar matches by equality (a list value matches when any element is equal); a list matcher matches by membership or overlap; an object matcher takes `eq`, `ne`, `in`, `nin`, `exists`, `contains`, `containsAll`, `containsAny`, `matches`, `imatches`, `gt`, `gte`, `lt`, `lte`. `all`, `any` and `not` combine conditions; field matchers beside them are ANDed in. An empty condition always matches; an unknown operator never matches. `match_frontmatter` uses the same language against the read file's YAML frontmatter.",A=`One JSON object per occurrence: \`{"on": \u2026, "match"?: [globs], "match_frontmatter"?: {\u2026}, "if"?: {\u2026}, "deliver": \u2026}\`; the flag set replaces the document's whole rule list. Whether to give one follows the owner. A document the writing node owns (the default) takes none: its rules fire only in that node, and other nodes reach it through the \`[[link]]\` that carries it. A document under any other owner needs one unless a document that already loads links to it: with neither, it is found only by a search that happens to match it, and the result says so. Choose the narrowest trigger that reaches the next agent who needs it, because every rule costs context in every node it fires on: \`file-read\` with a real glob for knowledge about specific code, \`command\` or \`pre-command\` for knowledge about a command, \`boot\` only for a person, preference or process with no file or command boundary. Deliver \`preview\` by default; \`content\` when the whole document is about one sentence (a preview line would be longer than it) or must always be followed. \`on\` is the node's activity: ${g.join(" | ")}. \`boot\` \u2014 every session start of the node. \`workspace-open\` \u2014 the node's first message when it works in the document's repo. \`file-read\` \u2014 the node reads the content of a file whose absolute path or basename matches a \`match\` glob, or whose frontmatter matches \`match_frontmatter\`; through the Read tool, or a bash segment of \`cat\`, \`sed\` (not \`-i\`), \`head\`, \`tail\` (not \`-f\`), \`nl\` or \`awk\` on a literal path (resolved after the command's own \`cd\`s; \`rg\`, \`grep\`, \`find\`, \`ls\`, \`wc\`, \`stat\` are searches, not reads, and never fire it). \`document-read\` \u2014 another document whose name matches is delivered at content, including an explicit read. \`command\` \u2014 a shell segment of a bash command matches (segments split on \`&&\`, \`||\`, \`;\`, \`|\` and newlines outside quotes, leading \`VAR=value\` dropped; \`*\` spans whole whitespace-separated tokens, \`?\` one character, quoted text is opaque). \`pre-command\` \u2014 as \`command\`, but runs before the command: when the node has not read the document, the command does not run and the document is returned instead; the node re-issues the command. \`slash-command\` \u2014 the document is a \`/<name>\` slash command whose body is the injected prompt. \`match\` is required on \`file-read\` (unless \`match_frontmatter\` is given), \`document-read\`, \`command\` and \`pre-command\`, and not allowed on \`boot\`, \`workspace-open\` and \`slash-command\`. `+x+` \`deliver\` is ${v.join(" | ")}: the bare name, the preview line, or the whole body. When several rules deliver one document to a node, the highest wins, and content already in the node's context is not delivered again. A content delivery is a read: the node becomes a watcher and is pushed later edits. The profile's delivery limit per owner caps what \`boot\` and \`workspace-open\` rules deliver for that owner.`;function T(e){return{kind:"flag",name:"rule",type:"string",required:!1,repeatable:!0,constraint:`${e} ${A}`}}o(T,"ruleParam");const D="One line, shown wherever the document is listed or delivered without its body. For most readers it is all they see, so it alone decides whether the document is opened. Write it as \"When <situation in the reader's work>, read this because <what it prevents or what the reader gains>\". Name the situation in the words the reader's task will contain (the request, file, command or symptom), not the document's topic; when a neighbouring document covers a similar situation, say which one this is not for. A rule that delivers at `preview` requires this shape, and `crtr doc lint` checks it.",S={preview:o(e=>({kind:"flag",name:"preview",type:"string",required:!1,constraint:e}),"preview"),kind:{kind:"flag",name:"kind",type:"enum",choices:[...b],required:!1,constraint:"knowledge is consulted for facts or procedures; preference directs behavior. Default knowledge."},summary:{kind:"flag",name:"summary",type:"string",required:!1,constraint:"A very short version of the content, shown in `crtr canvas list`."},privacy:o(e=>({kind:"flag",name:"privacy",type:"enum",choices:[...k],required:!1,constraint:e}),"privacy"),whyItExists:{kind:"flag",name:"why-it-exists",type:"string",required:!1,constraint:"The observed failure this document exists to prevent; shown only with `crtr canvas read --fields`."},unlisted:o(e=>({kind:"flag",name:"unlisted",type:"bool",required:!1,constraint:e}),"unlisted"),lintIgnore:{kind:"flag",name:"lint-ignore",type:"string",required:!1,repeatable:!0,constraint:"A `crtr doc lint` rule name to skip for this document."},extension:{kind:"flag",name:"extension",type:"string",required:!1,repeatable:!0,constraint:"One declared plugin field as `<plugin>.<field>=<json value>`."}};function c(e){return e===void 0?[]:Array.isArray(e)?e.map(String):[String(e)]}o(c,"list");function I(e){const t=[],n={};for(const[r,a]of[["preview","preview"],["kind","kind"],["summary","summary"],["privacy","privacy"],["whyItExists","why_it_exists"]])typeof e[r]=="string"&&(n[a]=e[r]);typeof n.preview=="string"&&/[\r\n]/.test(n.preview)&&t.push("--preview must be one line"),e.unlisted===!0&&(n.unlisted=!0);const i=c(e.lintIgnore);i.length>0&&(n.lint_ignore=i);const s=c(e.rule);if(s.length>0){const r=[];s.forEach((a,u)=>{try{const d=JSON.parse(a);typeof d!="object"||d===null||Array.isArray(d)?t.push(`--rule #${u+1} must be a JSON object`):r.push(d)}catch{t.push(`--rule #${u+1} is not valid JSON: ${a}`)}}),n.rules=r}const h={};for(const r of c(e.extension)){const a=/^([^.=]+)\.([^=]+)=(.*)$/s.exec(r);if(!a){t.push(`--extension ${r} is not <plugin>.<field>=<json value>`);continue}try{(h[a[1]]??={})[a[2]]=JSON.parse(a[3])}catch{t.push(`--extension ${r}: the value after = is not valid JSON`)}}if(Object.keys(h).length>0&&(n.extensions=h),t.length>0)throw m(t.join("; "),{next:"Fix every value above and rerun; `-h` on this leaf gives the rule grammar."});return n}o(I,"fieldsFromInput");function L(e){const t=e.owner;if(t===void 0)return{};const n=String(t);if(!/^(node|user|profile|app|repo)$|^(profile|repo):.+$/.test(n))throw m(`invalid --owner ${n}`,{field:"owner",next:`Pass one of ${p}.`});return{owner:n}}o(L,"ownerFromInput");function C(e,t){e instanceof y&&(e.code==="read_first"&&l(e,`Read it first with \`crtr canvas read ${t}\`, then rerun the edit.`),e.code==="stale_revision"&&l(e,`Someone edited it after your read. Read it again with \`crtr canvas read ${t}\`, make your change on the current text, and rerun the edit.`)),l(e)}o(C,"rethrowDocError");const f="Give it a --rule with `crtr doc edit`, link it from a document that loads, or accept it with `--lint-ignore unreached`.",U=`Present and true when the document is owned by someone other than a node, has no rule, and no document with a rule links to it: no agent will be routed to it. ${f}`;function F(e){const t=[];e.unreached===!0&&t.push(`Unreached: this document has no rule and no document with a rule links to it, so no agent will be routed to it. ${f}`);const n=e.unresolved_links,i=e.remote_links;return n?.length&&t.push(`Unresolved links (no document by these names yet): ${n.map(s=>`[[${s}]]`).join(", ")}`),i?.length&&t.push(`Not on this runtime: ${i.map(s=>`[[${s}]]`).join(", ")} \u2014 each may be on another runtime, or the name may be misspelled.`),t.map(s=>`
2
+ ${s}`).join("")}o(F,"renderLinkReport");export{S as FIELD_FLAGS,p as OWNER_VALUES,D as PREVIEW_TEXT,j as REF_CONSTRAINT,U as UNREACHED_CONSTRAINT,I as fieldsFromInput,L as ownerFromInput,O as ownerParam,F as renderLinkReport,C as rethrowDocError,T as ruleParam};
@@ -1 +1 @@
1
- var o=Object.defineProperty;var i=(e,n)=>o(e,"name",{value:n,configurable:!0});import{defineLeaf as a}from"../../core/command.js";import{cliClient as s,rethrowAsCliError as d}from"../api-client.js";import{FIELD_FLAGS as t,fieldsFromInput as l,ownerFromInput as u,ownerParam as m,renderLinkReport as c,ruleParam as h}from"./shared.js";const b=a({name:"write",description:"write a new document from a stdin body",whenToUse:"a spec, plan, map, finding, knowledge or preference should exist as a document other nodes can read; creation only \u2014 revise an existing one with `crtr doc edit`",help:{name:"doc write",summary:"write a new document from a stdin body",guide:"Most documents need only a name, a preview and a body: the writing node owns it, it has no delivery rules, and other nodes read it when pointed at it as `[[<name printed below>]]`, and each `[[link]]` in its body attaches that document's preview wherever this one is delivered in full. Give --owner or --rule only when the document must outlive this node or load on its own; each has focused help. Read, list and search documents with `crtr canvas read|list|search`.",params:[{kind:"positional",name:"name",required:!0,constraint:"Name under its owner: segments of letters, digits, `_` and `-`, joined by `/`. Must be free under that owner."},{kind:"stdin",name:"body",required:!0,constraint:"Document body (markdown), piped on stdin and saved byte for byte. Pipe it straight in with a quoted heredoc (`<<'EOF'`); an unquoted one lets the shell expand `$` and backticks in the text before it is saved."},{...t.preview("One line shown wherever the document is listed or delivered without its body, telling a reader whether to open it."),required:!0},t.kind,t.summary,t.privacy("`public` (default) or `private`: a private document is kept from apps without a private-read scope; the owner and anyone it is shared with still read it. A repo-owned document must be public."),m("Whose document it is; default the writing node."),h("A delivery rule that loads the document into nodes by their activity."),t.whyItExists,t.unlisted("Keep it out of listings; reads, links and rules still work."),t.lintIgnore,t.extension],output:[{name:"name",type:"string",required:!0,constraint:"Full name, `<owner-handle>/<name>`; point at it as `[[name]]`."},{name:"id",type:"string",required:!0,constraint:"Object id."},{name:"unresolved_links",type:"string[]",required:!1,constraint:"`[[links]]` in the body that name no document yet; absent when every link resolves."},{name:"remote_links",type:"string[]",required:!1,constraint:"`[[links]]` whose first segment is no owner on this runtime: on another runtime, or misspelled."}],outputKind:"object",effects:["Creates the document at revision 1 and makes the writer a watcher, so it is pushed later edits."]},run:i(async e=>{const n={name:e.name,body:e.body,...l(e),...u(e),cwd:process.cwd()};try{return{...await s().docs.write(n)}}catch(r){d(r)}},"run"),render:i(e=>`<written name="${String(e.name)}" id="${String(e.id)}">${c(e)}`,"render")});export{b as writeLeaf};
1
+ var a=Object.defineProperty;var r=(e,n)=>a(e,"name",{value:n,configurable:!0});import{defineLeaf as o}from"../../core/command.js";import{cliClient as s,rethrowAsCliError as d}from"../api-client.js";import{FIELD_FLAGS as t,PREVIEW_TEXT as u,UNREACHED_CONSTRAINT as m,fieldsFromInput as l,ownerFromInput as c,ownerParam as h,renderLinkReport as w,ruleParam as p}from"./shared.js";const k=o({name:"write",description:"write a new document from a stdin body",whenToUse:"a spec, plan, map, finding, knowledge or preference should exist as a document other nodes can read; creation only \u2014 revise an existing one with `crtr doc edit`",help:{name:"doc write",summary:"write a new document from a stdin body",guide:"A document for this node's own work (a spec, plan or finding) needs only a name, a preview and a body: the writing node owns it, it has no rules, and other nodes read it when pointed at it as `[[<name printed below>]]`. Each `[[link]]` in a body attaches that document's preview wherever this one is delivered in full. A document that must outlive this node takes --owner (it has focused help) and nearly always a --rule, since a rule is how it reaches the next agent. Read, list and search documents with `crtr canvas read|list|search`.",params:[{kind:"positional",name:"name",required:!0,constraint:"Name under its owner: segments of letters, digits, `_` and `-`, joined by `/`. Must be free under that owner."},{kind:"stdin",name:"body",required:!0,constraint:"Document body (markdown), piped on stdin and saved byte for byte. Pipe it straight in with a quoted heredoc (`<<'EOF'`); an unquoted one lets the shell expand `$` and backticks in the text before it is saved."},{...t.preview(u),required:!0},t.kind,t.summary,t.privacy("`public` (default) or `private`: a private document is kept from apps without a private-read scope; the owner and anyone it is shared with still read it. A repo-owned document must be public."),h("Whose document it is; default the writing node."),p("A delivery rule that loads the document into nodes by their activity."),t.whyItExists,t.unlisted("Keep it out of listings; reads, links and rules still work."),t.lintIgnore,t.extension],output:[{name:"name",type:"string",required:!0,constraint:"Full name, `<owner-handle>/<name>`; point at it as `[[name]]`."},{name:"id",type:"string",required:!0,constraint:"Object id."},{name:"unresolved_links",type:"string[]",required:!1,constraint:"`[[links]]` in the body that name no document yet; absent when every link resolves."},{name:"remote_links",type:"string[]",required:!1,constraint:"`[[links]]` whose first segment is no owner on this runtime: on another runtime, or misspelled."},{name:"unreached",type:"bool",required:!1,constraint:m}],outputKind:"object",effects:["Creates the document at revision 1 and makes the writer a watcher, so it is pushed later edits."]},run:r(async e=>{const n={name:e.name,body:e.body,...l(e),...c(e),cwd:process.cwd()};try{return{...await s().docs.write(n)}}catch(i){d(i)}},"run"),render:r(e=>`<written name="${String(e.name)}" id="${String(e.id)}">${w(e)}`,"render")});export{k as writeLeaf};
@@ -1,5 +1,6 @@
1
1
  import type { RunEvent } from '../../api/dto/run-events.js';
2
2
  import type { BlobStore } from '../blobs/index.js';
3
+ export declare const BODY_TYPES: string[];
3
4
  /** One fixed 128-sequence range of a run's archived events and the immutable objects that hold it. Passes that archive
4
5
  * different rows of one range write different objects; the range's events are their union. */
5
6
  export interface RunEventChunk {
@@ -12,6 +13,11 @@ export declare function listRunEventChunks(store: BlobStore, runId: string): Pro
12
13
  /** Read a range's events, each sequence once, ordered by sequence. An event body never changes after it is written,
13
14
  * so a sequence held by more than one object (a retried or concurrent pass) has the same body in each. A missing object is an error. */
14
15
  export declare function readRunEventChunk(store: BlobStore, chunk: RunEventChunk): Promise<RunEvent[]>;
16
+ /** The `ts` before which a run event is archived: body types at the first, every type at the second (the archiver's rule, and import verify's for rows it no longer finds). */
17
+ export declare function archiveCutoffs(now: number): {
18
+ bodyCutoff: string;
19
+ controlCutoff: string;
20
+ };
15
21
  /**
16
22
  * Archive the same 14-day payload/30-day control events formerly deleted by expireRunEvents.
17
23
  * No transaction, connection or lock is held across compression or blob I/O: the rows are read, each range's
@@ -1,5 +1,5 @@
1
- var g=Object.defineProperty;var u=(e,s)=>g(e,"name",{value:s,configurable:!0});import{createHash as v}from"node:crypto";import{promisify as w}from"node:util";import{zstdCompress as k,zstdDecompress as S}from"node:zlib";import{openDb as $,withCanvasWrite as x}from"../canvas/db.js";const D=w(k),N=w(S),l=128,R=16,_=["node.tool_call.completed","node.tool_call.started","node.system_prompt.set","node.thinking.done","node.output_text.done"],h=u(e=>`events/${e}/`,"prefix"),b=u(e=>String(e).padStart(R,"0"),"pad"),I=u(e=>{const s=Math.floor((e-1)/l)*l+1;return{first:s,last:s+l-1}},"range"),q=u((e,s,n,t)=>`${h(e)}${b(s)}-${b(n)}-${t}.jsonl.zst`,"chunkKey");async function z(e,s){const n=new Map;for(const t of await e.list(h(s))){const o=/\/(\d{16})-(\d{16})-[0-9a-f]{32}\.jsonl\.zst$/.exec(t);if(!o)throw new Error(`not a run-event chunk key: ${t}`);const c=Number(o[1]),a=n.get(c);a?a.keys.push(t):n.set(c,{first:c,last:Number(o[2]),keys:[t]})}return[...n.values()].sort((t,o)=>t.first-o.first)}u(z,"listRunEventChunks");async function H(e,s){const n=new Map;for(const t of s.keys){const o=await e.get(t);if(o===null)throw new Error(`run-event chunk missing: ${t}`);const c=(await N(o)).toString("utf8");for(const a of c===""?[]:c.split(`
2
- `)){const i=JSON.parse(a);n.has(i.sequence_number)||n.set(i.sequence_number,i)}}return[...n.values()].sort((t,o)=>t.sequence_number-o.sequence_number)}u(H,"readRunEventChunk");async function A(e,s,n=128){if(!Number.isSafeInteger(n)||n<0)throw new TypeError("limit must be a nonnegative safe integer");if(n===0)return 0;const t=new Date(s-336*60*6e4).toISOString(),o=new Date(s-720*60*6e4).toISOString(),c=_.map(()=>"?").join(", "),a=await(await $()).prepare(`SELECT run_id, sequence_number, body_json FROM run_events
3
- WHERE ts < ? AND (ts < ? OR type IN (${c})) ORDER BY ts LIMIT ?`).all(t,o,..._,n),i=new Map;for(const r of a){const{first:p,last:d}=I(Number(r.sequence_number)),f=`${r.run_id}
4
- ${p}`,m=i.get(f);m?m.rows.push(r):i.set(f,{runId:r.run_id,first:p,last:d,rows:[r]})}for(const{runId:r,first:p,last:d,rows:f}of i.values()){const m=f.map(E=>E.body_json).join(`
5
- `),y=v("sha256").update(m).digest("hex").slice(0,32);await e.put(q(r,p,d,y),await D(Buffer.from(m,"utf8")))}return await x(async r=>{const p=r.prepare("DELETE FROM run_events WHERE run_id = ? AND sequence_number = ?");let d=0;for(const f of a)d+=Number((await p.run(f.run_id,f.sequence_number)).changes);return d})}u(A,"archiveExpiredRunEvents");export{A as archiveExpiredRunEvents,z as listRunEventChunks,H as readRunEventChunk};
1
+ var g=Object.defineProperty;var i=(e,s)=>g(e,"name",{value:s,configurable:!0});import{createHash as v}from"node:crypto";import{promisify as _}from"node:util";import{zstdCompress as k,zstdDecompress as x}from"node:zlib";import{openDb as N,withCanvasWrite as S}from"../canvas/db.js";const C=_(k),$=_(x),l=128,q=16,w=["node.tool_call.completed","node.tool_call.started","node.system_prompt.set","node.thinking.done","node.output_text.done"],h=i(e=>`events/${e}/`,"prefix"),b=i(e=>String(e).padStart(q,"0"),"pad"),D=i(e=>{const s=Math.floor((e-1)/l)*l+1;return{first:s,last:s+l-1}},"range"),R=i((e,s,n,t)=>`${h(e)}${b(s)}-${b(n)}-${t}.jsonl.zst`,"chunkKey");async function H(e,s){const n=new Map;for(const t of await e.list(h(s))){const o=/\/(\d{16})-(\d{16})-[0-9a-f]{32}\.jsonl\.zst$/.exec(t);if(!o)throw new Error(`not a run-event chunk key: ${t}`);const a=Number(o[1]),f=n.get(a);f?f.keys.push(t):n.set(a,{first:a,last:Number(o[2]),keys:[t]})}return[...n.values()].sort((t,o)=>t.first-o.first)}i(H,"listRunEventChunks");async function A(e,s){const n=new Map;for(const t of s.keys){const o=await e.get(t);if(o===null)throw new Error(`run-event chunk missing: ${t}`);const a=(await $(o)).toString("utf8");for(const f of a===""?[]:a.split(`
2
+ `)){const p=JSON.parse(f);n.has(p.sequence_number)||n.set(p.sequence_number,p)}}return[...n.values()].sort((t,o)=>t.sequence_number-o.sequence_number)}i(A,"readRunEventChunk");function I(e){return{bodyCutoff:new Date(e-336*60*6e4).toISOString(),controlCutoff:new Date(e-720*60*6e4).toISOString()}}i(I,"archiveCutoffs");async function B(e,s,n=128){if(!Number.isSafeInteger(n)||n<0)throw new TypeError("limit must be a nonnegative safe integer");if(n===0)return 0;const{bodyCutoff:t,controlCutoff:o}=I(s),a=w.map(()=>"?").join(", "),f=await(await N()).prepare(`SELECT run_id, sequence_number, body_json FROM run_events
3
+ WHERE ts < ? AND (ts < ? OR type IN (${a})) ORDER BY ts LIMIT ?`).all(t,o,...w,n),p=new Map;for(const u of f){const{first:d,last:m}=D(Number(u.sequence_number)),r=`${u.run_id}
4
+ ${d}`,c=p.get(r);c?c.rows.push(u):p.set(r,{runId:u.run_id,first:d,last:m,rows:[u]})}for(const{runId:u,first:d,last:m,rows:r}of p.values()){const c=r.map(E=>E.body_json).join(`
5
+ `),y=v("sha256").update(c).digest("hex").slice(0,32);await e.put(R(u,d,m,y),await C(Buffer.from(c,"utf8")))}return await S(async u=>{const d=u.prepare("DELETE FROM run_events WHERE run_id = ? AND sequence_number = ?");let m=0;f.sort((r,c)=>r.run_id<c.run_id?-1:r.run_id>c.run_id?1:Number(r.sequence_number)-Number(c.sequence_number));for(const r of f)m+=Number((await d.run(r.run_id,r.sequence_number)).changes);return m})}i(B,"archiveExpiredRunEvents");export{w as BODY_TYPES,I as archiveCutoffs,B as archiveExpiredRunEvents,H as listRunEventChunks,A as readRunEventChunk};
@@ -13,9 +13,11 @@ export interface UniqueKey {
13
13
  }
14
14
  /** The columns that identify a row of `info`: its primary key, or every column in order for a table with none (`memory_reads`). */
15
15
  export declare const rowKey: (info: TableInfo) => string[];
16
+ /** `types` maps a column to its type name (`udt_name`), so a manifest key (the row key's columns as text) can be cast back and compared through the column's index. */
16
17
  export interface TableInfo {
17
18
  name: string;
18
19
  columns: string[];
20
+ types: Record<string, string>;
19
21
  primaryKey: string[];
20
22
  identity: string[];
21
23
  }
@@ -26,6 +28,9 @@ export interface Catalog {
26
28
  uniqueKeys: UniqueKey[];
27
29
  }
28
30
  export declare const q: (name: string) => string;
31
+ /** True when `alias`'s `columns` equal the manifest key held in `keyColumn` (a jsonb array of the key's columns as text, `m.k`). Each column is compared as itself against the key's
32
+ * element cast to the column's type, so the table's index on the key serves the join; building the key from the table's rows instead would defeat every index. */
33
+ export declare const keyMatch: (info: TableInfo, columns: readonly string[], alias: string, keyColumn: string) => string;
29
34
  /** Read the catalog of `schema` for `tables`. */
30
35
  export declare function readCatalog(db: CanvasDb, schema: string, tables: readonly string[]): Promise<Catalog>;
31
36
  /** Parents before children. Cycles (none in the schema today) are broken by the table list's order. */
@@ -1,9 +1,9 @@
1
- var g=Object.defineProperty;var r=(a,n)=>g(a,"name",{value:n,configurable:!0});const x=r(a=>a.primaryKey.length>0?a.primaryKey:a.columns,"rowKey"),y=r(a=>`"${a.replace(/"/g,'""')}"`,"q");async function O(a,n,p){const i=[...p],d=await a.prepareUncached(`SELECT table_name, column_name, is_identity FROM information_schema.columns
2
- WHERE table_schema = ? AND table_name = ANY(?::text[]) ORDER BY table_name, ordinal_position`).all(n,`{${i.map(e=>`"${e}"`).join(",")}}`),o=new Map;for(const e of i)o.set(e,{name:e,columns:[],primaryKey:[],identity:[]});for(const e of d){const s=o.get(e.table_name);s.columns.push(e.column_name),e.is_identity==="YES"&&s.identity.push(e.column_name)}const l=await a.prepareUncached(`SELECT c.conrelid::regclass::text AS tbl, c.contype, c.conname,
1
+ var g=Object.defineProperty;var r=(n,a)=>g(n,"name",{value:a,configurable:!0});const _=r(n=>n.primaryKey.length>0?n.primaryKey:n.columns,"rowKey"),u=r(n=>`"${n.replace(/"/g,'""')}"`,"q"),f=r((n,a,l,c)=>a.map((s,o)=>`${l}.${u(s)} = (${c} ->> ${o})::${u(n.types[s])}`).join(" AND "),"keyMatch");async function N(n,a,l){const c=[...l],s=await n.prepareUncached(`SELECT table_name, column_name, is_identity, udt_name FROM information_schema.columns
2
+ WHERE table_schema = ? AND table_name = ANY(?::text[]) ORDER BY table_name, ordinal_position`).all(a,`{${c.map(e=>`"${e}"`).join(",")}}`),o=new Map;for(const e of c)o.set(e,{name:e,columns:[],types:{},primaryKey:[],identity:[]});for(const e of s){const i=o.get(e.table_name);i.columns.push(e.column_name),i.types[e.column_name]=e.udt_name,e.is_identity==="YES"&&i.identity.push(e.column_name)}const d=await n.prepareUncached(`SELECT c.conrelid::regclass::text AS tbl, c.contype, c.conname,
3
3
  (SELECT array_agg(a.attname::text ORDER BY k.ord) FROM unnest(c.conkey) WITH ORDINALITY k(attnum, ord) JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum) AS cols,
4
4
  c.confrelid::regclass::text AS ptbl,
5
5
  (SELECT array_agg(a.attname::text ORDER BY k.ord) FROM unnest(c.confkey) WITH ORDINALITY k(attnum, ord) JOIN pg_attribute a ON a.attrelid = c.confrelid AND a.attnum = k.attnum) AS pcols
6
- FROM pg_constraint c WHERE c.connamespace = ?::regnamespace AND c.contype IN ('p', 'f')`).all(n),c=r(e=>e.replace(/^.*\./,"").replace(/"/g,""),"bare"),t=[];for(const e of l){const s=c(e.tbl);o.has(s)&&(e.contype==="p"?o.get(s).primaryKey=e.cols:o.has(c(e.ptbl))&&t.push({table:s,columns:e.cols,parent:c(e.ptbl),parentColumns:e.pcols}))}const u=(await a.prepareUncached(`SELECT t.relname AS tbl, i.relname AS name, pg_get_expr(x.indpred, x.indrelid) AS predicate, x.indexprs IS NOT NULL AS has_expr,
6
+ FROM pg_constraint c WHERE c.connamespace = ?::regnamespace AND c.contype IN ('p', 'f')`).all(a),p=r(e=>e.replace(/^.*\./,"").replace(/"/g,""),"bare"),t=[];for(const e of d){const i=p(e.tbl);o.has(i)&&(e.contype==="p"?o.get(i).primaryKey=e.cols:o.has(p(e.ptbl))&&t.push({table:i,columns:e.cols,parent:p(e.ptbl),parentColumns:e.pcols}))}const y=(await n.prepareUncached(`SELECT t.relname AS tbl, i.relname AS name, pg_get_expr(x.indpred, x.indrelid) AS predicate, x.indexprs IS NOT NULL AS has_expr,
7
7
  (SELECT array_agg(a.attname::text ORDER BY k.ord) FROM unnest(x.indkey::int2[]) WITH ORDINALITY k(attnum, ord) JOIN pg_attribute a ON a.attrelid = x.indrelid AND a.attnum = k.attnum) AS cols
8
8
  FROM pg_index x JOIN pg_class t ON t.oid = x.indrelid JOIN pg_class i ON i.oid = x.indexrelid
9
- WHERE t.relnamespace = ?::regnamespace AND x.indisunique AND NOT x.indisprimary`).all(n)).filter(e=>o.has(e.tbl)&&!e.has_expr).map(e=>({table:e.tbl,name:e.name,columns:e.cols,predicate:e.predicate}));return{schema:n,tables:o,foreignKeys:t,uniqueKeys:u}}r(O,"readCatalog");function _(a,n){const p=new Set(n),i=new Map(n.map(t=>[t,new Set]));for(const t of a.foreignKeys)p.has(t.table)&&p.has(t.parent)&&t.table!==t.parent&&i.get(t.table).add(t.parent);const d=[],o=new Set,l=new Set,c=r(t=>{if(!(o.has(t)||l.has(t))){l.add(t);for(const m of[...i.get(t)].sort())c(m);l.delete(t),o.add(t),d.push(t)}},"visit");for(const t of n)c(t);return d}r(_,"topologicalOrder");export{y as q,O as readCatalog,x as rowKey,_ as topologicalOrder};
9
+ WHERE t.relnamespace = ?::regnamespace AND x.indisunique AND NOT x.indisprimary`).all(a)).filter(e=>o.has(e.tbl)&&!e.has_expr).map(e=>({table:e.tbl,name:e.name,columns:e.cols,predicate:e.predicate}));return{schema:a,tables:o,foreignKeys:t,uniqueKeys:y}}r(N,"readCatalog");function O(n,a){const l=new Set(a),c=new Map(a.map(t=>[t,new Set]));for(const t of n.foreignKeys)l.has(t.table)&&l.has(t.parent)&&t.table!==t.parent&&c.get(t.table).add(t.parent);const s=[],o=new Set,d=new Set,p=r(t=>{if(!(o.has(t)||d.has(t))){d.add(t);for(const m of[...c.get(t)].sort())p(m);d.delete(t),o.add(t),s.push(t)}},"visit");for(const t of a)p(t);return s}r(O,"topologicalOrder");export{f as keyMatch,u as q,N as readCatalog,_ as rowKey,O as topologicalOrder};
@@ -1,6 +1,6 @@
1
- var y=Object.defineProperty;var m=(n,l)=>y(n,"name",{value:l,configurable:!0});import{openDb as C,withCanvasWrite as D}from"../../canvas/db.js";import{bundleKeys as A}from"../bundle/layout.js";import{q as r,readCatalog as $,rowKey as T,topologicalOrder as h}from"./catalog.js";import{decodeKeys as M}from"./copy.js";import{OBJECT_ID_COLUMNS as W}from"./rewrite.js";import{targetSchema as g}from"./stage.js";class O extends Error{static{m(this,"Refused")}}async function B(n,l){const _=await C(),c=await _.prepare("SELECT source_install_id, source_kind, state, created_at FROM import_runs WHERE run_id = ?").get(n);if(c===void 0)throw new Error(`no import run ${n}`);if(c.state!=="done"&&c.state!=="committed"&&c.state!=="failed")throw new Error(`import run ${n} is ${c.state}, not rollbackable`);const N=(await _.prepare("SELECT blob_key FROM import_node_files WHERE blob_key LIKE ?").all(`imports/${n}/node-files/%`)).map(t=>t.blob_key),E={run_id:n,rolled_back:!1,dependents:{},deleted:{}};try{await D(async t=>{const i=await g(t),L=(await t.prepareUncached("SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND table_type = 'BASE TABLE'").all(i)).map(e=>e.table_name),d=await $(t,i,L);d.tables.get("env_vars").primaryKey=["person","owner_kind","owner_id","name"],await t.exec("CREATE TEMP TABLE _rb (tbl text NOT NULL, k jsonb NOT NULL) ON COMMIT DROP");const R=await t.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ?").all(n);for(const{table_name:e,inserted_keys:o}of R){const a=M(o);for(let s=0;s<a.length;s+=5e3)await t.prepare("INSERT INTO _rb SELECT ?, e FROM jsonb_array_elements(?::jsonb) e").run(e,JSON.stringify(a.slice(s,s+5e3)))}const b=new Set(R.map(e=>e.table_name)),u=m((e,o,a)=>`jsonb_build_array(${o.map(s=>`${a}.${r(s)}::text`).join(", ")})`,"keyOf");for(const e of d.foreignKeys){const o=d.tables.get(e.parent),a=d.tables.get(e.table);if(e.table==="import_node_files"||!b.has(e.parent)||o===void 0||a===void 0||e.parentColumns.join()!==o.primaryKey.join())continue;const s=b.has(e.table)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e.table}' AND o.k = ${u(e.table,T(a),"c")})`:"",p=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${r(i)}.${r(e.table)} c WHERE ${e.columns.map(k=>`c.${r(k)} IS NOT NULL`).join(" AND ")}
2
- AND ${u(e.parent,e.columns,"c")} IN (SELECT k FROM _rb WHERE tbl = '${e.parent}') ${s}`).get()).n);p>0&&(E.dependents[e.table]=(E.dependents[e.table]??0)+p)}for(const[e,o]of W){const a=d.tables.get(e);if(a===void 0||!a.columns.includes(o)||a.primaryKey.length===0)continue;const s=b.has(e)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e}' AND o.k = ${u(e,a.primaryKey,"c")})`:"",p=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${r(i)}.${r(e)} c WHERE c.${r(o)} IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects') ${s}`).get()).n);p>0&&(E.dependents[`${e}.${o}`]=p)}const f=Number((await t.prepare("SELECT count(*) AS n FROM import_runs WHERE source_install_id = ? AND run_id <> ? AND created_at > ? AND (state IN ('loading', 'committed', 'done') OR (state = 'failed' AND committed_at IS NOT NULL))").get(c.source_install_id,n,c.created_at)).n);f>0&&(E.dependents.import_runs=f);const S=Number((await t.prepare("SELECT count(*) AS n FROM import_id_map m WHERE m.run_id <> ? AND m.kind = 'object' AND m.target_value IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects')").get(n)).n);if(S>0&&(E.dependents.import_id_map=S),Object.keys(E.dependents).length>0)throw new O;const w=(await t.prepareUncached(`SELECT DISTINCT r.document FROM ${r(i)}.revisions r WHERE jsonb_build_array(r.rev_id) IN (SELECT k FROM _rb WHERE tbl = 'revisions')
3
- AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = 'objects' AND o.k = jsonb_build_array(r.document))`).all()).map(e=>e.document);for(const e of h(d,[...b]).reverse()){const o=d.tables.get(e);if(o===void 0)continue;const a=await t.prepareUncached(`DELETE FROM ${r(i)}.${r(e)} t WHERE ${u(e,T(o),"t")} IN (SELECT k FROM _rb WHERE tbl = '${e}')`).run();E.deleted[e]=a.changes}for(const e of w)await t.prepareUncached(`UPDATE ${r(i)}.documents d SET
4
- heads_key = COALESCE((SELECT string_agg(r.rev_id, ',' ORDER BY r.rev_id) FROM ${r(i)}.revisions r WHERE r.document = d.object AND NOT EXISTS (SELECT 1 FROM ${r(i)}.revision_parents p WHERE p.parent = r.rev_id)), ''),
5
- revision = COALESCE((SELECT max(r.number) FROM ${r(i)}.revisions r WHERE r.document = d.object AND NOT EXISTS (SELECT 1 FROM ${r(i)}.revision_parents p WHERE p.parent = r.rev_id)), 0)
6
- WHERE d.object = ?`).run(e);await t.prepareUncached("DELETE FROM import_key_map km WHERE km.source_install_id = ? AND EXISTS (SELECT 1 FROM _rb r WHERE r.tbl = km.table_name AND r.k = jsonb_build_array(km.target_key))").run(c.source_install_id),await t.prepare("DELETE FROM import_id_map WHERE run_id = ?").run(n),await t.prepare("DELETE FROM import_manifest WHERE run_id = ?").run(n),await t.prepare("UPDATE import_runs SET state = 'rolled_back', step = 'rolled_back', finished_at = ? WHERE run_id = ?").run(new Date().toISOString(),n),await F(t,c)})}catch(t){if(t instanceof O)return E;throw t}await l.delete(A.manifest(n));for(const t of N)await l.delete(t);return E.rolled_back=!0,E}m(B,"rollbackRun");async function F(n,l){if(l.source_kind!=="machine")return;const _=await n.prepare("SELECT object FROM environments WHERE machine_id = ? AND kind = 'machine'").get(l.source_install_id);_!==void 0&&await n.prepare("UPDATE machine_credentials SET revoked_at = ? WHERE environment = ? AND revoked_at IS NULL").run(new Date().toISOString(),_.object)}m(F,"revokeFor");export{B as rollbackRun};
1
+ var A=Object.defineProperty;var R=(n,d)=>A(n,"name",{value:d,configurable:!0});import{openDb as C,withCanvasWrite as D}from"../../canvas/db.js";import{bundleKeys as h}from"../bundle/layout.js";import{keyMatch as m,q as a,readCatalog as M,rowKey as u,topologicalOrder as y}from"./catalog.js";import{decodeKeys as F}from"./copy.js";import{OBJECT_ID_COLUMNS as W}from"./rewrite.js";import{targetSchema as $}from"./stage.js";class O extends Error{static{R(this,"Refused")}}async function B(n,d){const _=await C(),s=await _.prepare("SELECT source_install_id, source_kind, state, created_at FROM import_runs WHERE run_id = ?").get(n);if(s===void 0)throw new Error(`no import run ${n}`);if(s.state!=="done"&&s.state!=="committed"&&s.state!=="failed")throw new Error(`import run ${n} is ${s.state}, not rollbackable`);const N=(await _.prepare("SELECT blob_key FROM import_node_files WHERE blob_key LIKE ?").all(`imports/${n}/node-files/%`)).map(t=>t.blob_key),E={run_id:n,rolled_back:!1,dependents:{},deleted:{}};try{await D(async t=>{const i=await $(t),L=(await t.prepareUncached("SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND table_type = 'BASE TABLE'").all(i)).map(e=>e.table_name),l=await M(t,i,L);l.tables.get("env_vars").primaryKey=["person","owner_kind","owner_id","name"],await t.exec("CREATE TEMP TABLE _rb (tbl text NOT NULL, k jsonb NOT NULL) ON COMMIT DROP");const S=await t.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ?").all(n);for(const{table_name:e,inserted_keys:o}of S){const r=F(o);for(let c=0;c<r.length;c+=5e3)await t.prepare("INSERT INTO _rb SELECT ?, e FROM jsonb_array_elements(?::jsonb) e").run(e,JSON.stringify(r.slice(c,c+5e3)))}const b=new Set(S.map(e=>e.table_name));await t.exec("ANALYZE _rb");for(const e of l.foreignKeys){const o=l.tables.get(e.parent),r=l.tables.get(e.table);if(e.table==="import_node_files"||!b.has(e.parent)||o===void 0||r===void 0||e.parentColumns.join()!==o.primaryKey.join())continue;const c=b.has(e.table)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e.table}' AND ${m(r,u(r),"c","o.k")})`:"",p=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${a(i)}.${a(e.table)} c WHERE ${e.columns.map(w=>`c.${a(w)} IS NOT NULL`).join(" AND ")}
2
+ AND EXISTS (SELECT 1 FROM _rb p WHERE p.tbl = '${e.parent}' AND ${m(r,e.columns,"c","p.k")}) ${c}`).get()).n);p>0&&(E.dependents[e.table]=(E.dependents[e.table]??0)+p)}for(const[e,o]of W){const r=l.tables.get(e);if(r===void 0||!r.columns.includes(o)||r.primaryKey.length===0)continue;const c=b.has(e)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e}' AND ${m(r,r.primaryKey,"c","o.k")})`:"",p=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${a(i)}.${a(e)} c WHERE c.${a(o)} IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects') ${c}`).get()).n);p>0&&(E.dependents[`${e}.${o}`]=p)}const T=Number((await t.prepare("SELECT count(*) AS n FROM import_runs WHERE source_install_id = ? AND run_id <> ? AND created_at > ? AND (state IN ('loading', 'committed', 'done') OR (state = 'failed' AND committed_at IS NOT NULL))").get(s.source_install_id,n,s.created_at)).n);T>0&&(E.dependents.import_runs=T);const f=Number((await t.prepare("SELECT count(*) AS n FROM import_id_map m WHERE m.run_id <> ? AND m.kind = 'object' AND m.target_value IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects')").get(n)).n);if(f>0&&(E.dependents.import_id_map=f),Object.keys(E.dependents).length>0)throw new O;const k=(await t.prepareUncached(`SELECT DISTINCT r.document FROM ${a(i)}.revisions r WHERE r.rev_id IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'revisions')
3
+ AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = 'objects' AND o.k ->> 0 = r.document)`).all()).map(e=>e.document);for(const e of y(l,[...b]).reverse()){const o=l.tables.get(e);if(o===void 0)continue;e==="run_events"&&await t.prepareUncached(`SELECT 1 FROM ${a(i)}.run_events t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = 'run_events' AND ${m(o,u(o),"t","k.k")}) ORDER BY t."run_id" COLLATE "C", t."sequence_number" FOR UPDATE`).all();const r=await t.prepareUncached(`DELETE FROM ${a(i)}.${a(e)} t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = '${e}' AND ${m(o,u(o),"t","k.k")})`).run();E.deleted[e]=r.changes}for(const e of k)await t.prepareUncached(`UPDATE ${a(i)}.documents d SET
4
+ heads_key = COALESCE((SELECT string_agg(r.rev_id, ',' ORDER BY r.rev_id) FROM ${a(i)}.revisions r WHERE r.document = d.object AND NOT EXISTS (SELECT 1 FROM ${a(i)}.revision_parents p WHERE p.parent = r.rev_id)), ''),
5
+ revision = COALESCE((SELECT max(r.number) FROM ${a(i)}.revisions r WHERE r.document = d.object AND NOT EXISTS (SELECT 1 FROM ${a(i)}.revision_parents p WHERE p.parent = r.rev_id)), 0)
6
+ WHERE d.object = ?`).run(e);await t.prepareUncached("DELETE FROM import_key_map km WHERE km.source_install_id = ? AND EXISTS (SELECT 1 FROM _rb r WHERE r.tbl = km.table_name AND r.k ->> 0 = km.target_key)").run(s.source_install_id),await t.prepare("DELETE FROM import_id_map WHERE run_id = ?").run(n),await t.prepare("DELETE FROM import_manifest WHERE run_id = ?").run(n),await t.prepare("UPDATE import_runs SET state = 'rolled_back', step = 'rolled_back', finished_at = ? WHERE run_id = ?").run(new Date().toISOString(),n),await H(t,s)})}catch(t){if(t instanceof O)return E;throw t}await d.delete(h.manifest(n));for(const t of N)await d.delete(t);return E.rolled_back=!0,E}R(B,"rollbackRun");async function H(n,d){if(d.source_kind!=="machine")return;const _=await n.prepare("SELECT object FROM environments WHERE machine_id = ? AND kind = 'machine'").get(d.source_install_id);_!==void 0&&await n.prepare("UPDATE machine_credentials SET revoked_at = ? WHERE environment = ? AND revoked_at IS NULL").run(new Date().toISOString(),_.object)}R(H,"revokeFor");export{B as rollbackRun};
@@ -1,12 +1,11 @@
1
- var g=Object.defineProperty;var c=(r,_)=>g(r,"name",{value:_,configurable:!0});import{KEY_MAPPED_TABLES as y}from"../bundle/layout.js";import{q as i,rowKey as M}from"./catalog.js";import{decodeKeys as F}from"./copy.js";const n=c((r,_)=>`${i(r)}.${i(_)}`,"sq"),U={messages:["seq"]},j=["claimed_by","lease_expires_at"];async function x(r,_,t,O,$,k){const N={},u=await r.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ?").all(_);await r.exec(`DROP TABLE IF EXISTS ${i(t)}._m; CREATE TABLE ${i(t)}._m (tbl text NOT NULL, k jsonb NOT NULL)`);for(const{table_name:e,inserted_keys:s}of u){const o=$.tables.get(e);if(o===void 0)continue;const E=F(s);if(E.length===0)continue;await r.prepare(`DELETE FROM ${i(t)}._m WHERE tbl = ?`).run(e);for(let a=0;a<E.length;a+=5e3)await r.prepare(`INSERT INTO ${i(t)}._m SELECT ?, e FROM jsonb_array_elements(?::jsonb) e`).run(e,JSON.stringify(E.slice(a,a+5e3)));const A=[...o.identity,...U[e]??[],...j].map(a=>`'${a.replace(/'/g,"''")}'`).join(", ")||"''",m=c(a=>`to_jsonb(${a}) - ARRAY[${A}]::text[]`,"strip"),p=M(o),D=c(a=>`jsonb_build_array(${p.map(l=>`${a}.${i(l)}::text`).join(", ")})`,"targetKey");let L;if(e in y){const a=y[e];L=`JOIN import_key_map km ON km.source_install_id = '${k.replace(/'/g,"''")}' AND km.table_name = '${e}' AND jsonb_build_array(km.target_key) = m.k
2
- JOIN ${n(t,e)} s ON s.${i(a)}::text = km.source_key`}else L=`JOIN ${n(t,e)} s ON ${p.map((a,l)=>`s.${i(a)}::text = m.k ->> ${l}`).join(" AND ")}`;const h=e==="revisions"?` AND m.k ->> 0 NOT IN (SELECT rev_id FROM ${n(t,"_arr_revisions")})`:e==="revision_parents"?` AND NOT EXISTS (SELECT 1 FROM ${n(t,"_arr_parents")} a WHERE a.child = m.k ->> 0 AND a.parent = m.k ->> 1)`:"",T=`FROM ${n(t,"_m")} m LEFT JOIN ${n(O,e)} t ON ${D("t")} = m.k ${L.replace("JOIN","LEFT JOIN")} WHERE m.tbl = '${e}'${h}
3
- AND (t.${i(p[0])} IS NULL OR s.${i(p[0])} IS NULL OR (${m("t")}) <> (${m("s")}))`,f=Number((await r.prepareUncached(`SELECT count(*) AS n ${T}`).get()).n);if(f>0){const a=await r.prepareUncached(`SELECT m.k::text AS k ${T} LIMIT 10`).all();N[e]={count:f,keys:a.map(l=>l.k)}}}for(const[e,s]of[["revisions",`FROM ${n(t,"_m")} m JOIN ${n(t,"_arr_revisions")} a ON a.rev_id = m.k ->> 0 LEFT JOIN revisions t ON t.rev_id = a.rev_id
4
- WHERE m.tbl = 'revisions' AND (t.rev_id IS NULL OR t.document <> a.document OR t.body_hash <> a.body_hash OR t.rationale IS DISTINCT FROM a.rationale OR t.created_at <> a.created_at)`],["revision_parents",`FROM ${n(t,"_m")} m JOIN ${n(t,"_arr_parents")} a ON a.child = m.k ->> 0 AND a.parent = m.k ->> 1 LEFT JOIN revision_parents t ON t.child = a.child AND t.parent = a.parent
5
- WHERE m.tbl = 'revision_parents' AND t.child IS NULL`]]){const o=Number((await r.prepareUncached(`SELECT count(*) AS n ${s}`).get()).n);o>0&&(N[`${e}.arrived`]={count:o,keys:[]})}const d={},b=`SELECT source AS key FROM ${n(t,"_idmap")} WHERE kind = 'object'`,v=c(e=>e==="messages"?`(${b})`:`(${b} UNION SELECT key FROM ${n(t,"_dropped")} WHERE tbl = 'objects')`,"droppedFor");let S=!1;for(const{table_name:e}of u){const s=$.tables.get(e);if(s===void 0||S)continue;const o=await r.prepareUncached("SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND data_type = 'text'").all(O,e);for(const{column_name:E}of o){if(s.primaryKey.includes(E)&&e==="objects")continue;if(await r.prepareUncached(`SELECT 1 AS found FROM ${n(t,"_m")} m JOIN ${n(O,e)} t ON jsonb_build_array(${s.primaryKey.map(m=>`t.${i(m)}::text`).join(", ")}) = m.k
6
- WHERE m.tbl = ? AND t.${i(E)} IN ${v(e)} LIMIT 1`).get(e)!==void 0){S=!0,N[`${e}.${E}`]={count:1,keys:["holds a dropped object id"]};break}}}d.no_dropped_id=!S;const R=u.find(e=>e.table_name==="revisions");let I=!0;R!==void 0&&(I=await r.prepare(`SELECT 1 AS missing FROM ${n(t,"_m")} m JOIN revisions r ON r.rev_id = m.k ->> 0 WHERE m.tbl = 'revisions'
7
- AND NOT EXISTS (SELECT 1 FROM bodies b WHERE b.hash = r.body_hash) LIMIT 1`).get()===void 0),d.revision_bodies_readable=I,d.revision_bodies_canonical=R===void 0||await r.prepare(`SELECT 1 AS wrong FROM ${n(t,"_m")} m JOIN revisions r ON r.rev_id = m.k ->> 0 JOIN bodies b ON b.hash = r.body_hash
8
- WHERE m.tbl = 'revisions' AND encode(sha256(convert_to(b.text, 'UTF8')), 'hex') <> b.hash LIMIT 1`).get()===void 0;const C=await r.prepare(`SELECT 1 AS found FROM (
1
+ var J=Object.defineProperty;var l=(r,d)=>J(r,"name",{value:d,configurable:!0});import{KEY_MAPPED_TABLES as D}from"../bundle/layout.js";import{keyMatch as C,q as o,rowKey as j}from"./catalog.js";import{archiveCutoffs as H,BODY_TYPES as W}from"../../events/run-event-chunks.js";import{decodeKeys as x}from"./copy.js";const a=l((r,d)=>`${o(r)}.${o(d)}`,"sq"),B={messages:["seq"]},q=["claimed_by","lease_expires_at"];async function Z(r,d,t,O,$,h){const _={},m={},{bodyCutoff:g,controlCutoff:M}=H(Date.now()),p=await r.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ?").all(d);await r.exec(`DROP TABLE IF EXISTS ${o(t)}._m; CREATE TABLE ${o(t)}._m (tbl text NOT NULL, k jsonb NOT NULL)`);for(const{table_name:e,inserted_keys:i}of p){const s=$.tables.get(e);if(s===void 0)continue;const E=x(i);if(E.length===0)continue;await r.prepare(`DELETE FROM ${o(t)}._m WHERE tbl = ?`).run(e);for(let n=0;n<E.length;n+=5e3)await r.prepare(`INSERT INTO ${o(t)}._m SELECT ?, e FROM jsonb_array_elements(?::jsonb) e`).run(e,JSON.stringify(E.slice(n,n+5e3)));await r.exec(`ANALYZE ${o(t)}._m`);const R=[...s.identity,...B[e]??[],...q].map(n=>`'${n.replace(/'/g,"''")}'`).join(", ")||"''",T=l(n=>`to_jsonb(${n}) - ARRAY[${R}]::text[]`,"strip"),c=j(s);let S;if(e in D){const n=D[e];S=`JOIN import_key_map km ON km.source_install_id = '${h.replace(/'/g,"''")}' AND km.table_name = '${e}' AND km.target_key = m.k ->> 0
2
+ JOIN ${a(t,e)} s ON s.${o(n)}::text = km.source_key`}else S=`JOIN ${a(t,e)} s ON ${c.map((n,u)=>`s.${o(n)}::text = m.k ->> ${u}`).join(" AND ")}`;const w=e==="revisions"?` AND m.k ->> 0 NOT IN (SELECT rev_id FROM ${a(t,"_arr_revisions")})`:e==="revision_parents"?` AND NOT EXISTS (SELECT 1 FROM ${a(t,"_arr_parents")} a WHERE a.child = m.k ->> 0 AND a.parent = m.k ->> 1)`:"",b=e==="run_events"?`(s.ts < '${M}' OR (s.ts < '${g}' AND s.type IN (${W.map(n=>`'${n}'`).join(", ")})))`:"false",y=`FROM ${a(t,"_m")} m LEFT JOIN ${a(O,e)} t ON ${C(s,c,"t","m.k")} ${S.replace("JOIN","LEFT JOIN")} WHERE m.tbl = '${e}'${w}`,k=`${y} AND ((t.${o(c[0])} IS NULL AND NOT (s.${o(c[0])} IS NOT NULL AND ${b})) OR s.${o(c[0])} IS NULL OR (${T("t")}) <> (${T("s")}))`;if(e==="run_events"){const n=Number((await r.prepareUncached(`SELECT count(*) AS n ${y} AND t.${o(c[0])} IS NULL AND s.${o(c[0])} IS NOT NULL AND ${b}`).get()).n);n>0&&(m[e]=n)}const v=Number((await r.prepareUncached(`SELECT count(*) AS n ${k}`).get()).n);if(v>0){const n=await r.prepareUncached(`SELECT m.k::text AS k ${k} LIMIT 10`).all();_[e]={count:v,keys:n.map(u=>u.k)}}}for(const[e,i]of[["revisions",`FROM ${a(t,"_m")} m JOIN ${a(t,"_arr_revisions")} a ON a.rev_id = m.k ->> 0 LEFT JOIN revisions t ON t.rev_id = a.rev_id
3
+ WHERE m.tbl = 'revisions' AND (t.rev_id IS NULL OR t.document <> a.document OR t.body_hash <> a.body_hash OR t.rationale IS DISTINCT FROM a.rationale OR t.created_at <> a.created_at)`],["revision_parents",`FROM ${a(t,"_m")} m JOIN ${a(t,"_arr_parents")} a ON a.child = m.k ->> 0 AND a.parent = m.k ->> 1 LEFT JOIN revision_parents t ON t.child = a.child AND t.parent = a.parent
4
+ WHERE m.tbl = 'revision_parents' AND t.child IS NULL`]]){const s=Number((await r.prepareUncached(`SELECT count(*) AS n ${i}`).get()).n);s>0&&(_[`${e}.arrived`]={count:s,keys:[]})}const N={},f=`SELECT source AS key FROM ${a(t,"_idmap")} WHERE kind = 'object'`,F=l(e=>e==="messages"?`(${f})`:`(${f} UNION SELECT key FROM ${a(t,"_dropped")} WHERE tbl = 'objects')`,"droppedFor");let L=!1;for(const{table_name:e}of p){const i=$.tables.get(e);if(i===void 0||L||i.primaryKey.length===0)continue;const s=await r.prepareUncached("SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND data_type = 'text'").all(O,e);for(const{column_name:E}of s){if(i.primaryKey.includes(E)&&e==="objects")continue;if(await r.prepareUncached(`SELECT 1 AS found FROM ${a(t,"_m")} m JOIN ${a(O,e)} t ON ${C(i,i.primaryKey,"t","m.k")}
5
+ WHERE m.tbl = ? AND t.${o(E)} IN ${F(e)} LIMIT 1`).get(e)!==void 0){L=!0,_[`${e}.${E}`]={count:1,keys:["holds a dropped object id"]};break}}}N.no_dropped_id=!L;const A=p.find(e=>e.table_name==="revisions");let I=!0;A!==void 0&&(I=await r.prepare(`SELECT 1 AS missing FROM ${a(t,"_m")} m JOIN revisions r ON r.rev_id = m.k ->> 0 WHERE m.tbl = 'revisions'
6
+ AND NOT EXISTS (SELECT 1 FROM bodies b WHERE b.hash = r.body_hash) LIMIT 1`).get()===void 0),N.revision_bodies_readable=I,N.revision_bodies_canonical=A===void 0||await r.prepare(`SELECT 1 AS wrong FROM ${a(t,"_m")} m JOIN revisions r ON r.rev_id = m.k ->> 0 JOIN bodies b ON b.hash = r.body_hash
7
+ WHERE m.tbl = 'revisions' AND encode(sha256(convert_to(b.text, 'UTF8')), 'hex') <> b.hash LIMIT 1`).get()===void 0;const U=await r.prepare(`SELECT 1 AS found FROM (
9
8
  SELECT month, payer, funding, COALESCE(sub, '') AS sub, grantee, COALESCE(provider, '') AS provider, COALESCE(SUM(usd), 0) AS usd, COALESCE(SUM(billed_usd), 0) AS billed
10
- FROM charges WHERE refused IS NULL AND kind <> 'take' AND (month, payer) IN (SELECT DISTINCT month, payer FROM ${n(t,"charges")}) GROUP BY 1, 2, 3, 4, 5, 6) c
9
+ FROM charges WHERE refused IS NULL AND kind <> 'take' AND (month, payer) IN (SELECT DISTINCT month, payer FROM ${a(t,"charges")}) GROUP BY 1, 2, 3, 4, 5, 6) c
11
10
  FULL JOIN charge_totals t ON t.month = c.month AND t.payer = c.payer AND t.funding = c.funding AND t.sub = c.sub AND t.grantee = c.grantee AND t.provider = c.provider
12
- WHERE (COALESCE(t.month, c.month), COALESCE(t.payer, c.payer)) IN (SELECT DISTINCT month, payer FROM ${n(t,"charges")}) AND (c.month IS NULL OR t.month IS NULL OR c.usd <> t.usd OR c.billed <> t.billed_usd) LIMIT 1`).get();return d.charge_totals_equal_recompute=C===void 0,{ok:Object.keys(N).length===0&&Object.values(d).every(Boolean),differences:N,invariants:d}}c(x,"verifyRun");export{x as verifyRun};
11
+ WHERE (COALESCE(t.month, c.month), COALESCE(t.payer, c.payer)) IN (SELECT DISTINCT month, payer FROM ${a(t,"charges")}) AND (c.month IS NULL OR t.month IS NULL OR c.usd <> t.usd OR c.billed <> t.billed_usd) LIMIT 1`).get();return N.charge_totals_equal_recompute=U===void 0,{ok:Object.keys(_).length===0&&Object.values(N).every(Boolean),differences:_,...Object.keys(m).length>0?{archived:m}:{},invariants:N}}l(Z,"verifyRun");export{Z as verifyRun};
@@ -1 +1,3 @@
1
- var re=Object.defineProperty;var u=(n,e)=>re(n,"name",{value:e,configurable:!0});import{ApiError as A}from"../../../api/errors.js";import{DOC_KINDS as H,DOC_UNSET_FIELDS as U}from"../../../api/dto/docs.js";import{PRIVACY_LEVELS_DTO as V}from"../../../api/dto/objects.js";import{openDb as se,withCanvasWrite as E}from"../../../core/canvas/db.js";import{CrtrError as ce}from"../../../core/errors.js";import{emitEvent as de}from"../../../core/events/emit.js";import{canChange as ue,spaceOf as fe}from"../../../core/graph/access.js";import{get as x,getMany as K}from"../../../core/graph/bodies.js";import{deleteDocument as me,documentRecord as M,editDocument as pe,heads as W,history as le,linksIn as G,moveDocument as he,readBase as we,setDocumentRecord as ye,withCurrentNames as ge,writeDocument as ve}from"../../../core/graph/documents.js";import{resolveName as X}from"../../../core/graph/names.js";import{getById as B}from"../../../core/graph/objects.js";import{noteRepoDocumentsChanged as _e}from"../../../core/graph/repo-sync/index.js";import{checkoutsForCwd as be}from"../../../core/graph/repo-sync/repos.js";import{lintRules as ke,rulesOf as Ae}from"../../../core/graph/rules.js";import{unifiedDiff as Ee}from"../../../core/graph/diff.js";import{ownerForGrantee as $e}from"../../../core/graph/objects.js";import{stubOf as Oe}from"../../../core/peer/stubs.js";import{forwarding as je}from"../../peer/forward.js";import{resolvedLocally as Re}from"./objects.js";import{ownerFromFlag as q,readerFor as $,resolveRef as z,warmReaderRepos as O}from"../reader.js";import{appCaller as Y,asApiError as De,requireOwnNamespace as Ce}from"./schemas.js";import{filterAsync as Ne,flatMapAsync as Se}from"../../../core/async-array.js";function y(n,e,t,o,r={}){return new A(n,e,t,{...r,error:e,message:t,next:o})}u(y,"refuse");const k=u((n,e)=>new A(400,"invalid_request",n,e),"invalid");function S(n){const e=n.body;if(e===void 0)return{};if(typeof e!="object"||e===null||Array.isArray(e))throw k("the request body must be a JSON object");return e}u(S,"bodyOf");const T=u(async n=>async e=>await be(n,e),"reposFnFor");function I(n,e){if(n instanceof ce){const t=n.details;if(n.code==="read_first")throw y(409,"read_first",n.message,`Read it first with \`crtr canvas read ${e?.id??"<ref>"}\`, then rerun the edit.`,t??{});if(n.code==="conflict")throw new A(409,"name_taken",n.message,t);if(n.code==="forbidden")throw typeof t?.next=="string"?y(403,"forbidden",n.message,t.next,t):new A(403,"forbidden",n.message,t);if(n.code==="scope_missing")throw y(403,"scope_missing",n.message,`Launch the run with \`${String(t?.scope)}\` in its scopes list.`,t??{});if(t?.rule==="repo-public-only")throw y(422,"repo_documents_are_public",n.message,'Own it as `user` and add a rule with `if: {"repo": "<handle>"}` so it loads only in that repo.')}throw De(n)}u(I,"mapGraphError");async function P(n,e,t){const o=await z(n,e,decodeURIComponent(t));if("remote"in o)throw y(404,"not_found",J(o.remote),"Check the name with `crtr canvas search`.");if("deleted"in o)throw new A(404,"not_found",`${o.deleted.name} is deleted`,{id:o.deleted.id,deleted:!0});if(o.type!=="document")throw k(`${t} is a ${o.type}, not a document`);return o}u(P,"refDocument");async function Z(n){const{stub:e}=await Re(decodeURIComponent(n.params.ref),n);if(e===null)return;const t=await Oe(await se(),e);if(t.object.type!=="document")return;const o=await je.current.label(t.home_machine);throw y(404,"not_here",`this document lives on runtime ${o.name}; edit it (or read its history) from a node there`,`Run the command from a node on ${o.name}.`,{id:t.object.id,home_machine:o.id})}u(Z,"refuseRemoteDocument");function J(n){return`no object named ${n} on this runtime; it may be on another runtime, or the name may be misspelled`}u(J,"remoteMessage");async function Te(n,e){const t=e.owner===null?null:await B(n,e.owner);return t?t.type==="node"?t.id:t.name:""}u(Te,"ownerHandle");async function D(n,e){const t=await Te(n,e);return t?`${t}/${e.name}`:e.name}u(D,"canonicalName");async function Ie(n,e){const t=e.owner===null?null:await B(n,e.owner),o=t?{id:t.id,type:t.type,handle:t.type==="node"?t.id:t.name}:null;return{id:e.id,type:e.type,kind:e.kind,owner:o,privacy:e.privacy,name:e.name,preview:e.preview??"",created_at:e.created_at,deleted_at:e.deleted_at,...e.type==="document"?{schema_type:e.schema_type??null}:{}}}u(Ie,"objectDTO");async function Fe(n,e){const t=e.owner===null?null:await B(n,e.owner);return t?.type==="repo"?t:null}u(Fe,"repoOwner");async function F(n,e,t,o){const r=[...new Map(await Se(t,async f=>{const a=await Fe(n,f);return a?[[a.id,a]]:[]})).values()],c=e.class==="node"?e.cwd:o,s=e.class==="node"?[...e.checkouts,...e.projectCheckouts].map(f=>f.root):[];return{repos:r,dirs:[...new Set([...c!==void 0?[c]:[],...s])]}}u(F,"repoChange");async function L(n){for(const e of n.repos)try{await _e(e,n.dirs)}catch(t){de({level:"warn",event:"repo_sync.failed",outcome:"failed",error:t,fields:{repo:e.name,step:"export",reason:t instanceof Error?t.message:String(t)}})}}u(L,"syncChanged");const Q=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function Le(n,e){if(n===void 0)return;if(!Array.isArray(n)){e.push("`rules` must be a list");return}const t=n.map(r=>{if(typeof r!="object"||r===null||Array.isArray(r))return r;const{match_frontmatter:c,...s}=r;return"matchFrontmatter"in s?{...s,match_frontmatter:s.matchFrontmatter}:c===void 0?s:{...s,matchFrontmatter:c}}),o=ke(t);if(o){e.push(o.replaceAll("matchFrontmatter","match_frontmatter"));return}return t}u(Le,"rulesFromDTO");function ee(n,e){const t={},o=u(a=>{const d=n[a];if(d!==void 0){if(typeof d!="string"){e.push(`\`${a}\` must be a string`);return}return d}},"str"),r=o("preview");r!==void 0&&(r.trim()===""||/[\r\n]/.test(r)?e.push("`preview` must be one non-empty line"):t.preview=r);const c=o("summary");c!==void 0&&(t.summary=c);const s=o("why_it_exists");if(s!==void 0&&(t.whyItExists=s),n.privacy!==void 0&&(V.includes(n.privacy)?t.privacy=n.privacy:e.push(`\`privacy\` must be one of ${V.join(", ")}`)),n.unlisted!==void 0&&(typeof n.unlisted!="boolean"?e.push("`unlisted` must be a boolean"):t.unlisted=n.unlisted),n.lint_ignore!==void 0){const a=n.lint_ignore;!Array.isArray(a)||a.some(d=>typeof d!="string")?e.push("`lint_ignore` must be a list of strings"):t.lintIgnore=a}if(n.extensions!==void 0){const a=n.extensions;typeof a!="object"||a===null||Array.isArray(a)||Object.values(a).some(d=>typeof d!="object"||d===null||Array.isArray(d))?e.push("`extensions` must map each plugin to an object of fields"):t.extensions=a}const f=Le(n.rules,e);return f!==void 0&&(t.rules=f),t}u(ee,"fieldsFrom");function te(n){if(n.length>0)throw k(n.join("; "),{errors:n})}u(te,"failOn");async function ne(n,e,t,o){const r=await Ne(G(t),async c=>"remote"in await X(n,e,c));return{...o.length>0?{unresolved_links:o}:{},...r.length>0?{remote_links:r}:{}}}u(ne,"linkReport");async function Me(n){const e=S(n),t=[],o=e.name;(typeof o!="string"||!Q.test(o))&&t.push("`name` must be segments of letters, digits, `_` or `-` joined by `/`"),typeof e.body!="string"&&t.push("`body` must be a string"),typeof e.preview!="string"&&t.push("`preview` is required");const r=e.kind??"knowledge";H.includes(r)||t.push(r==="report"?"reports are written only by `crtr push`":`\`kind\` must be one of ${H.join(", ")}`);const c=ee(e,t);e.cwd!==void 0&&typeof e.cwd!="string"&&t.push("`cwd` must be a string");const s=e.schema_type;s!==void 0&&typeof s!="string"&&t.push("`schema_type` must be a string");const f=e.relations;f!==void 0&&(!Array.isArray(f)||f.some(i=>typeof i!="object"||i===null||typeof i.relation!="string"||typeof i.subject!="string"))&&t.push("`relations` must be a list of {relation, subject} strings"),te(t);const a=e;await O(n.principal,a.cwd);const{dto:d,change:m}=await E(async i=>{const p=await $(i,n);a.schema_type!==void 0?await Ce(i,Y(n).app,a.schema_type):a.relations!==void 0&&Y(n);const h=a.owner==="user"&&p.class==="app"&&p.sub!==void 0?await $e(i,p.sub.startsWith("user:")?p.sub:`user:${p.sub}`):await q(i,p,a.owner,a.cwd);try{const{object:w,unresolved:v}=await ve(i,p,{...c,owner:h,name:a.name,kind:r,preview:c.preview,privacy:c.privacy??"public",...a.schema_type!==void 0?{schemaType:a.schema_type}:{},...a.relations!==void 0?{relations:a.relations}:{}},a.body,await T(i));return{dto:{id:w.id,name:await D(i,w),...await ne(i,p,a.body,v)},change:await F(i,p,[w],a.cwd)}}catch(w){I(w)}});return await L(m),d}u(Me,"write");function We(n,e){let t=n;e.forEach(({old:o,new:r},c)=>{const s=o===""?-1:t.indexOf(o);if(s<0)throw y(422,"replace_no_match",`replace[${c}]: old text not found in the revision you read`,"Copy the old text exactly from your last read and rerun.",{index:c});if(t.indexOf(o,s+1)>=0)throw y(422,"replace_ambiguous",`replace[${c}]: old text occurs more than once`,"Include more surrounding text so the old text matches once, and rerun.",{index:c});t=t.slice(0,s)+r+t.slice(s+o.length)})}u(We,"checkReplacements");async function Be(n){const e=S(n),t=[],o=e.body!==void 0,r=e.replace!==void 0;o&&r&&t.push("give `body` or `replace`, not both"),o&&typeof e.body!="string"&&t.push("`body` must be a string");const c=e.replace;r&&(!Array.isArray(c)||c.length===0||c.some(i=>typeof i!="object"||i===null||typeof i.old!="string"||typeof i.new!="string"))&&t.push("`replace` must be a non-empty list of {old, new} strings"),(typeof e.rationale!="string"||e.rationale.trim()==="")&&t.push("`rationale` is required"),e.verbatim!==void 0&&typeof e.verbatim!="boolean"&&t.push("`verbatim` must be a boolean"),e.base!==void 0&&(typeof e.base!="string"||e.base==="")&&t.push("`base` must be a non-empty heads key"),e.base!==void 0&&!o&&!r&&t.push("`base` applies only to a `body` or `replace` edit");const s=ee(e,t),f=e.unset??[];if(!Array.isArray(f)||f.some(i=>!U.includes(i)))t.push(`\`unset\` takes only ${U.join(", ")}`);else for(const i of f)i==="summary"&&(s.summary=null),i==="why_it_exists"&&(s.whyItExists=null),i==="unlisted"&&(s.unlisted=!1),i==="lint_ignore"&&(s.lintIgnore=null),i==="extensions"&&(s.extensions=null),i==="rules"&&(s.rules=[]);t.length===0&&!o&&!r&&Object.keys(s).length===0&&t.push("nothing to change: give `body`, `replace`, or a field"),te(t);const a=e;await Z(n),await O(n.principal);const{dto:d,synced:m}=await E(async i=>{const p=await $(i,n),h=await P(i,p,n.params.ref),w=await D(i,h),v=await F(i,p,[h]);try{if(!o&&!r)return await ye(i,p,h,s,a.rationale),{dto:{id:h.id,name:w,revision:(await M(i,h)).revision},synced:v};const g=a.base??await we(i,p,h);if(r&&g!==null){const _=await M(i,h),N=await W(i,h);_.source_path===null&&_.heads_key===g&&N.length===1&&We(await ge(i,h,await x(i,N[0].body_hash)),a.replace)}const R=a.verbatim===!0,C=o?{body:a.body,verbatim:R}:{replace:a.replace,verbatim:R},b=await pe(i,p,h,C,a.rationale,g,s,await T(i));if("stale"in b)throw y(409,"stale_revision",`${w} changed after your read; it is now at revision ${b.stale.revision}`,`Read it again with \`crtr canvas read ${w}\`, then redo your change on the current text.`,{stale:b.stale});const l=await x(i,(await W(i,h))[0].body_hash);return{dto:{id:h.id,name:w,revision:b.revision,...await ne(i,p,l,b.unresolved)},synced:v}}catch(g){I(g,h)}});return await L(m),d}u(Be,"edit");async function qe(n){const e=S(n);if(e.new_name===void 0&&e.owner===void 0)throw k("give a new name, an owner, or both");if(e.new_name!==void 0&&(typeof e.new_name!="string"||!Q.test(e.new_name)))throw k("`new_name` must be segments of letters, digits, `_` or `-` joined by `/`");await O(n.principal,e.cwd);const{dto:t,change:o}=await E(async r=>{const c=await $(r,n),s=await P(r,c,n.params.ref),f=e.owner===void 0?void 0:await q(r,c,e.owner,e.cwd);try{const a=await he(r,c,s,{...e.new_name!==void 0?{name:e.new_name}:{},...f?{owner:f}:{}},await T(r));return{dto:{id:a.id,name:await D(r,a)},change:await F(r,c,[s,a],e.cwd)}}catch(a){I(a,s)}});return await L(o),t}u(qe,"move");async function Pe(n){await O(n.principal);const{dto:e,change:t}=await E(async o=>{const r=await $(o,n),c=await P(o,r,n.params.ref),s=await D(o,c),f=await F(o,r,[c]);try{await me(o,r,c,await T(o))}catch(a){I(a,c)}return{dto:{id:c.id,name:s},change:f}});return await L(t),e}u(Pe,"remove");async function He(n){const e=n.query.get("diff"),t=e===null?void 0:Number(e);if(t!==void 0&&!(Number.isInteger(t)&&t>0))throw k("`diff` must be a revision number");return await Z(n),await O(n.principal),await E(async o=>{const r=await $(o,n),c=await z(o,r,decodeURIComponent(n.params.ref));if("remote"in c)throw y(404,"not_found",J(c.remote),"Check the name with `crtr canvas search`.");const s="deleted"in c?c.deleted:c;if(s.type!=="document")throw k(`${s.name} is a ${s.type}, not a document`);const f=await le(o,r,s),a={object:await Ie(o,s),revisions:f.map(d=>({rev_id:d.rev_id,number:d.number,author_id:d.author,rationale:d.rationale,verbatim:d.verbatim,created_at:d.created_at,parents:d.parents,acting_app:d.acting_app,acting_for:d.acting_for}))};if(t!==void 0){const d=f.find(p=>p.number===t);if(!d)throw new A(404,"not_found",`${s.name} has no revision ${t}`);const m=d.parents[0]===void 0?void 0:f.find(p=>p.rev_id===d.parents[0]),i=await K(o,m?[m.body_hash,d.body_hash]:[d.body_hash]);a.diff=Ee(m?i.get(m.body_hash):"",i.get(d.body_hash))}return a})}u(He,"revisionHistory");const oe=1e3,ie=1e3,ae=3e3,Ue=/^When\b.+\bbecause\b.+/,Ve=u(n=>{const e=n.trim();return e===""?0:e.split(/\s+/).length},"words");function xe(n,e){if(n.some(o=>o.on==="boot"&&o.deliver==="content")&&e>oe)return`body is ${e} words, over the ${oe}-word cap for a boot rule at content (the whole body enters every node's context). Keep the core here and move separate subjects into [[linked]] documents.`;const t=[...new Set(n.filter(o=>o.on!=="boot"&&o.deliver==="content").map(o=>o.on))];return t.length>0&&e>ie?`body is ${e} words, over the ${ie}-word cap for a content rule on ${t.join("/")}. Keep the core here and move separate subjects into [[linked]] documents.`:n.some(o=>o.on==="boot"&&o.deliver==="preview")&&e>ae?`body is ${e} words, over the ${ae}-word cap for a boot rule at preview. Keep the core here and move separate subjects into [[linked]] documents.`:null}u(xe,"lengthFinding");async function Ke(n){const e=S(n);return await O(n.principal,e.cwd),await E(async t=>{const o=await $(t,n),r=e.owner===void 0?null:await q(t,o,e.owner,e.cwd),c=await t.prepare("SELECT * FROM objects WHERE type = 'document' AND deleted_at IS NULL AND home_machine IS NULL AND kind != 'report' ORDER BY name").all(),s=[],f=new Map,a=[];for(const m of c)r&&m.owner!==r.id||await ue(t,o,m)&&a.push({doc:m,head:(await W(t,m))[0]});const d=await K(t,a.flatMap(m=>m.head?[m.head.body_hash]:[]));for(const{doc:m,head:i}of a){const p=await M(t,m),h=new Set(p.lint_ignore??[]),w=await D(t,m),v=u((l,_,N)=>{h.has(l)||s.push({name:w,severity:_,rule:l,message:N})},"add"),g=await Ae(t,m),R=i?d.get(i.body_hash):"",C=xe(g,Ve(R));C&&v("length","error",C),g.some(l=>l.deliver==="preview")&&!Ue.test(m.preview??"")&&v("preview-shape","error",`a rule delivers this document at preview, so the preview must read "When <situation in the reader's work>, read this because <what the reader gains>"`);const b=new Set((await t.prepare("SELECT written_as FROM edges WHERE type = 'links-to' AND src = ?").all(m.id)).map(l=>l.written_as));for(const l of G(R)){if(b.has(l))continue;const _=await X(t,o,l);"remote"in _||"object"in _||"deleted"in _||v("links","warning",`[[${l}]] names no object in your view`)}if(g.some(l=>l.on==="workspace-open"&&l.deliver==="content")){const l=await fe(t,m);l.type==="repo"&&!h.has("workspace-open")&&f.set(l.name,[...f.get(l.name)??[],w])}}for(const[m,i]of f)if(!(i.length<2))for(const p of i)s.push({name:p,severity:"warning",rule:"workspace-open",message:`repo ${m} has ${i.length} documents delivered at content on workspace-open (${i.join(", ")}); keep one and link the rest from it`});return{findings:s}})}u(Ke,"lint");const j=u((n,e=200)=>async t=>({status:e,body:await n(t)}),"ok"),wt=[{method:"POST",pattern:"/v1/docs",handler:j(Me,201)},{method:"PATCH",pattern:"/v1/docs/:ref",handler:j(Be)},{method:"POST",pattern:"/v1/docs/:ref/move",handler:j(qe)},{method:"DELETE",pattern:"/v1/docs/:ref",handler:j(Pe)},{method:"GET",pattern:"/v1/docs/:ref/history",handler:j(He)},{method:"POST",pattern:"/v1/docs/lint",handler:j(Ke)}];export{D as canonicalName,wt as docRoutes,F as repoChange,L as syncChanged};
1
+ var de=Object.defineProperty;var u=(n,e)=>de(n,"name",{value:e,configurable:!0});import{ApiError as A}from"../../../api/errors.js";import{DOC_KINDS as V,DOC_UNSET_FIELDS as x}from"../../../api/dto/docs.js";import{PRIVACY_LEVELS_DTO as G}from"../../../api/dto/objects.js";import{openDb as ue,withCanvasWrite as O}from"../../../core/canvas/db.js";import{CrtrError as fe}from"../../../core/errors.js";import{emitEvent as le}from"../../../core/events/emit.js";import{canChange as me,spaceOf as pe}from"../../../core/graph/access.js";import{get as K,getMany as X}from"../../../core/graph/bodies.js";import{deleteDocument as he,documentRecord as C,editDocument as we,heads as H,history as ye,linksIn as z,moveDocument as ge,readBase as _e,setDocumentRecord as ve,withCurrentNames as be,writeDocument as Ee}from"../../../core/graph/documents.js";import{resolveName as J}from"../../../core/graph/names.js";import{getById as T}from"../../../core/graph/objects.js";import{noteRepoDocumentsChanged as ke}from"../../../core/graph/repo-sync/index.js";import{checkoutsForCwd as Ae}from"../../../core/graph/repo-sync/repos.js";import{lintRules as Oe,rulesOf as Y}from"../../../core/graph/rules.js";import{unifiedDiff as $e}from"../../../core/graph/diff.js";import{ownerForGrantee as je}from"../../../core/graph/objects.js";import{stubOf as Re}from"../../../core/peer/stubs.js";import{forwarding as De}from"../../peer/forward.js";import{resolvedLocally as Ne}from"./objects.js";import{ownerFromFlag as q,readerFor as $,resolveRef as Z,warmReaderRepos as j}from"../reader.js";import{appCaller as Q,asApiError as Se,requireOwnNamespace as Ce}from"./schemas.js";import{filterAsync as Te,flatMapAsync as Ie}from"../../../core/async-array.js";function y(n,e,t,o,a={}){return new A(n,e,t,{...a,error:e,message:t,next:o})}u(y,"refuse");const k=u((n,e)=>new A(400,"invalid_request",n,e),"invalid");function I(n){const e=n.body;if(e===void 0)return{};if(typeof e!="object"||e===null||Array.isArray(e))throw k("the request body must be a JSON object");return e}u(I,"bodyOf");const F=u(async n=>async e=>await Ae(n,e),"reposFnFor");function L(n,e){if(n instanceof fe){const t=n.details;if(n.code==="read_first")throw y(409,"read_first",n.message,`Read it first with \`crtr canvas read ${e?.id??"<ref>"}\`, then rerun the edit.`,t??{});if(n.code==="conflict")throw new A(409,"name_taken",n.message,t);if(n.code==="forbidden")throw typeof t?.next=="string"?y(403,"forbidden",n.message,t.next,t):new A(403,"forbidden",n.message,t);if(n.code==="scope_missing")throw y(403,"scope_missing",n.message,`Launch the run with \`${String(t?.scope)}\` in its scopes list.`,t??{});if(t?.rule==="repo-public-only")throw y(422,"repo_documents_are_public",n.message,'Own it as `user` and add a rule with `if: {"repo": "<handle>"}` so it loads only in that repo.')}throw Se(n)}u(L,"mapGraphError");async function P(n,e,t){const o=await Z(n,e,decodeURIComponent(t));if("remote"in o)throw y(404,"not_found",te(o.remote),"Check the name with `crtr canvas search`.");if("deleted"in o)throw new A(404,"not_found",`${o.deleted.name} is deleted`,{id:o.deleted.id,deleted:!0});if(o.type!=="document")throw k(`${t} is a ${o.type}, not a document`);return o}u(P,"refDocument");async function ee(n){const{stub:e}=await Ne(decodeURIComponent(n.params.ref),n);if(e===null)return;const t=await Re(await ue(),e);if(t.object.type!=="document")return;const o=await De.current.label(t.home_machine);throw y(404,"not_here",`this document lives on runtime ${o.name}; edit it (or read its history) from a node there`,`Run the command from a node on ${o.name}.`,{id:t.object.id,home_machine:o.id})}u(ee,"refuseRemoteDocument");function te(n){return`no object named ${n} on this runtime; it may be on another runtime, or the name may be misspelled`}u(te,"remoteMessage");async function Fe(n,e){const t=e.owner===null?null:await T(n,e.owner);return t?t.type==="node"?t.id:t.name:""}u(Fe,"ownerHandle");async function N(n,e){const t=await Fe(n,e);return t?`${t}/${e.name}`:e.name}u(N,"canonicalName");async function Le(n,e){const t=e.owner===null?null:await T(n,e.owner),o=t?{id:t.id,type:t.type,handle:t.type==="node"?t.id:t.name}:null;return{id:e.id,type:e.type,kind:e.kind,owner:o,privacy:e.privacy,name:e.name,preview:e.preview??"",created_at:e.created_at,deleted_at:e.deleted_at,...e.type==="document"?{schema_type:e.schema_type??null}:{}}}u(Le,"objectDTO");async function Me(n,e){const t=e.owner===null?null:await T(n,e.owner);return t?.type==="repo"?t:null}u(Me,"repoOwner");async function M(n,e,t,o){const a=[...new Map(await Ie(t,async f=>{const r=await Me(n,f);return r?[[r.id,r]]:[]})).values()],c=e.class==="node"?e.cwd:o,s=e.class==="node"?[...e.checkouts,...e.projectCheckouts].map(f=>f.root):[];return{repos:a,dirs:[...new Set([...c!==void 0?[c]:[],...s])]}}u(M,"repoChange");async function W(n){for(const e of n.repos)try{await ke(e,n.dirs)}catch(t){le({level:"warn",event:"repo_sync.failed",outcome:"failed",error:t,fields:{repo:e.name,step:"export",reason:t instanceof Error?t.message:String(t)}})}}u(W,"syncChanged");const ne=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function We(n,e){if(n===void 0)return;if(!Array.isArray(n)){e.push("`rules` must be a list");return}const t=n.map(a=>{if(typeof a!="object"||a===null||Array.isArray(a))return a;const{match_frontmatter:c,...s}=a;return"matchFrontmatter"in s?{...s,match_frontmatter:s.matchFrontmatter}:c===void 0?s:{...s,matchFrontmatter:c}}),o=Oe(t);if(o){e.push(o.replaceAll("matchFrontmatter","match_frontmatter"));return}return t}u(We,"rulesFromDTO");function oe(n,e){const t={},o=u(r=>{const d=n[r];if(d!==void 0){if(typeof d!="string"){e.push(`\`${r}\` must be a string`);return}return d}},"str"),a=o("preview");a!==void 0&&(a.trim()===""||/[\r\n]/.test(a)?e.push("`preview` must be one non-empty line"):t.preview=a);const c=o("summary");c!==void 0&&(t.summary=c);const s=o("why_it_exists");if(s!==void 0&&(t.whyItExists=s),n.privacy!==void 0&&(G.includes(n.privacy)?t.privacy=n.privacy:e.push(`\`privacy\` must be one of ${G.join(", ")}`)),n.unlisted!==void 0&&(typeof n.unlisted!="boolean"?e.push("`unlisted` must be a boolean"):t.unlisted=n.unlisted),n.lint_ignore!==void 0){const r=n.lint_ignore;!Array.isArray(r)||r.some(d=>typeof d!="string")?e.push("`lint_ignore` must be a list of strings"):t.lintIgnore=r}if(n.extensions!==void 0){const r=n.extensions;typeof r!="object"||r===null||Array.isArray(r)||Object.values(r).some(d=>typeof d!="object"||d===null||Array.isArray(d))?e.push("`extensions` must map each plugin to an object of fields"):t.extensions=r}const f=We(n.rules,e);return f!==void 0&&(t.rules=f),t}u(oe,"fieldsFrom");function ie(n){if(n.length>0)throw k(n.join("; "),{errors:n})}u(ie,"failOn");async function re(n,e,t,o){const a=await Te(z(t),async c=>"remote"in await J(n,e,c));return{...o.length>0?{unresolved_links:o}:{},...a.length>0?{remote_links:a}:{}}}u(re,"linkReport");async function B(n,e,t){if(t?.includes("unreached")||e.schema_type!=null||e.owner===null)return!1;const o=await T(n,e.owner);return!o||o.type==="node"||(await Y(n,e)).length>0?!1:await n.prepare(`SELECT 1 FROM edges e JOIN objects s ON s.id = e.src
2
+ WHERE e.type = 'links-to' AND e.dst = ? AND e.src != e.dst AND s.deleted_at IS NULL
3
+ AND EXISTS (SELECT 1 FROM rules r WHERE r.object = s.id) LIMIT 1`).get(e.id)===void 0}u(B,"unreached");const Be="no rule delivers this document and no document with a rule links to it, so no agent will be routed to it; give it a rule, link it from a document that loads, or accept it with lint-ignore `unreached`";async function He(n){const e=I(n),t=[],o=e.name;(typeof o!="string"||!ne.test(o))&&t.push("`name` must be segments of letters, digits, `_` or `-` joined by `/`"),typeof e.body!="string"&&t.push("`body` must be a string"),typeof e.preview!="string"&&t.push("`preview` is required");const a=e.kind??"knowledge";V.includes(a)||t.push(a==="report"?"reports are written only by `crtr push`":`\`kind\` must be one of ${V.join(", ")}`);const c=oe(e,t);e.cwd!==void 0&&typeof e.cwd!="string"&&t.push("`cwd` must be a string");const s=e.schema_type;s!==void 0&&typeof s!="string"&&t.push("`schema_type` must be a string");const f=e.relations;f!==void 0&&(!Array.isArray(f)||f.some(i=>typeof i!="object"||i===null||typeof i.relation!="string"||typeof i.subject!="string"))&&t.push("`relations` must be a list of {relation, subject} strings"),ie(t);const r=e;await j(n.principal,r.cwd);const{dto:d,change:l}=await O(async i=>{const m=await $(i,n);r.schema_type!==void 0?await Ce(i,Q(n).app,r.schema_type):r.relations!==void 0&&Q(n);const p=r.owner==="user"&&m.class==="app"&&m.sub!==void 0?await je(i,m.sub.startsWith("user:")?m.sub:`user:${m.sub}`):await q(i,m,r.owner,r.cwd);try{const{object:w,unresolved:g}=await Ee(i,m,{...c,owner:p,name:r.name,kind:a,preview:c.preview,privacy:c.privacy??"public",...r.schema_type!==void 0?{schemaType:r.schema_type}:{},...r.relations!==void 0?{relations:r.relations}:{}},r.body,await F(i));return{dto:{id:w.id,name:await N(i,w),...await re(i,m,r.body,g),...await B(i,w,c.lintIgnore??null)?{unreached:!0}:{}},change:await M(i,m,[w],r.cwd)}}catch(w){L(w)}});return await W(l),d}u(He,"write");function qe(n,e){let t=n;e.forEach(({old:o,new:a},c)=>{const s=o===""?-1:t.indexOf(o);if(s<0)throw y(422,"replace_no_match",`replace[${c}]: old text not found in the revision you read`,"Copy the old text exactly from your last read and rerun.",{index:c});if(t.indexOf(o,s+1)>=0)throw y(422,"replace_ambiguous",`replace[${c}]: old text occurs more than once`,"Include more surrounding text so the old text matches once, and rerun.",{index:c});t=t.slice(0,s)+a+t.slice(s+o.length)})}u(qe,"checkReplacements");async function Pe(n){const e=I(n),t=[],o=e.body!==void 0,a=e.replace!==void 0;o&&a&&t.push("give `body` or `replace`, not both"),o&&typeof e.body!="string"&&t.push("`body` must be a string");const c=e.replace;a&&(!Array.isArray(c)||c.length===0||c.some(i=>typeof i!="object"||i===null||typeof i.old!="string"||typeof i.new!="string"))&&t.push("`replace` must be a non-empty list of {old, new} strings"),(typeof e.rationale!="string"||e.rationale.trim()==="")&&t.push("`rationale` is required"),e.verbatim!==void 0&&typeof e.verbatim!="boolean"&&t.push("`verbatim` must be a boolean"),e.base!==void 0&&(typeof e.base!="string"||e.base==="")&&t.push("`base` must be a non-empty heads key"),e.base!==void 0&&!o&&!a&&t.push("`base` applies only to a `body` or `replace` edit");const s=oe(e,t),f=e.unset??[];if(!Array.isArray(f)||f.some(i=>!x.includes(i)))t.push(`\`unset\` takes only ${x.join(", ")}`);else for(const i of f)i==="summary"&&(s.summary=null),i==="why_it_exists"&&(s.whyItExists=null),i==="unlisted"&&(s.unlisted=!1),i==="lint_ignore"&&(s.lintIgnore=null),i==="extensions"&&(s.extensions=null),i==="rules"&&(s.rules=[]);t.length===0&&!o&&!a&&Object.keys(s).length===0&&t.push("nothing to change: give `body`, `replace`, or a field"),ie(t);const r=e;await ee(n),await j(n.principal);const{dto:d,synced:l}=await O(async i=>{const m=await $(i,n),p=await P(i,m,n.params.ref),w=await N(i,p),g=await M(i,m,[p]);try{if(!o&&!a){await ve(i,m,p,s,r.rationale);const E=await C(i,p);return{dto:{id:p.id,name:w,revision:E.revision,...await B(i,p,E.lint_ignore)?{unreached:!0}:{}},synced:g}}const _=r.base??await _e(i,m,p);if(a&&_!==null){const E=await C(i,p),U=await H(i,p);E.source_path===null&&E.heads_key===_&&U.length===1&&qe(await be(i,p,await K(i,U[0].body_hash)),r.replace)}const D=r.verbatim===!0,S=o?{body:r.body,verbatim:D}:{replace:r.replace,verbatim:D},v=await we(i,m,p,S,r.rationale,_,s,await F(i));if("stale"in v)throw y(409,"stale_revision",`${w} changed after your read; it is now at revision ${v.stale.revision}`,`Read it again with \`crtr canvas read ${w}\`, then redo your change on the current text.`,{stale:v.stale});const h=await K(i,(await H(i,p))[0].body_hash),b=await C(i,p);return{dto:{id:p.id,name:w,revision:v.revision,...await re(i,m,h,v.unresolved),...await B(i,p,b.lint_ignore)?{unreached:!0}:{}},synced:g}}catch(_){L(_,p)}});return await W(l),d}u(Pe,"edit");async function Ue(n){const e=I(n);if(e.new_name===void 0&&e.owner===void 0)throw k("give a new name, an owner, or both");if(e.new_name!==void 0&&(typeof e.new_name!="string"||!ne.test(e.new_name)))throw k("`new_name` must be segments of letters, digits, `_` or `-` joined by `/`");await j(n.principal,e.cwd);const{dto:t,change:o}=await O(async a=>{const c=await $(a,n),s=await P(a,c,n.params.ref),f=e.owner===void 0?void 0:await q(a,c,e.owner,e.cwd);try{const r=await ge(a,c,s,{...e.new_name!==void 0?{name:e.new_name}:{},...f?{owner:f}:{}},await F(a));return{dto:{id:r.id,name:await N(a,r)},change:await M(a,c,[s,r],e.cwd)}}catch(r){L(r,s)}});return await W(o),t}u(Ue,"move");async function Ve(n){await j(n.principal);const{dto:e,change:t}=await O(async o=>{const a=await $(o,n),c=await P(o,a,n.params.ref),s=await N(o,c),f=await M(o,a,[c]);try{await he(o,a,c,await F(o))}catch(r){L(r,c)}return{dto:{id:c.id,name:s},change:f}});return await W(t),e}u(Ve,"remove");async function xe(n){const e=n.query.get("diff"),t=e===null?void 0:Number(e);if(t!==void 0&&!(Number.isInteger(t)&&t>0))throw k("`diff` must be a revision number");return await ee(n),await j(n.principal),await O(async o=>{const a=await $(o,n),c=await Z(o,a,decodeURIComponent(n.params.ref));if("remote"in c)throw y(404,"not_found",te(c.remote),"Check the name with `crtr canvas search`.");const s="deleted"in c?c.deleted:c;if(s.type!=="document")throw k(`${s.name} is a ${s.type}, not a document`);const f=await ye(o,a,s),r={object:await Le(o,s),revisions:f.map(d=>({rev_id:d.rev_id,number:d.number,author_id:d.author,rationale:d.rationale,verbatim:d.verbatim,created_at:d.created_at,parents:d.parents,acting_app:d.acting_app,acting_for:d.acting_for}))};if(t!==void 0){const d=f.find(m=>m.number===t);if(!d)throw new A(404,"not_found",`${s.name} has no revision ${t}`);const l=d.parents[0]===void 0?void 0:f.find(m=>m.rev_id===d.parents[0]),i=await X(o,l?[l.body_hash,d.body_hash]:[d.body_hash]);r.diff=$e(l?i.get(l.body_hash):"",i.get(d.body_hash))}return r})}u(xe,"revisionHistory");const ae=1e3,se=1e3,ce=3e3,Ge=/^When\b.+\bbecause\b.+/,Ke=u(n=>{const e=n.trim();return e===""?0:e.split(/\s+/).length},"words");function Xe(n,e){if(n.some(o=>o.on==="boot"&&o.deliver==="content")&&e>ae)return`body is ${e} words, over the ${ae}-word cap for a boot rule at content (the whole body enters every node's context). Keep the core here and move separate subjects into [[linked]] documents.`;const t=[...new Set(n.filter(o=>o.on!=="boot"&&o.deliver==="content").map(o=>o.on))];return t.length>0&&e>se?`body is ${e} words, over the ${se}-word cap for a content rule on ${t.join("/")}. Keep the core here and move separate subjects into [[linked]] documents.`:n.some(o=>o.on==="boot"&&o.deliver==="preview")&&e>ce?`body is ${e} words, over the ${ce}-word cap for a boot rule at preview. Keep the core here and move separate subjects into [[linked]] documents.`:null}u(Xe,"lengthFinding");async function ze(n){const e=I(n);return await j(n.principal,e.cwd),await O(async t=>{const o=await $(t,n),a=e.owner===void 0?null:await q(t,o,e.owner,e.cwd),c=await t.prepare("SELECT * FROM objects WHERE type = 'document' AND deleted_at IS NULL AND home_machine IS NULL AND kind != 'report' ORDER BY name").all(),s=[],f=new Map,r=[];for(const l of c)a&&l.owner!==a.id||await me(t,o,l)&&r.push({doc:l,head:(await H(t,l))[0]});const d=await X(t,r.flatMap(l=>l.head?[l.head.body_hash]:[]));for(const{doc:l,head:i}of r){const m=await C(t,l),p=new Set(m.lint_ignore??[]),w=await N(t,l),g=u((h,b,E)=>{p.has(h)||s.push({name:w,severity:b,rule:h,message:E})},"add"),_=await Y(t,l),D=i?d.get(i.body_hash):"",S=Xe(_,Ke(D));S&&g("length","error",S),_.some(h=>h.deliver==="preview")&&!Ge.test(l.preview??"")&&g("preview-shape","error",`a rule delivers this document at preview, so the preview must read "When <situation in the reader's work>, read this because <what the reader gains>"`);const v=new Set((await t.prepare("SELECT written_as FROM edges WHERE type = 'links-to' AND src = ?").all(l.id)).map(h=>h.written_as));for(const h of z(D)){if(v.has(h))continue;const b=await J(t,o,h);"remote"in b||"object"in b||"deleted"in b||g("links","warning",`[[${h}]] names no object in your view`)}if(await B(t,l,m.lint_ignore)&&g("unreached","warning",Be),_.some(h=>h.on==="workspace-open"&&h.deliver==="content")){const h=await pe(t,l);h.type==="repo"&&!p.has("workspace-open")&&f.set(h.name,[...f.get(h.name)??[],w])}}for(const[l,i]of f)if(!(i.length<2))for(const m of i)s.push({name:m,severity:"warning",rule:"workspace-open",message:`repo ${l} has ${i.length} documents delivered at content on workspace-open (${i.join(", ")}); keep one and link the rest from it`});return{findings:s}})}u(ze,"lint");const R=u((n,e=200)=>async t=>({status:e,body:await n(t)}),"ok"),_t=[{method:"POST",pattern:"/v1/docs",handler:R(He,201)},{method:"PATCH",pattern:"/v1/docs/:ref",handler:R(Pe)},{method:"POST",pattern:"/v1/docs/:ref/move",handler:R(Ue)},{method:"DELETE",pattern:"/v1/docs/:ref",handler:R(Ve)},{method:"GET",pattern:"/v1/docs/:ref/history",handler:R(xe)},{method:"POST",pattern:"/v1/docs/lint",handler:R(ze)}];export{N as canonicalName,_t as docRoutes,M as repoChange,W as syncChanged};
@@ -29,7 +29,7 @@ interface PiLike {
29
29
  * - orchestrator (terminal OR resident): bring the roadmap current, then
30
30
  * yield (it already has a roadmap to bring current first).
31
31
  * - resident/base (root conversation): yield to continue fresh if the chat is
32
- * growing into a job, else wrap up — a root can simply end.
32
+ * growing into a job, else keep working here until the task is done.
33
33
  * - terminal/base (worker): yield to continue if work remains, or `push final`
34
34
  * when close.
35
35
  *
@@ -1 +1 @@
1
- var J=Object.defineProperty;var l=(n,t)=>J(n,"name",{value:t,configurable:!0});import{brokerSignalClient as A}from"../core/runtime/broker/signal-stream.js";import{brokerExecutionId as K}from"../core/runtime/broker/daemon-ops.js";import{envNodeId as Z}from"../shared/env.js";import{stripCdPrefix as ee}from"../shared/strip-cd-prefix.js";import{brokerRecovery as te,mutateBrokerFault as j,recordBrokerTelemetry as ne,recordBrokerTurn as x,clearBrokerPushedFinal as re,consumeBrokerPushedFinal as oe}from"../core/runtime/broker/daemon-ops.js";import{bindBrokerSession as se,cachedBrokerNode as L,postBrokerIdle as ae,relaunchBrokerRoot as ie,settleBroker as Y}from"../core/runtime/broker/daemon-ops.js";import{emitEvent as F}from"../core/events/emit.js";import{CONTEXT_NUDGE_CUSTOM_TYPE as le,formatCard as ue}from"../shared/generated-context.js";import{isReviewBoundary as ce}from"../core/runtime/session-visibility.js";import{clearRefusedTurn as de,isRuntimeTeardownInProgress as fe,refuseTurn as he,runRefreshAbort as ye}from"../core/runtime/broker/extension-abort.js";import{announceMessageOrigin as z}from"../core/runtime/stamp/channel.js";const G=80;function pe(n,t){const i=t??{},s=l(w=>typeof w=="string"?w:"","pick"),h=ee(s(i.command).trim())||s(i.path)||s(i.file_path)||s(i.pattern)||s(i.description)||s(i.prompt),y=(h!==""?`${n}: ${h}`:n).replace(/\s+/g," ").trim();return y.length>G?y.slice(0,G):y}l(pe,"summarizeActivity");function me(n){for(let t=n.length-1;t>=0;t--)if(n[t]?.role==="assistant")return n[t]}l(me,"lastAssistantMessage");function ge(n){try{const t=n?.sessionManager?.getBranch();if(!Array.isArray(t))return[];const i=new Set;for(const s of t){if(!ce(s))continue;const u=s.details?.reviewId;typeof u=="string"&&i.add(u)}return[...i]}catch{return[]}}l(ge,"currentReviewBoundaryIds");const Q=1e4,C=[13e4,15e4,17e4,185e3,2e5];function we(n){const t=C[0],i=C[C.length-1];if(n<t)return null;if(n>=i)return i+Math.floor((n-i)/Q)*Q;let s=t;for(const u of C)n>=u&&(s=u);return s}l(we,"steerBand");function _e(n,t,i){const s=Math.round(n/1e3),u=n>=185e3;if(i==="orchestrator")return n<15e4?`Context ~${s}k and growing. When you reach a good stopping point, consider updating your roadmap (\`crtr doc edit roadmap\`) and running \`crtr node yield\` to refresh against it \u2014 no rush yet.`:u?`Context ~${s}k \u2014 this is getting long. Stop taking on new work now: bring your roadmap current, hand off anything outstanding, and \`crtr node yield\` immediately to refresh before this context overflows.`:`Context ~${s}k. Update your roadmap (\`crtr doc edit roadmap\`) so a fresh revive can continue, delegate any outstanding work, then \`crtr node yield\` to refresh.`;if(t==="resident"){const h="If substantial work remains, `crtr node yield` to continue fresh against your goal and your note. Add --promote only when worthwhile independent work can run in parallel and coordinating it should become your primary job; `crtr node yield -h` has the boundary.";return n<15e4?`Context ~${s}k and growing. ${h} Otherwise no rush \u2014 wrap up when you reach a good stopping point.`:u?`Context ~${s}k \u2014 this is getting long. Wrap up now before this context overflows: finish what's in hand, or \`crtr node yield\` immediately to continue fresh against your goal and your note if substantial work remains.`:`Context ~${s}k. ${h} If you're near done, just finish here; if there's more open-ended work, \`crtr node yield\` rather than letting this context grow.`}return n<15e4?`Context ~${s}k and growing. If you're near done, finish with \`crtr push final\`. If real work remains, \`crtr node yield\` to continue in a fresh window against your goal and your note \u2014 no rush yet.`:u?`Context ~${s}k \u2014 this is getting long. Wrap up now before this context overflows: \`crtr push final\` if you're close, otherwise \`crtr node yield\` immediately to continue in a fresh window against your goal and your note.`:`Context ~${s}k. If you're close, finish with \`crtr push final\`; otherwise \`crtr node yield\` now to refresh into a clean window and keep going against your goal and your note.`}l(_e,"steerNote");function ke(n){const t=Z();if(t===void 0||t.trim()==="")return;let i=0,s=0,u="",h=null,y=null;const w=new Set;let k=!1,I=!1;const N=l(e=>{if(!I){I=!0;try{ye(()=>e?.abort?.())}catch{}}},"abortForRefresh");let v;const V=A().subscribe("node",()=>{const e=A();k&&e.state==="connected"&&e.latestNode?.intent==="refresh"&&N(v)}),c=l((e,r)=>{F({event:"broker.daemon.operation.failed",level:"error",node_id:t,error:r,fields:{operation:e}})},"emitDaemonOperationFailure"),D=l((e,r)=>{if(e.action==="reprompt"){z(e.prompt,{type:"runtime",kind:"stop-guard"}),n.sendUserMessage(e.prompt,{deliverAs:"followUp"});return}if(e.action==="stay_resident"){ae(t).then(()=>A().stop(),o=>c("idle",o));return}if(e.action==="shutdown")try{r?.shutdown?.()}catch{}},"enactSettleDirective"),X=3e3;let O=0,S=Promise.resolve(),d=null,U=null,q=-1/0,p=null,R=0;const B=l(()=>{if(d===null||d===U)return;const e=d;U=e,q=Date.now(),S=S.then(()=>ne(t,e)).catch(r=>c("telemetry",r))},"queueTelemetry"),E=l((e,r)=>{if(d!==null&&d.tokens_in===i&&d.tokens_out===s&&d.model===u&&d.context_tokens===e&&d.last_activity===r)return;R=Math.max(Date.now(),R+1),d={tokens_in:i,tokens_out:s,model:u,context_tokens:e,last_activity:r,updated_at:new Date(R).toISOString()};const o=2e3-(Date.now()-q);o<=0?B():p===null&&(p=setTimeout(()=>{p=null,B()},o),p.unref?.())},"publishTelemetry"),$=l(()=>(p!==null&&clearTimeout(p),p=null,B(),S),"flushTelemetry");let M=Promise.resolve();const H=l(e=>(M=M.catch(()=>{}).then(async()=>{const r=await x(t,{event:"progress"});if(r.fault_link==="daemon\u2192node"&&(await te(t)).fault?.op==="conversation_write_failed"){if(!e)return;await(await import("../core/conversation-store/index.js")).flushConversation(),await j(t,{op:"clear",link:"daemon\u2192node"})}else(r.fault_link==="daemon\u2192node"||e&&r.fault_link==="pi\u2192provider")&&await j(t,{op:"clear",link:r.fault_link})}),M),"reportProgress"),T=l(()=>{const e=Date.now();e-O<X||(O=e,H(!1).catch(r=>c("turn_progress",r)))},"heartbeat");n.on("session_start",async(e,r)=>{try{const o=r?.sessionManager?.getSessionId?.();if(typeof o!="string"||o==="")return;const m=r?.sessionManager?.getSessionFile?.(),g=typeof m=="string"&&m!==""?m:null,_=typeof e?.reason=="string"?e.reason:null;_==="new"&&(i=0,s=0,w.clear());const a=await se(t,{piSessionId:o,sessionFile:g,pid:process.pid,reason:_,reviewBoundaryIds:ge(r)});if(a.action==="none"&&A().start(t,K()),a.action==="shutdown"){try{r?.shutdown?.()}catch{}return}if(a.action==="relaunch_root"){ie(t).catch(f=>{const b=f instanceof Error?f.message:String(f);r?.ui?.notify?.(`/new refused: ${b}`,"error"),F({event:"broker.daemon.operation.failed",level:"error",node_id:t,error:f,fields:{operation:"relaunch_root"}})});return}}catch(o){F({event:"broker.daemon.operation.failed",level:"error",node_id:t,error:o,fields:{operation:"session_bound"}})}}),n.on("agent_start",async(e,r)=>{k=!0,v=r;try{if(!(await x(t,{event:"started"})).applied)throw new Error("daemon refused turn open")}catch(o){c("turn_open",o),r?.ui?.notify?.("Turn refused: the broker no longer owns this node.","error"),he(()=>r?.abort?.())}}),n.on("input",async()=>{k||(I=!1),de();try{await re(t)}catch(e){throw c("clear_pushed_final",e),e}}),n.on("tool_execution_start",e=>{try{y=pe(String(e?.toolName??""),e?.args),E(h,y),T()}catch{}}),n.on("tool_execution_update",()=>{try{T()}catch{}}),n.on("message_update",()=>{try{T()}catch{}}),n.on("tool_execution_end",async(e,r)=>{try{T(),(await L(t)).intent==="refresh"&&N(r)}catch{}}),n.on("session_shutdown",async(e,r)=>{V(),k=!1,v=void 0,await $();try{await x(t,{event:"closed",end_reason:"teardown-aborted"})}catch(o){c("turn_close_teardown",o)}if(e?.reason==="quit")try{const o=await Y(t,{stopReason:"quit",pushedFinal:!1});D(o,r)}catch(o){c("settle_quit",o)}});const W=l(e=>{e?.role!=="assistant"||e.usage==null||(i+=Number(e.usage.input??0)||0,s+=Number(e.usage.output??0)||0,typeof e.model=="string"&&e.model!==""&&(u=e.model))},"accumulate");n.on("turn_end",async(e,r)=>{W(e?.message);let o=null;try{const a=r.getContextUsage()?.tokens;typeof a=="number"&&(o=a)}catch{}o!==null&&(h=o),E(o,y),await $();try{const a=e?.message?.stopReason!=="error"&&e?.message?.stopReason!=="aborted";await H(a)}catch(a){c("turn_end_fault_clear",a)}const m=Array.isArray(e?.message?.content)?e.message.content:[],g=e?.message?.stopReason??"",_=g!=="error"&&g!=="aborted"&&m.some(a=>a?.type==="toolCall");try{const a=o!==null?we(o):null,f=a!==null&&!w.has(a)?await L(t):null;if(a!==null&&f!==null){w.add(a);const b=ue("context-nudge",{},_e(a,f.lifecycle,f.mode));_?(z(b,{type:"runtime",kind:"context-nudge"}),n.sendUserMessage(b,{deliverAs:"steer"})):n.sendMessage({customType:le,content:b,display:!0},{deliverAs:"nextTurn"})}}catch(a){c("turn_boundary",a)}});let P=null;n.on("agent_end",e=>{P=e;try{const r=Array.isArray(e?.messages)?e.messages:[];for(const o of r)W(o)}catch{}}),n.on("agent_settled",async(e,r)=>{k=!1,v=void 0,E(h,y),await $();const o=P;if(P=null,fe())return;try{await x(t,{event:"closed",end_reason:"settled"})}catch(a){c("turn_close",a);return}const m=Array.isArray(o?.messages)?o.messages:[],g=me(m),_=typeof g?.stopReason=="string"?g.stopReason:"";try{const a=o===null?{pushedFinal:!1}:await oe(t),f=await Y(t,{stopReason:_,pushedFinal:a.pushedFinal});D(f,r)}catch(a){c("settle",a)}})}l(ke,"registerCanvasStophook");var Me=ke;export{Me as default,ke as registerCanvasStophook,_e as steerNote};
1
+ var J=Object.defineProperty;var l=(n,t)=>J(n,"name",{value:t,configurable:!0});import{brokerSignalClient as A}from"../core/runtime/broker/signal-stream.js";import{brokerExecutionId as K}from"../core/runtime/broker/daemon-ops.js";import{envNodeId as Z}from"../shared/env.js";import{stripCdPrefix as ee}from"../shared/strip-cd-prefix.js";import{brokerRecovery as te,mutateBrokerFault as Y,recordBrokerTelemetry as ne,recordBrokerTurn as x,clearBrokerPushedFinal as re,consumeBrokerPushedFinal as oe}from"../core/runtime/broker/daemon-ops.js";import{bindBrokerSession as se,cachedBrokerNode as j,postBrokerIdle as ae,relaunchBrokerRoot as ie,settleBroker as z}from"../core/runtime/broker/daemon-ops.js";import{emitEvent as F}from"../core/events/emit.js";import{CONTEXT_NUDGE_CUSTOM_TYPE as le,formatCard as ue}from"../shared/generated-context.js";import{isReviewBoundary as ce}from"../core/runtime/session-visibility.js";import{clearRefusedTurn as de,isRuntimeTeardownInProgress as fe,refuseTurn as he,runRefreshAbort as me}from"../core/runtime/broker/extension-abort.js";import{announceMessageOrigin as G}from"../core/runtime/stamp/channel.js";const Q=80;function ye(n,t){const i=t??{},s=l(w=>typeof w=="string"?w:"","pick"),u=ee(s(i.command).trim())||s(i.path)||s(i.file_path)||s(i.pattern)||s(i.description)||s(i.prompt),d=(u!==""?`${n}: ${u}`:n).replace(/\s+/g," ").trim();return d.length>Q?d.slice(0,Q):d}l(ye,"summarizeActivity");function ge(n){for(let t=n.length-1;t>=0;t--)if(n[t]?.role==="assistant")return n[t]}l(ge,"lastAssistantMessage");function pe(n){try{const t=n?.sessionManager?.getBranch();if(!Array.isArray(t))return[];const i=new Set;for(const s of t){if(!ce(s))continue;const c=s.details?.reviewId;typeof c=="string"&&i.add(c)}return[...i]}catch{return[]}}l(pe,"currentReviewBoundaryIds");const V=1e4,C=[13e4,15e4,17e4,185e3,2e5];function we(n){const t=C[0],i=C[C.length-1];if(n<t)return null;if(n>=i)return i+Math.floor((n-i)/V)*V;let s=t;for(const c of C)n>=c&&(s=c);return s}l(we,"steerBand");function _e(n,t,i){const s=Math.round(n/1e3),c=n>=185e3,u="This is not a request to stop: keep going until your task is done.";if(i==="orchestrator")return n<15e4?`Context ~${s}k and growing. ${u} When you reach a good stopping point, consider updating your roadmap (\`crtr doc edit roadmap\`) and running \`crtr node yield\` to refresh against it \u2014 no rush yet.`:c?`Context ~${s}k \u2014 this is getting long. ${u} Bring your roadmap current, hand off anything outstanding, and \`crtr node yield\` immediately to refresh before this context overflows; the fresh window continues the work.`:`Context ~${s}k. ${u} Update your roadmap (\`crtr doc edit roadmap\`) so a fresh revive can continue, delegate any outstanding work, then \`crtr node yield\` to refresh.`;if(t==="resident"){const d="If substantial work remains, `crtr node yield` to continue fresh against your goal and your note. Add --promote only when worthwhile independent work can run in parallel and coordinating it should become your primary job; `crtr node yield -h` has the boundary.";return n<15e4?`Context ~${s}k and growing. ${u} ${d} Otherwise no rush.`:c?`Context ~${s}k \u2014 this is getting long. ${u} If little remains, finish the task now; if much remains, \`crtr node yield\` immediately, with a note saying where things stand, to continue fresh against your goal before this context overflows.`:`Context ~${s}k. ${u} ${d} If little remains, finish the task here; if much remains, \`crtr node yield\` rather than letting this context grow.`}return n<15e4?`Context ~${s}k and growing. ${u} If the task is done, finish with \`crtr push final\`. If real work remains, \`crtr node yield\` to continue in a fresh window against your goal and your note \u2014 no rush yet.`:c?`Context ~${s}k \u2014 this is getting long. ${u} \`crtr push final\` only if the task is done; otherwise \`crtr node yield\` immediately, with a note saying where things stand, to continue in a fresh window before this context overflows.`:`Context ~${s}k. ${u} If the task is done, finish with \`crtr push final\`; otherwise \`crtr node yield\` now to refresh into a clean window and keep going against your goal and your note.`}l(_e,"steerNote");function ke(n){const t=Z();if(t===void 0||t.trim()==="")return;let i=0,s=0,c="",u=null,d=null;const w=new Set;let k=!1,I=!1;const N=l(e=>{if(!I){I=!0;try{me(()=>e?.abort?.())}catch{}}},"abortForRefresh");let v;const W=A().subscribe("node",()=>{const e=A();k&&e.state==="connected"&&e.latestNode?.intent==="refresh"&&N(v)}),f=l((e,r)=>{F({event:"broker.daemon.operation.failed",level:"error",node_id:t,error:r,fields:{operation:e}})},"emitDaemonOperationFailure"),D=l((e,r)=>{if(e.action==="reprompt"){G(e.prompt,{type:"runtime",kind:"stop-guard"}),n.sendUserMessage(e.prompt,{deliverAs:"followUp"});return}if(e.action==="stay_resident"){ae(t).then(()=>A().stop(),o=>f("idle",o));return}if(e.action==="shutdown")try{r?.shutdown?.()}catch{}},"enactSettleDirective"),X=3e3;let O=0,$=Promise.resolve(),h=null,U=null,q=-1/0,y=null,S=0;const B=l(()=>{if(h===null||h===U)return;const e=h;U=e,q=Date.now(),$=$.then(()=>ne(t,e)).catch(r=>f("telemetry",r))},"queueTelemetry"),R=l((e,r)=>{if(h!==null&&h.tokens_in===i&&h.tokens_out===s&&h.model===c&&h.context_tokens===e&&h.last_activity===r)return;S=Math.max(Date.now(),S+1),h={tokens_in:i,tokens_out:s,model:c,context_tokens:e,last_activity:r,updated_at:new Date(S).toISOString()};const o=2e3-(Date.now()-q);o<=0?B():y===null&&(y=setTimeout(()=>{y=null,B()},o),y.unref?.())},"publishTelemetry"),E=l(()=>(y!==null&&clearTimeout(y),y=null,B(),$),"flushTelemetry");let M=Promise.resolve();const H=l(e=>(M=M.catch(()=>{}).then(async()=>{const r=await x(t,{event:"progress"});if(r.fault_link==="daemon\u2192node"&&(await te(t)).fault?.op==="conversation_write_failed"){if(!e)return;await(await import("../core/conversation-store/index.js")).flushConversation(),await Y(t,{op:"clear",link:"daemon\u2192node"})}else(r.fault_link==="daemon\u2192node"||e&&r.fault_link==="pi\u2192provider")&&await Y(t,{op:"clear",link:r.fault_link})}),M),"reportProgress"),T=l(()=>{const e=Date.now();e-O<X||(O=e,H(!1).catch(r=>f("turn_progress",r)))},"heartbeat");n.on("session_start",async(e,r)=>{try{const o=r?.sessionManager?.getSessionId?.();if(typeof o!="string"||o==="")return;const g=r?.sessionManager?.getSessionFile?.(),p=typeof g=="string"&&g!==""?g:null,_=typeof e?.reason=="string"?e.reason:null;_==="new"&&(i=0,s=0,w.clear());const a=await se(t,{piSessionId:o,sessionFile:p,pid:process.pid,reason:_,reviewBoundaryIds:pe(r)});if(a.action==="none"&&A().start(t,K()),a.action==="shutdown"){try{r?.shutdown?.()}catch{}return}if(a.action==="relaunch_root"){ie(t).catch(m=>{const b=m instanceof Error?m.message:String(m);r?.ui?.notify?.(`/new refused: ${b}`,"error"),F({event:"broker.daemon.operation.failed",level:"error",node_id:t,error:m,fields:{operation:"relaunch_root"}})});return}}catch(o){F({event:"broker.daemon.operation.failed",level:"error",node_id:t,error:o,fields:{operation:"session_bound"}})}}),n.on("agent_start",async(e,r)=>{k=!0,v=r;try{if(!(await x(t,{event:"started"})).applied)throw new Error("daemon refused turn open")}catch(o){f("turn_open",o),r?.ui?.notify?.("Turn refused: the broker no longer owns this node.","error"),he(()=>r?.abort?.())}}),n.on("input",async()=>{k||(I=!1),de();try{await re(t)}catch(e){throw f("clear_pushed_final",e),e}}),n.on("tool_execution_start",e=>{try{d=ye(String(e?.toolName??""),e?.args),R(u,d),T()}catch{}}),n.on("tool_execution_update",()=>{try{T()}catch{}}),n.on("message_update",()=>{try{T()}catch{}}),n.on("tool_execution_end",async(e,r)=>{try{T(),(await j(t)).intent==="refresh"&&N(r)}catch{}}),n.on("session_shutdown",async(e,r)=>{W(),k=!1,v=void 0,await E();try{await x(t,{event:"closed",end_reason:"teardown-aborted"})}catch(o){f("turn_close_teardown",o)}if(e?.reason==="quit")try{const o=await z(t,{stopReason:"quit",pushedFinal:!1});D(o,r)}catch(o){f("settle_quit",o)}});const L=l(e=>{e?.role!=="assistant"||e.usage==null||(i+=Number(e.usage.input??0)||0,s+=Number(e.usage.output??0)||0,typeof e.model=="string"&&e.model!==""&&(c=e.model))},"accumulate");n.on("turn_end",async(e,r)=>{L(e?.message);let o=null;try{const a=r.getContextUsage()?.tokens;typeof a=="number"&&(o=a)}catch{}o!==null&&(u=o),R(o,d),await E();try{const a=e?.message?.stopReason!=="error"&&e?.message?.stopReason!=="aborted";await H(a)}catch(a){f("turn_end_fault_clear",a)}const g=Array.isArray(e?.message?.content)?e.message.content:[],p=e?.message?.stopReason??"",_=p!=="error"&&p!=="aborted"&&g.some(a=>a?.type==="toolCall");try{const a=o!==null?we(o):null,m=a!==null&&!w.has(a)?await j(t):null;if(a!==null&&m!==null){w.add(a);const b=ue("context-nudge",{},_e(a,m.lifecycle,m.mode));_?(G(b,{type:"runtime",kind:"context-nudge"}),n.sendUserMessage(b,{deliverAs:"steer"})):n.sendMessage({customType:le,content:b,display:!0},{deliverAs:"nextTurn"})}}catch(a){f("turn_boundary",a)}});let P=null;n.on("agent_end",e=>{P=e;try{const r=Array.isArray(e?.messages)?e.messages:[];for(const o of r)L(o)}catch{}}),n.on("agent_settled",async(e,r)=>{k=!1,v=void 0,R(u,d),await E();const o=P;if(P=null,fe())return;try{await x(t,{event:"closed",end_reason:"settled"})}catch(a){f("turn_close",a);return}const g=Array.isArray(o?.messages)?o.messages:[],p=ge(g),_=typeof p?.stopReason=="string"?p.stopReason:"";try{const a=o===null?{pushedFinal:!1}:await oe(t),m=await z(t,{stopReason:_,pushedFinal:a.pushedFinal});D(m,r)}catch(a){f("settle",a)}})}l(ke,"registerCanvasStophook");var Me=ke;export{Me as default,ke as registerCanvasStophook,_e as steerNote};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.620",
3
+ "version": "0.3.622",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -145,7 +145,7 @@
145
145
  },
146
146
  "license": "UNLICENSED",
147
147
  "dependencies": {
148
- "@north-light/identity": "0.3.620",
148
+ "@north-light/identity": "0.3.622",
149
149
  "@earendil-works/chord": "1.1.0",
150
150
  "@earendil-works/pi-agent-core": "1.1.0",
151
151
  "@earendil-works/pi-ai": "1.1.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.620",
3
+ "version": "0.3.622",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",