@north-light/cli 0.3.678 → 0.3.679

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/api/client.d.ts +0 -8
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/routes.d.ts +0 -2
  4. package/dist/api/routes.js +1 -1
  5. package/dist/clients/attach/viewer.js +2 -2
  6. package/dist/commands/sys.js +1 -1
  7. package/dist/core/graph/objects.d.ts +0 -3
  8. package/dist/core/graph/objects.js +10 -10
  9. package/dist/daemon/api/operations.js +1 -1
  10. package/dist/daemon/api/server.js +1 -1
  11. package/docs/ci-runner.md +1 -1
  12. package/package.json +3 -3
  13. package/packages/crouter-api/dist/api/client.js +0 -7
  14. package/packages/crouter-api/dist/api/routes.js +0 -2
  15. package/packages/crouter-api/dist/clients/attach/viewer.js +1 -1
  16. package/packages/crouter-api/dist/commands/node-context.js +1 -1
  17. package/packages/crouter-api/dist/commands/sys.js +1 -2
  18. package/packages/crouter-api/dist/core/graph/objects.js +0 -15
  19. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +1 -1
  20. package/packages/crouter-api/dist/daemon/api/operations.js +0 -2
  21. package/packages/crouter-api/package.json +1 -1
  22. package/packages/crouter-identity/package.json +1 -1
  23. package/packages/crouter-plugin/package.json +3 -3
  24. package/runtime.lock.json +14 -14
  25. package/scripts/sandbox-bootstrap.sh +8 -4
  26. package/dist/api/dto/repo-import.d.ts +0 -25
  27. package/dist/api/dto/repo-import.js +0 -0
  28. package/dist/commands/sys/repo-docs.d.ts +0 -1
  29. package/dist/commands/sys/repo-docs.js +0 -2
  30. package/dist/core/graph/repo-sync/exchange.d.ts +0 -25
  31. package/dist/core/graph/repo-sync/exchange.js +0 -1
  32. package/dist/core/graph/repo-sync/ref-format.d.ts +0 -51
  33. package/dist/core/graph/repo-sync/ref-format.js +0 -1
  34. package/dist/daemon/api/handlers/repo-import.d.ts +0 -2
  35. package/dist/daemon/api/handlers/repo-import.js +0 -2
  36. package/packages/crouter-api/dist/api/dto/repo-import.js +0 -5
  37. package/packages/crouter-api/dist/commands/sys/repo-docs.js +0 -96
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.678",
3
+ "version": "0.3.679",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.678",
9
+ "version": "0.3.679",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
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.678",
32
- "@north-light/plugin": "0.3.678",
31
+ "@north-light/identity": "0.3.679",
32
+ "@north-light/plugin": "0.3.679",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -10667,17 +10667,17 @@
10667
10667
  },
10668
10668
  "packages/crouter-api": {
10669
10669
  "name": "@north-light/api",
10670
- "version": "0.3.678",
10670
+ "version": "0.3.679",
10671
10671
  "license": "UNLICENSED"
10672
10672
  },
10673
10673
  "packages/crouter-env-docker": {
10674
10674
  "name": "@north-light/env-docker",
10675
- "version": "0.3.678",
10675
+ "version": "0.3.679",
10676
10676
  "license": "UNLICENSED"
10677
10677
  },
