@north-light/cli 0.3.753 → 0.3.754
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/bin/runtime-generation-manifest.mjs +3 -10
- package/dist/commands/sys/doctor.js +1 -1
- package/dist/commands/sys/signin.js +2 -3
- package/dist/commands/sys/update.js +1 -1
- package/dist/core/auto-update.js +4 -4
- package/dist/core/import/load/prepare.d.ts +3 -0
- package/dist/core/import/load/prepare.js +12 -12
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/self-update.d.ts +1 -4
- package/dist/core/self-update.js +1 -1
- package/package.json +3 -4
- package/packages/crouter-api/dist/commands/sys/doctor.js +0 -9
- package/packages/crouter-api/dist/commands/sys/signin.js +0 -4
- package/packages/crouter-api/dist/commands/sys/update.js +1 -2
- package/packages/crouter-api/dist/core/import/load/prepare.js +6 -0
- package/packages/crouter-api/dist/core/self-update.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/install-runtime.mjs +2 -2
- package/scripts/self-update.mjs +14 -5
- package/dist/commands/sys/old-package.d.ts +0 -9
- package/dist/commands/sys/old-package.js +0 -1
- package/packages/crouter-api/dist/commands/sys/old-package.js +0 -20
- package/scripts/lib/update-target.mjs +0 -78
|
@@ -11,18 +11,11 @@ export function runtimeHome() {
|
|
|
11
11
|
export const GENERATION_ID = /^[a-f0-9]{64}$/;
|
|
12
12
|
export const MANIFEST_SCHEMA = 1;
|
|
13
13
|
export const PACKAGE_NAME = '@north-light/cli';
|
|
14
|
-
/**
|
|
15
|
-
*
|
|
16
|
-
* `@crouter/cli` keeps its own copy of this file as its launch shim, and that
|
|
17
|
-
* shim refuses a generation whose manifest names a package it does not know.
|
|
18
|
-
* Recording the old name lets an install that moved to `@north-light/cli` keep
|
|
19
|
-
* launching through the shim it already has. */
|
|
20
|
-
export const GENERATION_PACKAGE_NAME = '@crouter/cli';
|
|
21
|
-
/** Names earlier releases recorded in a generation manifest. A generation installed
|
|
22
|
-
* before the rename is still valid, so the selector accepts these as well. */
|
|
14
|
+
/** Names earlier releases recorded in a generation manifest (every release up to the removal of the
|
|
15
|
+
* `@crouter/cli` bridge recorded `@crouter/cli`). A generation installed under one of them is still valid. */
|
|
23
16
|
export const LEGACY_PACKAGE_NAMES = new Set(['crouter', 'crtr', '@north-light/crouter', '@crouter/cli']);
|
|
24
17
|
export function isKnownPackageName(name) {
|
|
25
|
-
return name === PACKAGE_NAME ||
|
|
18
|
+
return name === PACKAGE_NAME || LEGACY_PACKAGE_NAMES.has(name);
|
|
26
19
|
}
|
|
27
20
|
export const ENTRY_NAMES = ['broker', 'cli', 'daemon', 'launcher'];
|
|
28
21
|
/** Entries every generation carries. Generations installed before the root
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var D=Object.defineProperty;var p=(e,o)=>D(e,"name",{value:o,configurable:!0});import{envGrantee as q,envProfileId as x}from"../../shared/env.js";import{requiredPluginEnv as I}from"../../core/plugin-env.js";import{createHash as _}from"node:crypto";import{lstat as w,readFile as T,readdir as C,readlink as E}from"node:fs/promises";import{readFileSync as H}from"node:fs";import{dirname as b,isAbsolute as S,join as h,relative as L,resolve as j,sep as M}from"node:path";import{defineLeaf as B}from"../../core/command.js";import{normalizeRequires as G,readConfig as K,updateConfig as z}from"../../core/config.js";import{scopeRoot as A,listScopes as J,marketplacesDir as W,pluginsDir as V}from"../../core/scope.js";import{readMarketplaceManifest as U,readPluginManifest as Z}from"../../core/manifest.js";import{pathExists as $,listDirs as O,removePath as Q}from"../../core/fs-utils.js";import{lsRemote as X}from"../../core/git.js";import{cliClient as P}from"../api-client.js";import{detectNerdFont as Y,nerdFontInstallCommand as ee,NERD_FONT_SELECT_HINT as R}from"../../core/runtime/nerd-font.js";import{oldPackageInstalled as ne}from"./old-package.js";import{detectPackageManager as te}from"./setup-core.js";import{validateEffectiveCommandPlugins as ie}from"../../core/command-plugins/discovery.js";import{adaptPluginContributions as oe}from"../../core/command-plugins/compose.js";import{resolveCommandRegistry as ae}from"../../core/command-manifests/registry.js";import{applyCommandExtensions as se,orphanCommandExtensionValidations as re}from"../../core/command-plugins/extensions.js";import{discoverHookRegistry as ce}from"../../core/command-hooks/discovery.js";import{resolveBinContributions as le}from"../../core/runtime/bin-contributions.js";import{inspectHumanActions as de}from"../../core/human-actions.js";import{composeAppProcessEnv as ue,overlayBrokerEnv as me,resolvePathExecutable as pe}from"../../core/runtime/spawn-env.js";import{listAllPlugins as fe}from"../../core/resolver.js";import{SUBTREE_NAMES as he,coreCommandPaths as ge,coreHookCatalog as $e,extensibleCoreBranches as ye}from"../../build-root.js";import{processGeneration as ve,processLocatedGeneration as ke,runtimeManifest as y,selectedGeneration as we}from"./shared.js";import{CONFIG_FILE as be}from"../../types.js";function f(e,o,i){return{scope:e,name:o,status:"pass",message:i}}p(f,"pass");function m(e,o,i,a){return{scope:e,name:o,status:"fail",message:i,...a?{remediation:a}:{}}}p(m,"failCheck");async function k(e){try{switch(e.kind){case"remove_config_key":{if(!e.scope||!e.configKey)return!1;const o=e.configKey.split(".");return await z(e.scope,i=>{let a=i;for(let r=0;r<o.length-1;r++){const n=a[o[r]];if(typeof n!="object"||n===null)return;a=n}delete a[o[o.length-1]]}),!0}case"rm_path":return e.path?(Q(e.path),!0):!1;case"human_action":return!1;default:return!1}}catch{return!1}}p(k,"applyRemediation");function xe(e){return[`${e.link} ${e.kind}`,`disposition=${e.retry.disposition}`,typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`attempt=${e.retry.attempt}/${e.retry.max}`:void 0,typeof e.retry.nextAt=="string"?`nextAt=${e.retry.nextAt}`:void 0].filter(i=>i!==void 0).join(" \xB7 ")}p(xe,"faultMessage");function N(e){return/^[A-Za-z0-9._:/@%+=,-]+$/u.test(e)?e:`'${e.replaceAll("'","'\\''")}'`}p(N,"shellArgument");function _e(e,o){const i={connection:"restore connectivity","rate-limit":"wait for the rate limit to clear",overloaded:"wait for load to drop",auth:"re-authenticate",protocol:"fix the protocol mismatch","context-overflow":"shrink the task or loaded context, or choose a larger-context model before spawning the node again",other:"fix the underlying issue",wedged:"read `crtr canvas read wedged-child-on-runaway-bash` \u2014 if a runaway subprocess is to blame, kill it (not the node); if the broker had no subprocess, the daemon SIGTERM-kicks it and starts a fresh recovery cycle automatically","model-not-found":"pass a valid `--model provider/id` or configure credentials for an authenticated provider, then revive the node (`crtr node lifecycle revive <id>`)"},a=e.retry.disposition==="auto"?e.retry.by==="client"?"client redialing":typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`auto-retrying, attempt ${e.retry.attempt}/${e.retry.max}`:"auto-retrying":e.retry.disposition==="fatal"?"parked fatal":"manual",r=`crtr sys logs --node ${N(o)} --operation ${N(e.operation_id)}`;return{kind:"human_action",description:`${i[e.kind]}; ${a}; inspect the correlated operation with ${r}`,command:r}}p(_e,"faultRemediation");async function Ce(e){const o=[],i=new Set(e),a=new Set(he),[r,n]=await Promise.all([ge(),ye()]),d=ie(a,void 0,void 0,r,n);for(const l of d){const t=l.plugin;if(!i.has(t.scope))continue;const c=l.issues.filter(s=>s.code!=="command_collision");if(c.length===0){const s=l.contributions.map(u=>u.node.name).join(", ");o.push(f(t.scope,`plugin:${t.name}:commands`,s.length>0?`contributes top-level command(s): ${s}`:"command manifest valid"));continue}c.forEach((s,u)=>{const g={kind:"human_action",description:`${s.next} Inspect with \`pkg plugin show ${t.name}\`; then update (\`pkg plugin update --name ${t.name}\`) or remove (\`pkg plugin remove ${t.name}\`) the plugin.`},v=s.path!==void 0?` at ${s.path}`:"";o.push(m(t.scope,`plugin:${t.name}:commands[${u}]`,`${s.code}${v}: ${s.message} (received ${s.received}, expected ${s.expected})`,g))})}if(i.has("project")){const l=ae(oe(d.flatMap(s=>s.contributions)).contributions,a),c=[...se(l.contributions).validations,...re(l.contributions)];for(const s of c){if(s.issue===void 0){o.push(f("project",`extension:${s.branch}`,`repository fragment valid: ${s.fragmentPath}`));continue}const u=s.issue;o.push(m("project",`extension:${s.branch}`,`${u.code} at ${u.path??s.fragmentPath}: ${u.message} (received ${u.received}, expected ${u.expected})`,{kind:"human_action",description:u.next}))}}return o}p(Ce,"runCommandPluginChecks");async function Ee(e){const o=new Set(e),i=ce(await $e()),a=[];for(const r of i.validations){const n=r.plugin;if(!o.has(n.scope))continue;const d=i.issues.filter(l=>l.plugin===n.name&&l.scope===n.scope);if(d.length===0){const l=r.hooks.map(c=>`${c.target} [${c.phase} ${c.op}]`),t=(r.manifest?.schemaVersion===2?r.manifest.lifecycle:[]).map(c=>`${c.event} [${c.phase} ${c.op}; effects: ${c.effects.join(", ")}]`);a.push(f(n.scope,`plugin:${n.name}:hooks`,`effective hook declaration(s): ${[...l,...t].join("; ")}`));continue}d.forEach((l,t)=>{const c=r.manifestPath??h(n.root,".crouter-plugin","plugin.json"),s=l.path!==void 0?`${c}:${l.path}`:c;a.push(m(n.scope,`plugin:${n.name}:hooks[${t}]`,`${l.code} at ${s}: ${l.message} (received ${l.received}, expected ${l.expected})`,{kind:"human_action",description:`${l.next} Inspect with \`crtr pkg plugin show ${n.name}\`; then disable (\`crtr pkg plugin disable ${n.name} --scope ${n.scope}\`), update (\`crtr pkg plugin update --name ${n.name}\`), or remove (\`crtr pkg plugin remove ${n.name}\`) the plugin.`}))})}return a}p(Ee,"runHookPluginChecks");function Se(e){const o=new Set(e),{bins:i,issues:a}=le(process.cwd(),x()||null),r=[];for(const n of a)o.has(n.scope)&&r.push(m(n.scope,`bin:${n.name}`,`${n.origin}: ${n.message}`,{kind:"human_action",description:`Fix the \`bin.${n.name}\` declaration in ${n.origin} \u2014 point it at an executable regular file inside that contributor's own root, or remove it. A same-precedence collision is resolved by renaming one of the claimants.`}));for(const n of i.values())o.has(n.scope)&&r.push(f(n.scope,`bin:${n.name}`,`${n.origin} \u2192 ${n.target}`));return r}p(Se,"runBinContributionChecks");function je(e){const o=new Set(e),i=h(A("user"),be),a=[],r=new Map;for(const n of de(process.cwd())){if("kind"in n){if(n.kind==="unknown_action")continue;const c=n.configOrigin===i?"user":"project",s=n.block===!0,u=s?void 0:r.get(n.name);if(!s&&u===void 0&&r.set(n.name,n.configOrigin),!o.has(c))continue;const g=s?`humanActions:block@${n.configOrigin}`:`humanActions:${n.name}@${n.configOrigin}`,v={kind:"human_action",description:s?`Fix or remove the \`humanActions\` block in ${n.configOrigin}. Actions run argv directly without a shell.`:`Fix or remove the \`humanActions.${n.name}\` declaration in ${n.configOrigin}. Actions run argv directly without a shell.`};u!==void 0?a.push({scope:c,name:g,status:"pass",message:`warning: shadowed by ${u}; ${n.configOrigin}: ${n.reason}`,remediation:v}):a.push(m(c,g,`${n.configOrigin}: ${n.reason}`,v));continue}const d=n.configOrigin===i?"user":"project",l=r.get(n.name);if(l===void 0&&r.set(n.name,n.configOrigin),!o.has(d))continue;const t=l===void 0?"":`shadowed by ${l}; `;a.push(f(d,`humanActions:${n.name}@${n.configOrigin}`,`${t}${n.configOrigin} \u2192 ${n.argv[0]} (cwd ${n.cwd})`))}return a}p(je,"runHumanActionChecks");async function Ae(e){const o=new Set(e),i=x()??null,a=q()??"app:terminal",r=P(),n=p(t=>Object.fromEntries(t.map(c=>[c,""])),"present"),d=me({argv:[],env:{CRTR_NODE_CWD:process.cwd(),CRTR_PROFILE_ID:i??"",CRTR_GRANTEE:a}},ue(process.cwd(),i,a,n((await r.listAppEnv()).names),i===null?{}:n((await r.listProfileEnv(i)).names))),l=[];for(const t of fe())if(!(!o.has(t.scope)||!t.enabled)){for(const c of I(t.manifest.env))d[c]!==void 0?l.push(f(t.scope,`env:${c}`,`plugin "${t.name}" has ${c}`)):l.push(m(t.scope,`env:${c}`,`plugin "${t.name}" needs ${c}`,{kind:"human_action",description:`crtr sys env set --name ${c}`}));if(t.manifest.requires!==void 0)for(const[c,s]of Object.entries(G(t.manifest.requires))){const u=pe(c,d,process.cwd());u!==null?l.push(f(t.scope,`requires:${c}`,`plugin "${t.name}" \u2192 ${u}`)):l.push(m(t.scope,`requires:${c}`,`plugin "${t.name}" requires executable "${c}" on PATH`,{kind:"human_action",description:s}))}}return l}p(Ae,"runRequiresChecks");async function Oe(e){const o=[];async function i(a){for(const r of await C(a)){const n=h(a,r),d=L(e,n).replaceAll(M,"/");if(d==="generation.json")continue;const l=await w(n);if(l.isDirectory())await i(n);else if(l.isFile()){const t=await T(n);o.push({path:d,size:l.size,sha256:_("sha256").update(t).digest("hex")})}else if(l.isSymbolicLink()){const t=await E(n);if(S(t)||!y.contained(e,j(b(n),t)))throw new Error(`generation symlink escapes root: ${d}`);o.push({path:d,size:Buffer.byteLength(t),sha256:_("sha256").update(t).digest("hex"),symlink:!0})}else throw new Error(`unsupported generation file: ${d}`)}}return p(i,"walk"),await i(e),y.sortInventory(o)}p(Oe,"inventory");async function Pe(e){async function o(i){const a=await w(i);if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`generation directory is invalid: ${i}`);if((a.mode&146)!==0)throw new Error(`generation path is writable: ${i}`);for(const r of await C(i)){const n=h(i,r),d=await w(n);if(d.isDirectory())await o(n);else if(d.isFile()){if((d.mode&146)!==0)throw new Error(`generation path is writable: ${n}`)}else if(d.isSymbolicLink()){const l=await E(n);if(S(l)||!y.contained(e,j(b(n),l)))throw new Error(`generation symlink escapes root: ${n}`)}else throw new Error(`unsupported generation file: ${n}`)}}p(o,"walk"),await o(e)}p(Pe,"verifySealed");function Re(){const e=Y();if(e.installed)return f("user","terminal:nerd-font",`installed (${e.evidence}) \u2014 if icons still render as boxes, ${R}`);const o=ee(te());return m("user","terminal:nerd-font","no Nerd Font installed \u2014 viewer tool/command icons will render as tofu boxes",{kind:"human_action",description:`Install a Nerd Font (${o.hint}), ${R}`,...o.command?{command:o.command}:{}})}p(Re,"runNerdFontCheck");function Ne(){const e=ne();return e===void 0?f("canvas","package:old-crouter","the old @crouton-kit/crouter package is not installed"):m("canvas","package:old-crouter",e.message,{kind:"human_action",description:"Remove the old package, then reinstall this one",command:`${e.uninstall} && npm i -g @north-light/cli@latest`})}p(Ne,"oldPackageCheck");function Fe(e,o){const i=`runtime:${e}:source`;let a;try{a=JSON.parse(H(h(b(o.root),`${o.id}.source.json`),"utf8"))}catch{return f("canvas",i,"not recorded (installed from a package, or before install sources were recorded)")}const r=`${a.branch??"?"} @ ${a.commit?.slice(0,9)??"?"} from ${a.checkout??"?"}${a.node?` by node ${a.node}`:""}, ${a.installedAt??""}`;return a.unlanded===void 0||a.unlanded.length===0?f("canvas",i,`origin/main: ${r}`):m("canvas",i,`unlanded code is installed (${a.unlanded.join("; ")}): ${r}. Land it and reinstall from origin/main.`)}p(Fe,"installSourceCheck");async function F(e,o,i){if(o.generation===null){const d=o.error??"no runtime generation";return[i?f("canvas",`runtime:${e}`,d):m("canvas",`runtime:${e}`,d)]}const a=o.generation,r=[],n=y.validateManifestShape(a.manifest,{id:a.id,entryName:"cli"});if(!n.ok)return[m("canvas",`runtime:${e}:manifest`,n.error)];r.push(f("canvas",`runtime:${e}:manifest`,`${a.id} ${a.manifest.packageVersion}`)),r.push(Fe(e,a));try{await Pe(a.root),r.push(f("canvas",`runtime:${e}:sealing`,"generation tree is sealed and contained"))}catch(d){r.push(m("canvas",`runtime:${e}:sealing`,d instanceof Error?d.message:String(d)))}try{const d=await Oe(a.root),l=y.sortInventory(a.manifest.files);JSON.stringify(a.manifest.files)!==JSON.stringify(l)?r.push(m("canvas",`runtime:${e}:inventory`,"manifest inventory is not in canonical runtime-generation-manifest order")):JSON.stringify(d)!==JSON.stringify(l)?r.push(m("canvas",`runtime:${e}:inventory`,"full generation inventory hash does not match generation.json")):r.push(f("canvas",`runtime:${e}:inventory`,`${d.length} files hash-verified`))}catch(d){r.push(m("canvas",`runtime:${e}:inventory`,d instanceof Error?d.message:String(d)))}return r}p(F,"generationChecks");async function De(){const e=[];for(const o of await P().listNodes()){const i=o.fault??null;if(i===null)continue;const a=`fault:${o.node_id}:${i.link}`,r=_e(i,o.node_id);e.push(m("canvas",a,xe(i),r))}return e}p(De,"runFaultChecks");async function qe(e,o){const i=[];if(!A(e))return i;const r=K(e),n=W(e);for(const t of Object.keys(r.marketplaces)){if(!n){i.push(m(e,`marketplace:${t}:dir`,"marketplaces directory unavailable"));continue}const c=h(n,t);if($(c))i.push(f(e,`marketplace:${t}:dir`,"directory exists"));else{const s={kind:"remove_config_key",description:`Drop stale config entry config.${e}.marketplaces.${t}`,scope:e,configKey:`marketplaces.${t}`};o.fix&&await k(s)?i.push({scope:e,name:`marketplace:${t}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:s}):i.push(m(e,`marketplace:${t}:dir`,`directory missing: ${c}`,s))}}const d=V(e);for(const t of Object.keys(r.plugins)){if(!d){i.push(m(e,`plugin:${t}:dir`,"plugins directory unavailable"));continue}const c=h(d,t);if($(c))i.push(f(e,`plugin:${t}:dir`,"directory exists"));else{const s={kind:"remove_config_key",description:`Drop stale config entry config.${e}.plugins.${t}`,scope:e,configKey:`plugins.${t}`};o.fix&&await k(s)?i.push({scope:e,name:`plugin:${t}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:s}):i.push(m(e,`plugin:${t}:dir`,`directory missing: ${c}`,s))}}if(n&&$(n))for(const t of O(n)){const c=h(n,t),s=U(c);if(s){i.push(f(e,`marketplace:${t}:manifest`,"manifest valid"));for(const u of s.plugins){if(u.source.startsWith("http://")||u.source.startsWith("https://")||u.source.startsWith("git@"))continue;const g=h(c,u.source);$(g)?i.push(f(e,`marketplace:${t}:plugin-source:${u.name}`,"source resolves")):i.push(m(e,`marketplace:${t}:plugin-source:${u.name}`,`source path does not resolve: ${g}`))}}else{const u={kind:"rm_path",description:"Remove dangling marketplace directory (no valid .crouter-marketplace/marketplace.json)",path:c};o.fix&&await k(u)?i.push({scope:e,name:`marketplace:${t}:manifest`,status:"fail",message:"no valid marketplace.json \u2014 removed dangling directory",fixed:!0,remediation:u}):i.push(m(e,`marketplace:${t}:manifest`,`no valid marketplace.json in ${c}`,u))}}const l=new Map;if(d&&$(d))for(const t of O(d)){const c=h(d,t),s=Z(c);if(!s){const u={kind:"rm_path",description:"Remove dangling plugin directory (no valid .crouter-plugin/plugin.json)",path:c};o.fix&&await k(u)?i.push({scope:e,name:`plugin:${t}:manifest`,status:"fail",message:"no valid plugin.json \u2014 removed dangling directory",fixed:!0,remediation:u}):i.push(m(e,`plugin:${t}:manifest`,`no valid plugin.json in ${c}`,u));continue}i.push(f(e,`plugin:${t}:manifest`,"manifest valid")),l.has(t)?i.push(m(e,`plugin:${t}:duplicate`,`duplicate plugin name within scope (also at ${l.get(t)})`)):l.set(t,c),o.remote&&s.source&&(X(s.source).status!==0?i.push(m(e,`plugin:${t}:remote`,`git remote unreachable: ${s.source}`)):i.push(f(e,`plugin:${t}:remote`,"git remote reachable")))}return i}p(qe,"runChecksForScope");const pn=B({name:"doctor",description:"diagnose installation health",whenToUse:"something in your crtr install looks off and you want it diagnosed \u2014 a plugin or marketplace manifest is missing, a config entry points at a directory that no longer exists, or a plugin command/hook declaration is malformed. Reports each problem with a structured remediation, and can apply the safe repairs for you.",help:{name:"sys doctor",summary:"diagnose runtime integrity, missing manifests, and broken config entries",params:[{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Scope to check. Default: all scopes."},{kind:"flag",name:"fix",type:"bool",required:!1,constraint:"Apply each non-pass check's remediation and report what was fixed."},{kind:"flag",name:"remote",type:"bool",required:!1,constraint:"Check git remotes with ls-remote (slow \u2014 makes network calls)."}],output:[{name:"checks",type:"object[]",required:!0,constraint:"Each: {scope, name, status, message, fixed?, remediation?}. status: pass | fail. scope may be user | project | canvas. bin:<name> checks report bare-binary contributions (a `bin` block in a plugin manifest or a scope config.json): a pass names the contributor and the resolved target, a fail names an unsafe/reserved command name, malformed target declaration, missing/non-executable/escaping target, or same-precedence name collision that installed nothing; their remediation is always a human_action. humanActions:<name>@<config-origin> checks validate each user/project scope completion-action declaration: action-name and argv shape, cwd directory, argv[0] regular-file existence, and execute permission; they never execute an action. A malformed effective declaration fails; a malformed shadowed declaration is a pass-level warning that names the winning and shadowed origins. requires:<name> checks report each enabled plugin manifest PATH requirement: a pass names the plugin and resolved executable path; a fail names the plugin and carries its declared install hint as remediation. Runtime checks validate selected and process generation manifests, sealing/containment, and full SHA-256 inventories. terminal:nerd-font (user scope) reports whether a Nerd Font is installed for the viewer's icon glyphs; its remediation is always a human_action carrying the platform install command, never auto-fixed. Plugin checks appear as plugin:<name>:commands and plugin:<name>:hooks; both are validated statically and never execute plugin code. Hook failures identify manifest/path/target/event/collision problems and carry disable/update/remove/show remediation; healthy command hooks list effective target, phase, and op, while lifecycle hooks list event, phase, op, and effects. remediation (when present) is {kind, description, ...payload} where kind is remove_config_key | rm_path | human_action; fault human_action remediations include the canonical logs command. Sorted by scope then name."},{name:"ok",type:"boolean",required:!0,constraint:"True when no unresolved fail checks remain."}],outputKind:"object",effects:["Read-only unless --fix is passed. Runtime verification reads and hashes every selected/process generation file; plugin command and hook manifests, bare-binary (`bin`) declarations, humanActions declarations, and advisory `requires` PATH checks never execute plugin or contributed binaries.","With --fix: applies each non-pass check's `remediation` \u2014 removes stale config entries and deletes dangling plugin/marketplace directories; canvas fault findings and plugin command/hook findings stay read-only (--fix never chmods or rewrites third-party plugin content).","Each non-pass result carries a structured `remediation` describing the fix action (absolute paths, exact config keys, or a human_action with its command) so callers can apply it directly without --fix."]},run:p(async e=>{const o=e.scope,i=e.fix,a=e.remote,r=J(o),n=[];for(const s of r){const u=await qe(s,{fix:i,remote:a});n.push(...u)}r.includes("user")&&n.push(Re()),n.push(...await Ce(r)),n.push(...await Ee(r)),n.push(...Se(r)),n.push(...je(r)),n.push(...await Ae(r)),n.push(Ne()),n.push(...await De());const d=ve();n.push(...await F("selected",we(),d===null)),n.push(...await F("process",ke(),!0));const l={user:0,project:1,builtin:2,canvas:3};n.sort((s,u)=>s.scope!==u.scope?l[s.scope]-l[u.scope]:s.name.localeCompare(u.name));const t=!n.some(s=>s.status==="fail"&&s.fixed!==!0),c=n.filter(s=>s.status==="fail"&&s.fixed!==!0).length;return{checks:n,ok:t,failed:c}},"run")});export{Ce as runCommandPluginChecks,pn as sysDoctorLeaf};
|
|
1
|
+
var D=Object.defineProperty;var p=(e,o)=>D(e,"name",{value:o,configurable:!0});import{envGrantee as q,envProfileId as x}from"../../shared/env.js";import{requiredPluginEnv as I}from"../../core/plugin-env.js";import{createHash as _}from"node:crypto";import{lstat as w,readFile as T,readdir as E,readlink as C}from"node:fs/promises";import{readFileSync as H}from"node:fs";import{dirname as b,isAbsolute as S,join as h,relative as L,resolve as j,sep as M}from"node:path";import{defineLeaf as B}from"../../core/command.js";import{normalizeRequires as G,readConfig as K,updateConfig as z}from"../../core/config.js";import{scopeRoot as A,listScopes as J,marketplacesDir as W,pluginsDir as V}from"../../core/scope.js";import{readMarketplaceManifest as U,readPluginManifest as Z}from"../../core/manifest.js";import{pathExists as $,listDirs as O,removePath as Q}from"../../core/fs-utils.js";import{lsRemote as X}from"../../core/git.js";import{cliClient as P}from"../api-client.js";import{detectNerdFont as Y,nerdFontInstallCommand as ee,NERD_FONT_SELECT_HINT as R}from"../../core/runtime/nerd-font.js";import{detectPackageManager as ne}from"./setup-core.js";import{validateEffectiveCommandPlugins as te}from"../../core/command-plugins/discovery.js";import{adaptPluginContributions as ie}from"../../core/command-plugins/compose.js";import{resolveCommandRegistry as oe}from"../../core/command-manifests/registry.js";import{applyCommandExtensions as ae,orphanCommandExtensionValidations as se}from"../../core/command-plugins/extensions.js";import{discoverHookRegistry as re}from"../../core/command-hooks/discovery.js";import{resolveBinContributions as ce}from"../../core/runtime/bin-contributions.js";import{inspectHumanActions as le}from"../../core/human-actions.js";import{composeAppProcessEnv as de,overlayBrokerEnv as ue,resolvePathExecutable as me}from"../../core/runtime/spawn-env.js";import{listAllPlugins as pe}from"../../core/resolver.js";import{SUBTREE_NAMES as fe,coreCommandPaths as he,coreHookCatalog as ge,extensibleCoreBranches as $e}from"../../build-root.js";import{processGeneration as ye,processLocatedGeneration as ve,runtimeManifest as y,selectedGeneration as ke}from"./shared.js";import{CONFIG_FILE as we}from"../../types.js";function f(e,o,i){return{scope:e,name:o,status:"pass",message:i}}p(f,"pass");function m(e,o,i,a){return{scope:e,name:o,status:"fail",message:i,...a?{remediation:a}:{}}}p(m,"failCheck");async function k(e){try{switch(e.kind){case"remove_config_key":{if(!e.scope||!e.configKey)return!1;const o=e.configKey.split(".");return await z(e.scope,i=>{let a=i;for(let r=0;r<o.length-1;r++){const n=a[o[r]];if(typeof n!="object"||n===null)return;a=n}delete a[o[o.length-1]]}),!0}case"rm_path":return e.path?(Q(e.path),!0):!1;case"human_action":return!1;default:return!1}}catch{return!1}}p(k,"applyRemediation");function be(e){return[`${e.link} ${e.kind}`,`disposition=${e.retry.disposition}`,typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`attempt=${e.retry.attempt}/${e.retry.max}`:void 0,typeof e.retry.nextAt=="string"?`nextAt=${e.retry.nextAt}`:void 0].filter(i=>i!==void 0).join(" \xB7 ")}p(be,"faultMessage");function N(e){return/^[A-Za-z0-9._:/@%+=,-]+$/u.test(e)?e:`'${e.replaceAll("'","'\\''")}'`}p(N,"shellArgument");function xe(e,o){const i={connection:"restore connectivity","rate-limit":"wait for the rate limit to clear",overloaded:"wait for load to drop",auth:"re-authenticate",protocol:"fix the protocol mismatch","context-overflow":"shrink the task or loaded context, or choose a larger-context model before spawning the node again",other:"fix the underlying issue",wedged:"read `crtr canvas read wedged-child-on-runaway-bash` \u2014 if a runaway subprocess is to blame, kill it (not the node); if the broker had no subprocess, the daemon SIGTERM-kicks it and starts a fresh recovery cycle automatically","model-not-found":"pass a valid `--model provider/id` or configure credentials for an authenticated provider, then revive the node (`crtr node lifecycle revive <id>`)"},a=e.retry.disposition==="auto"?e.retry.by==="client"?"client redialing":typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`auto-retrying, attempt ${e.retry.attempt}/${e.retry.max}`:"auto-retrying":e.retry.disposition==="fatal"?"parked fatal":"manual",r=`crtr sys logs --node ${N(o)} --operation ${N(e.operation_id)}`;return{kind:"human_action",description:`${i[e.kind]}; ${a}; inspect the correlated operation with ${r}`,command:r}}p(xe,"faultRemediation");async function _e(e){const o=[],i=new Set(e),a=new Set(fe),[r,n]=await Promise.all([he(),$e()]),d=te(a,void 0,void 0,r,n);for(const l of d){const t=l.plugin;if(!i.has(t.scope))continue;const c=l.issues.filter(s=>s.code!=="command_collision");if(c.length===0){const s=l.contributions.map(u=>u.node.name).join(", ");o.push(f(t.scope,`plugin:${t.name}:commands`,s.length>0?`contributes top-level command(s): ${s}`:"command manifest valid"));continue}c.forEach((s,u)=>{const g={kind:"human_action",description:`${s.next} Inspect with \`pkg plugin show ${t.name}\`; then update (\`pkg plugin update --name ${t.name}\`) or remove (\`pkg plugin remove ${t.name}\`) the plugin.`},v=s.path!==void 0?` at ${s.path}`:"";o.push(m(t.scope,`plugin:${t.name}:commands[${u}]`,`${s.code}${v}: ${s.message} (received ${s.received}, expected ${s.expected})`,g))})}if(i.has("project")){const l=oe(ie(d.flatMap(s=>s.contributions)).contributions,a),c=[...ae(l.contributions).validations,...se(l.contributions)];for(const s of c){if(s.issue===void 0){o.push(f("project",`extension:${s.branch}`,`repository fragment valid: ${s.fragmentPath}`));continue}const u=s.issue;o.push(m("project",`extension:${s.branch}`,`${u.code} at ${u.path??s.fragmentPath}: ${u.message} (received ${u.received}, expected ${u.expected})`,{kind:"human_action",description:u.next}))}}return o}p(_e,"runCommandPluginChecks");async function Ee(e){const o=new Set(e),i=re(await ge()),a=[];for(const r of i.validations){const n=r.plugin;if(!o.has(n.scope))continue;const d=i.issues.filter(l=>l.plugin===n.name&&l.scope===n.scope);if(d.length===0){const l=r.hooks.map(c=>`${c.target} [${c.phase} ${c.op}]`),t=(r.manifest?.schemaVersion===2?r.manifest.lifecycle:[]).map(c=>`${c.event} [${c.phase} ${c.op}; effects: ${c.effects.join(", ")}]`);a.push(f(n.scope,`plugin:${n.name}:hooks`,`effective hook declaration(s): ${[...l,...t].join("; ")}`));continue}d.forEach((l,t)=>{const c=r.manifestPath??h(n.root,".crouter-plugin","plugin.json"),s=l.path!==void 0?`${c}:${l.path}`:c;a.push(m(n.scope,`plugin:${n.name}:hooks[${t}]`,`${l.code} at ${s}: ${l.message} (received ${l.received}, expected ${l.expected})`,{kind:"human_action",description:`${l.next} Inspect with \`crtr pkg plugin show ${n.name}\`; then disable (\`crtr pkg plugin disable ${n.name} --scope ${n.scope}\`), update (\`crtr pkg plugin update --name ${n.name}\`), or remove (\`crtr pkg plugin remove ${n.name}\`) the plugin.`}))})}return a}p(Ee,"runHookPluginChecks");function Ce(e){const o=new Set(e),{bins:i,issues:a}=ce(process.cwd(),x()||null),r=[];for(const n of a)o.has(n.scope)&&r.push(m(n.scope,`bin:${n.name}`,`${n.origin}: ${n.message}`,{kind:"human_action",description:`Fix the \`bin.${n.name}\` declaration in ${n.origin} \u2014 point it at an executable regular file inside that contributor's own root, or remove it. A same-precedence collision is resolved by renaming one of the claimants.`}));for(const n of i.values())o.has(n.scope)&&r.push(f(n.scope,`bin:${n.name}`,`${n.origin} \u2192 ${n.target}`));return r}p(Ce,"runBinContributionChecks");function Se(e){const o=new Set(e),i=h(A("user"),we),a=[],r=new Map;for(const n of le(process.cwd())){if("kind"in n){if(n.kind==="unknown_action")continue;const c=n.configOrigin===i?"user":"project",s=n.block===!0,u=s?void 0:r.get(n.name);if(!s&&u===void 0&&r.set(n.name,n.configOrigin),!o.has(c))continue;const g=s?`humanActions:block@${n.configOrigin}`:`humanActions:${n.name}@${n.configOrigin}`,v={kind:"human_action",description:s?`Fix or remove the \`humanActions\` block in ${n.configOrigin}. Actions run argv directly without a shell.`:`Fix or remove the \`humanActions.${n.name}\` declaration in ${n.configOrigin}. Actions run argv directly without a shell.`};u!==void 0?a.push({scope:c,name:g,status:"pass",message:`warning: shadowed by ${u}; ${n.configOrigin}: ${n.reason}`,remediation:v}):a.push(m(c,g,`${n.configOrigin}: ${n.reason}`,v));continue}const d=n.configOrigin===i?"user":"project",l=r.get(n.name);if(l===void 0&&r.set(n.name,n.configOrigin),!o.has(d))continue;const t=l===void 0?"":`shadowed by ${l}; `;a.push(f(d,`humanActions:${n.name}@${n.configOrigin}`,`${t}${n.configOrigin} \u2192 ${n.argv[0]} (cwd ${n.cwd})`))}return a}p(Se,"runHumanActionChecks");async function je(e){const o=new Set(e),i=x()??null,a=q()??"app:terminal",r=P(),n=p(t=>Object.fromEntries(t.map(c=>[c,""])),"present"),d=ue({argv:[],env:{CRTR_NODE_CWD:process.cwd(),CRTR_PROFILE_ID:i??"",CRTR_GRANTEE:a}},de(process.cwd(),i,a,n((await r.listAppEnv()).names),i===null?{}:n((await r.listProfileEnv(i)).names))),l=[];for(const t of pe())if(!(!o.has(t.scope)||!t.enabled)){for(const c of I(t.manifest.env))d[c]!==void 0?l.push(f(t.scope,`env:${c}`,`plugin "${t.name}" has ${c}`)):l.push(m(t.scope,`env:${c}`,`plugin "${t.name}" needs ${c}`,{kind:"human_action",description:`crtr sys env set --name ${c}`}));if(t.manifest.requires!==void 0)for(const[c,s]of Object.entries(G(t.manifest.requires))){const u=me(c,d,process.cwd());u!==null?l.push(f(t.scope,`requires:${c}`,`plugin "${t.name}" \u2192 ${u}`)):l.push(m(t.scope,`requires:${c}`,`plugin "${t.name}" requires executable "${c}" on PATH`,{kind:"human_action",description:s}))}}return l}p(je,"runRequiresChecks");async function Ae(e){const o=[];async function i(a){for(const r of await E(a)){const n=h(a,r),d=L(e,n).replaceAll(M,"/");if(d==="generation.json")continue;const l=await w(n);if(l.isDirectory())await i(n);else if(l.isFile()){const t=await T(n);o.push({path:d,size:l.size,sha256:_("sha256").update(t).digest("hex")})}else if(l.isSymbolicLink()){const t=await C(n);if(S(t)||!y.contained(e,j(b(n),t)))throw new Error(`generation symlink escapes root: ${d}`);o.push({path:d,size:Buffer.byteLength(t),sha256:_("sha256").update(t).digest("hex"),symlink:!0})}else throw new Error(`unsupported generation file: ${d}`)}}return p(i,"walk"),await i(e),y.sortInventory(o)}p(Ae,"inventory");async function Oe(e){async function o(i){const a=await w(i);if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`generation directory is invalid: ${i}`);if((a.mode&146)!==0)throw new Error(`generation path is writable: ${i}`);for(const r of await E(i)){const n=h(i,r),d=await w(n);if(d.isDirectory())await o(n);else if(d.isFile()){if((d.mode&146)!==0)throw new Error(`generation path is writable: ${n}`)}else if(d.isSymbolicLink()){const l=await C(n);if(S(l)||!y.contained(e,j(b(n),l)))throw new Error(`generation symlink escapes root: ${n}`)}else throw new Error(`unsupported generation file: ${n}`)}}p(o,"walk"),await o(e)}p(Oe,"verifySealed");function Pe(){const e=Y();if(e.installed)return f("user","terminal:nerd-font",`installed (${e.evidence}) \u2014 if icons still render as boxes, ${R}`);const o=ee(ne());return m("user","terminal:nerd-font","no Nerd Font installed \u2014 viewer tool/command icons will render as tofu boxes",{kind:"human_action",description:`Install a Nerd Font (${o.hint}), ${R}`,...o.command?{command:o.command}:{}})}p(Pe,"runNerdFontCheck");function Re(e,o){const i=`runtime:${e}:source`;let a;try{a=JSON.parse(H(h(b(o.root),`${o.id}.source.json`),"utf8"))}catch{return f("canvas",i,"not recorded (installed from a package, or before install sources were recorded)")}const r=`${a.branch??"?"} @ ${a.commit?.slice(0,9)??"?"} from ${a.checkout??"?"}${a.node?` by node ${a.node}`:""}, ${a.installedAt??""}`;return a.unlanded===void 0||a.unlanded.length===0?f("canvas",i,`origin/main: ${r}`):m("canvas",i,`unlanded code is installed (${a.unlanded.join("; ")}): ${r}. Land it and reinstall from origin/main.`)}p(Re,"installSourceCheck");async function F(e,o,i){if(o.generation===null){const d=o.error??"no runtime generation";return[i?f("canvas",`runtime:${e}`,d):m("canvas",`runtime:${e}`,d)]}const a=o.generation,r=[],n=y.validateManifestShape(a.manifest,{id:a.id,entryName:"cli"});if(!n.ok)return[m("canvas",`runtime:${e}:manifest`,n.error)];r.push(f("canvas",`runtime:${e}:manifest`,`${a.id} ${a.manifest.packageVersion}`)),r.push(Re(e,a));try{await Oe(a.root),r.push(f("canvas",`runtime:${e}:sealing`,"generation tree is sealed and contained"))}catch(d){r.push(m("canvas",`runtime:${e}:sealing`,d instanceof Error?d.message:String(d)))}try{const d=await Ae(a.root),l=y.sortInventory(a.manifest.files);JSON.stringify(a.manifest.files)!==JSON.stringify(l)?r.push(m("canvas",`runtime:${e}:inventory`,"manifest inventory is not in canonical runtime-generation-manifest order")):JSON.stringify(d)!==JSON.stringify(l)?r.push(m("canvas",`runtime:${e}:inventory`,"full generation inventory hash does not match generation.json")):r.push(f("canvas",`runtime:${e}:inventory`,`${d.length} files hash-verified`))}catch(d){r.push(m("canvas",`runtime:${e}:inventory`,d instanceof Error?d.message:String(d)))}return r}p(F,"generationChecks");async function Ne(){const e=[];for(const o of await P().listNodes()){const i=o.fault??null;if(i===null)continue;const a=`fault:${o.node_id}:${i.link}`,r=xe(i,o.node_id);e.push(m("canvas",a,be(i),r))}return e}p(Ne,"runFaultChecks");async function Fe(e,o){const i=[];if(!A(e))return i;const r=K(e),n=W(e);for(const t of Object.keys(r.marketplaces)){if(!n){i.push(m(e,`marketplace:${t}:dir`,"marketplaces directory unavailable"));continue}const c=h(n,t);if($(c))i.push(f(e,`marketplace:${t}:dir`,"directory exists"));else{const s={kind:"remove_config_key",description:`Drop stale config entry config.${e}.marketplaces.${t}`,scope:e,configKey:`marketplaces.${t}`};o.fix&&await k(s)?i.push({scope:e,name:`marketplace:${t}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:s}):i.push(m(e,`marketplace:${t}:dir`,`directory missing: ${c}`,s))}}const d=V(e);for(const t of Object.keys(r.plugins)){if(!d){i.push(m(e,`plugin:${t}:dir`,"plugins directory unavailable"));continue}const c=h(d,t);if($(c))i.push(f(e,`plugin:${t}:dir`,"directory exists"));else{const s={kind:"remove_config_key",description:`Drop stale config entry config.${e}.plugins.${t}`,scope:e,configKey:`plugins.${t}`};o.fix&&await k(s)?i.push({scope:e,name:`plugin:${t}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:s}):i.push(m(e,`plugin:${t}:dir`,`directory missing: ${c}`,s))}}if(n&&$(n))for(const t of O(n)){const c=h(n,t),s=U(c);if(s){i.push(f(e,`marketplace:${t}:manifest`,"manifest valid"));for(const u of s.plugins){if(u.source.startsWith("http://")||u.source.startsWith("https://")||u.source.startsWith("git@"))continue;const g=h(c,u.source);$(g)?i.push(f(e,`marketplace:${t}:plugin-source:${u.name}`,"source resolves")):i.push(m(e,`marketplace:${t}:plugin-source:${u.name}`,`source path does not resolve: ${g}`))}}else{const u={kind:"rm_path",description:"Remove dangling marketplace directory (no valid .crouter-marketplace/marketplace.json)",path:c};o.fix&&await k(u)?i.push({scope:e,name:`marketplace:${t}:manifest`,status:"fail",message:"no valid marketplace.json \u2014 removed dangling directory",fixed:!0,remediation:u}):i.push(m(e,`marketplace:${t}:manifest`,`no valid marketplace.json in ${c}`,u))}}const l=new Map;if(d&&$(d))for(const t of O(d)){const c=h(d,t),s=Z(c);if(!s){const u={kind:"rm_path",description:"Remove dangling plugin directory (no valid .crouter-plugin/plugin.json)",path:c};o.fix&&await k(u)?i.push({scope:e,name:`plugin:${t}:manifest`,status:"fail",message:"no valid plugin.json \u2014 removed dangling directory",fixed:!0,remediation:u}):i.push(m(e,`plugin:${t}:manifest`,`no valid plugin.json in ${c}`,u));continue}i.push(f(e,`plugin:${t}:manifest`,"manifest valid")),l.has(t)?i.push(m(e,`plugin:${t}:duplicate`,`duplicate plugin name within scope (also at ${l.get(t)})`)):l.set(t,c),o.remote&&s.source&&(X(s.source).status!==0?i.push(m(e,`plugin:${t}:remote`,`git remote unreachable: ${s.source}`)):i.push(f(e,`plugin:${t}:remote`,"git remote reachable")))}return i}p(Fe,"runChecksForScope");const dn=B({name:"doctor",description:"diagnose installation health",whenToUse:"something in your crtr install looks off and you want it diagnosed \u2014 a plugin or marketplace manifest is missing, a config entry points at a directory that no longer exists, or a plugin command/hook declaration is malformed. Reports each problem with a structured remediation, and can apply the safe repairs for you.",help:{name:"sys doctor",summary:"diagnose runtime integrity, missing manifests, and broken config entries",params:[{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Scope to check. Default: all scopes."},{kind:"flag",name:"fix",type:"bool",required:!1,constraint:"Apply each non-pass check's remediation and report what was fixed."},{kind:"flag",name:"remote",type:"bool",required:!1,constraint:"Check git remotes with ls-remote (slow \u2014 makes network calls)."}],output:[{name:"checks",type:"object[]",required:!0,constraint:"Each: {scope, name, status, message, fixed?, remediation?}. status: pass | fail. scope may be user | project | canvas. bin:<name> checks report bare-binary contributions (a `bin` block in a plugin manifest or a scope config.json): a pass names the contributor and the resolved target, a fail names an unsafe/reserved command name, malformed target declaration, missing/non-executable/escaping target, or same-precedence name collision that installed nothing; their remediation is always a human_action. humanActions:<name>@<config-origin> checks validate each user/project scope completion-action declaration: action-name and argv shape, cwd directory, argv[0] regular-file existence, and execute permission; they never execute an action. A malformed effective declaration fails; a malformed shadowed declaration is a pass-level warning that names the winning and shadowed origins. requires:<name> checks report each enabled plugin manifest PATH requirement: a pass names the plugin and resolved executable path; a fail names the plugin and carries its declared install hint as remediation. Runtime checks validate selected and process generation manifests, sealing/containment, and full SHA-256 inventories. terminal:nerd-font (user scope) reports whether a Nerd Font is installed for the viewer's icon glyphs; its remediation is always a human_action carrying the platform install command, never auto-fixed. Plugin checks appear as plugin:<name>:commands and plugin:<name>:hooks; both are validated statically and never execute plugin code. Hook failures identify manifest/path/target/event/collision problems and carry disable/update/remove/show remediation; healthy command hooks list effective target, phase, and op, while lifecycle hooks list event, phase, op, and effects. remediation (when present) is {kind, description, ...payload} where kind is remove_config_key | rm_path | human_action; fault human_action remediations include the canonical logs command. Sorted by scope then name."},{name:"ok",type:"boolean",required:!0,constraint:"True when no unresolved fail checks remain."}],outputKind:"object",effects:["Read-only unless --fix is passed. Runtime verification reads and hashes every selected/process generation file; plugin command and hook manifests, bare-binary (`bin`) declarations, humanActions declarations, and advisory `requires` PATH checks never execute plugin or contributed binaries.","With --fix: applies each non-pass check's `remediation` \u2014 removes stale config entries and deletes dangling plugin/marketplace directories; canvas fault findings and plugin command/hook findings stay read-only (--fix never chmods or rewrites third-party plugin content).","Each non-pass result carries a structured `remediation` describing the fix action (absolute paths, exact config keys, or a human_action with its command) so callers can apply it directly without --fix."]},run:p(async e=>{const o=e.scope,i=e.fix,a=e.remote,r=J(o),n=[];for(const s of r){const u=await Fe(s,{fix:i,remote:a});n.push(...u)}r.includes("user")&&n.push(Pe()),n.push(...await _e(r)),n.push(...await Ee(r)),n.push(...Ce(r)),n.push(...Se(r)),n.push(...await je(r)),n.push(...await Ne());const d=ye();n.push(...await F("selected",ke(),d===null)),n.push(...await F("process",ve(),!0));const l={user:0,project:1,builtin:2,canvas:3};n.sort((s,u)=>s.scope!==u.scope?l[s.scope]-l[u.scope]:s.name.localeCompare(u.name));const t=!n.some(s=>s.status==="fail"&&s.fixed!==!0),c=n.filter(s=>s.status==="fail"&&s.fixed!==!0).length;return{checks:n,ok:t,failed:c}},"run")});export{_e as runCommandPluginChecks,dn as sysDoctorLeaf};
|
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
var O=Object.defineProperty;var i=(e,n)=>O(e,"name",{value:n,configurable:!0});import{spawn as w}from"node:child_process";import{mkdirSync as
|
|
2
|
-
`),
|
|
3
|
-
`);const t=e.directoryUrl===void 0?F():String(e.directoryUrl),r=await K(m);if(r!==void 0)return N()?(S(void 0),{account:r.account.display,moving:!0}):(await z(r),{account:r.account.display,moved:!0});const s=g();if(s!==void 0){const{account:d}=await l(t,m,{accept:Q(s)});return await E(t),await p(),await u(),{account:d}}if(!T())return await X(t);const{account:o}=await l(t,m);return N()?(S(B()),{account:o,moving:!0}):(await H({directoryUrl:t,notify:null}),{account:o,moved:!0})},"run"),render:i(e=>e.moving===!0?`<signin account="${e.account}" moving="true">${Y(String(e.account))}</signin>`:`<signin account="${e.account}"${e.moved===!0?' moved="true"':""}/>`,"render")});async function Z(){return await p(),await u(),(await j()).signed_in===!1}i(Z,"stopMovedComputer");async function ee(e){if(b()===void 0)return;const n=await _(e.directoryUrl);let t;try{t=await fetch(new URL(`/v1/machines/${e.environmentId}`,e.apiUrl),{method:"DELETE",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(3e4)})}catch(r){throw f(r,e.apiUrl)}if(!t.ok&&t.status!==404)throw new a("machine_revoke_failed",`Northlight refused to revoke this computer's machine credential (HTTP ${t.status}): ${(await t.text()).slice(0,300)}`,c.GENERAL,{next:"Run `crtr sys signout` again."})}i(ee,"revokeMachine");const ye=y({name:"signout",description:"sign this computer's crtr out, revoke its credential, and stop its agents",whenToUse:"this computer should stop acting as the person on Northlight, or its stored sign-in may have leaked",help:{name:"sys signout",summary:"revoke the stored credential, delete it from this computer, and on a moved computer stop every agent and cron here",params:[],output:[{name:"signed_out",type:"boolean",required:!0,constraint:"False when no sign-in was stored."},{name:"revoked",type:"boolean",required:!0,constraint:"True when the directory ended the credential now; false when it was already ended or none was stored."},{name:"stopped",type:"boolean",required:!0,constraint:"True when this computer's records are in Northlight and its agents and running crons have stopped; false on a computer whose records are local, where nothing else is tied to the sign-in."}],outputKind:"object",effects:["On a fleet machine first calls `DELETE /v1/machines/<environment>` with the stored sign-in, which ends the machine credential (no running daemon needed). Then calls `POST /v1/developer/token/revoke` with the stored secret, then deletes `runtime/secrets/person-credential` and `person-bearer.json`. A bearer already issued stays valid for at most 5 minutes.","On a computer whose records are in Northlight: restarts the daemon, which stops every agent and running cron here and takes no new work until `crtr sys signin`; agents keep their mail on Northlight and wake after it. Commands answer `not_signed_in`."]},run:i(async()=>{const e=g();e!==void 0&&await ee(e);const{signedOut:n,revoked:t}=await I(),r=e===void 0?!1:await Z();return{signed_out:n,revoked:t,stopped:r}},"run"),render:i(e=>`<signout signed_out="${e.signed_out}" revoked="${e.revoked}" stopped="${e.stopped}"/>`,"render")});export{X as registerFreshComputer,m as showSignIn,ve as sysSigninLeaf,ye as sysSignoutLeaf};
|
|
1
|
+
var O=Object.defineProperty;var i=(e,n)=>O(e,"name",{value:n,configurable:!0});import{spawn as w}from"node:child_process";import{mkdirSync as R,openSync as P}from"node:fs";import{dirname as v,join as U}from"node:path";import{defineLeaf as y}from"../../core/command.js";import{CrtrError as a}from"../../core/errors.js";import{controlPlaneUrl as C,personAccount as k,personBearer as _,readPersonCredential as b,signIn as m,signOut as x}from"../../core/directory/person-credential.js";import{hasLocalCanvas as T,moveRecordPath as I,readMachineConfig as l,readOrCreateInstallId as L,writeMachineConfig as D,writeMachineCredential as M}from"../../daemon/machine-link/config.js";import{probeDaemonHealth as j,sanitizedDaemonEnv as q,spawnDaemon as h,stopAllDaemons as g}from"../../daemon/manage.js";import{hostname as G}from"node:os";import{northlightUnreachable as p}from"../../core/directory/reach.js";import{envNodeId as B}from"../../shared/env.js";import{ExitCode as c}from"../../types.js";import{insideBroker as N}from"./join.js";import{defaultDirectoryUrl as F,finishMove as z,registerThisMac as E,runMove as H,settleEarlierMove as K}from"./import/move.js";import{WAIT_FOR_PID_ENV as J}from"./import/start.js";function V(e){const[n,t]=process.platform==="darwin"?["open",[e]]:["xdg-open",[e]];try{w(n,t,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}i(V,"openBrowser");function u(e){process.stderr.write(`Confirm this code at ${e.verificationUri}: ${e.userCode}
|
|
2
|
+
`),V(e.complete)}i(u,"showSignIn");function W(e){return async n=>{if(e.runId===void 0)return e.account===void 0||e.account.id===n.account.id?void 0:new a("signin_other_account",`This computer belongs to the Northlight account ${e.account.display}. Sign in to that account.`,c.USAGE);let t;try{t=await fetch(new URL(`/v1/imports/${e.runId}`,e.apiUrl),{headers:{authorization:`Bearer ${n.bearer}`},signal:AbortSignal.timeout(3e4)})}catch(r){return p(r,e.apiUrl)}if(!t.ok)return t.status===404?new a("signin_other_account",`This computer's crtr belongs to the Northlight account ${e.account?.display??"it was moved into"}. Sign in to that account.`,c.USAGE):new a("signin_unchecked",`the control plane did not say which account owns this computer (HTTP ${t.status}); nothing was written.`,c.GENERAL,{next:"Retry `crtr sys signin`."})}}i(W,"sameAccountOnly");function S(e){const n=U(v(I()),"move.log");R(v(n),{recursive:!0});const t=P(n,"a",384),r=q();for(const o of["CRTR_API_SOCKET","CRTR_API_TOKEN","CRTR_API_URL"])delete r[o];r[J]=String(process.pid);const s=[...process.execArgv,process.argv[1],"sys","import","start","--kind","machine",...e===void 0?[]:["--notify",e]];w(process.execPath,s,{detached:!0,stdio:["ignore",t,t],env:r}).unref()}i(S,"startDetachedMove");async function Q(e){const n=b()===void 0?(await m(e,u),await k(e)):await k(e),t=await C(e),r=await _(e),s=i(async $=>{try{return await fetch(new URL(`/v1/machines${$?"?rotate=1":""}`,t),{method:"POST",headers:{authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({install_id:L(),name:G().slice(0,64)}),signal:AbortSignal.timeout(3e4)})}catch(A){throw p(A,t)}},"post");let o=await s(!1);o.status===409&&(await o.clone().text()).includes("credential_exists")&&(o=await s(!0));const f=await o.text();if(!o.ok)throw new a("machine_registration_failed",`Northlight refused to register this computer (HTTP ${o.status}): ${f.slice(0,300)}`,c.GENERAL,{next:"Run `crtr sys signin` again."});const d=JSON.parse(f);if(typeof d.credential!="string"||typeof d.environment_id!="string")throw new a("machine_registration_failed","Northlight answered without a credential",c.GENERAL);return M(d.credential),D({apiUrl:t,environmentId:d.environment_id,directoryUrl:e,account:n}),await E(e),await g(),await h(),{account:n.display}}i(Q,"registerFreshComputer");const X=i(e=>`Signed in as ${e}. crtr is now moving this computer's records to Northlight; every agent here pauses for seconds to minutes. End your turn now; this conversation carries on when the move finishes.`,"MOVING"),fe=y({name:"signin",description:"sign this computer's crtr in to the person's Northlight account and register it as one of their machines",whenToUse:"the person agreed to sign in to Northlight (a Northlight command needs the account, or they asked), or a command answered `not_signed_in` or `move_unfinished`",help:{name:"sys signin",summary:"pair this computer with the person's Northlight account in the browser, move this computer's records into it, and register it with the directory",guide:"Prints a code and opens the directory's confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. On a computer whose records are still local it then moves them into the account: run from a terminal it prints each step and returns when done; run from inside a node it returns at once and the node is messaged when the move finishes or fails. A computer already moved accepts only the account it moved into. For an unfinished move (`move_unfinished`), it checks the account's move result and finishes the switch-over if the records arrived. If the stored sign-in is missing or revoked, it first pairs only the account recorded for that move. Until the result is known, agents remain paused. Once the records are in the account the computer is also registered as one of the account's machines: a signing key is made here (the private key never leaves this computer) and only its public half goes to the directory, under the same sign-in. A computer already registered keeps its registration; one signed in earlier without it is registered by running this again. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.",params:[{kind:"flag",name:"directory-url",type:"string",required:!1,constraint:"Directory base URL (http or https). Default: the one in `runtime/machine.json`, else the stored sign-in's, else Northlight's."}],output:[{name:"account",type:"string",required:!0,constraint:"The account this computer is now signed in as."},{name:"moved",type:"boolean",required:!1,constraint:"Present when this command moved the records, or finished an earlier move's switch-over."},{name:"moving",type:"boolean",required:!1,constraint:"Present when the move runs on in its own process (run from inside a node): end the turn; the node is messaged when it finishes or fails."}],outputKind:"object",effects:["Calls the directory (`POST /v1/developer/logins`, then polls `/v1/developer/logins/poll`) and, once approved, writes `runtime/secrets/person-credential` (0600) and replaces the cached bearer. A declined, abandoned or refused sign-in writes nothing and leaves an existing sign-in as it was.","Starts the local daemon first when it is not running, and waits until it serves.","On a computer whose records are local: the move of `crtr sys import start --kind machine` (drains the daemon, uploads, restarts it in machine role); a move confirmed failed before the account holds the records ends the drain and signs this computer out again. If the account's result is unknown, the move record and drain remain for recovery. From inside a node it runs as a detached process logging to `runtime/import/move.log`.","On a computer with no local records: registers it with `POST /v1/machines`, writes `runtime/machine.json` and `runtime/secrets/machine-credential`, and starts the machine daemon. Run again after `northlight_unreachable`, it resumes at registration with the stored sign-in.","On a moved computer: restarts the daemon so it reconnects to Northlight.","Unless this computer is already registered: calls `PUT <directory>/v1/runtimes/registration` with the sign-in bearer and a new public ES256 key, then writes `runtime/secrets/runtime-client.json` (0600) holding the private key and the returned runtime identity."]},run:i(async e=>{(l()!==void 0||T())&&await h();const n=e.directoryUrl===void 0?F():String(e.directoryUrl),t=await K(u);if(t!==void 0)return N()?(S(void 0),{account:t.account.display,moving:!0}):(await z(t),{account:t.account.display,moved:!0});const r=l();if(r!==void 0){const{account:o}=await m(n,u,{accept:W(r)});return await E(n),await g(),await h(),{account:o}}if(!T())return await Q(n);const{account:s}=await m(n,u);return N()?(S(B()),{account:s,moving:!0}):(await H({directoryUrl:n,notify:null}),{account:s,moved:!0})},"run"),render:i(e=>e.moving===!0?`<signin account="${e.account}" moving="true">${X(String(e.account))}</signin>`:`<signin account="${e.account}"${e.moved===!0?' moved="true"':""}/>`,"render")});async function Y(){return await g(),await h(),(await j()).signed_in===!1}i(Y,"stopMovedComputer");async function Z(e){if(b()===void 0)return;const n=await _(e.directoryUrl);let t;try{t=await fetch(new URL(`/v1/machines/${e.environmentId}`,e.apiUrl),{method:"DELETE",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(3e4)})}catch(r){throw p(r,e.apiUrl)}if(!t.ok&&t.status!==404)throw new a("machine_revoke_failed",`Northlight refused to revoke this computer's machine credential (HTTP ${t.status}): ${(await t.text()).slice(0,300)}`,c.GENERAL,{next:"Run `crtr sys signout` again."})}i(Z,"revokeMachine");const we=y({name:"signout",description:"sign this computer's crtr out, revoke its credential, and stop its agents",whenToUse:"this computer should stop acting as the person on Northlight, or its stored sign-in may have leaked",help:{name:"sys signout",summary:"revoke the stored credential, delete it from this computer, and on a moved computer stop every agent and cron here",params:[],output:[{name:"signed_out",type:"boolean",required:!0,constraint:"False when no sign-in was stored."},{name:"revoked",type:"boolean",required:!0,constraint:"True when the directory ended the credential now; false when it was already ended or none was stored."},{name:"stopped",type:"boolean",required:!0,constraint:"True when this computer's records are in Northlight and its agents and running crons have stopped; false on a computer whose records are local, where nothing else is tied to the sign-in."}],outputKind:"object",effects:["On a fleet machine first calls `DELETE /v1/machines/<environment>` with the stored sign-in, which ends the machine credential (no running daemon needed). Then calls `POST /v1/developer/token/revoke` with the stored secret, then deletes `runtime/secrets/person-credential` and `person-bearer.json`. A bearer already issued stays valid for at most 5 minutes.","On a computer whose records are in Northlight: restarts the daemon, which stops every agent and running cron here and takes no new work until `crtr sys signin`; agents keep their mail on Northlight and wake after it. Commands answer `not_signed_in`."]},run:i(async()=>{const e=l();e!==void 0&&await Z(e);const{signedOut:n,revoked:t}=await x(),r=e===void 0?!1:await Y();return{signed_out:n,revoked:t,stopped:r}},"run"),render:i(e=>`<signout signed_out="${e.signed_out}" revoked="${e.revoked}" stopped="${e.stopped}"/>`,"render")});export{Q as registerFreshComputer,u as showSignIn,fe as sysSigninLeaf,we as sysSignoutLeaf};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var d=Object.defineProperty;var l=(i,s)=>d(i,"name",{value:s,configurable:!0});import{defineLeaf as u}from"../../core/command.js";import{updateState as p}from"../../core/config.js";import{projectScopeRoot as f}from"../../core/scope.js";import{selfCheck as
|
|
1
|
+
var d=Object.defineProperty;var l=(i,s)=>d(i,"name",{value:s,configurable:!0});import{defineLeaf as u}from"../../core/command.js";import{updateState as p}from"../../core/config.js";import{projectScopeRoot as f}from"../../core/scope.js";import{selfCheck as h,selfUpdate as m,contentCheck as g}from"../../core/self-update.js";import{marketUpdate as k}from"../pkg/market-manage.js";import{pluginUpdate as y}from"../pkg/plugin-manage.js";import{nowIso as b}from"../../core/fs-utils.js";import{processLocatedGeneration as w,readPackageVersion as _,runtimeManifest as v,selectedGeneration as j}from"./shared.js";const x=u({name:"update",description:"update binary and content",whenToUse:"upgrading crtr or its installed plugins and marketplaces \u2014 pull the latest binary, refresh installed content, or both, or just check what is out of date without applying anything.",help:{name:"sys update",summary:"update the crtr binary and/or installed plugins and marketplaces",params:[{kind:"flag",name:"target",type:"enum",choices:["self","content","all"],required:!1,constraint:"What to update. Default: all."},{kind:"flag",name:"check",type:"bool",required:!1,constraint:"Check for updates without applying them (bounded, blocking)."}],output:[{name:"target",type:"string",required:!1,constraint:"Present when applying updates: self | content | all."},{name:"status",type:"string",required:!1,constraint:"done | failed when applying updates."},{name:"error",type:"string",required:!1,constraint:"Failure message when status is failed."},{name:"warning",type:"string",required:!1,constraint:"Present when the update was applied but recording the self-check time failed, or a marketplace with no registered url was skipped; status stays done."},{name:"updates",type:"object[]",required:!1,constraint:"Present when --check. Each: {name, current, latest, up_to_date, unreachable, kind}."},{name:"up_to_date",type:"boolean",required:!1,constraint:"Present when --check. True when all items are up to date."}],outputKind:"object",effects:["--check \u2014 read-only, bounded network calls.","Default (no --check) \u2014 launches a background job; returns job handle immediately.","Content update replaces each marketplace and source-installed plugin checkout with a freshly staged revision, discarding local modifications in those directories."]},run:l(async i=>{const s=i.target,c=i.check,n=s!==void 0?s:"all";if(c){const t=[];if(n==="self"||n==="all"){const e=h();e!==null?t.push({name:e.package,kind:"self",current:e.current,latest:e.latest,up_to_date:e.current===e.latest,unreachable:!1}):t.push({name:"@north-light/cli",kind:"self",current:null,latest:null,up_to_date:!0,unreachable:!0})}if(n==="content"||n==="all"){const e=g();for(const o of e)t.push({name:o.name,kind:o.kind,current:o.current,latest:o.latest,up_to_date:o.up_to_date,unreachable:o.unreachable})}const r=t.every(e=>e.up_to_date||e.unreachable);return{updates:t,up_to_date:r}}const a=[];try{if(n==="self"||n==="all"){m();const t=["user"];f()&&t.unshift("project");for(const r of t)try{await p(r,e=>{e.last_self_check=b()})}catch(e){a.push(`recording the ${r}-scope self-check failed: ${e instanceof Error?e.message:String(e)}`)}}if(n==="content"||n==="all"){const t=await k.run({});for(const r of t.skipped??[])a.push(`marketplace ${r.name} skipped: ${r.reason}`);await y.run({})}return a.length===0?{target:n,status:"done"}:{target:n,status:"done",warning:a.join("; ")}}catch(t){const r=t instanceof Error?t.message:String(t);return{target:n,status:"failed",error:r}}},"run")}),E=u({name:"version",description:"print installed version",whenToUse:"you need the installed crtr version \u2014 to report it in a bug or confirm an upgrade landed.",help:{name:"sys version",summary:"report selected and process runtime generations",params:[],output:[{name:"version",type:"string",required:!0,constraint:"Version from this process generation manifest; package.json version in a development checkout."},{name:"selected_generation",type:"object",required:!0,constraint:"Selected runtime generation: {id, version, status}; id/version are null when no selection exists."},{name:"process_generation",type:"object",required:!0,constraint:"Generation containing this loaded module: {id, version, status}; id/version are null in a development checkout."},{name:"drift",type:"boolean",required:!0,constraint:"True when selected and process generation ids differ."}],outputKind:"object",effects:["None. Read-only."]},run:l(async i=>{const s=l(a=>{if(a.generation===null)return{id:null,version:null,status:a.error??"no runtime generation"};const{id:t,manifest:r}=a.generation,e=v.validateManifestShape(r,{id:t,entryName:"cli"});return{id:t,version:typeof r.packageVersion=="string"?r.packageVersion:null,status:e.ok?"valid":e.error}},"describe"),c=s(j()),n=s(w());return{version:n.version??_(),selected_generation:c,process_generation:n,drift:c.id!==null&&n.id!==null&&c.id!==n.id}},"run")});export{x as sysUpdateLeaf,E as sysVersionLeaf};
|
package/dist/core/auto-update.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var h=Object.defineProperty;var
|
|
2
|
-
`)}else n==="apply"&&(p("applying self-update in background"),U());if(
|
|
3
|
-
`)}}else
|
|
4
|
-
`)}}}
|
|
1
|
+
var h=Object.defineProperty;var s=(r,t)=>h(r,"name",{value:t,configurable:!0});import{spawn as u}from"node:child_process";import{readConfig as _,readState as m,updateState as f}from"./config.js";import{nowIso as l}from"./fs-utils.js";import{info as p}from"./output.js";import{SELF_UPDATE_SCRIPT as g,selfCheck as k,contentCheck as w}from"./self-update.js";import{envDebug as S}from"../shared/env.js";const y=3600*1e3,v=new Set(["update","help","--help","-h","--version","-v"]);function b(r){const t=r[2];return t===void 0?!0:v.has(t)}s(b,"shouldSkipForArgv");function D(r,t){if(!r)return!1;const n=Date.parse(r);return Number.isFinite(n)?Date.now()-n<t*y:!1}s(D,"withinInterval");function U(){u(process.execPath,[g],{detached:!0,stdio:"ignore"}).unref()}s(U,"spawnDetachedSelfUpdate");function C(){u("crtr",["update","--content"],{detached:!0,stdio:"ignore"}).unref()}s(C,"spawnDetachedContentUpdate");async function F(r){try{if(process.env.CRTR_NO_AUTO_UPDATE==="1"||b(r))return;const t=_("user"),{crtr:n,content:o,interval_hours:d}=t.auto_update;if(n===!1&&o===!1)return;const c=m("user");if(c.last_self_check===void 0){await f("user",e=>{e.last_self_check=l()});return}if(D(c.last_self_check,d))return;if(await f("user",e=>{e.last_self_check=l()}),n==="notify"){const e=k();e!==null&&e.latest!==e.current&&process.stderr.write(`crtr: ${e.package} v${e.latest} available (current ${e.current}) \u2014 run \`crtr sys update\`
|
|
2
|
+
`)}else n==="apply"&&(p("applying self-update in background"),U());if(o==="notify"){const e=w().filter(a=>!a.up_to_date&&!a.unreachable);if(e.length>0){const a=e.map(i=>`${i.kind} ${i.name}`).join(", ");process.stderr.write(`crtr: updates available for ${a} \u2014 run \`crtr sys update\`
|
|
3
|
+
`)}}else o==="apply"&&(p("applying content updates in background"),C())}catch(t){if(S()){const n=t instanceof Error?t.message:String(t);process.stderr.write(`crtr: auto-update hook error: ${n}
|
|
4
|
+
`)}}}s(F,"maybeAutoUpdate");export{F as maybeAutoUpdate};
|
|
@@ -36,6 +36,9 @@ export declare function dropExistingWatches(db: CanvasDb, schema: string, target
|
|
|
36
36
|
watches: number;
|
|
37
37
|
watch_subscriptions: number;
|
|
38
38
|
}>;
|
|
39
|
+
/** A hosted cron runs in its anchor node's sandbox and fails with no anchor. A Mac cron made without `--anchor` has none, so a staged cron of a hosted source with no anchor
|
|
40
|
+
* takes its creator as anchor when that node is staged (still in the bundle after the drops). The anchor's `ON DELETE CASCADE` then removes the cron with its creator. Runs after the drops. Returns the crons anchored. */
|
|
41
|
+
export declare function anchorCronsToCreator(db: CanvasDb, schema: string): Promise<number>;
|
|
39
42
|
/** A staged idempotency key whose (grantee, key) the target already holds is already imported (a hosted person's runs the control plane has since served): it is dropped, the target's
|
|
40
43
|
* row stands, so the copy never inserts it and verify never compares it. Only this key is skipped; any other difference still fails. Returns the dropped rows. Runs before the pre-check. */
|
|
41
44
|
export declare function dropExistingIdempotencyKeys(db: CanvasDb, schema: string, target: string): Promise<number>;
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var A=Object.defineProperty;var
|
|
2
|
-
AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${s("nodes")} WHERE status IN ('active', 'idle'))`).all();let
|
|
1
|
+
var A=Object.defineProperty;var d=(e,a)=>A(e,"name",{value:a,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as M,mapPath as S}from"../bundle/layout.js";import{IDEMPOTENCY_WINDOW_MS as C}from"../../runs/operations.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as g}from"../../conversation-store/row-store.js";import{runBlobKey as H}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const c=d((e,a)=>`${l(e)}.${l(a)}`,"sq");async function J(e,a,o){if(o.length===0)return 0;const n=d(E=>c(a,E),"S"),i=`(SELECT node_id FROM ${n("nodes")} WHERE status IN ('active', 'idle'))`;let s=0;const p=d(async(E,r,t,$=!1)=>{const R=await e.prepareUncached(`SELECT ${l(r)}::text AS value FROM ${n(E)} WHERE ${t} AND ${l(r)} IS NOT NULL`).all();for(const{value:m}of R){const T=$?v(m,o):S(o,m);T!==m&&(await e.prepareUncached(`UPDATE ${n(E)} SET ${l(r)} = ? WHERE ${l(r)}::text = ? AND ${t}`).run(T,m),s+=1)}},"apply");return await p("nodes","cwd",`node_id IN ${i}`),await p("worktrees","path",`node_id IN ${i}`),await p("worktrees","repo_root",`node_id IN ${i}`),await p("crons","cwd",`anchor_node IN ${i}`),await p("provider_approvals","prepared_files","TRUE",!0),await p("upload_uses","path",`run_id IN ${i}`),s}d(J,"rewritePaths");async function Y(e,a,o,n,i){if(o.length===0)return 0;const s=d(r=>c(a,r),"S"),p=await e.prepareUncached(`SELECT conversation_id, blob_key FROM ${s("conversation_parts")} WHERE seq = 0
|
|
2
|
+
AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${s("nodes")} WHERE status IN ('active', 'idle'))`).all();let E=0;for(const{conversation_id:r,blob_key:t}of p){const $=H(i,t),R=await n.get($);if(R===null)throw new N("rewrite-paths","bundle_invalid",`${$} is missing: the header of conversation ${r} cannot be rewritten`);const m=g(R,r,T=>S(o,T));m!==null&&(await n.put($,m),E+=1),await e.prepareUncached(`UPDATE ${s("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((m??R).length,r)}return E}d(Y,"rewriteConversationHeaders");async function X(e,a){const o=c(a,"human_requests"),n=d(s=>`CASE WHEN ${s} IS NULL OR ${s} NOT LIKE '/%' THEN ${s}
|
|
3
3
|
WHEN rtrim(${s}, '/') = rtrim(request_dir, '/') THEN 'requests/' || request_id
|
|
4
4
|
WHEN ${s} LIKE rtrim(request_dir, '/') || '/%' THEN 'requests/' || request_id || '/' || substr(${s}, length(rtrim(request_dir, '/')) + 2)
|
|
5
|
-
ELSE 'requests/' || request_id || '/source/' || regexp_replace(${s}, '^.*/', '') END`,"moved"),i=await e.prepareUncached(`UPDATE ${o} SET file = ${
|
|
6
|
-
request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}
|
|
7
|
-
WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name),$=await e.prepareUncached(`SELECT 1 AS found FROM ${
|
|
8
|
-
WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(
|
|
9
|
-
CREATE TABLE ${
|
|
10
|
-
COALESCE((SELECT array_agg(p.parent) FROM ${
|
|
11
|
-
FROM ${
|
|
12
|
-
FROM (SELECT * FROM ${
|
|
13
|
-
FROM (SELECT ctid AS row_id, * FROM ${
|
|
14
|
-
FROM ${
|
|
5
|
+
ELSE 'requests/' || request_id || '/source/' || regexp_replace(${s}, '^.*/', '') END`,"moved"),i=await e.prepareUncached(`UPDATE ${o} SET file = ${n("file")}, presentation_dir = ${n("presentation_dir")},
|
|
6
|
+
request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}d(X,"rewriteRequestPaths");function v(e,a){const o=d(n=>typeof n=="string"?S(a,n):Array.isArray(n)?n.map(o):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([i,s])=>[i,o(s)])):n,"walk");try{return JSON.stringify(o(JSON.parse(e)))}catch{return S(a,e)}}d(v,"rewriteJsonPaths");async function G(e,a,o,n,i){const s=d(r=>c(a,r),"S"),p=await e.prepareUncached(`SELECT id, name FROM ${s("profiles")} ORDER BY id`).all();let E=0;for(const r of p){const t=await e.prepareUncached(`SELECT o.id FROM ${s("objects")} o JOIN ${s("identities")} i ON i.object = o.id AND i.scheme = 'profile' AND i.external_id = ?
|
|
7
|
+
WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name),$=await e.prepareUncached(`SELECT 1 AS found FROM ${c(o,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,r.name,r.id),R=t===void 0?void 0:await e.prepareUncached(`SELECT 1 AS found FROM ${c(o,"objects")} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(r.name,t.id);if($===void 0&&R===void 0)continue;const m=`${r.name}-${n}`;await e.prepareUncached(`UPDATE ${s("profiles")} SET name = ? WHERE id = ?`).run(m,r.id),t!==void 0&&await e.prepareUncached(`UPDATE ${s("objects")} SET name = ? WHERE id = ?`).run(m,t.id),E+=1}return E}d(G,"renameClashingProfiles");async function z(e,a,o,n){const i=await e.prepareUncached(`UPDATE ${c(a,"charges")} s SET id = s.id || ':install-' || ?::text FROM ${c(o,"charges")} t
|
|
8
|
+
WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(n);return Number(i.changes)}d(z,"renameClashingLegacyCharges");async function Q(e,a,o){const n=`FROM ${c(o,"watches")} t WHERE t.watcher = s.watcher AND t.object = s.object`,i=await e.prepareUncached(`DELETE FROM ${c(a,"watch_subscriptions")} u USING ${c(a,"watches")} s WHERE u.watch = s.watch_id AND EXISTS (SELECT 1 ${n})`).run(),s=await e.prepareUncached(`DELETE FROM ${c(a,"watches")} s WHERE EXISTS (SELECT 1 ${n})`).run();return{watches:Number(s.changes),watch_subscriptions:Number(i.changes)}}d(Q,"dropExistingWatches");async function V(e,a){const o=await e.prepareUncached(`UPDATE ${c(a,"crons")} c SET anchor_node = c.created_by WHERE c.anchor_node IS NULL AND c.created_by IN (SELECT node_id FROM ${c(a,"nodes")})`).run();return Number(o.changes)}d(V,"anchorCronsToCreator");async function Z(e,a,o){const n=await e.prepareUncached(`DELETE FROM ${c(a,"idempotency_keys")} s WHERE EXISTS (SELECT 1 FROM ${c(o,"idempotency_keys")} t WHERE t.grantee = s.grantee AND t.key = s.key)`).run();return Number(n.changes)}d(Z,"dropExistingIdempotencyKeys");async function ee(e,a){const o=await e.prepareUncached(`DELETE FROM ${c(a,"idempotency_keys")} WHERE created_at <= ?`).run(new Date(Date.now()-C).toISOString());return Number(o.changes)}d(ee,"dropExpiredIdempotencyKeys");async function ne(e,a,o,n,i){const s=d(r=>c(a,r),"S"),p=[],E=await e.prepareUncached(`SELECT id, grantee FROM ${s("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const r of E){let t=n.kind==="machine"?n.environmentObject??null:null;if(n.kind==="hosted"){const $=await e.prepareUncached(`SELECT environment_id FROM ${c(o,"profiles")} WHERE id = ?`).get(r.id);if($?.environment_id!=null)t=$.environment_id;else{t=await U(e,{profileId:r.id,grantee:r.grantee??"app:terminal",person:i}),p.push({table:"objects",key:[t]},{table:"environments",key:[t]});for(const R of await e.prepareUncached("SELECT resource_type, resource_id, relation, subject_type, subject_id, subject_relation FROM relations WHERE resource_id = ?").all(t))p.push({table:"relations",key:[R.resource_type,R.resource_id,R.relation,R.subject_type,R.subject_id,R.subject_relation]})}}if(t===null)throw new N("fill","bundle_invalid",`profile ${r.id} has no environment and the source names none`);await e.prepareUncached(`UPDATE ${s("profiles")} SET environment_id = ? WHERE id = ?`).run(t,r.id)}return p}d(ne,"fillEnvironments");async function te(e,a,o,n){const i=d(E=>c(a,E),"S"),s={},p=d(async(E,r,...t)=>{const $=Number((await e.prepareUncached(r).run(...t)).changes);$>0&&(s[E]=(s[E]??0)+$)},"del");await p("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),n.kind==="hosted"&&(await e.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await e.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[E,r]of Object.entries(M))await p(E,`DELETE FROM ${i(E)} WHERE ${l(r)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,n.installId,E);for(const E of o.tables.values())E.columns.includes("claimed_by")&&E.columns.includes("lease_expires_at")&&await e.prepareUncached(`UPDATE ${i(E.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return s}d(te,"pruneStaged");async function re(e,a,o){const n=d(p=>c(a,p),"S"),i=`(SELECT d.object FROM ${n("documents")} d WHERE EXISTS (SELECT 1 FROM ${c(o,"documents")} t WHERE t.object = d.object))`;await e.exec(`CREATE TABLE ${n("_arr_revisions")} AS SELECT r.* FROM ${n("revisions")} r WHERE r.document IN ${i};
|
|
9
|
+
CREATE TABLE ${n("_arr_parents")} AS SELECT p.* FROM ${n("revision_parents")} p WHERE p.child IN (SELECT rev_id FROM ${n("revisions")} WHERE document IN ${i})`);const s=await e.prepareUncached(`SELECT r.document, r.rev_id, r.body_hash, r.rationale, r.created_at,
|
|
10
|
+
COALESCE((SELECT array_agg(p.parent) FROM ${n("revision_parents")} p WHERE p.child = r.rev_id), ARRAY[]::text[]) AS parents
|
|
11
|
+
FROM ${n("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await e.prepareUncached(`DELETE FROM ${n("revision_parents")} WHERE child IN (SELECT rev_id FROM ${n("revisions")} WHERE document IN ${i})`).run(),await e.prepareUncached(`DELETE FROM ${n("revisions")} WHERE document IN ${i}`).run(),await e.prepareUncached(`DELETE FROM ${n("objects")} WHERE id IN ${i}`).run(),await e.prepareUncached(`DELETE FROM ${n("documents")} WHERE object IN ${i}`).run(),s.map(p=>({...p}))}d(re,"takeRepoSyncedDocuments");const b={edges:["created_at"],relations:["created_at"]},W={charges:["payer","units","usd"]};async function ae(e,a,o,n,i,s,p){const E=d(t=>[...p.get(t)??[],...t==="profiles"?["environment_id"]:[],...b[t]??[],"claimed_by","lease_expires_at"],"ignored"),r=[];for(const t of i){const $=n.tables.get(t);if($===void 0||s.has(t)||$.primaryKey.length===0)continue;const R=$.primaryKey,m=R.some(u=>$.identity.includes(u)),T=R.map(u=>`s.${l(u)} = t.${l(u)}`).join(" AND "),L=m?"TRUE":R.map(u=>`s.${l(u)} IS DISTINCT FROM t.${l(u)}`).join(" OR "),I=new Set([...$.identity,...p.get(t)??[]]);for(const u of n.uniqueKeys.filter(h=>h.table===t&&!h.columns.every(f=>I.has(f)))){const h=u.predicate===null?"":` WHERE ${u.predicate}`,f=u.columns.map(_=>`s.${l(_)} = t.${l(_)}`).join(" AND "),O=await e.prepareUncached(`SELECT ${u.columns.map(_=>`s.${l(_)}::text`).join(" || ',' || ")} AS value
|
|
12
|
+
FROM (SELECT * FROM ${c(a,t)}${h}) s JOIN (SELECT * FROM ${c(o,t)}${h}) t ON ${f} AND (${L}) LIMIT 10`).all();O.length>0&&r.push({table:t,key:u.name,values:O.map(_=>_.value)});const D=m?"TRUE":R.map(_=>`a.${l(_)} IS DISTINCT FROM b.${l(_)}`).join(" OR "),y=await e.prepareUncached(`SELECT DISTINCT ${u.columns.map(_=>`a.${l(_)}::text`).join(" || ',' || ")} AS value
|
|
13
|
+
FROM (SELECT ctid AS row_id, * FROM ${c(a,t)}${h}) a JOIN (SELECT ctid AS row_id, * FROM ${c(a,t)}${h}) b ON ${u.columns.map(_=>`a.${l(_)} = b.${l(_)}`).join(" AND ")} AND a.row_id < b.row_id AND (${D}) LIMIT 10`).all();y.length>0&&r.push({table:t,key:u.name,values:y.map(_=>_.value),staged:!0})}const w=$.columns.filter(u=>!$.identity.includes(u)&&!E(t).includes(u)&&(W[t]?.includes(u)??!0));if(w.length>0&&!m){const u=w.map(f=>`s.${l(f)} IS DISTINCT FROM t.${l(f)}`).join(" OR "),h=await e.prepareUncached(`SELECT ${R.map(f=>`s.${l(f)}::text`).join(" || ',' || ")} AS value
|
|
14
|
+
FROM ${c(a,t)} s JOIN ${c(o,t)} t ON ${T} WHERE ${u} LIMIT 10`).all();h.length>0&&r.push({table:t,key:"primary key payload",values:h.map(f=>f.value)})}}if(r.length>0){const t=r[0];throw new N("pre-check","unique_conflict",`${t.table} ${t.key} collides ${t.staged===!0?"within the bundle":"with the target"}: ${t.values.join(", ")}`,{collisions:r})}}d(ae,"precheck");export{V as anchorCronsToCreator,Z as dropExistingIdempotencyKeys,Q as dropExistingWatches,ee as dropExpiredIdempotencyKeys,ne as fillEnvironments,ae as precheck,te as pruneStaged,z as renameClashingLegacyCharges,G as renameClashingProfiles,Y as rewriteConversationHeaders,J as rewritePaths,X as rewriteRequestPaths,re as takeRepoSyncedDocuments};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Z=Object.defineProperty;var m=(e,p)=>Z(e,"name",{value:p,configurable:!0});import{createZstdCompress as x}from"node:zlib";import{once as D}from"node:events";import{keyBatches as V}from"./keys.js";import{blobStore as X}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as A}from"../../canvas/db.js";import{runAsPerson as B}from"../../canvas/person.js";import{insertImportedRevisions as ee}from"../../graph/documents.js";import{getById as te}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ae,rowKeys as L,SEQ_TABLES as ne}from"../bundle/layout.js";import{readCatalog as ie}from"./catalog.js";import{appendManifest as W,copyRows as se}from"./copy.js";import{
|
|
2
|
-
`)}return n.end(),await
|
|
1
|
+
var Z=Object.defineProperty;var m=(e,p)=>Z(e,"name",{value:p,configurable:!0});import{createZstdCompress as x}from"node:zlib";import{once as D}from"node:events";import{keyBatches as V}from"./keys.js";import{blobStore as X}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as A}from"../../canvas/db.js";import{runAsPerson as B}from"../../canvas/person.js";import{insertImportedRevisions as ee}from"../../graph/documents.js";import{getById as te}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ae,rowKeys as L,SEQ_TABLES as ne}from"../bundle/layout.js";import{readCatalog as ie}from"./catalog.js";import{appendManifest as W,copyRows as se}from"./copy.js";import{anchorCronsToCreator as re,pruneStaged as oe,precheck as de,dropExistingIdempotencyKeys as pe,dropExpiredIdempotencyKeys as ce,dropExistingWatches as ue,renameClashingLegacyCharges as le,renameClashingProfiles as fe,rewriteConversationHeaders as me,rewritePaths as _e,rewriteRequestPaths as we,takeRepoSyncedDocuments as ge}from"./prepare.js";import{boundSub as be,dropRefusedMessages as he,checkSourcePerson as ye,checkStagedBlobKeys as Se,checkStagedPersons as ve,checkStagedReferences as Ee,checkStagedRequestKeys as Re}from"./bind.js";import{deleteBlobs as Ie,deleteRunBlobs as Oe,deleteRunPrefix as Pe,moveRunBlobs as je}from"./blobs.js";import{dropStubRows as ke,findFleetGrant as Te,grantMissing as Ce,mapProfileIds as Me,renameClashingRepos as De,rewriteIds as Ae,rewritePerson as Be,scopeRepoIdentities as Ne}from"./rewrite.js";import{dropStaging as K,ImportLaneError as g,stage as Le,stagingSchema as We,targetSchema as Ke}from"./stage.js";import{verifyRun as He}from"./verify.js";import{sandboxPathMap as Je,writeNodeFiles as Ue}from"./path-map.js";import{allStoreKeys as Fe,readPluginsStore as Ge,recordImportedActivations as $e,writeStores as qe}from"./stores.js";import{openImportGrants as Ye}from"./open-grants.js";import{publishImportedPlugins as ze}from"./publish-plugins.js";import{COPIED_TABLES as Qe}from"../bundle/layout.js";import{emitEvent as Ze}from"../../events/emit.js";import{ClaimLostError as xe}from"../../../daemon/reconcilers/row-claim.js";const Ve=10*6e4,Xe=30*6e4,R=m(()=>new Date().toISOString(),"now"),H=m(async(e,p)=>{await(await E()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(p,e)},"setStep");async function et(e,p){const s=await e.get(N.source(p));if(s===null)throw new g("stage","bundle_invalid","source.json is missing");const n=JSON.parse(s.toString("utf8"));if(typeof n.rowParts!="object"||n.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return n}m(et,"readSource");async function tt(e,p,s,n,a,r,o){const i=[];for(const t of L(s.run_id,"grants",n)){const c=await e.get(t);if(c===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);i.push(...ae(c))}if(i.length===0)return;const _=i.map(t=>({sub:be(t.sub,n.person,s.person,"grants.sub"),grantee:t.grantee}));await o(s.run_id);const f=[];for(const t of _)await Te(p,a,r,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw Ce(f)}m(tt,"ensureGrants");async function Ct(e,p,s={}){const n=s.blobs??await X(),a=await E(),r=We(e.run_id);let o="start";const i=m(async t=>{o=t,await p.assertOwned(),await H(e.run_id,t),await s.atStep?.(t)},"at");let _=e.state==="committed";const f=[];try{const t=await et(n,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const c=await Ke(a),I=[...Qe],h=await ie(a,c,[...I,"grants"]);if(!_){const l={},P=[],j=[],k=s.fleetRuntime??process.env.CRTR_RUNTIME??null;await ye(a,c,t.person,e.person),await i("open-grants"),await tt(n,a,e,t,c,k,s.openGrants??Ye),await i("publish-plugins");const J=await Ge(n,e.run_id),S=await B(e.person,()=>ze(J));if(S.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=Ve)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${S.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:S.unavailable});await p.assertOwned(),await H(e.run_id,"waiting_for_directory");return}j.push(...S.refused),await i("stage");const U=await Le(a,e.run_id,t.counts,d=>L(e.run_id,d,t),d=>n.get(d));for(const[d,u]of Object.entries(U))l[d]={staged:u,inserted:0,mapped:0,dropped:0};const w={db:a,schema:r,target:c,catalog:h,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:t.shippedBodies??{}};await i("bind-staged");for(const[d,u]of Object.entries(await ve(w)))b(l,d,u);for(const[d,u]of Object.entries(await Se(w)))b(l,d,u);await i("rewrite-person"),await Be(w),await Ne(w),await i("prune");const F=await oe(a,r,h,t),v=t.kind==="hosted"?Je(t.pathPrefixes??[]):[];await i("rewrite-paths"),await _e(a,r,v),await me(a,r,v,n,e.run_id),await we(a,r),await Re(w);const G=await Me(w);await fe(a,r,c,t.installId,e.person),await i("rewrite-ids");const T=await Ae(w,G);await i("drop");const $=await ge(a,r,c),q=await ke(w);for(const[d,u]of Object.entries({...F}))b(l,d,u);for(const[d,u]of Object.entries(q))b(l,d,u);for(const[d,u]of Object.entries(await he(w,{installId:t.installId,person:e.person,runId:e.run_id})))b(l,d,u);await Ee(w,{installId:t.installId,person:e.person,runId:e.run_id}),await De(w),await le(a,r,c,t.installId);for(const[d,u]of Object.entries(await ue(a,r,c)))b(l,d,u);b(l,"idempotency_keys",await pe(a,r,c)),b(l,"idempotency_keys",await ce(a,r)),t.kind==="hosted"&&await re(a,r),await i("pre-check");const Y=new Map([["messages",["seq"]],...ne.map(d=>[d,["seq"]])]);await de(a,r,c,h,I,new Set,Y),await i("blobs"),await je(a,r,c,e.person,n,e.run_id,f),await i("copy"),await B(e.person,()=>A(async d=>{await p.assertOwned({extendLeaseMs:Xe});const u=await se({db:d,runId:e.run_id,schema:r,target:c,catalog:h,source:t,person:e.person,idMap:T,pathMap:v}),C=await it(d,e.run_id,$);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await Ue(d,r,e.run_id,t);const M=await qe({db:d,blobs:n,runId:e.run_id,person:e.person,objectMap:T.object});for(const[z,Q]of Object.entries(M.inserted))u.inserted[z]=Q.length;return P.push(...M.unresolvedPlugins),await d.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...nt(l,u),unresolved_plugins:P,refused_plugins:j}),R(),e.run_id),u})),_=!0,await s.atStep?.("committed")}await i("verify");const y=await He(a,e.run_id,r,c,h,t.installId);if(await a.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await i("manifest");const O=N.manifest(e.run_id);await n.put(O,await st(e.run_id)),await K(a,e.run_id);for(const l of Fe(e.run_id))await n.delete(l);await Oe(n,e.run_id),await A(async l=>{await $e(l,e.run_id,e.person),await l.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(O,R(),e.run_id)})}catch(t){if(t instanceof xe)throw t;const c=at(t,o);Ze({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await K(a,e.run_id).catch(()=>{}),_||await Ie(n,f,!0),await a.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),await Pe(n,e.run_id,{keepNodeFiles:_,bestEffort:!0})}}m(Ct,"processRun");function at(e,p){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const s=e.code;return{step:p,code:typeof s=="string"?s:"import_failed",message:e instanceof Error?e.message:String(e)}}m(at,"failureOf");function b(e,p,s){(e[p]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=s}m(b,"addDropped");function nt(e,p){for(const[s,n]of Object.entries(p.inserted))(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=n;for(const[s,n]of Object.entries(p.mapped))(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=n;return e}m(nt,"withInserted");async function it(e,p,s){const n=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(s.map(o=>o.rev_id)))).map(o=>o.rev_id)),a=s.filter(o=>!n.has(o.rev_id)),r=new Map;for(const o of s)r.set(o.document,[...r.get(o.document)??[],o]);for(const[o,i]of r){const _=await te(e,o);_!==null&&await ee(e,_,i.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await W(e,p,"revisions",a.map(o=>[o.rev_id])),await W(e,p,"revision_parents",a.flatMap(o=>o.parents.map(i=>[o.rev_id,i]))),a.length}m(it,"arrive");async function st(e){const s=await(await E()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e),n=x(),a=[];n.on("data",i=>a.push(i));const r=D(n,"end"),o=m(async i=>{n.write(i,"utf8")||await D(n,"drain")},"put");for(const i of s){await o(`{"table":${JSON.stringify(i.table_name)},"keys":[`);let _=!0;for await(const f of V(i.inserted_keys))await o((_?"":",")+f.map(t=>JSON.stringify(t)).join(",")),_=!1;await o(`]}
|
|
2
|
+
`)}return n.end(),await r,Buffer.concat(a)}m(st,"manifestFile");export{Xe as COPY_LEASE_MS,Ve as GRANT_WAIT_MS,Ct as processRun};
|
|
@@ -4,11 +4,8 @@ export declare function selfUpdate(): void;
|
|
|
4
4
|
export interface SelfCheckResult {
|
|
5
5
|
current: string;
|
|
6
6
|
latest: string;
|
|
7
|
-
/** The npm package an update installs from: this install's own name
|
|
8
|
-
* `@north-light/cli` for an install of the deprecated `@crouter/cli`. */
|
|
7
|
+
/** The npm package an update installs from: this install's own name. */
|
|
9
8
|
package: string;
|
|
10
|
-
/** True when an update moves this install to a different package. */
|
|
11
|
-
migrating: boolean;
|
|
12
9
|
}
|
|
13
10
|
/** Check whether a newer crtr version is available on npm. The package to ask
|
|
14
11
|
* comes from scripts/self-update.mjs, so a check and an update always agree.
|
package/dist/core/self-update.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var _=Object.defineProperty;var s=(t,r)=>_(t,"name",{value:r,configurable:!0});import{spawnSync as c}from"node:child_process";import{fileURLToPath as g}from"node:url";import{join as l,dirname as x}from"node:path";import{listAllPlugins as P,listAllMarketplaces as R}from"./resolver.js";import{crtrVersion as S}from"../shared/crtr-version.js";import{fetch as i,currentSha as f,remoteSha as p}from"./git.js";import{general as m}from"./errors.js";const b=g(import.meta.url),w=x(b),T=l(w,"..",".."),h=l(T,"scripts","self-update.mjs");function y(){return S()}s(y,"currentVersion");function V(){const t=c(process.execPath,[h],{stdio:"inherit"});if(t.error)throw m(`self-update failed: ${t.error.message}`);if(t.status!==0)throw m(`self-update failed (${t.status??t.signal??"unknown"})`)}s(V,"selfUpdate");function $(){const t=c(process.execPath,[h,"--resolve"],{encoding:"utf8"});if(t.status!==0)return null;try{const r=JSON.parse(t.stdout);return typeof r.latest!="string"?null:{current:y(),latest:r.latest,package:r.package}}catch{return null}}s($,"selfCheck");function v(){const t=[],r=R();for(const e of r){if(i(e.root,e.ref).status!==0){t.push({name:e.name,kind:"marketplace",current:null,latest:null,up_to_date:!0,unreachable:!0});continue}const a=f(e.root),n=p(e.root,e.ref),o=a!==null&&n!==null?a===n:!0;t.push({name:e.name,kind:"marketplace",current:a,latest:n,up_to_date:o,unreachable:!1})}const d=P();for(const e of d){if(!e.enabled||e.sourceMarketplace)continue;const u="main";if(i(e.root,u).status!==0){t.push({name:e.name,kind:"plugin",current:null,latest:null,up_to_date:!0,unreachable:!0});continue}const n=f(e.root),o=p(e.root,u),k=n!==null&&o!==null?n===o:!0;t.push({name:e.name,kind:"plugin",current:n,latest:o,up_to_date:k,unreachable:!1})}return t}s(v,"contentCheck");export{h as SELF_UPDATE_SCRIPT,v as contentCheck,y as currentVersion,$ as selfCheck,V as selfUpdate};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.754",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -77,7 +77,6 @@
|
|
|
77
77
|
"scripts/lib/canvas-schema-gate.mjs",
|
|
78
78
|
"scripts/lib/install-source.mjs",
|
|
79
79
|
"scripts/lib/pack-args.mjs",
|
|
80
|
-
"scripts/lib/update-target.mjs",
|
|
81
80
|
"scripts/lib/runtime-deps-key.mjs",
|
|
82
81
|
"scripts/runtime-smoke.mjs",
|
|
83
82
|
"scripts/build-native-linux.mjs",
|
|
@@ -158,8 +157,8 @@
|
|
|
158
157
|
},
|
|
159
158
|
"license": "UNLICENSED",
|
|
160
159
|
"dependencies": {
|
|
161
|
-
"@north-light/identity": "0.3.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
160
|
+
"@north-light/identity": "0.3.754",
|
|
161
|
+
"@north-light/plugin": "0.3.754",
|
|
163
162
|
"@earendil-works/chord": "1.5.2",
|
|
164
163
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
165
164
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -12,7 +12,6 @@ import { pathExists, listDirs, removePath } from '../../core/fs-utils.js';
|
|
|
12
12
|
import { lsRemote } from '../../core/git.js';
|
|
13
13
|
import { cliClient } from '../api-client.js';
|
|
14
14
|
import { detectNerdFont, nerdFontInstallCommand, NERD_FONT_SELECT_HINT } from '../../core/runtime/nerd-font.js';
|
|
15
|
-
import { oldPackageInstalled } from './old-package.js';
|
|
16
15
|
import { detectPackageManager } from './setup-core.js';
|
|
17
16
|
import { validateEffectiveCommandPlugins } from '../../core/command-plugins/discovery.js';
|
|
18
17
|
import { adaptPluginContributions } from '../../core/command-plugins/compose.js';
|
|
@@ -387,13 +386,6 @@ function runNerdFontCheck() {
|
|
|
387
386
|
...(plan.command ? { command: plan.command } : {}),
|
|
388
387
|
});
|
|
389
388
|
}
|
|
390
|
-
/** `@crouton-kit/crouter` installed beside this package fights it for the `crtr` bin, and npm refuses to install over it; only uninstalling it first works. */
|
|
391
|
-
function oldPackageCheck() {
|
|
392
|
-
const old = oldPackageInstalled();
|
|
393
|
-
if (old === undefined)
|
|
394
|
-
return pass('canvas', 'package:old-crouter', 'the old @crouton-kit/crouter package is not installed');
|
|
395
|
-
return failCheck('canvas', 'package:old-crouter', old.message, { kind: 'human_action', description: 'Remove the old package, then reinstall this one', command: `${old.uninstall} && npm i -g @north-light/cli@latest` });
|
|
396
|
-
}
|
|
397
389
|
/** Where the generation was installed from (`<id>.source.json` beside it, written by install-runtime). */
|
|
398
390
|
function installSourceCheck(label, generation) {
|
|
399
391
|
const name = `runtime:${label}:source`;
|
|
@@ -638,7 +630,6 @@ export const sysDoctorLeaf = defineLeaf({
|
|
|
638
630
|
allResults.push(...runBinContributionChecks(scopes));
|
|
639
631
|
allResults.push(...runHumanActionChecks(scopes));
|
|
640
632
|
allResults.push(...await runRequiresChecks(scopes));
|
|
641
|
-
allResults.push(oldPackageCheck());
|
|
642
633
|
allResults.push(...await runFaultChecks());
|
|
643
634
|
const processLocation = processGeneration();
|
|
644
635
|
allResults.push(...await generationChecks('selected', selectedGeneration(), processLocation === null));
|
|
@@ -13,7 +13,6 @@ import { envNodeId } from '../../shared/env.js';
|
|
|
13
13
|
import { ExitCode } from '../../types.js';
|
|
14
14
|
import { insideBroker } from './join.js';
|
|
15
15
|
import { defaultDirectoryUrl, finishMove, registerThisMac, runMove, settleEarlierMove } from './import/move.js';
|
|
16
|
-
import { oldPackageInstalled } from './old-package.js';
|
|
17
16
|
import { WAIT_FOR_PID_ENV } from './import/start.js';
|
|
18
17
|
/** Open the confirm page in the person's browser; a failure to open it is harmless because the code and address are printed too. */
|
|
19
18
|
function openBrowser(url) {
|
|
@@ -126,9 +125,6 @@ export const sysSigninLeaf = defineLeaf({
|
|
|
126
125
|
// A computer with local records needs its daemon (the move reads the canvas through it) and a machine's daemon is the machine role; a fresh computer starts none until it is registered.
|
|
127
126
|
if (readMachineConfig() !== undefined || hasLocalCanvas())
|
|
128
127
|
await spawnDaemon();
|
|
129
|
-
const oldPackage = oldPackageInstalled();
|
|
130
|
-
if (oldPackage !== undefined)
|
|
131
|
-
process.stderr.write(`${oldPackage.message}\n`);
|
|
132
128
|
const directoryUrl = input.directoryUrl === undefined ? defaultDirectoryUrl() : String(input.directoryUrl);
|
|
133
129
|
const unfinished = await settleEarlierMove(showSignIn);
|
|
134
130
|
if (unfinished !== undefined) {
|
|
@@ -47,8 +47,7 @@ export const sysUpdateLeaf = defineLeaf({
|
|
|
47
47
|
kind: 'self',
|
|
48
48
|
current: r.current,
|
|
49
49
|
latest: r.latest,
|
|
50
|
-
|
|
51
|
-
up_to_date: !r.migrating && r.current === r.latest,
|
|
50
|
+
up_to_date: r.current === r.latest,
|
|
52
51
|
unreachable: false,
|
|
53
52
|
});
|
|
54
53
|
}
|
|
@@ -121,6 +121,12 @@ export async function dropExistingWatches(db, schema, target) {
|
|
|
121
121
|
const watches = await db.prepareUncached(`DELETE FROM ${sq(schema, 'watches')} s WHERE EXISTS (SELECT 1 ${same})`).run();
|
|
122
122
|
return { watches: Number(watches.changes), watch_subscriptions: Number(subs.changes) };
|
|
123
123
|
}
|
|
124
|
+
/** A hosted cron runs in its anchor node's sandbox and fails with no anchor. A Mac cron made without `--anchor` has none, so a staged cron of a hosted source with no anchor
|
|
125
|
+
* takes its creator as anchor when that node is staged (still in the bundle after the drops). The anchor's `ON DELETE CASCADE` then removes the cron with its creator. Runs after the drops. Returns the crons anchored. */
|
|
126
|
+
export async function anchorCronsToCreator(db, schema) {
|
|
127
|
+
const done = await db.prepareUncached(`UPDATE ${sq(schema, 'crons')} c SET anchor_node = c.created_by WHERE c.anchor_node IS NULL AND c.created_by IN (SELECT node_id FROM ${sq(schema, 'nodes')})`).run();
|
|
128
|
+
return Number(done.changes);
|
|
129
|
+
}
|
|
124
130
|
/** A staged idempotency key whose (grantee, key) the target already holds is already imported (a hosted person's runs the control plane has since served): it is dropped, the target's
|
|
125
131
|
* row stands, so the copy never inserts it and verify never compares it. Only this key is skipped; any other difference still fails. Returns the dropped rows. Runs before the pre-check. */
|
|
126
132
|
export async function dropExistingIdempotencyKeys(db, schema, target) {
|
|
@@ -34,7 +34,7 @@ export function selfCheck() {
|
|
|
34
34
|
const parsed = JSON.parse(res.stdout);
|
|
35
35
|
if (typeof parsed.latest !== 'string')
|
|
36
36
|
return null;
|
|
37
|
-
return { current: currentVersion(), latest: parsed.latest, package: parsed.package
|
|
37
|
+
return { current: currentVersion(), latest: parsed.latest, package: parsed.package };
|
|
38
38
|
}
|
|
39
39
|
catch {
|
|
40
40
|
return null;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.754",
|
|
4
4
|
"description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/api/index.js",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.754",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@north-light/api": "0.3.
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.754",
|
|
31
|
+
"@north-light/identity": "0.3.754"
|
|
32
32
|
},
|
|
33
33
|
"license": "UNLICENSED",
|
|
34
34
|
"publishConfig": {
|
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.754",
|
|
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.754",
|
|
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.
|
|
32
|
-
"@north-light/plugin": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.754",
|
|
32
|
+
"@north-light/plugin": "0.3.754",
|
|
33
33
|
"cron-parser": "^5.6.0",
|
|
34
34
|
"esbuild": "0.28.2",
|
|
35
35
|
"jose": "^6.2.12",
|
|
@@ -11902,17 +11902,17 @@
|
|
|
11902
11902
|
},
|
|
11903
11903
|
"packages/crouter-api": {
|
|
11904
11904
|
"name": "@north-light/api",
|
|
11905
|
-
"version": "0.3.
|
|
11905
|
+
"version": "0.3.754",
|
|
11906
11906
|
"license": "UNLICENSED"
|
|
11907
11907
|
},
|
|
11908
11908
|
"packages/crouter-env-docker": {
|
|
11909
11909
|
"name": "@north-light/env-docker",
|
|
11910
|
-
"version": "0.3.
|
|
11910
|
+
"version": "0.3.754",
|
|
11911
11911
|
"license": "UNLICENSED"
|
|
11912
11912
|
},
|
|
11913
11913
|
"packages/crouter-identity": {
|
|
11914
11914
|
"name": "@north-light/identity",
|
|
11915
|
-
"version": "0.3.
|
|
11915
|
+
"version": "0.3.754",
|
|
11916
11916
|
"license": "UNLICENSED",
|
|
11917
11917
|
"dependencies": {
|
|
11918
11918
|
"jose": "^6.2.1"
|
|
@@ -11920,21 +11920,21 @@
|
|
|
11920
11920
|
},
|
|
11921
11921
|
"packages/crouter-plugin": {
|
|
11922
11922
|
"name": "@north-light/plugin",
|
|
11923
|
-
"version": "0.3.
|
|
11923
|
+
"version": "0.3.754",
|
|
11924
11924
|
"license": "UNLICENSED",
|
|
11925
11925
|
"dependencies": {
|
|
11926
|
-
"@north-light/api": "0.3.
|
|
11927
|
-
"@north-light/identity": "0.3.
|
|
11926
|
+
"@north-light/api": "0.3.754",
|
|
11927
|
+
"@north-light/identity": "0.3.754"
|
|
11928
11928
|
}
|
|
11929
11929
|
},
|
|
11930
11930
|
"packages/crouter-sdk": {
|
|
11931
11931
|
"name": "@north-light/sdk",
|
|
11932
|
-
"version": "0.3.
|
|
11932
|
+
"version": "0.3.754",
|
|
11933
11933
|
"license": "UNLICENSED",
|
|
11934
11934
|
"dependencies": {
|
|
11935
|
-
"@north-light/api": "0.3.
|
|
11936
|
-
"@north-light/identity": "0.3.
|
|
11937
|
-
"@north-light/plugin": "0.3.
|
|
11935
|
+
"@north-light/api": "0.3.754",
|
|
11936
|
+
"@north-light/identity": "0.3.754",
|
|
11937
|
+
"@north-light/plugin": "0.3.754",
|
|
11938
11938
|
"jose": "^6.2.1"
|
|
11939
11939
|
},
|
|
11940
11940
|
"bin": {
|
|
@@ -7,7 +7,7 @@ import { existsSync } from 'node:fs';
|
|
|
7
7
|
import { homedir, hostname, userInfo } from 'node:os';
|
|
8
8
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
9
9
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
10
|
-
import { ENTRY_NAMES, GENERATION_ID,
|
|
10
|
+
import { ENTRY_NAMES, GENERATION_ID, MANIFEST_KEYS, MANIFEST_SCHEMA, PACKAGE_NAME, contained, isKnownPackageName, isSealed, publishedMarkerPath, runtimeHome, sortInventory, validateManifestShape } from '../bin/runtime-generation-manifest.mjs';
|
|
11
11
|
import { patchPiTreeRootOrdering } from './patch-pi-tree-root-ordering.mjs';
|
|
12
12
|
import { smokeValidate } from './runtime-smoke.mjs';
|
|
13
13
|
import { scrubInheritedBrokerEnv, unsafeIsolationReason } from './lib/isolation-env.mjs';
|
|
@@ -599,7 +599,7 @@ async function install() {
|
|
|
599
599
|
const manifest = {
|
|
600
600
|
schema: MANIFEST_SCHEMA,
|
|
601
601
|
id,
|
|
602
|
-
packageName:
|
|
602
|
+
packageName: PACKAGE_NAME,
|
|
603
603
|
packageVersion: pkg.version,
|
|
604
604
|
nodeVersion: process.version,
|
|
605
605
|
platform: process.platform,
|
package/scripts/self-update.mjs
CHANGED
|
@@ -4,20 +4,29 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
|
4
4
|
import { dirname, join } from 'node:path';
|
|
5
5
|
import { tmpdir } from 'node:os';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
|
-
import { resolveUpdateTarget } from './lib/update-target.mjs';
|
|
8
7
|
|
|
9
8
|
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
10
9
|
const own = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
|
|
11
10
|
const resolving = process.argv.includes('--resolve');
|
|
12
|
-
const
|
|
13
|
-
|
|
11
|
+
const PACKAGE_NAME = own.name;
|
|
12
|
+
|
|
13
|
+
/** `npm view <name> version`, or null when the package is unreachable or unpublished. */
|
|
14
|
+
function latestVersion(name) {
|
|
15
|
+
const res = spawnSync('npm', ['view', name, 'version', '--json'], { encoding: 'utf8' });
|
|
16
|
+
if (res.error || res.status !== 0) return null;
|
|
17
|
+
try {
|
|
18
|
+
const parsed = JSON.parse(res.stdout);
|
|
19
|
+
return typeof parsed === 'string' ? parsed : null;
|
|
20
|
+
} catch {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
14
24
|
|
|
15
25
|
// `--resolve` reports the package an update would install, for `crtr sys update --check`.
|
|
16
26
|
if (resolving) {
|
|
17
|
-
process.stdout.write(`${JSON.stringify({
|
|
27
|
+
process.stdout.write(`${JSON.stringify({ package: PACKAGE_NAME, latest: latestVersion(PACKAGE_NAME), current: own.version })}\n`);
|
|
18
28
|
process.exit(0);
|
|
19
29
|
}
|
|
20
|
-
if (target.migrating) process.stderr.write(`crtr: moving from ${own.name} to ${target.package} (${target.reason})\n`);
|
|
21
30
|
|
|
22
31
|
function run(command, args, options) {
|
|
23
32
|
const result = spawnSync(command, args, options);
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
export declare const OLD_PACKAGE = "@crouton-kit/crouter";
|
|
2
|
-
export declare const OLD_PACKAGE_UNINSTALL = "npm uninstall -g @crouton-kit/crouter";
|
|
3
|
-
/** Where a global install of this package sits beside the old one: `<lib>/node_modules/@north-light/cli` → `<lib>/node_modules/@crouton-kit/crouter`. */
|
|
4
|
-
export declare function oldPackageDir(packageRoot: string): string | undefined;
|
|
5
|
-
/** The old package installed next to this one, with the message that names the command that removes it; undefined when it is absent. */
|
|
6
|
-
export declare function oldPackageInstalled(packageRoot?: string): {
|
|
7
|
-
uninstall: string;
|
|
8
|
-
message: string;
|
|
9
|
-
} | undefined;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var a=Object.defineProperty;var e=(t,n)=>a(t,"name",{value:n,configurable:!0});import{existsSync as d}from"node:fs";import{dirname as c,join as o,sep as r}from"node:path";import{fileURLToPath as m}from"node:url";const i="@crouton-kit/crouter",s=`npm uninstall -g ${i}`;function u(t){const n=`${r}node_modules${r}@north-light${r}cli`,l=t.lastIndexOf(n);return l<0?void 0:o(t.slice(0,l),"node_modules",i)}e(u,"oldPackageDir");function $(t=o(c(m(import.meta.url)),"..","..","..")){const n=u(t);if(!(n===void 0||!d(o(n,"package.json"))))return{uninstall:s,message:`The old ${i} package is still installed at ${n} and owns the \`crtr\` command. Run \`${s}\`, then \`npm i -g @north-light/cli@latest\`.`}}e($,"oldPackageInstalled");export{i as OLD_PACKAGE,s as OLD_PACKAGE_UNINSTALL,u as oldPackageDir,$ as oldPackageInstalled};
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
// The old `@crouton-kit/crouter` package declares the same `crtr` bin as `@north-light/cli`. npm checks bin ownership before any install script runs,
|
|
2
|
-
// so `npm i -g @north-light/cli` over it fails with EEXIST and no script of ours can prevent that; the old package has to be uninstalled first.
|
|
3
|
-
import { existsSync } from 'node:fs';
|
|
4
|
-
import { dirname, join, sep } from 'node:path';
|
|
5
|
-
import { fileURLToPath } from 'node:url';
|
|
6
|
-
export const OLD_PACKAGE = '@crouton-kit/crouter';
|
|
7
|
-
export const OLD_PACKAGE_UNINSTALL = `npm uninstall -g ${OLD_PACKAGE}`;
|
|
8
|
-
/** Where a global install of this package sits beside the old one: `<lib>/node_modules/@north-light/cli` → `<lib>/node_modules/@crouton-kit/crouter`. */
|
|
9
|
-
export function oldPackageDir(packageRoot) {
|
|
10
|
-
const marker = `${sep}node_modules${sep}@north-light${sep}cli`;
|
|
11
|
-
const at = packageRoot.lastIndexOf(marker);
|
|
12
|
-
return at < 0 ? undefined : join(packageRoot.slice(0, at), 'node_modules', OLD_PACKAGE);
|
|
13
|
-
}
|
|
14
|
-
/** The old package installed next to this one, with the message that names the command that removes it; undefined when it is absent. */
|
|
15
|
-
export function oldPackageInstalled(packageRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..')) {
|
|
16
|
-
const dir = oldPackageDir(packageRoot);
|
|
17
|
-
if (dir === undefined || !existsSync(join(dir, 'package.json')))
|
|
18
|
-
return undefined;
|
|
19
|
-
return { uninstall: OLD_PACKAGE_UNINSTALL, message: `The old ${OLD_PACKAGE} package is still installed at ${dir} and owns the \`crtr\` command. Run \`${OLD_PACKAGE_UNINSTALL}\`, then \`npm i -g @north-light/cli@latest\`.` };
|
|
20
|
-
}
|
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
// Which npm package a self-update installs from.
|
|
2
|
-
//
|
|
3
|
-
// The CLI moved from `@crouter/cli` to `@north-light/cli`. An install of the old
|
|
4
|
-
// name keeps updating itself, and this module is how it finds the new one: an
|
|
5
|
-
// install named `@crouter/cli` switches to `@north-light/cli` as soon as the old
|
|
6
|
-
// package is deprecated, or the new one is published at the same version or
|
|
7
|
-
// later. An install already named `@north-light/cli` never looks back.
|
|
8
|
-
//
|
|
9
|
-
// The switch needs no `npm install -g`. A self-update stages a runtime
|
|
10
|
-
// generation from the downloaded tarball and leaves the global shim alone, and
|
|
11
|
-
// the shim launches whichever generation is selected (bin/runtime-selector.mjs),
|
|
12
|
-
// so installing a generation from `@north-light/cli` moves the install without
|
|
13
|
-
// touching the old package's files. A generation recorded under the old name
|
|
14
|
-
// stays valid (bin/runtime-generation-manifest.mjs, LEGACY_PACKAGE_NAMES).
|
|
15
|
-
//
|
|
16
|
-
// This file is plain JavaScript and takes npm as a parameter because
|
|
17
|
-
// scripts/self-update.mjs runs it before any compiled code is available, and
|
|
18
|
-
// src/core/self-update.ts reaches it through `self-update.mjs --resolve`.
|
|
19
|
-
import { spawnSync } from 'node:child_process';
|
|
20
|
-
|
|
21
|
-
export const CURRENT_PACKAGE = '@north-light/cli';
|
|
22
|
-
export const LEGACY_PACKAGE = '@crouter/cli';
|
|
23
|
-
|
|
24
|
-
/** Compare `X.Y.Z` release versions; a prerelease suffix is ignored. Returns <0, 0 or >0. */
|
|
25
|
-
export function compareVersions(a, b) {
|
|
26
|
-
const parts = (v) => String(v).split(/[-+]/)[0].split('.').map((n) => Number.parseInt(n, 10) || 0);
|
|
27
|
-
const left = parts(a);
|
|
28
|
-
const right = parts(b);
|
|
29
|
-
for (let i = 0; i < Math.max(left.length, right.length); i++) {
|
|
30
|
-
const delta = (left[i] ?? 0) - (right[i] ?? 0);
|
|
31
|
-
if (delta !== 0) return delta;
|
|
32
|
-
}
|
|
33
|
-
return 0;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/** `npm view <name> version deprecated`, or null when the package is unreachable or unpublished. */
|
|
37
|
-
export function npmView(name) {
|
|
38
|
-
const res = spawnSync('npm', ['view', name, 'version', 'deprecated', '--json'], { encoding: 'utf8' });
|
|
39
|
-
if (res.error || res.status !== 0) return null;
|
|
40
|
-
try {
|
|
41
|
-
const parsed = JSON.parse(res.stdout);
|
|
42
|
-
if (typeof parsed === 'string') return { version: parsed, deprecated: null };
|
|
43
|
-
if (parsed && typeof parsed.version === 'string') {
|
|
44
|
-
return { version: parsed.version, deprecated: typeof parsed.deprecated === 'string' && parsed.deprecated !== '' ? parsed.deprecated : null };
|
|
45
|
-
}
|
|
46
|
-
} catch {
|
|
47
|
-
// A body that is not JSON is the same as no answer.
|
|
48
|
-
}
|
|
49
|
-
return null;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Decide the package to update from.
|
|
54
|
-
* @param {string} ownName the installed package's name (package.json `name`)
|
|
55
|
-
* @param {string} ownVersion the installed package's version
|
|
56
|
-
* @param {(name: string) => ({ version: string, deprecated: string | null } | null)} view
|
|
57
|
-
* @param {{ needLatest?: boolean }} [options] `needLatest: false` skips the registry lookup an install of the current name
|
|
58
|
-
* would only use to report a version
|
|
59
|
-
* @returns {{ package: string, latest: string | null, migrating: boolean, reason: string }}
|
|
60
|
-
* `latest` is null when the registry could not be reached.
|
|
61
|
-
*/
|
|
62
|
-
export function resolveUpdateTarget(ownName, ownVersion, view = npmView, { needLatest = true } = {}) {
|
|
63
|
-
if (ownName !== LEGACY_PACKAGE) {
|
|
64
|
-
const own = needLatest ? view(ownName) : null;
|
|
65
|
-
return { package: ownName, latest: own?.version ?? null, migrating: false, reason: 'installed package is current' };
|
|
66
|
-
}
|
|
67
|
-
const old = view(LEGACY_PACKAGE);
|
|
68
|
-
const next = view(CURRENT_PACKAGE);
|
|
69
|
-
if (next !== null) {
|
|
70
|
-
if (old?.deprecated) {
|
|
71
|
-
return { package: CURRENT_PACKAGE, latest: next.version, migrating: true, reason: `${LEGACY_PACKAGE} is deprecated: ${old.deprecated}` };
|
|
72
|
-
}
|
|
73
|
-
if (compareVersions(next.version, old?.version ?? ownVersion) >= 0) {
|
|
74
|
-
return { package: CURRENT_PACKAGE, latest: next.version, migrating: true, reason: `${CURRENT_PACKAGE}@${next.version} is published` };
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
return { package: LEGACY_PACKAGE, latest: old?.version ?? null, migrating: false, reason: `${CURRENT_PACKAGE} is not available yet` };
|
|
78
|
-
}
|