@north-light/cli 0.3.621 → 0.3.623
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/docs.d.ts +6 -2
- package/dist/builtin-memory/crouter-sdk/release-notes.md +4 -0
- package/dist/builtin-memory/insights/init.md +1 -1
- package/dist/builtin-memory/internal/INDEX.md +1 -1
- package/dist/builtin-memory/internal/memory-loading.md +2 -2
- package/dist/builtin-memory/internal/plugins.md +2 -2
- package/dist/commands/doc/edit.js +1 -1
- package/dist/commands/doc/lint.js +2 -2
- package/dist/commands/doc/shared.d.ts +3 -0
- package/dist/commands/doc/shared.js +2 -2
- package/dist/commands/doc/write.js +1 -1
- package/dist/core/canvas/schema-pg/015-exposures-object-index.sql +10 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/daemon/api/handlers/docs.js +3 -1
- package/dist/pi-extensions/canvas-stophook.d.ts +1 -1
- package/dist/pi-extensions/canvas-stophook.js +1 -1
- package/docs/sdk/release-notes.md +4 -0
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
package/dist/api/contract.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
|
|
2
|
-
export declare const CONTRACT_LEVEL = "1.
|
|
2
|
+
export declare const CONTRACT_LEVEL = "1.49";
|
|
3
3
|
/** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
|
|
4
4
|
export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
|
|
5
5
|
/** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
|
package/dist/api/contract.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.
|
|
1
|
+
var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.49",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
|
package/dist/api/dto/docs.d.ts
CHANGED
|
@@ -45,7 +45,11 @@ export interface DocLinkReportDTO {
|
|
|
45
45
|
unresolved_links?: string[];
|
|
46
46
|
remote_links?: string[];
|
|
47
47
|
}
|
|
48
|
-
|
|
48
|
+
/** `unreached`: present and true when no agent will be routed to the document — not node-owned, no rule, and no document with a rule links to it. */
|
|
49
|
+
export interface DocReachDTO {
|
|
50
|
+
unreached?: boolean;
|
|
51
|
+
}
|
|
52
|
+
export interface DocWrittenDTO extends DocLinkReportDTO, DocReachDTO {
|
|
49
53
|
id: string;
|
|
50
54
|
name: string;
|
|
51
55
|
}
|
|
@@ -71,7 +75,7 @@ export interface DocEditRequest {
|
|
|
71
75
|
extensions?: Record<string, Record<string, unknown>>;
|
|
72
76
|
unset?: DocUnsetField[];
|
|
73
77
|
}
|
|
74
|
-
export interface DocEditedDTO extends DocLinkReportDTO {
|
|
78
|
+
export interface DocEditedDTO extends DocLinkReportDTO, DocReachDTO {
|
|
75
79
|
id: string;
|
|
76
80
|
name: string;
|
|
77
81
|
revision: number;
|
|
@@ -9,6 +9,10 @@ when-and-why-to-read: When you need Release notes, this knowledge should be read
|
|
|
9
9
|
|
|
10
10
|
Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
|
|
11
11
|
|
|
12
|
+
## 0.3.622
|
|
13
|
+
|
|
14
|
+
`oauth.authorizeUrl` takes an optional `loginHint`: a phone number your app already collected, sent as the standard `login_hint`. A signed-out person's sign-in page then shows the number with one "Text me a link" button instead of asking for it (US and Canadian numbers in any format they type; a number the directory cannot text only prefills its form). Nothing is texted until the person presses the button. No existing call changes.
|
|
15
|
+
|
|
12
16
|
## 0.3.613
|
|
13
17
|
|
|
14
18
|
`oauth.appMember('user:<id>')` asks the directory whether that person is on the team that holds your app, for your app's own staff pages. It answers `{member: true, role: 'admin' | 'member'}` or `{member: false}` (an unknown user is `member: false`) by calling `GET /v1/apps/self/members/:user_id` as the app itself, and caches nothing, so someone removed from the team is refused at their next call. A 401 re-mints the directory token once. Nothing existing changes.
|
|
@@ -32,7 +32,7 @@ Search the chosen owner before creating. Use `insights/<topic>` under the chosen
|
|
|
32
32
|
|
|
33
33
|
## Create the listener
|
|
34
34
|
|
|
35
|
-
Run `crtr doc write -h`, then create the listener document under the chosen owner, named `insights/<topic>`, as a preference with the rule `on: boot`, `deliver: preview` (`--rule`, see `crtr doc write
|
|
35
|
+
Run `crtr doc write -h`, then create the listener document under the chosen owner, named `insights/<topic>`, as a preference with the rule `on: boot`, `deliver: preview` (`--rule`, see `crtr doc write -h`).
|
|
36
36
|
|
|
37
37
|
Its preview must name the actual domain trigger: when user-supplied information, a correction, or a user response relates to this domain, read the preference because recognizing the underlying principle preserves knowledge future decisions can use.
|
|
38
38
|
|
|
@@ -34,7 +34,7 @@ crtr keeps one graph of **objects** in one SQLite database (`canvas.db`). Docume
|
|
|
34
34
|
- **marketplaces** — authoring a crtr marketplace: the marketplace.json index, local-link and remote-Git plugin sources, auto-bump CI, dual-publishing.
|
|
35
35
|
- **examples/** — worked compositions of the primitives into complete systems, e.g. the iMessage assistant node.
|
|
36
36
|
|
|
37
|
-
Adjacent, outside this dir: writing documents (kind, delivery rules, preview, the asked-to-remember workflow) is owned by `crtr doc write -h` and its focused `--owner -h
|
|
37
|
+
Adjacent, outside this dir: writing documents (kind, delivery rules, preview, the asked-to-remember workflow) is owned by `crtr doc write -h` and its focused `--owner -h` — the guide lives on that `-h` surface so it is delivered exactly when you write. Finding and reading objects is `crtr canvas -h`; registering a custom object is `crtr custom-object -h`.
|
|
38
38
|
|
|
39
39
|
Briefly: **plugins** package documents and commands, with command execution selected by `plugin.json.transport` (`exec` for a trusted local executable or `http` for a fetched remote REST manifest); **marketplaces** index and distribute plugins. Plugin commands enter the **external-command** fallthrough, leaving the core fast-path untouched.
|
|
40
40
|
|
|
@@ -9,7 +9,7 @@ surfaces:
|
|
|
9
9
|
|
|
10
10
|
# How documents load
|
|
11
11
|
|
|
12
|
-
A document is an object on the canvas ([[internal]] has the model): it has an owner, a privacy level and a name, and any node that may read it can `crtr canvas read` it. Whether it also *loads on its own* — into a node's boot context, when a file is read, when a command runs — is decided only by the document's **rules**; the runtime never guesses. A rule is one `on` event, one `deliver` level and one optional `if`, plus structural ordering. The writing contract (flags, preview craft) is `crtr doc write -h
|
|
12
|
+
A document is an object on the canvas ([[internal]] has the model): it has an owner, a privacy level and a name, and any node that may read it can `crtr canvas read` it. Whether it also *loads on its own* — into a node's boot context, when a file is read, when a command runs — is decided only by the document's **rules**; the runtime never guesses. A rule is one `on` event, one `deliver` level and one optional `if`, plus structural ordering. The writing contract (flags, preview craft) is `crtr doc write -h`; which owner to write under is `internal/agent-shaping`; where state lives is `internal/storage-tiers`. This document is the mechanics between those: what actually fires, when, and in what order.
|
|
13
13
|
|
|
14
14
|
(In a package file — a builtin or plugin `memory/*.md` — rules are authored in the package-file frontmatter (`surfaces`, `gate`, `slash`) and converted into these rules on import; see `internal/plugins`. Everything below describes the converted rules.)
|
|
15
15
|
|
|
@@ -39,7 +39,7 @@ Silence is the absence of a rule; there is no `none` level. `summary` is **not**
|
|
|
39
39
|
|
|
40
40
|
## Conditions
|
|
41
41
|
|
|
42
|
-
A rule's `if` is the eligibility predicate over the receiving node — kind, mode, lifecycle, orchestration depth, cwd, the repos it is eligible for (`repo`: those enclosing its cwd and those of its profile's project paths; use `cwd` for location), profile — using the standard matcher vocabulary (`crtr doc write
|
|
42
|
+
A rule's `if` is the eligibility predicate over the receiving node — kind, mode, lifecycle, orchestration depth, cwd, the repos it is eligible for (`repo`: those enclosing its cwd and those of its profile's project paths; use `cwd` for location), profile — using the standard matcher vocabulary (`crtr doc write -h`). When it fails, that rule delivers nothing; there is no document-level condition, so one document can choose a different level by node kind with two rules. No `if` means always eligible. Persona prose is just boot-content documents with an `if` (`if: {kind: developer, mode: base}`); guidance that should scale with effort is one predicate (`orchestration.depth: {gte: 2}`), not a mechanism.
|
|
43
43
|
|
|
44
44
|
## Listings and dedup
|
|
45
45
|
|
|
@@ -35,7 +35,7 @@ The frontmatter of a `memory/` file is the **package-file format**, not the `crt
|
|
|
35
35
|
| `unlisted`, `privacy`, `lint-ignore`, `extensions` | the document fields of the same names (a package document is always public and shipped) |
|
|
36
36
|
| `name` | an explicit local name, instead of one derived from the path |
|
|
37
37
|
|
|
38
|
-
Delivery semantics (events, levels, `if`) are the rule model in [[internal/memory-loading]]; `crtr doc write
|
|
38
|
+
Delivery semantics (events, levels, `if`) are the rule model in [[internal/memory-loading]]; `crtr doc write -h` documents the rule JSON the converted rules take. The loader's `lint-ignore` accepts `length`, `broad-memory-read` and `orphan` and records it on the document, but `crtr doc lint` never checks package documents (see the end of this page), so it suppresses nothing there. A file whose frontmatter fails validation blocks install and update.
|
|
39
39
|
|
|
40
40
|
File naming decides the document name: a directory's `INDEX.md` is the document named for the directory (reading it lists the names under it), a package-root `INDEX.md` is `index`, and a leading `NN-` ordering prefix is stripped from every segment (`04-orchestration-kernel.md` is `orchestration-kernel`). Renaming or moving a file changes the document's name, and `[[links]]` to the old name stop resolving.
|
|
41
41
|
|
|
@@ -265,7 +265,7 @@ Standard semver:
|
|
|
265
265
|
|
|
266
266
|
`crtr pkg plugin disable <name>` flips the per-scope config without removing files. A disabled plugin's documents are removed from the canvas: they are not listed and `crtr canvas read <plugin>/<name>` no longer finds them. Re-enable with `crtr pkg plugin enable <name>`.
|
|
267
267
|
|
|
268
|
-
Individual documents inside an enabled plugin are kept out of automatic delivery and listings by giving them no delivery rules plus `unlisted: true` (or a rule whose `if` fails — that suppresses automatic delivery only; an explicit read by name still resolves), not by a command — see `crtr doc write
|
|
268
|
+
Individual documents inside an enabled plugin are kept out of automatic delivery and listings by giving them no delivery rules plus `unlisted: true` (or a rule whose `if` fails — that suppresses automatic delivery only; an explicit read by name still resolves), not by a command — see `crtr doc write -h`.
|
|
269
269
|
|
|
270
270
|
## What goes in a plugin
|
|
271
271
|
|
|
@@ -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
|
|
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
|
|
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{
|
|
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(
|
|
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
|
|
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};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
-- 015-exposures-object-index.sql — an index on `exposures (object)`. One transaction, additions only: `schema_min_reader` is not
|
|
2
|
+
-- touched, so the previous release (version 14) still opens the result. It never names the index, and no statement it runs changes
|
|
3
|
+
-- meaning with it present.
|
|
4
|
+
--
|
|
5
|
+
-- `exposures.object REFERENCES objects(id) ON DELETE CASCADE` had no index leading with `object`: the primary key is
|
|
6
|
+
-- (node, object, channel), so every deleted object made Postgres skip-scan the whole primary key across every node to find the rows
|
|
7
|
+
-- the cascade removes. Measured on the cycle-6 rehearsal database (about 1M rows, 8,512 nodes): 135 ms and 12,174 index searches per
|
|
8
|
+
-- deleted object, growing with the node count; an import rollback deletes about 42.5k objects. `IF NOT EXISTS` because the gate
|
|
9
|
+
-- database already has this index, built by hand under this name.
|
|
10
|
+
CREATE INDEX IF NOT EXISTS exposures_object ON exposures (object);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
2
2
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
3
3
|
* one below the live database's `schema_min_reader`. */
|
|
4
|
-
export declare const CANVAS_SCHEMA_VERSION =
|
|
4
|
+
export declare const CANVAS_SCHEMA_VERSION = 15;
|
|
5
5
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
6
6
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
7
7
|
* it is put in a `search_path` connection option. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=
|
|
1
|
+
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=15;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
|
|
@@ -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
|
|
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
|
|
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};
|
|
@@ -7,6 +7,10 @@ description: Behavior changes in @north-light/sdk that an app must act on, newes
|
|
|
7
7
|
|
|
8
8
|
Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
|
|
9
9
|
|
|
10
|
+
## 0.3.622
|
|
11
|
+
|
|
12
|
+
`oauth.authorizeUrl` takes an optional `loginHint`: a phone number your app already collected, sent as the standard `login_hint`. A signed-out person's sign-in page then shows the number with one "Text me a link" button instead of asking for it (US and Canadian numbers in any format they type; a number the directory cannot text only prefills its form). Nothing is texted until the person presses the button. No existing call changes.
|
|
13
|
+
|
|
10
14
|
## 0.3.613
|
|
11
15
|
|
|
12
16
|
`oauth.appMember('user:<id>')` asks the directory whether that person is on the team that holds your app, for your app's own staff pages. It answers `{member: true, role: 'admin' | 'member'}` or `{member: false}` (an unknown user is `member: false`) by calling `GET /v1/apps/self/members/:user_id` as the app itself, and caches nothing, so someone removed from the team is refused at their next call. A 401 re-mints the directory token once. Nothing existing changes.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.623",
|
|
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.
|
|
148
|
+
"@north-light/identity": "0.3.623",
|
|
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",
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.623",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.623",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
29
29
|
"@milkdown/prose": "^7.22.3",
|
|
30
30
|
"@milkdown/utils": "^7.22.3",
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.623",
|
|
32
32
|
"cron-parser": "^5.6.0",
|
|
33
33
|
"esbuild": "^0.27.7",
|
|
34
34
|
"jose": "^6.2.12",
|
|
@@ -11956,17 +11956,17 @@
|
|
|
11956
11956
|
},
|
|
11957
11957
|
"packages/crouter-api": {
|
|
11958
11958
|
"name": "@north-light/api",
|
|
11959
|
-
"version": "0.3.
|
|
11959
|
+
"version": "0.3.623",
|
|
11960
11960
|
"license": "UNLICENSED"
|
|
11961
11961
|
},
|
|
11962
11962
|
"packages/crouter-env-docker": {
|
|
11963
11963
|
"name": "@north-light/env-docker",
|
|
11964
|
-
"version": "0.3.
|
|
11964
|
+
"version": "0.3.623",
|
|
11965
11965
|
"license": "UNLICENSED"
|
|
11966
11966
|
},
|
|
11967
11967
|
"packages/crouter-identity": {
|
|
11968
11968
|
"name": "@north-light/identity",
|
|
11969
|
-
"version": "0.3.
|
|
11969
|
+
"version": "0.3.623",
|
|
11970
11970
|
"license": "UNLICENSED",
|
|
11971
11971
|
"dependencies": {
|
|
11972
11972
|
"jose": "^6.2.1"
|
|
@@ -11974,21 +11974,21 @@
|
|
|
11974
11974
|
},
|
|
11975
11975
|
"packages/crouter-plugin": {
|
|
11976
11976
|
"name": "@north-light/plugin",
|
|
11977
|
-
"version": "0.3.
|
|
11977
|
+
"version": "0.3.623",
|
|
11978
11978
|
"license": "UNLICENSED",
|
|
11979
11979
|
"dependencies": {
|
|
11980
|
-
"@north-light/api": "0.3.
|
|
11981
|
-
"@north-light/identity": "0.3.
|
|
11980
|
+
"@north-light/api": "0.3.623",
|
|
11981
|
+
"@north-light/identity": "0.3.623"
|
|
11982
11982
|
}
|
|
11983
11983
|
},
|
|
11984
11984
|
"packages/crouter-sdk": {
|
|
11985
11985
|
"name": "@north-light/sdk",
|
|
11986
|
-
"version": "0.3.
|
|
11986
|
+
"version": "0.3.623",
|
|
11987
11987
|
"license": "UNLICENSED",
|
|
11988
11988
|
"dependencies": {
|
|
11989
|
-
"@north-light/api": "0.3.
|
|
11990
|
-
"@north-light/identity": "0.3.
|
|
11991
|
-
"@north-light/plugin": "0.3.
|
|
11989
|
+
"@north-light/api": "0.3.623",
|
|
11990
|
+
"@north-light/identity": "0.3.623",
|
|
11991
|
+
"@north-light/plugin": "0.3.623",
|
|
11992
11992
|
"jose": "^6.2.1"
|
|
11993
11993
|
},
|
|
11994
11994
|
"bin": {
|