10678
10678
  "packages/crouter-identity": {
10679
10679
  "name": "@north-light/identity",
10680
- "version": "0.3.678",
10680
+ "version": "0.3.679",
10681
10681
  "license": "UNLICENSED",
10682
10682
  "dependencies": {
10683
10683
  "jose": "^6.2.1"
@@ -10685,21 +10685,21 @@
10685
10685
  },
10686
10686
  "packages/crouter-plugin": {
10687
10687
  "name": "@north-light/plugin",
10688
- "version": "0.3.678",
10688
+ "version": "0.3.679",
10689
10689
  "license": "UNLICENSED",
10690
10690
  "dependencies": {
10691
- "@north-light/api": "0.3.678",
10692
- "@north-light/identity": "0.3.678"
10691
+ "@north-light/api": "0.3.679",
10692
+ "@north-light/identity": "0.3.679"
10693
10693
  }
10694
10694
  },
10695
10695
  "packages/crouter-sdk": {
10696
10696
  "name": "@north-light/sdk",
10697
- "version": "0.3.678",
10697
+ "version": "0.3.679",
10698
10698
  "license": "UNLICENSED",
10699
10699
  "dependencies": {
10700
- "@north-light/api": "0.3.678",
10701
- "@north-light/identity": "0.3.678",
10702
- "@north-light/plugin": "0.3.678",
10700
+ "@north-light/api": "0.3.679",
10701
+ "@north-light/identity": "0.3.679",
10702
+ "@north-light/plugin": "0.3.679",
10703
10703
  "jose": "^6.2.1"
10704
10704
  },
10705
10705
  "bin": {
@@ -41,10 +41,14 @@ if ! id "$RUN_USER" >/dev/null 2>&1; then
41
41
  fi
42
42
  mkdir -p /run/crtr /var/lib/crtr /work "$RELEASES"
43
43
  chown "$RUN_USER" /run/crtr /var/lib/crtr /work
44
- # Blaxel unpacks an image into a read-only layer that does not keep file ownership: everything the release image chowned to `crtr` at build
45
- # (`/work/.crtr`, the home) is root-owned in the sandbox, and the start script, running as `crtr`, could not write `/work/.crtr/plugins-revision`.
46
- # These are the small trees the image creates; they are handed over here on every boot.
47
- for dir in /work/.crtr "/home/$RUN_USER"; do [ ! -e "$dir" ] || chown -R "$RUN_USER" "$dir"; done
44
+ # Blaxel's image conversion makes every file of a built image root-owned whatever the Dockerfile chowns, so git would refuse /work ("dubious ownership")
45
+ # and `crtr` could not write node_modules, its home or the Postgres data directory. Hand the trees over here, still as root, once per sandbox
46
+ # (the marker is in the sandbox's own filesystem, so a later start skips the recursive chown).
47
+ if [ ! -e "$ROOT/.owned" ]; then
48
+ for dir in /work "/home/$RUN_USER" /var/lib/crtr; do [ ! -e "$dir" ] || chown -R "$RUN_USER:$RUN_USER" "$dir"; done
49
+ if id postgres >/dev/null 2>&1 && [ -d /var/lib/postgresql ]; then chown -R postgres /var/lib/postgresql; fi
50
+ mkdir -p "$ROOT" && : > "$ROOT/.owned"
51
+ fi
48
52
  # pi's grep tool wants ripgrep; the release image has it, and installing it once per sandbox avoids a GitHub download at the first grep.
49
53
  rg=present
50
54
  if ! command -v rg >/dev/null 2>&1; then
@@ -1,25 +0,0 @@
1
- export interface RepoImportRequest {
2
- /** `docs/<id>.json` → file text, as read from the ref. */
3
- tree: Record<string, string>;
4
- /** Legacy markdown files: `name` is the path under the legacy dir without `.md`; `text` the whole file. */
5
- legacy?: Array<{
6
- name: string;
7
- text: string;
8
- }>;
9
- }
10
- export interface RepoImportDTO {
11
- repo: string;
12
- created: number;
13
- revisions: number;
14
- deleted: number;
15
- needs_merge: string[];
16
- refused: Array<{
17
- path: string;
18
- reason: string;
19
- }>;
20
- legacy_imported: string[];
21
- legacy_skipped: Array<{
22
- name: string;
23
- reason: string;
24
- }>;
25
- }
File without changes
@@ -1 +0,0 @@
1
- export declare const sysRepoDocsBranch: import("../../core/command.js").BranchDef;
@@ -1,2 +0,0 @@
1
- var u=Object.defineProperty;var n=(e,r)=>u(e,"name",{value:r,configurable:!0});import{execFileSync as g}from"node:child_process";import{readdirSync as y,readFileSync as w,statSync as $}from"node:fs";import{join as S,relative as k}from"node:path";import{defineBranch as v,defineLeaf as p}from"../../core/command.js";import{general as j,usage as b}from"../../core/errors.js";import{cliClient as m,rethrowAsCliError as l}from"../api-client.js";const f="refs/crtr/docs",d=n((e,r)=>g("git",r,{cwd:e,encoding:"utf8",maxBuffer:512*1024*1024,stdio:["ignore","pipe","pipe"]}),"git");function h(e,r=[]){for(const i of y(e)){const o=S(e,i);$(o).isDirectory()?h(o,r):i.endsWith(".md")&&r.push(o)}return r}n(h,"walk");const q=p({name:"import",tier:"hidden",description:"one-time: upload refs/crtr/docs (and legacy files) into a repo object",help:{name:"sys repo-docs import",summary:"fetch `refs/crtr/docs` from this checkout's origin and upload it into the repo object, keeping document ids and revision history",params:[{kind:"flag",name:"repo",type:"string",required:!0,constraint:"The repo object handle to import into (you need edit on it)."},{kind:"flag",name:"legacy-dir",type:"string",required:!1,constraint:"A directory of legacy markdown files (e.g. the old memory folder); files whose name is neither on the ref nor in the canvas are uploaded too."}],output:[{name:"summary",type:"string",required:!0,constraint:"Counts of what landed and what was refused."}],outputKind:"object",effects:["Runs `git fetch origin refs/crtr/docs` in the current directory, posts the tree to `POST /v1/repos/:repo/import`; re-running changes nothing already imported."]},run:n(async e=>{const r=typeof e.repo=="string"?e.repo:"";if(r==="")throw b("--repo <handle> is required");const i=process.cwd();try{d(i,["fetch","--quiet","origin",`+${f}:refs/crtr/import-tip`])}catch(t){throw j(`could not fetch ${f} from origin: ${t.message.slice(0,300)}`)}const o={};for(const t of d(i,["ls-tree","-r","--name-only","refs/crtr/import-tip"]).split(`
2
- `).filter(c=>c.startsWith("docs/")&&c.endsWith(".json")))o[t]=d(i,["show",`refs/crtr/import-tip:${t}`]);const s=typeof e.legacyDir=="string"?e.legacyDir:void 0,a=s===void 0?void 0:h(s).map(t=>({name:k(s,t).replace(/\.md$/,"").replace(/\/INDEX$/,"/index"),text:w(t,"utf8")}));try{return{...await m().importRepoDocs(r,{tree:o,...a!==void 0?{legacy:a}:{}}),files:Object.keys(o).length}}catch(t){l(t)}},"run"),render:n(e=>`<repo-docs-import repo="${String(e.repo)}" files="${String(e.files)}" created="${String(e.created)}" revisions="${String(e.revisions)}" deleted="${String(e.deleted)}" refused="${e.refused.length}" legacy-imported="${e.legacy_imported.length}" legacy-skipped="${e.legacy_skipped.length}">${JSON.stringify({refused:e.refused,legacy_skipped:e.legacy_skipped})}</repo-docs-import>`,"render")}),D=p({name:"rename",tier:"hidden",description:"one-time: change a repo object's handle",help:{name:"sys repo-docs rename",summary:"give the repo object `<old>` the handle `<new>`; its id and documents are unchanged",params:[{kind:"positional",name:"old",required:!0,constraint:"The current repo handle."},{kind:"positional",name:"new",required:!0,constraint:"The new handle; refused when another live repo holds it."}],output:[{name:"id",type:"string",required:!0,constraint:"The repo object id."},{name:"name",type:"string",required:!0,constraint:"Its handle now."}],outputKind:"object",effects:["Renames the repo object. Links are edges to ids, so they keep resolving."]},run:n(async e=>{try{return{...await m().renameRepo(String(e.old),String(e.new))}}catch(r){l(r)}},"run"),render:n(e=>`<repo id="${String(e.id)}" name="${String(e.name)}" renamed="${String(e.renamed)}"/>`,"render")}),E=v({name:"repo-docs",tier:"hidden",description:"one-time repo-document cutover",whenToUse:"the production cutover of repo documents from the git ref into the canvas",help:{name:"sys repo-docs",summary:"import `refs/crtr/docs` into a repo object, or rename a repo handle (removed after the cutover)",model:"Hidden, temporary commands."},children:[q,D]});export{E as sysRepoDocsBranch};
@@ -1,25 +0,0 @@
1
- import type { ReposFn } from '../reader.js';
2
- import type { ObjectRow } from '../types.js';
3
- import { type CanvasDb } from '../../canvas/db.js';
4
- export interface ImportResult {
5
- created: number;
6
- revisions: number;
7
- deleted: number;
8
- needsMerge: string[];
9
- refused: Array<{
10
- path: string;
11
- reason: string;
12
- }>;
13
- }
14
- /**
15
- * Apply the difference between two trees (the one last imported and the new one) to the
16
- * repo's documents, in one transaction. Per changed file: a file that does not parse, is not
17
- * public, or names an id held by an object outside this repo is refused and reported; a new
18
- * document is created with its id; arriving revisions are added (author NULL); changed record
19
- * fields and a rename are applied; a tombstone or a removed file deletes. Each document
20
- * publishes once: `created`, `edited` (with `heads` and `needs_merge`) or `deleted`. A
21
- * document that fails is rolled back alone and reported in `refused`.
22
- */
23
- export declare function importTree(db: CanvasDb, repo: ObjectRow, before: Map<string, string>, after: Map<string, string>, reposFn?: ReposFn): Promise<ImportResult>;
24
- /** Whether any link target in a serialized ref file is one of `arrived`. */
25
- export declare function namesArrived(text: string, arrived: ReadonlySet<string>): boolean;
@@ -1 +0,0 @@
1
- var A=Object.defineProperty;var m=(t,n)=>A(t,"name",{value:n,configurable:!0});import{put as $}from"../bodies.js";import{setLinks as j,setUnresolved as M}from"../edges.js";import{collectUnlinked as U,deleteDocument as x,documentRecord as H,heads as D,importDocument as L,insertImportedRevisions as W,moveDocument as J,restoreDocument as P,setDocumentRecord as B}from"../documents.js";import{CrtrError as z}from"../../errors.js";import{publish as O}from"../events.js";import{getById as v,setObjectKind as G}from"../objects.js";import{parseDoc as k}from"./ref-format.js";import{withCanvasWrite as I}from"../../canvas/db.js";import{mapAsync as K}from"../../async-array.js";function V(t){if(t.type!=="repo")throw new Error(`${t.type} ${t.id} is not a repo object`)}m(V,"assertRepoRefSpace");function q(t){return[...t].sort((n,a)=>n.position-a.position).map(n=>({on:n.on,deliver:n.deliver,...n.match!==null&&n.match!==void 0?{match:n.match}:{},...n.match_frontmatter!==null&&n.match_frontmatter!==void 0?{matchFrontmatter:n.match_frontmatter}:{},...n.if!==null&&n.if!==void 0?{if:n.if}:{}}))}m(q,"toRuleSpecs");const Q=m((t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null),"same");function N(t,n){const a={},i=m(p=>!t||!Q(t[p],n[p]),"differs");return i("preview")&&(a.preview=n.preview),i("summary")&&(a.summary=n.summary),i("why_it_exists")&&(a.whyItExists=n.why_it_exists),i("unlisted")&&(a.unlisted=n.unlisted),i("lint_ignore")&&(a.lintIgnore=n.lint_ignore),i("extensions")&&(a.extensions=n.extensions),i("rules")&&(a.rules=q(n.rules)),a}m(N,"changedFields");async function me(t,n,a,i,p){V(n);const c={created:0,revisions:0,deleted:0,needsMerge:[],refused:[]},l=[];for(const[r,s]of i){if(a.get(r)===s)continue;const e=k(r,s);if(!e.ok){c.refused.push({path:r,reason:e.reason});continue}const f=a.has(r)?k(r,a.get(r)):null;l.push({path:r,prior:f?.ok?f.doc:null,doc:e.doc})}for(const[r,s]of a){if(i.has(r))continue;const e=k(r,s);e.ok&&l.push({path:r,prior:e.doc,doc:null,priorId:e.doc.id})}const _=[];return await I(async()=>{for(const s of l)for(const e of s.doc?.revisions??[])await $(t,e.body,e.body_hash);let r=l;for(;;){const s=[];for(const e of r){const f={created:0,revisions:0,deleted:0,needsMerge:[],refused:[]};try{const u=[];await I(async()=>await ee(t,n,e.prior,e.doc,e.priorId??e.doc.id,f,p,u),{savepoint:!0}),_.push(...u),c.created+=f.created,c.revisions+=f.revisions,c.deleted+=f.deleted,c.needsMerge.push(...f.needsMerge)}catch(u){b(u)?s.push({w:e,error:u}):c.refused.push({path:e.path,reason:u.message})}}if(s.length===0)break;if(s.length===r.length){for(const e of s)c.refused.push({path:e.w.path,reason:e.error.message});break}r=s.map(e=>e.w)}await X(t,i,new Set(_),new Set(l.map(s=>s.path)))},{savepoint:!0}),c}m(me,"importTree");async function X(t,n,a,i){if(a.size===0)return;const p=t.prepare("INSERT INTO edges (type, src, dst, written_as, created_at) VALUES ('links-to', ?, ?, ?, ?) ON CONFLICT DO NOTHING"),c=new Date().toISOString();for(const[l,_]of n){if(!i.has(l)&&!Z(_,a))continue;const r=k(l,_);if(!r.ok||r.doc.deleted_at)continue;const s=await v(t,r.doc.id);if(!s||s.type!=="document"||s.deleted_at)continue;const e=(await D(t,s))[0],f=r.doc.revisions.find(u=>u.rev_id===e?.rev_id)?.links??[];for(const u of f){const h=await v(t,u.dst);h&&h.id!==s.id&&await p.run(s.id,h.id,u.written_as,c)}}}m(X,"completeLinks");const Y=/"dst":\s*"((?:[^"\\]|\\.)*)"/g;function Z(t,n){for(const a of t.matchAll(Y))if(n.has(F(a[1])))return!0;return!1}m(Z,"namesArrived");function F(t){if(!t.includes("\\"))return t;try{return JSON.parse(`"${t}"`)}catch{return t}}m(F,"decodeJsonString");function b(t){return t instanceof z&&t.code==="conflict"&&t.details?.holder!==void 0}m(b,"isNameConflict");async function ee(t,n,a,i,p,c,l,_){const r=await v(t,p);if(r&&(r.type!=="document"||r.owner!==n.id))throw new Error(`id ${p} is held by ${r.type} ${r.name} outside ${n.name}`);if(!i){r&&!r.deleted_at&&(await x(t,null,r,l),c.deleted++);return}const s=t.prepare("SELECT count(*) AS n FROM revisions WHERE document = ?");let e,f=!1,u=!1,h=0,y=0;if(r){e=r,h=(await H(t,e)).revision,e.created_at!==i.created_at&&(await t.prepare("UPDATE objects SET created_at = ? WHERE id = ?").run(i.created_at,e.id),e=await v(t,e.id));const o=i.kind;(a?a.kind!==o:e.kind!==o)&&await G(t,e,o),u=!!e.deleted_at&&i.deleted_at===null&&(a===null||a.deleted_at!=null);let d=N(u?null:a,i);if(i.deleted_at&&e.deleted_at){const{rules:g,...E}=d;d=E}u&&(e=await P(t,e,i.name,l),_?.push(e.id)),Object.keys(d).length>0&&(e=await B(t,null,e,d)),i.name!==e.name&&!e.deleted_at&&(e=await J(t,null,e,{name:i.name},l))}else{const d=i.revisions.filter(g=>g.parents.length===0).sort((g,E)=>g.number-E.number||g.rev_id.localeCompare(E.rev_id))[0];if(!d)throw new Error(`${i.name}: no root revision`);e=await L(t,{id:i.id,owner:n,name:i.name,kind:i.kind,preview:i.preview,privacy:"public",...N(null,i),revisions:[{rev_id:d.rev_id,body_hash:d.body_hash,author:null,rationale:d.rationale,created_at:d.created_at}]},l),e.created_at!==i.created_at&&(await t.prepare("UPDATE objects SET created_at = ? WHERE id = ?").run(i.created_at,e.id),e=await v(t,e.id)),f=!0,_?.push(e.id),y=1}const C=(await s.get(e.id)).n,{headCount:S}=await W(t,e,i.revisions.map(o=>({rev_id:o.rev_id,parents:o.parents,body_hash:o.body_hash,rationale:o.rationale,created_at:o.created_at})));y+=(await s.get(e.id)).n-C,c.revisions+=y;const w=(await D(t,e))[0],R=new Map(i.revisions.map(o=>[o.rev_id,o]));if(y>0||u){const o=(await K(R.get(w.rev_id)?.links??[],async d=>({written_as:d.written_as,dst:await v(t,d.dst)}))).filter(d=>d.dst!==null);await U(t,await j(t,e,o),l),await M(t,e,[])}if(S>1&&c.needsMerge.push(e.id),i.deleted_at&&!e.deleted_at){await x(t,null,e,l,i.deleted_at),c.deleted++;return}if(i.deleted_at&&e.deleted_at&&e.deleted_at!==i.deleted_at&&await t.prepare("UPDATE objects SET deleted_at = ? WHERE id = ?").run(i.deleted_at,e.id),f){c.created++,await O(t,{event:"created",object:e,actor:null,attrs:{revision:w.number},pointer:w.rev_id},l);return}if(u){c.created++,await O(t,{event:"created",object:e,actor:null,attrs:{revision:w.number},pointer:w.rev_id},l);return}if(y===0)return;const T=i.revisions.filter(o=>!a?.revisions.some(d=>d.rev_id===o.rev_id)).sort((o,d)=>d.number-o.number||d.created_at.localeCompare(o.created_at))[0]??R.get(w.rev_id);await O(t,{event:"edited",object:e,actor:null,pointer:w.rev_id,attrs:{revision:w.number,from_revision:h,rationale:T?.rationale??null,author:T?.author??null,heads:S,needs_merge:S>1}},l)}m(ee,"importOne");export{me as importTree,Z as namesArrived};
@@ -1,51 +0,0 @@
1
- import type { RuleOn } from '../types.js';
2
- export interface RefRule {
3
- position: number;
4
- on: RuleOn;
5
- match: unknown;
6
- match_frontmatter: unknown;
7
- if: unknown;
8
- deliver: 'name' | 'preview' | 'content';
9
- }
10
- export interface RefRevision {
11
- rev_id: string;
12
- number: number;
13
- parents: string[];
14
- body: string;
15
- body_hash: string;
16
- /** Object id of the author on the runtime that wrote it; null when unknown. */
17
- author: string | null;
18
- rationale: string | null;
19
- created_at: string;
20
- links: Array<{
21
- written_as: string;
22
- dst: string;
23
- }>;
24
- }
25
- export interface RefDocument {
26
- id: string;
27
- name: string;
28
- kind: string;
29
- privacy: 'public';
30
- preview: string;
31
- summary: string | null;
32
- why_it_exists: string | null;
33
- unlisted: boolean;
34
- lint_ignore: unknown;
35
- extensions: unknown;
36
- created_at: string;
37
- deleted_at: string | null;
38
- rules: RefRule[];
39
- revisions: RefRevision[];
40
- }
41
- export declare const docPath: (id: string) => string;
42
- /** Parse one ref file. Refuses anything not public, a body whose hash disagrees, or an id that is not the file name.
43
- * Each body is checked against the hash it arrived with, then held as `canonical` makes it (NUL → U+FFFD, hash of that text), so every consumer of a
44
- * parsed file — prior export, import, merge — sees the one representation the database stores. */
45
- export declare function parseDoc(path: string, text: string): {
46
- ok: true;
47
- doc: RefDocument;
48
- } | {
49
- ok: false;
50
- reason: string;
51
- };
@@ -1 +0,0 @@
1
- var y=Object.defineProperty;var a=(o,t)=>y(o,"name",{value:t,configurable:!0});import{canonical as u,hashOf as p}from"../bodies.js";const h=a(o=>`docs/${o}.json`,"docPath"),m=new Set(["boot","workspace-open","file-read","document-read","command","pre-command","slash-command"]),b=new Set(["name","preview","content"]),s=a(o=>typeof o=="string","isStr"),i=a(o=>o===null||typeof o=="string","isStrOrNull");function _(o,t){let n;try{n=JSON.parse(t)}catch(e){return{ok:!1,reason:`not JSON: ${e.message}`}}if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,reason:"not an object"};const r=n;if(r.privacy!=="public")return{ok:!1,reason:`privacy is ${String(r.privacy)}; a repo holds only public documents`};if(!s(r.id)||h(r.id)!==o)return{ok:!1,reason:`id ${String(r.id)} does not match file ${o}`};for(const e of["name","kind","preview","created_at"])if(!s(r[e]))return{ok:!1,reason:`${e} is not a string`};for(const e of["summary","why_it_exists","deleted_at"])if(!i(r[e]))return{ok:!1,reason:`${e} is not a string or null`};if(typeof r.unlisted!="boolean")return{ok:!1,reason:"unlisted is not a boolean"};if(!Array.isArray(r.rules))return{ok:!1,reason:"rules is not an array"};for(const e of r.rules)if(!e||typeof e.position!="number"||!m.has(e.on)||!b.has(e.deliver))return{ok:!1,reason:"malformed rule"};if(!Array.isArray(r.revisions)||r.revisions.length===0)return{ok:!1,reason:"no revisions"};const d=new Set;for(const e of r.revisions){if(!e||!s(e.rev_id)||typeof e.number!="number"||!s(e.body)||!s(e.body_hash)||!s(e.created_at)||!i(e.author)||!i(e.rationale)||!Array.isArray(e.parents)||!e.parents.every(s)||!Array.isArray(e.links))return{ok:!1,reason:"malformed revision"};if(d.has(e.rev_id))return{ok:!1,reason:`revision ${e.rev_id} appears twice`};if(d.add(e.rev_id),p(e.body)!==e.body_hash)return{ok:!1,reason:`revision ${e.rev_id} body does not match body_hash`}}const l=r.revisions.map(e=>{const{text:f,hash:c}=u(e.body,e.body_hash);return f===e.body?e:{...e,body:f,body_hash:c}});return{ok:!0,doc:{...r,revisions:l}}}a(_,"parseDoc");export{h as docPath,_ as parseDoc};
@@ -1,2 +0,0 @@
1
- import type { RouteTable } from '../router.js';
2
- export declare const repoImportRoutes: RouteTable;
@@ -1,2 +0,0 @@
1
- var N=Object.defineProperty;var l=(e,o)=>N(e,"name",{value:o,configurable:!0});import{randomUUID as b}from"node:crypto";import{ApiError as s}from"../../../api/errors.js";import{withCanvasWrite as v}from"../../../core/canvas/db.js";import{parseFrontmatterGeneric as I}from"../../../core/frontmatter.js";import{importTree as L}from"../../../core/graph/repo-sync/exchange.js";import{parseDoc as D}from"../../../core/graph/repo-sync/ref-format.js";import{check as g}from"../../../core/permissions/evaluator.js";import{documentFields as O}from"../../../migrations/004-canvas-documents/fields.js";import{hashOf as R}from"../../../core/graph/bodies.js";import{renameRepoObject as k}from"../../../core/graph/objects.js";import{asApiError as $}from"./schemas.js";import{readerFor as E}from"../reader.js";const U=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;async function j(e){if(e.principal.class!=="person")throw new s(403,"forbidden","the import is run by the person");const o=e.body;if(!o||typeof o.tree!="object"||o.tree===null)throw new s(400,"invalid_request","`tree` must map file paths to text");const i=decodeURIComponent(e.params.repo);return await v(async r=>{const a=await r.prepare("SELECT * FROM objects WHERE type = 'repo' AND name = ? AND deleted_at IS NULL AND home_machine IS NULL").get(i);if(!a)throw new s(404,"not_found",`no repo named '${i}'`);const f=await E(r,e);if(!await g(r,f,"edit",a.id))throw new s(403,"forbidden",`you may not edit repo ${i}`);const u=new Map(Object.entries(o.tree)),h=new Set;for(const[t,m]of u){const n=D(t,m);n.ok&&h.add(n.doc.name)}for(const t of await r.prepare("SELECT name FROM objects WHERE type = 'document' AND owner = ?").all(a.id))h.add(t.name);const y=[],d=[];for(const t of o.legacy??[]){if(!U.test(t.name)){d.push({name:t.name,reason:"not a valid document name"});continue}if(h.has(t.name)){d.push({name:t.name,reason:"already on the ref or in the canvas"});continue}let m;try{m=I(t.text)}catch(p){d.push({name:t.name,reason:`unreadable frontmatter: ${p.message}`});continue}const n=O(m.data,m.body,{missingPrivacy:"public"});if(n.privacy!=="public"){d.push({name:t.name,reason:"private; a repo holds only public documents"});continue}const w=new Date().toISOString(),_=b(),A={id:_,name:t.name,kind:n.kind==="preference"?"preference":"knowledge",privacy:"public",preview:n.preview,summary:n.summary,why_it_exists:n.whyItExists,unlisted:n.unlisted,lint_ignore:n.lintIgnore,extensions:n.extensions,created_at:w,deleted_at:null,rules:n.rules.map((p,S)=>({position:S,on:p.on,match:p.match??null,match_frontmatter:p.matchFrontmatter??null,if:p.if??null,deliver:p.deliver})),revisions:[{rev_id:b(),number:1,parents:[],body:m.body,body_hash:R(m.body),author:null,rationale:"imported from legacy files",created_at:w,links:[]}]};u.set(`docs/${_}.json`,`${JSON.stringify(A)}
2
- `),y.push(t.name)}const c=await L(r,a,new Map,u);return{repo:a.id,created:c.created,revisions:c.revisions,deleted:c.deleted,needs_merge:c.needsMerge,refused:c.refused,legacy_imported:y,legacy_skipped:d}})}l(j,"run");async function F(e){if(e.principal.class!=="person")throw new s(403,"forbidden","the rename is run by the person");const o=e.body?.to;if(typeof o!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(o))throw new s(400,"invalid_request","`to` must be a handle");const i=decodeURIComponent(e.params.repo);try{return await v(async r=>{const a=await r.prepare("SELECT * FROM objects WHERE type = 'repo' AND name = ? AND deleted_at IS NULL AND home_machine IS NULL").get(i);if(!a)throw new s(404,"not_found",`no repo named '${i}'`);if(!await g(r,await E(r,e),"share",a.id))throw new s(403,"forbidden",`only the owner of repo ${i} may rename it`);const f=await k(r,i,o);return{id:a.id,name:o,renamed:f}})}catch(r){throw $(r)}}l(F,"rename");const K=[{method:"POST",pattern:"/v1/repos/:repo/rename",handler:l(async e=>({status:200,body:await F(e)}),"handler")},{method:"POST",pattern:"/v1/repos/:repo/import",maxBodyBytes:256*1024*1024,handler:l(async e=>({status:200,body:await j(e)}),"handler")}];export{K as repoImportRoutes};
@@ -1,5 +0,0 @@
1
- // `POST /v1/repos/:repo/import` — the one-time upload of a repo's `refs/crtr/docs` tree (and, optionally, legacy
2
- // legacy markdown files) into its repo object. Removed after the production cutover.
3
- //
4
- // PURITY (spec §3.1): Node built-ins + `src/api/*` only.
5
- export {};
@@ -1,96 +0,0 @@
1
- // Hidden one-time cutover commands: `crtr sys repo-docs import|rename`. Removed after the production cutover.
2
- import { execFileSync } from 'node:child_process';
3
- import { readdirSync, readFileSync, statSync } from 'node:fs';
4
- import { join, relative } from 'node:path';
5
- import { defineBranch, defineLeaf } from '../../core/command.js';
6
- import { general, usage } from '../../core/errors.js';
7
- import { cliClient, rethrowAsCliError } from '../api-client.js';
8
- const REF = 'refs/crtr/docs';
9
- const git = (cwd, args) => execFileSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
10
- function walk(dir, out = []) {
11
- for (const e of readdirSync(dir)) {
12
- const p = join(dir, e);
13
- if (statSync(p).isDirectory())
14
- walk(p, out);
15
- else if (e.endsWith('.md'))
16
- out.push(p);
17
- }
18
- return out;
19
- }
20
- const importLeaf = defineLeaf({
21
- name: 'import',
22
- tier: 'hidden',
23
- description: 'one-time: upload refs/crtr/docs (and legacy files) into a repo object',
24
- help: {
25
- name: 'sys repo-docs import',
26
- summary: 'fetch `refs/crtr/docs` from this checkout\'s origin and upload it into the repo object, keeping document ids and revision history',
27
- params: [
28
- { kind: 'flag', name: 'repo', type: 'string', required: true, constraint: 'The repo object handle to import into (you need edit on it).' },
29
- { kind: 'flag', name: 'legacy-dir', type: 'string', required: false, constraint: 'A directory of legacy markdown files (e.g. the old memory folder); files whose name is neither on the ref nor in the canvas are uploaded too.' },
30
- ],
31
- output: [{ name: 'summary', type: 'string', required: true, constraint: 'Counts of what landed and what was refused.' }],
32
- outputKind: 'object',
33
- effects: ['Runs `git fetch origin refs/crtr/docs` in the current directory, posts the tree to `POST /v1/repos/:repo/import`; re-running changes nothing already imported.'],
34
- },
35
- run: async (input) => {
36
- const repo = typeof input['repo'] === 'string' ? input['repo'] : '';
37
- if (repo === '')
38
- throw usage('--repo <handle> is required');
39
- const cwd = process.cwd();
40
- try {
41
- git(cwd, ['fetch', '--quiet', 'origin', `+${REF}:refs/crtr/import-tip`]);
42
- }
43
- catch (e) {
44
- throw general(`could not fetch ${REF} from origin: ${e.message.slice(0, 300)}`);
45
- }
46
- const tree = {};
47
- for (const path of git(cwd, ['ls-tree', '-r', '--name-only', 'refs/crtr/import-tip']).split('\n').filter((p) => p.startsWith('docs/') && p.endsWith('.json'))) {
48
- tree[path] = git(cwd, ['show', `refs/crtr/import-tip:${path}`]);
49
- }
50
- const legacyDir = typeof input['legacyDir'] === 'string' ? input['legacyDir'] : undefined;
51
- const legacy = legacyDir === undefined ? undefined : walk(legacyDir).map((p) => ({
52
- name: relative(legacyDir, p).replace(/\.md$/, '').replace(/\/INDEX$/, '/index'), text: readFileSync(p, 'utf8'),
53
- }));
54
- try {
55
- const r = await cliClient().importRepoDocs(repo, { tree, ...(legacy !== undefined ? { legacy } : {}) });
56
- return { ...r, files: Object.keys(tree).length };
57
- }
58
- catch (err) {
59
- rethrowAsCliError(err);
60
- }
61
- },
62
- render: (r) => `<repo-docs-import repo="${String(r['repo'])}" files="${String(r['files'])}" created="${String(r['created'])}" revisions="${String(r['revisions'])}" deleted="${String(r['deleted'])}" refused="${r['refused'].length}" legacy-imported="${r['legacy_imported'].length}" legacy-skipped="${r['legacy_skipped'].length}">${JSON.stringify({ refused: r['refused'], legacy_skipped: r['legacy_skipped'] })}</repo-docs-import>`,
63
- });
64
- const renameLeaf = defineLeaf({
65
- name: 'rename',
66
- tier: 'hidden',
67
- description: 'one-time: change a repo object\'s handle',
68
- help: {
69
- name: 'sys repo-docs rename',
70
- summary: 'give the repo object `<old>` the handle `<new>`; its id and documents are unchanged',
71
- params: [
72
- { kind: 'positional', name: 'old', required: true, constraint: 'The current repo handle.' },
73
- { kind: 'positional', name: 'new', required: true, constraint: 'The new handle; refused when another live repo holds it.' },
74
- ],
75
- output: [{ name: 'id', type: 'string', required: true, constraint: 'The repo object id.' }, { name: 'name', type: 'string', required: true, constraint: 'Its handle now.' }],
76
- outputKind: 'object',
77
- effects: ['Renames the repo object. Links are edges to ids, so they keep resolving.'],
78
- },
79
- run: async (input) => {
80
- try {
81
- return { ...await cliClient().renameRepo(String(input['old']), String(input['new'])) };
82
- }
83
- catch (err) {
84
- rethrowAsCliError(err);
85
- }
86
- },
87
- render: (r) => `<repo id="${String(r['id'])}" name="${String(r['name'])}" renamed="${String(r['renamed'])}"/>`,
88
- });
89
- export const sysRepoDocsBranch = defineBranch({
90
- name: 'repo-docs',
91
- tier: 'hidden',
92
- description: 'one-time repo-document cutover',
93
- whenToUse: 'the production cutover of repo documents from the git ref into the canvas',
94
- help: { name: 'sys repo-docs', summary: 'import `refs/crtr/docs` into a repo object, or rename a repo handle (removed after the cutover)', model: 'Hidden, temporary commands.' },
95
- children: [importLeaf, renameLeaf],
96
- });