@north-light/cli 0.3.754 → 0.3.756
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.d.ts +1 -2
- package/dist/api/client.js +3 -3
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/health.d.ts +0 -54
- package/dist/api/routes.d.ts +0 -1
- package/dist/api/routes.js +1 -1
- package/dist/build-root.d.ts +0 -3
- package/dist/build-root.js +1 -1
- package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
- package/dist/builtin-memory/internal/storage-tiers.md +1 -1
- package/dist/cli.js +8 -9
- package/dist/clients/attach/viewer.js +481 -481
- package/dist/commands/sys/branch.js +1 -1
- package/dist/commands/sys/daemon.js +1 -1
- package/dist/commands/sys.js +1 -1
- package/dist/core/bootstrap.js +1 -1
- package/dist/core/canvas/boot.d.ts +0 -25
- package/dist/core/canvas/boot.js +1 -1
- package/dist/core/canvas/executions.d.ts +0 -3
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/pid.d.ts +0 -10
- package/dist/core/canvas/pid.js +5 -5
- package/dist/core/directory/join.js +1 -1
- package/dist/core/grants/mirror.d.ts +0 -5
- package/dist/core/grants/mirror.js +6 -6
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/human/page-schema.d.ts +1 -1
- package/dist/core/io.js +4 -4
- package/dist/core/layout.d.ts +0 -2
- package/dist/core/layout.js +2 -2
- package/dist/core/runs/operations.js +7 -7
- package/dist/core/scoped-state/db.js +2 -2
- package/dist/daemon/api/handlers/daemon.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/map.d.ts +1 -6
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/control.d.ts +0 -8
- package/dist/daemon/crtrd.js +18 -20
- package/dist/daemon/manage.js +3 -3
- package/docs/sdk/release-notes.md +6 -0
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +0 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +0 -1
- package/packages/crouter-api/dist/build-root.js +0 -9
- package/packages/crouter-api/dist/commands/sys/branch.js +1 -1
- package/packages/crouter-api/dist/commands/sys/daemon.js +1 -1
- package/packages/crouter-api/dist/commands/sys.js +1 -2
- package/packages/crouter-api/dist/core/canvas/executions.js +1 -17
- package/packages/crouter-api/dist/core/canvas/pid.js +0 -16
- package/packages/crouter-api/dist/core/directory/join.js +18 -1
- package/packages/crouter-api/dist/core/grants/mirror.js +0 -7
- package/packages/crouter-api/dist/core/grants/sync.js +2 -2
- package/packages/crouter-api/dist/core/io.js +0 -5
- package/packages/crouter-api/dist/core/layout.js +2 -19
- package/packages/crouter-api/dist/core/runs/operations.js +6 -0
- package/packages/crouter-api/dist/daemon/api/map.js +0 -16
- package/packages/crouter-api/dist/daemon/api/operations.js +0 -1
- package/packages/crouter-api/dist/daemon/manage.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/dist/commands/sys/migrate.d.ts +0 -1
- package/dist/commands/sys/migrate.js +0 -1
- package/dist/core/feed/inbox-migrate.d.ts +0 -11
- package/dist/core/feed/inbox-migrate.js +0 -3
- package/dist/core/graph/bodies-boot-copy.d.ts +0 -28
- package/dist/core/graph/bodies-boot-copy.js +0 -1
- package/dist/core/layout-migrate/index.d.ts +0 -38
- package/dist/core/layout-migrate/index.js +0 -4
- package/dist/core/layout-migrate/loose-keys.d.ts +0 -2
- package/dist/core/layout-migrate/loose-keys.js +0 -1
- package/dist/core/layout-migrate/paths.d.ts +0 -30
- package/dist/core/layout-migrate/paths.js +0 -1
- package/dist/core/layout-migrate/stored-paths.d.ts +0 -9
- package/dist/core/layout-migrate/stored-paths.js +0 -11
- package/dist/core/layout-migrate/stores.d.ts +0 -30
- package/dist/core/layout-migrate/stores.js +0 -3
- package/dist/core/scoped-state/migrate.d.ts +0 -15
- package/dist/core/scoped-state/migrate.js +0 -3
- package/dist/daemon/boot-migrations.d.ts +0 -14
- package/dist/daemon/boot-migrations.js +0 -1
- package/dist/migrations/004-canvas-documents/apply.d.ts +0 -8
- package/dist/migrations/004-canvas-documents/apply.js +0 -1
- package/dist/migrations/004-canvas-documents/index.d.ts +0 -16
- package/dist/migrations/004-canvas-documents/index.js +0 -2
- package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +0 -16
- package/dist/migrations/004-canvas-documents/legacy/discover.js +0 -1
- package/dist/migrations/004-canvas-documents/legacy/history.d.ts +0 -5
- package/dist/migrations/004-canvas-documents/legacy/history.js +0 -2
- package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +0 -7
- package/dist/migrations/004-canvas-documents/legacy/nested.js +0 -1
- package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +0 -14
- package/dist/migrations/004-canvas-documents/legacy/parse.js +0 -1
- package/dist/migrations/004-canvas-documents/legacy/types.d.ts +0 -91
- package/dist/migrations/004-canvas-documents/legacy/types.js +0 -0
- package/dist/migrations/004-canvas-documents/plan.d.ts +0 -102
- package/dist/migrations/004-canvas-documents/plan.js +0 -3
- package/dist/migrations/004-canvas-documents/pointers.d.ts +0 -23
- package/dist/migrations/004-canvas-documents/pointers.js +0 -4
- package/dist/migrations/activation.d.ts +0 -17
- package/dist/migrations/activation.js +0 -2
- package/packages/crouter-api/dist/commands/sys/migrate.js +0 -79
- package/packages/crouter-api/dist/core/layout-migrate/index.js +0 -523
- package/packages/crouter-api/dist/core/layout-migrate/paths.js +0 -118
- package/packages/crouter-api/dist/core/layout-migrate/stored-paths.js +0 -424
- package/packages/crouter-api/dist/core/layout-migrate/stores.js +0 -543
- package/packages/crouter-api/dist/core/locked-file.js +0 -121
- package/packages/crouter-api/dist/core/scoped-state/db.js +0 -271
- package/packages/crouter-api/dist/core/scoped-state/legacy-profiles.js +0 -65
- package/packages/crouter-api/dist/core/scoped-state/migrate.js +0 -332
- package/packages/crouter-api/dist/core/scoped-state/schema.js +0 -52
- package/packages/crouter-api/dist/migrations/004-canvas-documents/apply.js +0 -113
- package/packages/crouter-api/dist/migrations/004-canvas-documents/index.js +0 -89
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/discover.js +0 -251
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/history.js +0 -37
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/nested.js +0 -37
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/parse.js +0 -24
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/types.js +0 -3
- package/packages/crouter-api/dist/migrations/004-canvas-documents/plan.js +0 -410
- package/packages/crouter-api/dist/migrations/004-canvas-documents/pointers.js +0 -95
- package/packages/crouter-api/dist/migrations/activation.js +0 -46
|
@@ -34,6 +34,8 @@ import { isPortableModelToken } from '../runtime/launch.js';
|
|
|
34
34
|
import { parseDurationMs } from '../wake.js';
|
|
35
35
|
import { expandModelCandidates, parseModelSpec } from '../model-routes.js';
|
|
36
36
|
import { payerOfGrant } from '../grants/mirror.js';
|
|
37
|
+
import { ownsWithoutRow } from '../grants/owner.js';
|
|
38
|
+
import { environmentPayerOfProfile } from '../ledger/index.js';
|
|
37
39
|
import { runUsage } from '../ledger/read.js';
|
|
38
40
|
import { ZERO_RUN_USAGE } from '../../api/dto/run-events.js';
|
|
39
41
|
import { isolatedBrokerLauncherAvailable } from '../runtime/host.js';
|
|
@@ -278,6 +280,10 @@ export async function startRun(principal, input, idempotencyKey, resolveAttachme
|
|
|
278
280
|
await ensureAppSpace(principal.grantee);
|
|
279
281
|
const profile = input.profile === undefined ? await ensureAppProfile(principal.grantee) : loadExactProfileManifest(input.profile);
|
|
280
282
|
const owner = profile.manifest.grantee ?? 'app:terminal';
|
|
283
|
+
// An app environment runs with no person: only an owner principal of the environment's app (no grant row, `sub` in its namespace) may start in it.
|
|
284
|
+
if (await environmentPayerOfProfile(profile.profileId) !== null && !ownsWithoutRow(owner, principal.sub, principal.grant)) {
|
|
285
|
+
throw new RunError(403, 'app_environment', `an app environment starts runs for ${owner} only, not for ${principal.sub}`, 'profile');
|
|
286
|
+
}
|
|
281
287
|
if (owner !== principal.grantee) {
|
|
282
288
|
const permission = `crtr:memory:rw:${owner}:profile:${profile.profileId}`;
|
|
283
289
|
if (!principal.resolved.some((held) => covers(held, permission)) ||
|
|
@@ -27,22 +27,6 @@ import { WorktreeError } from '../../core/worktree.js';
|
|
|
27
27
|
import { ApiError } from '../../api/errors.js';
|
|
28
28
|
import { RunError } from '../../core/runs/operations.js';
|
|
29
29
|
import { ExitCode } from '../../types.js';
|
|
30
|
-
export function toMigrateStateDTO(result, options) {
|
|
31
|
-
const { report } = result;
|
|
32
|
-
return {
|
|
33
|
-
stores: report.stores.map((s) => ({ root: s.root, owner: { ...s.owner }, docs: s.docs, ...(s.skipped === undefined ? {} : { skipped: s.skipped }) })),
|
|
34
|
-
counts: report.counts,
|
|
35
|
-
rewrites: report.rewrites,
|
|
36
|
-
dropped_fields: report.droppedFields,
|
|
37
|
-
skipped: report.skipped,
|
|
38
|
-
resolutions: report.resolutions.map((r) => ({ kind: r.kind, message: r.message, paths: r.paths })),
|
|
39
|
-
blockers: result.blockers.map((b) => ({ kind: b.kind, message: b.message, paths: b.paths })),
|
|
40
|
-
dryRun: result.dryRun,
|
|
41
|
-
pending: result.pending,
|
|
42
|
-
resumed: options.resumed,
|
|
43
|
-
...(options.resumeError === undefined ? {} : { resume_error: options.resumeError }),
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
30
|
// Node projections
|
|
47
31
|
/** Read the optional machine result without letting a missing or malformed sidecar obscure the durable outcome row. */
|
|
48
32
|
async function readStructuredResult(nodeId) {
|
|
@@ -235,7 +235,6 @@ export const OPERATIONS = [
|
|
|
235
235
|
{ name: 'canvas.get.131', method: 'GET', path: '/v1/canvas/graph', classes: ['person', 'broker'], resource: 'canvas-read' },
|
|
236
236
|
{ name: 'canvas.post.132', method: 'POST', path: '/v1/canvas/prune', classes: ['person', 'broker'], resource: 'none' },
|
|
237
237
|
{ name: 'daemon.post.133', method: 'POST', path: '/v1/daemon/restart', classes: ['person', 'broker'], resource: 'daemon-control' },
|
|
238
|
-
{ name: 'daemon.post.134', method: 'POST', path: '/v1/daemon/migrate', classes: ['person', 'broker'], resource: 'daemon-control' },
|
|
239
238
|
{ name: 'daemon.drain.start', method: 'POST', path: '/v1/daemon/drain', classes: ['person'], resource: 'daemon-control' },
|
|
240
239
|
{ name: 'daemon.drain.end', method: 'DELETE', path: '/v1/daemon/drain', classes: ['person'], resource: 'daemon-control' },
|
|
241
240
|
{ name: 'daemon.post.135', method: 'POST', path: '/v1/daemon/admit', classes: ['person', 'broker'], resource: 'daemon-control' },
|
|
@@ -63,7 +63,7 @@ export const DAEMON_ENV_STRIP_KEYS = [
|
|
|
63
63
|
const DAEMON_CRTR_ENV_NAMES = new Set([
|
|
64
64
|
'CRTR_HOME', 'CRTR_RUNTIME_HOME', 'CRTR_PIDFILE', 'CRTR_RUNTIME', 'CRTR_INSTALL_ID',
|
|
65
65
|
'CRTR_LOG', 'CRTR_DEBUG', 'CRTR_DEBUG_PID_LIVENESS', 'CRTR_TIMING', 'CRTR_TIMING_PROC',
|
|
66
|
-
'CRTR_NO_DAEMON_AUTOSTART', 'CRTR_NO_AUTO_UPDATE', 'CRTR_NO_AUTO_INIT', 'CRTR_NO_EXPORTS',
|
|
66
|
+
'CRTR_NO_DAEMON_AUTOSTART', 'CRTR_NO_AUTO_UPDATE', 'CRTR_NO_AUTO_INIT', 'CRTR_NO_EXPORTS',
|
|
67
67
|
'CRTR_POSTGRES_HOME', 'CRTR_DATABASE_URL', 'CRTR_DATABASE_SCHEMA', 'CRTR_DATABASE_POOL_MAX', 'CRTR_SCHEMA_DATABASE_URL',
|
|
68
68
|
'CRTR_DOCUMENT_PORT', 'CRTR_LAUNCHER_SOCKET', 'CRTR_API_ADDRESS', 'CRTR_DIRECTORY_URL', 'CRTR_PUBLIC_API_URL',
|
|
69
69
|
'CRTR_CANVAS_URL', 'CRTR_CANVAS_CLIENT_ID', 'CRTR_CANVAS_JWK_FILE', 'CRTR_SECRETS_KEY', 'CRTR_IMPORT_SERVICE_TOKEN',
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.756",
|
|
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.756",
|
|
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.756",
|
|
31
|
+
"@north-light/identity": "0.3.756"
|
|
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.756",
|
|
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.756",
|
|
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.756",
|
|
32
|
+
"@north-light/plugin": "0.3.756",
|
|
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.756",
|
|
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.756",
|
|
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.756",
|
|
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.756",
|
|
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.756",
|
|
11927
|
+
"@north-light/identity": "0.3.756"
|
|
11928
11928
|
}
|
|
11929
11929
|
},
|
|
11930
11930
|
"packages/crouter-sdk": {
|
|
11931
11931
|
"name": "@north-light/sdk",
|
|
11932
|
-
"version": "0.3.
|
|
11932
|
+
"version": "0.3.756",
|
|
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.756",
|
|
11936
|
+
"@north-light/identity": "0.3.756",
|
|
11937
|
+
"@north-light/plugin": "0.3.756",
|
|
11938
11938
|
"jose": "^6.2.1"
|
|
11939
11939
|
},
|
|
11940
11940
|
"bin": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const sysMigrateLeaf: import("../../core/command.js").LeafDef;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var s=Object.defineProperty;var n=(o,e)=>s(o,"name",{value:e,configurable:!0});import{defineLeaf as i}from"../../core/command.js";import{general as d}from"../../core/errors.js";import{cliClient as l,rethrowAsCliError as u}from"../api-client.js";import{layoutNeedsMigration as m}from"../../core/layout.js";import{migrateLayout as h}from"../../core/layout-migrate/index.js";const g=i({name:"migrate",description:"migrate an old runtime layout offline, then import the legacy memory stores into the canvas",whenToUse:"when the daemon reports startup `blocked` by the canvas import, or after moving from a release that kept memory as markdown stores. Run --dry-run first to see the plan and what it resolves; a write run on an imported home does nothing.",help:{name:"sys migrate",summary:"move an old runtime layout offline, then plan or run the daemon-owned canvas import",guide:"A layout migration requires the daemon to be stopped, runs in this process, and stops after writing the layout version; start the daemon and run `crtr sys migrate` again. The daemon then plans the canvas import: every legacy store (the user store, each profile store, every repository `.crouter/memory` reached from a profile project or a node's cwd, node context folders and reports) becomes documents with their revision history, owned by the person, a profile, a repo, or a node. Both stages resolve leftovers and clashes themselves (a folder with no node row is set aside, two repos with one namespace get distinct handles, an unparseable file imports as its raw text, and so on) and list each in `layout_resolutions` and `resolutions`, on the dry run too. The daemon runs the import itself at startup; only a blocker (the store migrations of a skipped release never ran) makes it write nothing and hold startup in `blocked`. The import writes in one transaction and resumes startup. The markdown files are left on disk and are never read again.",params:[{kind:"flag",name:"dry-run",type:"bool",required:!1,constraint:"Plan and report without writing. On an imported home, returns the recorded report with pending false."}],output:[{name:"loose_keys",type:"string[]",required:!1,constraint:"Loose credential paths moved or set aside; never values."},{name:"layout_moved",type:"number",required:!1,constraint:"Old-layout paths moved or stored paths rewritten on this run; present when the layout migration ran."},{name:"layout_resolutions",type:"string[]",required:!1,constraint:"One line per leftover the layout migration resolved (or, under --dry-run, will resolve): set-aside folders, moved profile files, closed worktree rows, cleared transcript paths."},{name:"layout_absent_credentials",type:"string[]",required:!1,constraint:"Old credential files the layout migration looked for and did not find (or, under --dry-run, will not find); present when the layout migration ran. An absent file is legitimate when the old home never held that credential."},{name:"stores",type:"object[]",required:!1,constraint:"Every store root found: {root, owner, docs, skipped?}; skipped is duplicate-worktree for a second checkout of an imported repo."},{name:"counts",type:"object",required:!1,constraint:"Planned (or written) totals: documents.<kind>, documents.owner.<person|profile|repo|node>, revisions, documents.rewritten, owners, stores, profile-limits, and informational counts. Empty on a write run over an imported home."},{name:"rewrites",type:"object[]",required:!1,constraint:"Pointer rewrites in head bodies: {path, from, to}."},{name:"dropped_fields",type:"object[]",required:!1,constraint:"Frontmatter fields with no canvas equivalent: {path, field}."},{name:"skipped",type:"object[]",required:!1,constraint:"Files or roots not imported, with the reason: {path, reason}."},{name:"resolutions",type:"object[]",required:!1,constraint:"Clashes the import resolved itself: {kind, message, paths}; kind is invalid-source, invalid-history, name-clash, repo-handle, profile-handle, repo-identity, or delivery-limit."},{name:"blockers",type:"object[]",required:!1,constraint:"{kind, message, paths}; kind is marker (the store migrations of a skipped release never ran). A blocker makes the command fail with this whole report in `received`; nothing is written."},{name:"dryRun",type:"boolean",required:!0,constraint:"True when nothing was written."},{name:"pending",type:"boolean",required:!1,constraint:"True while this home has not been imported."},{name:"resumed",type:"boolean",required:!1,constraint:"True only when this run resumed a blocked daemon startup."},{name:"resume_error",type:"string",required:!1,constraint:"Present when the import succeeded but normal daemon startup then failed."}],outputKind:"object",effects:["With an old layout and no layout version, refuses while a daemon answers, moves the runtime records, sets aside leftovers under runtime/set-aside/, rewrites stored paths and writes the layout version last, then stops; the next run, with the daemon started, plans or runs the canvas import.","Without --dry-run and with no blockers: stores revision bodies, converts profile project memory caps into profile delivery limits, and writes owners, documents, revisions, links, and the authoring nodes' watches in one canvas transaction, recorded so it runs once.","Under --dry-run: read-only, writes nothing."]},run:n(async o=>{const e=o.dryRun===!0,t=m()?await h(e):null;if(e&&t!==null)return{layout_resolutions:t.resolutions,layout_absent_credentials:t.absentCredentials,dryRun:e,follow_up:"Preview only \u2014 re-run without --dry-run to migrate the layout; the canvas import is planned after it."};if(t!==null)return{layout_moved:t.moved,layout_resolutions:t.resolutions,layout_absent_credentials:t.absentCredentials,dryRun:e,follow_up:"Layout migrated. Start the daemon (in a container, `docker compose exec`), then run `crtr sys migrate --dry-run` against it to plan the canvas import."};let r;try{r=await l().migrateState({dry_run:e})}catch(a){u(a)}if(r.blockers.length>0)throw d(`canvas import blocked by ${r.blockers.length} finding(s) \u2014 nothing was written`,{received:r,next:"Do what received.blockers[].message says, then run `crtr sys migrate` again."});return{...r,follow_up:r.pending?"Preview only \u2014 re-run without --dry-run to import.":e?"Already imported \u2014 this is the recorded report.":void 0}},"run")});export{g as sysMigrateLeaf};
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
export interface InboxMigrationSummary {
|
|
2
|
-
nodes: number;
|
|
3
|
-
entries: number;
|
|
4
|
-
cursors: number;
|
|
5
|
-
failures: number;
|
|
6
|
-
}
|
|
7
|
-
/** Scan every node dir under the local canvas and migrate legacy inbox state.
|
|
8
|
-
* Idempotent; a node that fails migration is reported and skipped so one bad
|
|
9
|
-
* dir cannot block daemon boot (its broker stays crash-faulted, same as
|
|
10
|
-
* before the migration existed). */
|
|
11
|
-
export declare function migrateLegacyInboxIdentities(): InboxMigrationSummary;
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
var h=Object.defineProperty;var d=(r,t)=>h(r,"name",{value:t,configurable:!0});import{existsSync as l,readFileSync as w,readdirSync as x,renameSync as I,rmSync as E,statSync as C,writeFileSync as O}from"node:fs";import{join as F}from"node:path";import{createHash as L}from"node:crypto";import{inboxPath as N,nodesRoot as R}from"../canvas/index.js";import{emitEvent as U}from"../events/emit.js";const S=/^(?!0{32}$)[0-9a-f]{32}$/,_=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,j=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;function z(r,t,e,n){return L("sha256").update(`crouter:legacy-inbox:${r}\0${t}\0${e}\0${n}`).digest("hex").slice(0,32)}d(z,"legacyIdentity");function b(r,t,e,n,i){if(i===void 0)return z(r,t,e,n);if(typeof i=="string"){if(S.test(i))return i;if(_.test(i))return i.replaceAll("-","").toLowerCase()}}d(b,"normalize");function p(r,t){const e=`${r}.tmp`;O(e,t,"utf8"),I(e,r)}d(p,"atomicWrite");function A(r){const t=N(r),e=`${t}.cursor`;let n=0,i=[];if(l(t)){const f=w(t,"utf8");if(f!==""){const s=f.split(`
|
|
2
|
-
`);s.at(-1)===""&&s.pop();const g=s.map((a,m)=>{const o=JSON.parse(a),u=b("entry",r,m,a,o.entry_id),y=b("operation",r,m,a,o.operation_id);if(u===void 0||y===void 0)throw new Error(`unmigratable inbox row ${m}: ${String(o.entry_id)}`);const $=u!==o.entry_id||y!==o.operation_id;return $&&(n+=1),o.entry_id=u,o.operation_id=y,{line:$?JSON.stringify(o):a,ts:o.ts,entry_id:u}});i=g,n>0&&p(t,g.map(a=>`${a.line}
|
|
3
|
-
`).join(""))}}if(!l(e))return{entries:n,cursor:!1};const c=w(e,"utf8").trim();if(c===""||S.test(c))return{entries:n,cursor:!1};if(_.test(c))return p(e,c.replaceAll("-","").toLowerCase()),{entries:n,cursor:!0};if(j.test(c)){let f=-1;for(let s=0;s<i.length;s+=1)i[s].ts<=c&&(f=s);return f<0?E(e):p(e,i[f].entry_id),{entries:n,cursor:!0}}throw new Error(`unrecognized inbox cursor: ${c.slice(0,64)}`)}d(A,"migrateNode");function X(){const r={nodes:0,entries:0,cursors:0,failures:0},t=R();if(!l(t))return r;for(const e of x(t))try{if(!C(F(t,e)).isDirectory())continue;const{entries:n,cursor:i}=A(e);(n>0||i)&&(r.nodes+=1,r.entries+=n,i&&(r.cursors+=1))}catch(n){r.failures+=1,U({level:"warn",event:"inbox.migrate.node_failed",node_id:e,error:n})}return r}d(X,"migrateLegacyInboxIdentities");export{X as migrateLegacyInboxIdentities};
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
/** D106 first boot on a Mac: copy every document text still in the old `<canvas home>/bodies/<hh>/<hash>` files into the `bodies` table.
|
|
2
|
-
* A file is copied only when the sha256 of its text equals its name; any other is skipped and reported. A text with NULs is stored as `canonical`
|
|
3
|
-
* makes it (NUL → U+FFFD, under the hash of that text) and every revision naming the file's hash is rekeyed to the canonical hash in the same transaction.
|
|
4
|
-
* Rows go in with `ON CONFLICT DO NOTHING` in batches of one transaction each, so an interrupted run resumes and a finished one changes nothing.
|
|
5
|
-
* The files stay in place for a rollback to the previous build. Cloud roles never call this: their text was never on a disk that survives. */
|
|
6
|
-
export interface BodiesBootCopyReport {
|
|
7
|
-
scanned: number;
|
|
8
|
-
copied: number;
|
|
9
|
-
mismatched: string[];
|
|
10
|
-
nulReplaced: Array<{
|
|
11
|
-
hash: string;
|
|
12
|
-
replaced: number;
|
|
13
|
-
}>;
|
|
14
|
-
}
|
|
15
|
-
export declare function copyBodyFilesToTable(root?: string): Promise<BodiesBootCopyReport>;
|
|
16
|
-
/** Rows #822 stored under the hash of the text before its NULs became U+FFFD. */
|
|
17
|
-
export interface BodyHashRepairReport {
|
|
18
|
-
rekeyed: number;
|
|
19
|
-
removed: number;
|
|
20
|
-
unresolved: string[];
|
|
21
|
-
}
|
|
22
|
-
/** D106 correction, every role, before readers serve: a `bodies` row whose key is not the sha256 of its text is rekeyed to the canonical hash.
|
|
23
|
-
* Rows are found by the database hashing every text and paged by key. A mismatch is repaired only when an intact original — the retained
|
|
24
|
-
* `<home>/bodies/<hh>/<hash>` file — becomes exactly the stored text under `storable`.
|
|
25
|
-
* Each page is one transaction: the canonical row is stored (or confirmed to hold the same text), every revision naming the old hash is rekeyed,
|
|
26
|
-
* and the invalid old-key row is deleted — the one place a body row is removed, as correction of an invalid duplicate, because leaving it would
|
|
27
|
-
* keep every future dump invalid. A mismatch with no such original is never rehashed: it is returned in `unresolved`. A re-run changes nothing. */
|
|
28
|
-
export declare function repairBodyHashes(root?: string): Promise<BodyHashRepairReport>;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var T=Object.defineProperty;var f=(o,s)=>T(o,"name",{value:s,configurable:!0});import{existsSync as u,readdirSync as w,readFileSync as m}from"node:fs";import{join as l}from"node:path";import{openDb as y,withCanvasWrite as E}from"../canvas/db.js";import{crtrHome as b}from"../canvas/paths.js";import{canonical as x,hashOf as d,store as R,storable as v}from"./bodies.js";const F=200;async function g(o,s,p){return(await o.prepare("UPDATE revisions SET body_hash = ? WHERE body_hash = ?").run(p,s)).changes}f(g,"rekeyRevisions");async function k(o=l(b(),"bodies")){const s={scanned:0,copied:0,mismatched:[],nulReplaced:[]};if(!u(o))return s;const p=new Set((await(await y()).prepare("SELECT hash FROM bodies").all()).map(t=>t.hash));let h=[];const r=f(async()=>{if(h.length===0)return;const t=h;h=[],await E(async a=>{for(const n of t)await R(a,n.hash,n.text)&&(s.copied+=1),n.file!==n.hash&&await g(a,n.file,n.hash)})},"flush");for(const t of w(o,{withFileTypes:!0}))if(!(!t.isDirectory()||!/^[0-9a-f]{2}$/.test(t.name)))for(const a of w(l(o,t.name))){if(!/^[0-9a-f]{64}$/.test(a)||(s.scanned+=1,p.has(a)))continue;const n=m(l(o,t.name,a),"utf8");if(d(n)!==a||!a.startsWith(t.name)){s.mismatched.push(a);continue}const{text:e,hash:i}=x(n,a);e!==n&&s.nulReplaced.push({hash:a,replaced:n.split("\0").length-1}),h.push({file:a,hash:i,text:e}),h.length>=F&&await r()}return await r(),s}f(k,"copyBodyFilesToTable");const S=50;async function B(o=l(b(),"bodies")){const s={rekeyed:0,removed:0,unresolved:[]},h=(await y()).prepare(`SELECT hash, text FROM bodies WHERE hash > ? AND encode(sha256(convert_to(text, 'UTF8')), 'hex') <> hash ORDER BY hash LIMIT ${S}`);for(let r="";;){const t=await h.all(r);if(t.length===0)break;r=t[t.length-1].hash;const a=new Map;for(const e of t){const i=l(o,e.hash.slice(0,2),e.hash);if(!u(i))continue;const c=m(i,"utf8");d(c)===e.hash&&a.set(e.hash,c)}const n=t.filter(e=>a.has(e.hash)&&v(a.get(e.hash))===e.text);for(const e of t)n.includes(e)||s.unresolved.push(e.hash);n.length!==0&&await E(async e=>{for(const i of n){const c=d(i.text);await R(e,c,i.text),s.rekeyed+=await g(e,i.hash,c),s.removed+=(await e.prepare("DELETE FROM bodies WHERE hash = ?").run(i.hash)).changes}})}return s}f(B,"repairBodyHashes");export{k as copyBodyFilesToTable,B as repairBodyHashes};
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { OldToNewPathMap } from './paths.js';
|
|
2
|
-
export { OldToNewPathMap, oldToNewPathMap } from './paths.js';
|
|
3
|
-
export interface LayoutMigration {
|
|
4
|
-
map: OldToNewPathMap;
|
|
5
|
-
moved: number;
|
|
6
|
-
/** Exactly the filesystem operations that changed a source path. */
|
|
7
|
-
changes: string[];
|
|
8
|
-
/** One line per leftover the migration resolved itself (a dry run lists what it would do). */
|
|
9
|
-
resolutions: string[];
|
|
10
|
-
/** Old stored path prefix → new path, rewritten as text in migrated markdown bodies. */
|
|
11
|
-
bodyPaths: Array<[string, string]>;
|
|
12
|
-
/** Credential sources that did not exist; legitimate when the old volume never held one. */
|
|
13
|
-
absentCredentials: string[];
|
|
14
|
-
dryRun: boolean;
|
|
15
|
-
}
|
|
16
|
-
export declare function isJunkFile(name: string): boolean;
|
|
17
|
-
/** Where a leftover the new layout has no place for is kept: `runtime/set-aside/<kind>/<name>`, never overwriting. */
|
|
18
|
-
export declare function setAsidePath(migration: LayoutMigration, kind: string, name: string): string;
|
|
19
|
-
/** Move a leftover aside (a rename; never a copy). */
|
|
20
|
-
export declare function setAside(from: string, kind: string, migration: LayoutMigration, name?: string): string;
|
|
21
|
-
/**
|
|
22
|
-
* What to do with a destination that already exists before a move. A file is
|
|
23
|
-
* renamed atomically, so a file present at both paths was never written by
|
|
24
|
-
* this migration: an identical copy drops the source, an empty file is
|
|
25
|
-
* removed, and anything else is kept aside under `runtime/set-aside/replaced/`.
|
|
26
|
-
*/
|
|
27
|
-
export type Claim = {
|
|
28
|
-
action: 'merge' | 'drop-source' | 'remove-destination' | 'set-aside-destination';
|
|
29
|
-
line?: string;
|
|
30
|
-
};
|
|
31
|
-
export declare function claim(from: string, to: string, migration: LayoutMigration, wholeDirectory?: boolean): Claim;
|
|
32
|
-
/** Rename within the volume; merge an existing directory on interrupted runs, never overwrite a file. */
|
|
33
|
-
export declare function movePath(from: string, to: string, migration: LayoutMigration, wholeDirectory?: boolean): void;
|
|
34
|
-
/** Dry-run lines for a move: the claims the real run would make, without touching anything. */
|
|
35
|
-
export declare function previewMove(from: string, to: string, migration: LayoutMigration, wholeDirectory?: boolean): void;
|
|
36
|
-
export declare function sameFile(from: string, to: string): boolean;
|
|
37
|
-
export declare function daemonAnswers(socketPath: string): Promise<boolean>;
|
|
38
|
-
export declare function migrateLayout(dryRun: boolean): Promise<LayoutMigration | null>;
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var X=Object.defineProperty;var l=(t,e)=>X(t,"name",{value:e,configurable:!0});import{DatabaseSync as _}from"node:sqlite";import{randomUUID as L}from"node:crypto";import{symlinkSync as Z,linkSync as ee,chmodSync as M,chownSync as j,closeSync as g,cpSync as te,existsSync as d,fsyncSync as C,lchownSync as ne,lstatSync as f,mkdirSync as v,openSync as S,readFileSync as w,readlinkSync as D,readSync as O,readdirSync as h,renameSync as k,rmSync as A,rmdirSync as b,unlinkSync as $,writeSync as R}from"node:fs";import{request as re}from"node:http";import{basename as T,dirname as m,isAbsolute as oe,join as c,relative as E,resolve as se}from"node:path";import{LEGACY_LOCAL_PERSON as ie}from"../canvas/legacy-person.js";import{LAYOUT_VERSION as ce,assertSupportedLayoutMarker as U}from"../layout.js";import{InputError as q}from"../io.js";import{syncDirectory as ae}from"../fs-utils.js";import{oldToNewPathMap as ue}from"./paths.js";import{conversations as le,memoryAndProfiles as de,previewStores as fe,profileFolders as pe,repairMovedRepositories as he,worktrees as me}from"./stores.js";import{storedPaths as ye}from"./stored-paths.js";import{OldToNewPathMap as Ge,oldToNewPathMap as Je}from"./paths.js";const ve=new Set([".DS_Store","Thumbs.db","desktop.ini"]);function we(t){return ve.has(t)||t.startsWith("._")}l(we,"isJunkFile");function F(t,e,n){const r=c(t.map.old.root,"runtime","set-aside",e);let o=c(r,n);for(let i=2;d(o);i++)o=c(r,`${n}.${i}`);return o}l(F,"setAsidePath");function I(t,e,n,r=T(t)){const o=F(n,e,r);return v(m(o),{recursive:!0}),k(t,o),n.moved++,n.changes.push(`${t} -> ${o} (set aside)`),o}l(I,"setAside");function be(t){const e=f(t);return e.isDirectory()?h(t).length===0:e.isFile()&&e.size===0}l(be,"empty");function W(t,e,n,r=!1){const o=f(t),i=f(e);if(o.isDirectory()&&i.isDirectory()&&!r)return{action:"merge"};if(o.isFile()&&i.isFile()&&K(t,e))return{action:"drop-source"};if(be(e))return{action:"remove-destination",line:`stray-destination: removed empty ${i.isDirectory()?"folder":"file"} ${e} that predates the migration`};const s=F(n,"replaced",E(n.map.old.root,e));return{action:"set-aside-destination",line:`stray-destination: ${e} predates the migration; moved it to ${s} and put ${t} in its place`}}l(W,"claim");function x(t,e,n,r=!1){if(d(t)&&t!==e){if(d(e)){const o=W(t,e,n,r);if(o.line&&n.resolutions.push(o.line),o.action==="merge"){for(const i of h(t))x(c(t,i),c(e,i),n);b(t);return}if(o.action==="drop-source"){A(t,{recursive:!0}),n.changes.push(`${t} (identical to ${e}; removed)`);return}o.action==="remove-destination"?(A(e,{recursive:!0}),n.changes.push(`${e} (removed)`)):I(e,"replaced",n,E(n.map.old.root,e))}v(m(e),{recursive:!0}),k(t,e),n.moved++,n.changes.push(`${t} -> ${e}`)}}l(x,"movePath");function z(t,e,n,r=!1){if(!d(t)||t===e||!d(e))return;const o=W(t,e,n,r);if(o.line&&n.resolutions.push(o.line),o.action==="merge")for(const i of h(t))z(c(t,i),c(e,i),n)}l(z,"previewMove");function B(t){const{map:e}=t,n=c(e.old.canvas,"nodes"),r=c(e.old.canvas,"canvas.db"),o=c(e.old.root,"runtime","canvas.db"),i=d(r)?r:d(o)&&f(o).size>0?o:"";if(!i){if(d(n))throw new Error("old node records exist without canvas.db");return null}const s=new _(i,{readOnly:t.dryRun||i!==r});try{if(i===r&&!t.dryRun&&s.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get().busy!==0)throw new Error("old canvas WAL is busy; stop every database user before migrating");return new Map(s.prepare("SELECT node_id, grantee FROM nodes").all().map(a=>{const u=a.grantee===ie?"terminal":a.grantee.startsWith("app:")?a.grantee.slice(4):"";if(!u)throw new Error(`node ${a.node_id} has no app assignment`);return[a.node_id,u]}))}finally{s.close()}}l(B,"canvasNodeApps");function G(t,e){const n=c(t.map.old.canvas,"nodes");if(!d(n))return[];const r=[];for(const o of h(n)){const i=c(n,o),s=f(i).isDirectory();e.has(o)&&s||r.push({path:i,remove:!s&&we(o)})}return r}l(G,"orphanNodeEntries");function J(t,e){return t.remove?`node-leftover: deleted ${t.path} (not a node record)`:`node-leftover: ${t.path} has no node row; moved to ${F(e,"nodes",T(t.path))}`}l(J,"orphanLine");function ge(t){const{map:e}=t,n=c(e.old.canvas,"nodes"),r=B(t);if(r){for(const[o,i]of r)e.node(o,i);if(d(n)){for(const o of G(t,r)){if(t.resolutions.push(J(o,t)),o.remove){$(o.path),t.changes.push(`${o.path} (removed)`);continue}const i=I(o.path,"nodes",t),s=c(e.old.targetRoot,E(e.old.root,i));for(const a of new Set([e.old.storedCanvas,e.old.storedScope,c(e.old.storedScope,"canvas")]))e.add(c(a,"nodes",T(o.path)),s)}for(const[o,i]of r){const s=c(n,o);if(d(s)){for(const a of["context","reports","attachments"])x(c(s,a),c(e.old.root,"apps",i,"nodes",o,a),t);for(const a of h(s))["worktree","view.sock","broker-launch.json","system-prompt.md","situational-context.md","injected-docs.json"].includes(a)||x(c(s,a),c(e.old.root,"runtime","nodes",o,a),t);h(s).length===0&&b(s)}}h(n).length===0&&b(n)}}}l(ge,"records");const Y=["auth.json","anthropic-credentials.json","openai-codex-credentials.json","openai-credentials.json","crouter-operations.db"];function Se(t,e,n){if(!d(t))return;if(!f(t).isFile())throw new Error(`credential source is not a regular file: ${t}`);const r=w(t);if(d(e)){(!f(e).isFile()||!w(e).equals(r))&&n.resolutions.push(`credential: kept the existing ${e}; the older ${t} differs and stays where it is`);return}v(m(e),{recursive:!0});const o=c(m(e),`.${L()}.tmp`);try{const i=S(o,"wx",384);try{for(let s=0;s<r.length;)s+=R(i,r,s,r.length-s);C(i)}finally{g(i)}if(k(o,e),!w(e).equals(r))throw new Error(`credential verification failed: ${e}`)}finally{d(o)&&$(o)}n.moved++,n.changes.push(`${t} -> ${e} (source retained)`)}l(Se,"copyCredential");function H(t){if(!d(t))return;const e=new _(t);try{if(e.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get().busy!==0)throw new Error(`SQLite WAL is busy: ${t}`)}finally{e.close()}}l(H,"checkpointDb");function K(t,e){if(f(t).size!==f(e).size)return!1;const n=S(t,"r"),r=S(e,"r"),o=Buffer.allocUnsafe(64*1024),i=Buffer.allocUnsafe(o.length);try{for(;;){const s=O(n,o,0,o.length,null);if(s===0)return!0;let a=0;for(;a<s;){const u=O(r,i,a,s-a,null);if(u===0)return!1;a+=u}if(!o.subarray(0,s).equals(i.subarray(0,s)))return!1}}finally{g(n),g(r)}}l(K,"sameFile");function P(t,e,n=!1){let r;try{r=f(e)}catch(u){if(u.code==="ENOENT")return!1;throw u}const o=f(t);if(o.isSymbolicLink())return r.isSymbolicLink()&&D(t)===D(e);if(o.isFile())return r.isFile()&&K(t,e);if(!o.isDirectory()||!r.isDirectory())return!1;const i=h(t).filter(u=>!n||u!==".git"),s=h(e).filter(u=>!n||u!==".git"),a=new Set(s);return i.length===s.length&&i.every(u=>a.has(u)&&P(c(t,u),c(e,u),n))}l(P,"sameTree");function ke(t,e,n){if(!d(t))return;if(!f(t).isDirectory())throw new Error(`hosted work is not a directory: ${t}`);if(d(e)){if(P(t,e,!0))return;if(!f(e).isDirectory()||h(e).length!==0){n.resolutions.push(`hosted-work: kept the existing ${e}; the old ${t} differs and stays where it is`);return}b(e)}v(m(e),{recursive:!0});const r=c(m(e),`.work-${L()}.migrating`);try{if(te(t,r,{recursive:!0,verbatimSymlinks:!0,preserveTimestamps:!0}),!P(t,r))throw new Error(`hosted work copy verification failed: ${t}`);k(r,e),n.moved++,n.changes.push(`${t} -> ${e} (source retained)`)}finally{d(r)&&A(r,{recursive:!0,force:!0})}}l(ke,"copyHostedWork");function Q(t){const{old:e}=t.map,n=c(e.root,"runtime"),r=c(n,"scope"),o=[];for(const i of["canvas.db","canvas.db-wal","canvas.db-shm","on-disk-migrations.json","requests","reviews","plugins","marketplaces","crtrd.log","crtrd.err","cache"])o.push([c(e.canvas,i),c(n,i)]);for(const i of["prompts","personas","config.json","profile-defaults.json","operations.db","operations.db-wal","operations.db-shm"])o.push([c(e.scope,i),c(r,i)]);for(const i of["support","prompt-reviews","plugins","marketplaces"])o.push([c(e.scope,i),c(n,i)]);return o.push([c(e.canvas,"secrets"),c(n,"secrets")]),o}l(Q,"topLevelMoves");function $e(t){const{old:e}=t.map,n=c(e.root,"runtime");H(c(e.scope,"operations.db"));for(const[r,o]of Q(t)){const i=Ee(r);x(r,o,t,!0),xe(i,r,o,t)}H(c(e.agent,"crouter-operations.db"));for(const r of Y)Se(c(e.agent,r),c(n,"secrets",r),t);process.platform==="linux"&&ke(e.work,c(e.root,"user","files"),t)}l($e,"topLevel");function Ee(t){if(!d(t)||!f(t).isDirectory())return[];const e=[];for(const n of h(t)){const r=c(t,n);if(!f(r).isSymbolicLink())continue;const o=D(r);oe(o)||e.push({name:n,target:o})}return e}l(Ee,"relativeLinks");function xe(t,e,n,r){if(!(t.length===0||!d(n)))for(const{name:o,target:i}of t){const s=c(n,o);if(!Ne(s))continue;const a=r.map.mapPath(se(e,i)),u=E(n,a);u!==i&&($(s),Z(u,s),r.changes.push(`${s}: link ${i} -> ${u}`))}}l(xe,"retargetLinks");function Ne(t){try{return f(t),!0}catch{return!1}}l(Ne,"lstatExists");function Le(t){if(process.platform!=="linux")return;if(process.getuid?.()!==0)throw new Error("Linux layout migration requires root for the ownership pass");const e=w("/etc/passwd","utf8").split(`
|
|
2
|
-
`).find(s=>s.startsWith("crtrd:")),n=w("/etc/group","utf8").split(`
|
|
3
|
-
`).find(s=>s.startsWith("crtr-data:"));if(!e||!n)throw new Error("layout migration requires crtrd user and crtr-data group");const r=Number(e.split(":")[2]),o=Number(n.split(":")[2]);if(!Number.isInteger(r)||!Number.isInteger(o))throw new Error("invalid migration user or group");const i=l((s,a)=>{if(!d(s))return;const u=f(s);if(u.isSymbolicLink()){ne(s,r,a?o:u.gid);return}if(j(s,r,a?o:u.gid),u.isDirectory()){M(s,a?1528:448);for(const y of h(s))i(c(s,y),a)}else a&&M(s,u.mode&73?504:432)},"walk");i(c(t,"runtime"),!1),i(c(t,"user"),!0),i(c(t,"apps"),!0)}l(Le,"ownership");function De(t){return new Promise(e=>{const n=re({socketPath:t,path:"/healthz",method:"GET",timeout:1e3},r=>{r.resume(),e(!0)});n.on("timeout",()=>n.destroy(new Error("daemon probe timed out"))),n.on("error",r=>{r.code==="ENOENT"||r.code==="ECONNREFUSED"?e(!1):e(!0)}),n.end()})}l(De,"daemonAnswers");async function We(t){const e=ue(),n=e.old,r=c(n.root,"runtime","layout");if(d(r))return U(r),null;const o=new Set([c(n.canvas,"crtrd.sock"),c(n.scope,"crtrd.sock"),process.platform==="linux"?"/run/crtr/api.sock":c(n.root,"runtime","api.sock")]);for(const p of o)if(await De(p))throw new q({error:"daemon_running",message:`cannot migrate while a daemon answers on ${p}`,next:"Stop the daemon that owns this volume, then run `crtr sys migrate` again."});if(process.platform==="linux"&&!d(n.agent))throw new q({error:"credential_volume_missing",message:`the old credential volume is not mounted at ${n.agent}`,next:`Mount the old provider-auth volume at ${n.agent}, then run \`crtr sys migrate\` again.`});const i=Y.map(p=>c(n.agent,p)).filter(p=>!d(p)),s={map:e,moved:0,changes:[],resolutions:[],bodyPaths:[],absentCredentials:i,dryRun:t};if(t){const p=B(s);if(p)for(const N of G(s,p))s.resolutions.push(J(N,s));for(const[N,V]of Q(s))z(N,V,s,!0);return fe(s),s}pe(s);const a=[ge,me,$e,he,de,le,ye];for(const p of a)p(s);n.canvas!==n.root&&d(n.canvas)&&h(n.canvas).length===0&&b(n.canvas),Le(n.root),v(m(r),{recursive:!0});const u=`${r}.${L()}.tmp`,y=S(u,"wx",384);try{try{if(process.platform==="linux"){const p=f(m(r));j(u,p.uid,p.gid)}R(y,`${ce}
|
|
4
|
-
`),C(y)}finally{g(y)}try{ee(u,r)}catch(p){if(p.code==="EEXIST")U(r);else throw p}}finally{$(u)}return ae(m(r)),s}l(We,"migrateLayout");export{Ge as OldToNewPathMap,W as claim,De as daemonAnswers,we as isJunkFile,We as migrateLayout,x as movePath,Je as oldToNewPathMap,z as previewMove,K as sameFile,I as setAside,F as setAsidePath};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var u=Object.defineProperty;var c=(o,i)=>u(o,"name",{value:i,configurable:!0});import{existsSync as p,mkdirSync as f,readFileSync as d,renameSync as l}from"node:fs";import{join as a}from"node:path";import{layoutRoot as y}from"../layout.js";import{listAppEnvNames as A,setAppEnvVar as E}from"../profiles/app-env-store.js";async function $(o=!1){if(process.platform!=="darwin")return[];const i=y(),m=a(i,"runtime","set-aside","loose-keys"),t=[];for(const n of["exa.key","composio.key","secrets.json"]){const e=a(i,n);if(!p(e))continue;const s=a(m,n);if(n==="exa.key"&&!(await A("app:terminal")).includes("EXA_API_KEY")){const r=d(e,"utf8").trim();if(!r||r.includes("\0")){t.push(`${e}: invalid or empty; left untouched`);continue}o||await E("app:terminal","EXA_API_KEY",r),t.push(`${e}: imported EXA_API_KEY into app:terminal`)}if(p(s)){t.push(`${e}: destination already exists; left untouched`);continue}o||(f(m,{recursive:!0,mode:448}),l(e,s)),t.push(`${e}: moved to ${s}`)}return t}c($,"migrateLooseKeys");export{$ as migrateLooseKeys};
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
export interface OldLayout {
|
|
2
|
-
root: string;
|
|
3
|
-
targetRoot: string;
|
|
4
|
-
canvas: string;
|
|
5
|
-
scope: string;
|
|
6
|
-
agent: string;
|
|
7
|
-
storedCanvas: string;
|
|
8
|
-
storedScope: string;
|
|
9
|
-
storedAgent: string;
|
|
10
|
-
work: string;
|
|
11
|
-
}
|
|
12
|
-
/** Sources are physical paths; stored prefixes are paths seen by the old daemon. */
|
|
13
|
-
export declare function oldLayout(): OldLayout;
|
|
14
|
-
export declare class OldToNewPathMap {
|
|
15
|
-
readonly old: OldLayout;
|
|
16
|
-
private readonly entries;
|
|
17
|
-
private readonly retired;
|
|
18
|
-
/** Stored paths inside a removed folder with no new location; left unchanged. */
|
|
19
|
-
readonly dangling: Set<string>;
|
|
20
|
-
constructor(old: OldLayout);
|
|
21
|
-
add(from: string, to: string): void;
|
|
22
|
-
/** A path whose planned destination changed: a worktree folder set aside instead of moving into its node. */
|
|
23
|
-
redirect(from: string, to: string): void;
|
|
24
|
-
/** A removed folder: the folder itself maps to `to`, and a stored path inside it with no finer entry is refused. */
|
|
25
|
-
retire(from: string, to: string): void;
|
|
26
|
-
node(nodeId: string, app: string): void;
|
|
27
|
-
/** Rewrites only approved old prefixes; later steps register profile and session paths. */
|
|
28
|
-
mapPath(path: string): string;
|
|
29
|
-
}
|
|
30
|
-
export declare function oldToNewPathMap(): OldToNewPathMap;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var f=Object.defineProperty;var d=(i,t)=>f(i,"name",{value:t,configurable:!0});import{existsSync as g}from"node:fs";import{homedir as u}from"node:os";import{isAbsolute as a,join as s,relative as l,resolve as h,sep as m}from"node:path";import{layoutRoot as w}from"../layout.js";function v(){const i=w(),t=process.platform==="linux",e=t&&i==="/"?"/volume":i,r=t?"/home/agent/.crouter":e,o=g(s(e,"canvas"))?s(e,"canvas"):e,n=t?"/home/agent/.pi/agent":h(process.env.PI_CODING_AGENT_DIR||s(u(),".pi","agent"));return{root:e,targetRoot:i,canvas:o,scope:e,agent:n,storedCanvas:o===e?r:s(r,"canvas"),storedScope:r,storedAgent:n,work:"/home/crtr/work"}}d(v,"oldLayout");class b{static{d(this,"OldToNewPathMap")}old;entries=new Map;retired=new Map;dangling=new Set;constructor(t){this.old=t;const e=s(t.targetRoot,"runtime"),r=s(e,"scope");for(const o of new Set([t.storedCanvas,t.storedScope,s(t.storedScope,"canvas")]))for(const n of["canvas.db","canvas.db-wal","canvas.db-shm","requests","reviews","plugins","marketplaces","secrets","crtrd.log","crtrd.err","cache"])this.add(s(o,n),s(e,n));for(const o of["prompts","personas","config.json","profile-defaults.json","operations.db","operations.db-wal","operations.db-shm"])this.add(s(t.storedScope,o),s(r,o));for(const o of["support","prompt-reviews","plugins","marketplaces"])this.add(s(t.storedScope,o),s(e,o));this.add(s(t.storedScope,"memory"),s(t.targetRoot,"user","memory")),this.add(t.storedScope,r),this.add(t.work,s(t.targetRoot,"user","files"));for(const o of["auth.json","anthropic-credentials.json","openai-codex-credentials.json","openai-credentials.json","crouter-operations.db"])this.add(s(t.storedAgent,o),s(e,"secrets",o));for(const o of new Set([t.storedCanvas,t.storedScope,s(t.storedScope,"canvas")]))this.add(s(o,"secrets","runtime-client.json"),s(e,"secrets","runtime-client.json"))}add(t,e){if(!a(t)||!a(e))throw new Error("migration paths must be absolute");const r=this.entries.get(t);if(r&&r!==e)throw new Error(`conflicting migration path: ${t}`);this.entries.set(t,e)}redirect(t,e){if(!a(t)||!a(e))throw new Error("migration paths must be absolute");this.entries.set(t,e)}retire(t,e){if(!a(t)||!a(e))throw new Error("migration paths must be absolute");const r=this.retired.get(t);if(r&&r!==e)throw new Error(`conflicting migration path: ${t}`);this.retired.set(t,e)}node(t,e){if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(t)||!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e))throw new Error("unsafe migration node or app id");const r=s(this.old.targetRoot,"runtime","nodes",t),o=s(this.old.targetRoot,"apps",e,"nodes",t);for(const n of new Set([this.old.storedCanvas,this.old.storedScope,s(this.old.storedScope,"canvas")])){const p=s(n,"nodes",t);for(const c of["job","messages","meta.json","inbox.jsonl","passive.jsonl","transcript.jsonl","session.ptr"])this.add(s(p,c),s(r,c));for(const c of["context","reports","attachments","worktree"])this.add(s(p,c),s(o,c));this.add(s(p,"context","memory"),s(this.old.targetRoot,"apps",e,"memory","nodes",t))}}mapPath(t){if(!a(t))return t;const e=this.retired.get(t);if(e)return e;let r="";for(const o of this.entries.keys())(t===o||t.startsWith(o+m))&&o.length>r.length&&(r=o);for(const o of this.retired.keys())if(t.startsWith(o+m)&&o.length>r.length)return this.dangling.add(t),t;return r?h(this.entries.get(r),l(r,t)):t}}function R(){return new b(v())}d(R,"oldToNewPathMap");export{b as OldToNewPathMap,v as oldLayout,R as oldToNewPathMap};
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import type { LayoutMigration } from './index.js';
|
|
2
|
-
export declare function storedPaths(migration: LayoutMigration): void;
|
|
3
|
-
/**
|
|
4
|
-
* Markdown links a moved profile folder by its old absolute path (or its `~/`
|
|
5
|
-
* spelling); point each at the new location. Scans the documents the canvas
|
|
6
|
-
* import reads: user and app memory, profile files, and node context. A dry
|
|
7
|
-
* run scans the same documents at their old locations and writes nothing.
|
|
8
|
-
*/
|
|
9
|
-
export declare function rewriteBodyPaths(migration: LayoutMigration): void;
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
var P=Object.defineProperty;var y=(e,c)=>P(e,"name",{value:c,configurable:!0});import{DatabaseSync as S}from"node:sqlite";import{closeSync as F,existsSync as m,fsyncSync as C,lstatSync as D,openSync as B,readFileSync as $,readdirSync as g,renameSync as J,unlinkSync as x,writeFileSync as q}from"node:fs";import{basename as L,dirname as N,join as a,relative as v,resolve as H,sep as A}from"node:path";import{homedir as G}from"node:os";function M(e,c){return typeof e=="string"?c.map.mapPath(e):Array.isArray(e)?e.map(r=>M(r,c)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,i])=>[r,M(i,c)])):e}y(M,"mappedJson");function b(e,c){const r=JSON.parse(e),i=M(r,c);return JSON.stringify(i)===JSON.stringify(r)?e:JSON.stringify(i)}y(b,"rewriteJson");function O(e,c){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(c)!==void 0}y(O,"tableExists");function T(e,c,r){if(!m(e))return;const i=new S(e);try{i.exec("BEGIN IMMEDIATE");try{for(const[f,p]of Object.entries(c)){if(!O(i,f))continue;const u=new Set(i.prepare(`PRAGMA table_info("${f}")`).all().map(o=>o.name)),d=[...(p.paths??[]).filter(o=>u.has(o)),...(p.json??[]).filter(o=>u.has(o))];if(d.length===0)continue;const s=i.prepare(`SELECT rowid AS migration_rowid, ${d.map(o=>`"${o}"`).join(", ")} FROM "${f}"`).all();for(const o of s){const l=[];for(const n of d){const t=o[n];if(typeof t!="string")continue;const h=(p.json??[]).includes(n)?b(t,r):r.map.mapPath(t);h!==t&&l.push([n,h])}l.length&&(i.prepare(`UPDATE "${f}" SET ${l.map(([n])=>`"${n}" = ?`).join(", ")} WHERE rowid = ?`).run(...l.map(([,n])=>n),o.migration_rowid),r.moved+=l.length,r.changes.push(`${e}:${f}:${String(o.migration_rowid)} (${l.map(([n])=>n).join(", ")})`))}}i.exec("COMMIT")}catch(f){throw i.exec("ROLLBACK"),f}}finally{i.close()}}y(T,"rewriteDb");const k={nodes:{paths:["cwd","fork_source_file","pi_session_file"],json:["launch_config_json","review_binding_json","metadata_json","outcome_detail_json"]},sessions:{paths:["transcript_path","fork_source_path"]},worktrees:{paths:["path","repo_root"],json:["sweep_observed_json","abandoned_json","land_intent_json","disposal_json"]},crons:{paths:["cwd"],json:["env_json","sink"]},human_action_deliveries:{paths:["cwd"],json:["argv_json","completion_json","last_failure_json"]},deliveries:{json:["adapter_json"]},reviews:{paths:["origin_session_file","review_dir","branch_file","output_path","file","presentation_dir"],json:["result_json","specification_json"]},human_requests:{paths:["request_dir","file","presentation_dir"],json:["specification_json","action_json","progress_json","feedback_json","result_json"]},run_events:{json:["body_json"]},webhook_deliveries:{json:["payload_json","document_json","last_failure_json","argv_json"]}},W={scope_owners:{paths:["root"]},profiles:{paths:["home"]},profile_projects:{paths:["path"]},profile_defaults:{paths:["directory"]},scope_bookkeeping:{paths:["active_canvas"]},scope_settings:{json:["raw_json"]}};function E(e,c,r){if(!m(e))return;const i=$(e,"utf8"),f=r(i);if(f===i)return;const p=D(e);if(!p.isFile())throw new Error(`migration path is not a regular file: ${e}`);const u=`${e}.migration-tmp`;if(m(u))throw new Error(`migration temporary file already exists: ${u}`);try{q(u,f,{flag:"wx",mode:p.mode});const d=B(u,"r");try{C(d)}finally{F(d)}J(u,e)}finally{m(u)&&x(u)}c.moved++,c.changes.push(`${e} (stored paths)`)}y(E,"rewriteFile");function _(e,c){if(m(e))for(const r of g(e,{withFileTypes:!0})){const i=a(e,r.name);r.isDirectory()?_(i,c):r.isFile()&&c(i)}}y(_,"walk");function U(e,c,r){const{map:i}=e,{old:f}=i,p=new Map,u=new Set,d=new Set;_(c,n=>{if(!n.includes("/conversations/")||!n.endsWith(".jsonl"))return;const t=L(n);p.has(t)?u.add(t):p.set(t,a(f.targetRoot,v(f.root,n)))});const s=y(n=>{if(typeof n=="string"){if(!n.startsWith(f.storedAgent+A+"sessions"+A)||d.has(n)||i.mapPath(n)!==n)return;const t=L(n);if(u.has(t)||!p.has(t)){d.has(n)||e.resolutions.push(`lost-transcript: ${n} is referenced but ${u.has(t)?"matches more than one moved transcript":"exists nowhere"}; left the reference unchanged`),d.add(n);return}i.add(n,p.get(t))}else if(Array.isArray(n))for(const t of n)s(t);else if(n!==null&&typeof n=="object")for(const t of Object.values(n))s(t)},"reference"),o=y(n=>{if(n.endsWith("/meta.json")||n.endsWith(".json")&&(n.includes("/tickets/")||n.includes("/requests/")))s(JSON.parse($(n,"utf8")));else if(n.endsWith(".jsonl")&&n.includes("/conversations/")){const t=$(n,"utf8");s(JSON.parse(t.slice(0,t.indexOf(`
|
|
2
|
-
`)<0?void 0:t.indexOf(`
|
|
3
|
-
`))))}else if(n.endsWith(".md")&&(n.includes("/memory/")||n.includes("/profiles/"))){const t=$(n,"utf8");if(!t.startsWith(`---
|
|
4
|
-
`))return;const h=t.indexOf(`
|
|
5
|
-
---`,4);if(h<0)return;for(const j of t.slice(0,h).split(`
|
|
6
|
-
`)){const w=j.match(/^\s*session_file:\s*["']?([^"'\n]+)["']?$/);w&&s(w[1])}}},"inspect");_(c,o),_(a(f.root,"user","memory"),o),_(a(r,"nodes"),o),_(a(r,"tickets"),o),_(a(r,"requests"),o);const l=a(r,"canvas.db");if(m(l)){const n=new S(l,{readOnly:!0});try{for(const[t,h]of Object.entries(k)){if(!O(n,t))continue;const j=new Set(n.prepare(`PRAGMA table_info("${t}")`).all().map(w=>w.name));for(const w of[...h.paths??[],...h.json??[]].filter(R=>j.has(R)))for(const R of n.prepare(`SELECT "${w}" AS value FROM "${t}" WHERE "${w}" LIKE ?`).all(`%${f.storedAgent}/sessions/%`))(h.json??[]).includes(w)?s(JSON.parse(R.value)):s(R.value)}}finally{n.close()}}}y(U,"recoverSessionMappings");function se(e){const{root:c}=e.map.old,r=a(c,"runtime"),i=a(c,"apps");U(e,i,r),T(a(r,"canvas.db"),k,e),T(a(r,"scope","operations.db"),W,e);const f=new Set,p=a(r,"canvas.db");if(m(p)){const s=new S(p,{readOnly:!0});try{if(O(s,"nodes")&&s.prepare("PRAGMA table_info(nodes)").all().some(o=>o.name==="cwd"))for(const o of s.prepare("SELECT cwd FROM nodes").all())f.add(o.cwd)}finally{s.close()}}const u=a(r,"scope","operations.db");if(m(u)){const s=new S(u,{readOnly:!0});try{if(O(s,"profile_projects"))for(const o of s.prepare("SELECT path FROM profile_projects").all())f.add(o.path)}finally{s.close()}}for(const s of f){const o=e.map.old.targetRoot;let l=s.startsWith(o+"/")?H(c,v(o,s)):s;for(;l!==N(l);)T(a(l,".crouter","operations.db"),W,e),l=N(l)}_(a(i),s=>{s.endsWith("/.crouter/operations.db")&&T(s,W,e),s.endsWith("/meta.json")&&E(s,e,o=>b(o,e)),s.endsWith(".md")&&(s.includes("/memory/")||s.includes("/profiles/"))&&I(s,e),s.endsWith(".jsonl")&&s.includes("/conversations/")&&X(s,e)}),_(a(c,"user","memory"),s=>{s.endsWith(".md")&&I(s,e)}),Y(e);for(const s of e.map.dangling)e.resolutions.push(`dangling-path: ${s} names a file the new layout drops; left the stored path unchanged`);_(a(c,"user","files"),s=>{s.endsWith("/.crouter/operations.db")&&T(s,W,e)}),_(a(r,"nodes"),s=>{s.endsWith("/meta.json")&&E(s,e,o=>b(o,e)),s.endsWith("/session.ptr")&&x(s)}),_(a(r,"tickets"),s=>{s.endsWith(".json")&&E(s,e,o=>b(o,e))}),_(a(r,"requests"),s=>{s.endsWith(".json")&&E(s,e,o=>b(o,e))});const d=a(r,"canvas.db");if(m(d)){const s=new S(d);try{s.exec("DROP TABLE IF EXISTS layout_header_rewrites")}finally{s.close()}}}y(se,"storedPaths");function I(e,c){E(e,c,r=>{if(!r.startsWith(`---
|
|
7
|
-
`))return r;const i=r.indexOf(`
|
|
8
|
-
---`,4);return i<0?r:r.slice(0,i).replace(/^(\s*session_file:\s*)([^\n]+)$/gm,(p,u,d)=>{const s=d.match(/^(["'])(.*)\1$/),o=s?s[2]:d.trim(),l=c.map.mapPath(o);return l===o?p:`${u}${s?s[1]:""}${l}${s?s[1]:""}`})+r.slice(i)})}y(I,"rewriteMemory");function X(e,c){const r=a(c.map.old.root,"runtime","canvas.db");if(!m(r)){E(e,c,f=>{const p=f.indexOf(`
|
|
9
|
-
`),u=p<0?f:f.slice(0,p);return b(u,c)+(p<0?"":f.slice(p))});return}const i=new S(r);try{i.exec("CREATE TABLE IF NOT EXISTS layout_header_rewrites (path TEXT PRIMARY KEY, old_header TEXT NOT NULL, new_header TEXT NOT NULL)");const f=i.prepare("SELECT old_header, new_header FROM layout_header_rewrites WHERE path = ?").get(e),p=$(e,"utf8"),u=p.indexOf(`
|
|
10
|
-
`),d=u<0?p:p.slice(0,u),s=f?.new_header??b(d,c);if(f&&d!==f.old_header&&d!==s)throw new Error(`conversation header changed during migration: ${e}`);if(!f&&s!==d){const o=a(c.map.old.targetRoot,v(c.map.old.root,e)),l=Buffer.byteLength(s)-Buffer.byteLength(d);i.exec("BEGIN IMMEDIATE");try{i.prepare("INSERT INTO layout_header_rewrites (path, old_header, new_header) VALUES (?, ?, ?)").run(e,d,s),l!==0&&O(i,"sessions")&&i.prepare("UPDATE sessions SET event_offset = event_offset + ? WHERE transcript_path = ? AND event_offset > 0").run(l,o),i.exec("COMMIT")}catch(n){throw i.exec("ROLLBACK"),n}}d!==s&&E(e,c,o=>{const l=o.indexOf(`
|
|
11
|
-
`);if((l<0?o:o.slice(0,l))!==d)throw new Error(`conversation header changed during migration: ${e}`);return s+(l<0?"":o.slice(l))}),(f||s!==d)&&i.prepare("DELETE FROM layout_header_rewrites WHERE path = ?").run(e)}finally{i.close()}}y(X,"rewriteHeader");function K(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}y(K,"escape");function Y(e){const c=e.bodyPaths;if(c.length===0)return;const r=G(),i=[];for(const[t,h]of c)i.push([t,h]),t.startsWith(r+A)&&i.push([`~${t.slice(r.length)}`,h.startsWith(r+A)?`~${h.slice(r.length)}`:h]);i.sort((t,h)=>h[0].length-t[0].length);const f=new RegExp(`(${i.map(([t])=>K(t)).join("|")})(?![A-Za-z0-9_-])`,"g"),p=new Map(i),{root:u,scope:d,canvas:s}=e.map.old,o=y(t=>{if(!t.endsWith(".md"))return;if(e.dryRun){const j=$(t,"utf8").match(f)?.length??0;j&&e.resolutions.push(`profile-extra-link: rewrote ${j} link(s) to moved profile files in ${t}`);return}let h=0;E(t,e,j=>j.replace(f,w=>(h++,p.get(w)))),h&&e.resolutions.push(`profile-extra-link: rewrote ${h} link(s) to moved profile files in ${t}`)},"visit"),l=y(t=>{if(m(t))for(const h of g(t))_(a(t,h,"context"),o)},"nodeContexts");if(e.dryRun){_(a(d,"memory"),o),_(a(d,"profiles"),o),l(a(s,"nodes"));return}_(a(u,"user","memory"),o);const n=a(u,"apps");if(m(n))for(const t of g(n))_(a(n,t,"memory"),o),_(a(n,t,"profiles"),o),_(a(n,t,"files","profiles"),o),l(a(n,t,"nodes"))}y(Y,"rewriteBodyPaths");export{Y as rewriteBodyPaths,se as storedPaths};
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import { profileSpace } from '../layout.js';
|
|
2
|
-
import type { LayoutMigration } from './index.js';
|
|
3
|
-
export interface ProfileFolder {
|
|
4
|
-
id: string;
|
|
5
|
-
source: string;
|
|
6
|
-
/** No scoped-state row: the whole folder moves to `files`. */
|
|
7
|
-
target: ReturnType<typeof profileSpace> | null;
|
|
8
|
-
files: string;
|
|
9
|
-
/** Entries with no slot in the new layout, moved under `files` at the same name. */
|
|
10
|
-
extras: string[];
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* A profile is its scoped-state row; the row is authoritative even when an
|
|
14
|
-
* interrupted run already removed the old profile folder. There is no profile
|
|
15
|
-
* folder in the new layout: the old folder's own path (the profile's
|
|
16
|
-
* scope_owners.root) becomes its memory folder. What else the folder holds is
|
|
17
|
-
* the profile's own files and moves to `apps/<app>/files/profiles/<id>/`; a
|
|
18
|
-
* folder with no row moves there whole, under the terminal app.
|
|
19
|
-
*/
|
|
20
|
-
export declare function profileFolders(migration: LayoutMigration): {
|
|
21
|
-
folders: ProfileFolder[];
|
|
22
|
-
junk: string[];
|
|
23
|
-
aside: string[];
|
|
24
|
-
};
|
|
25
|
-
export declare function memoryAndProfiles(migration: LayoutMigration): void;
|
|
26
|
-
export declare function conversations(migration: LayoutMigration): void;
|
|
27
|
-
export declare function repairMovedRepositories(migration: LayoutMigration): void;
|
|
28
|
-
export declare function worktrees(migration: LayoutMigration): void;
|
|
29
|
-
/** Every resolution the real run would make, computed without changing anything. */
|
|
30
|
-
export declare function previewStores(migration: LayoutMigration): void;
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
var se=Object.defineProperty;var h=(e,t)=>se(e,"name",{value:t,configurable:!0});import{DatabaseSync as z}from"node:sqlite";import{closeSync as re,copyFileSync as ne,existsSync as u,realpathSync as pe,fsyncSync as ce,lstatSync as $,mkdirSync as B,openSync as ae,readFileSync as T,readdirSync as E,renameSync as M,rmdirSync as F,unlinkSync as L,writeFileSync as J}from"node:fs";import{execFileSync as Y}from"node:child_process";import{basename as A,dirname as b,isAbsolute as Z,join as n,relative as k,resolve as C,sep as P}from"node:path";import{LEGACY_LOCAL_PERSON as q}from"../canvas/legacy-person.js";import{profileSpace as ie}from"../layout.js";import{isJunkFile as j,movePath as S,sameFile as O,setAside as x,setAsidePath as H}from"./index.js";import{rewriteBodyPaths as de}from"./stored-paths.js";function D(e,t){Y("git",["-c",`safe.directory=${e}`,"-C",e,...t],{stdio:"pipe"})}h(D,"gitInRepo");function _(e,t){const{root:s,targetRoot:p}=t.map.old;return C(s,k(p,e))}h(_,"physical");function N(e,t=!1){const{old:s}=e.map,p=n(s.canvas,"canvas.db"),o=n(s.root,"runtime","canvas.db"),r=u(p)?p:o;return u(r)&&$(r).size>0?new z(r,{readOnly:!t||e.dryRun}):null}h(N,"canvasDb");function W(e){return new Map(e.prepare("SELECT node_id, grantee FROM nodes").all().map(({node_id:t,grantee:s})=>{const p=s===q?"terminal":s.startsWith("app:")?s.slice(4):"";if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(p))throw new Error(`node ${t} has no valid app`);return[t,p]}))}h(W,"nodeApps");function G(e,t,s){return n(s.map.old.targetRoot,"apps",e,"files","profiles",t)}h(G,"profileFiles");function K(e,t,s,p){if(!u(e))return;if(!u(t)){S(e,t,p);return}const o=$(e),r=$(t);if(o.isDirectory()&&r.isDirectory()){for(const d of E(e))K(n(e,d),n(t,d),n(s,d),p);F(e);return}if(o.isFile()&&r.isFile()&&O(e,t)){L(e);return}const a=_(s,p);p.dryRun||S(e,a,p),p.resolutions.push(`profile-home: ${t} differs from the profile's ${e}; kept the app home's copy, moved the profile's to ${a}`)}h(K,"mergeHome");function Q(e,t,s,p){if(!u(e)||!u(t))return;const o=$(e),r=$(t);if(o.isDirectory()&&r.isDirectory()){for(const a of E(e))Q(n(e,a),n(t,a),n(s,a),p);return}o.isFile()&&r.isFile()&&O(e,t)||p.resolutions.push(`profile-home: ${t} differs from the profile's ${e}; kept the app home's copy, moved the profile's to ${_(s,p)}`)}h(Q,"previewHome");function V(e,t,s){e.bodyPaths.some(([p])=>p===t)||e.bodyPaths.push([t,s])}h(V,"bodyPath");function X(e){const{map:t}=e,s=[n(t.old.scope,"operations.db"),n(t.old.root,"runtime","scope","operations.db")].find(u),p=s?new z(s,{readOnly:!0}):null,o=new Map;try{if(p&&p.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='profiles'").get())for(const i of p.prepare("SELECT id, grantee FROM profiles").all())o.set(i.id,i.grantee)}finally{p?.close()}const r=new Map;for(const[i,c]of o){const w=c==null||c===q?"terminal":c.startsWith("app:")?c.slice(4):"",f=ie(w,i),y=n(t.old.storedScope,"profiles",i);t.retire(y,f.dir),t.add(n(y,"memory"),f.dir),t.add(n(y,"env.json"),f.env),t.add(n(y,"home"),f.home),r.set(i,{target:f,app:w})}const a=n(t.old.scope,"profiles"),d={folders:[],junk:[],aside:[]};if(!u(a))return d;for(const i of E(a)){const c=n(a,i);if(!$(c).isDirectory()){(j(i)?d.junk:d.aside).push(c);continue}if(i===".locks"){for(const l of E(c)){const v=n(c,l);!(l.endsWith(".lock")&&$(v).isFile())&&!j(l)&&d.aside.push(v)}continue}const w=n(t.old.storedScope,"profiles",i),f=r.get(i);if(!f){const l=G("terminal",i,e);t.add(w,l),V(e,w,l),d.folders.push({id:i,source:c,target:null,files:l,extras:[]});continue}const y=G(f.app,i,e),R=[];for(const l of E(c)){const v=$(n(c,l));(l==="memory"||l==="home"?v.isDirectory():l==="env.json"||l==="profile.json"||l.endsWith(".lock")?v.isFile():j(l))||(R.push(l),t.add(n(w,l),n(y,l)),V(e,n(w,l),n(y,l)))}d.folders.push({id:i,source:c,target:f.target,files:y,extras:R})}return d}h(X,"profileFolders");function g(e,t){for(const s of e.folders){s.target||t.resolutions.push(`profile-folder: ${s.source} has no profile row; moved whole to ${_(s.files,t)}`);for(const p of s.extras)t.resolutions.push(`profile-extra: ${n(s.source,p)} moved to ${_(n(s.files,p),t)}`)}for(const s of e.junk)t.resolutions.push(`profile-leftover: deleted ${s} (not profile data)`);for(const s of e.aside)t.resolutions.push(`profile-leftover: ${s} is not a profile; moved to ${H(t,"profiles",A(s))}`)}h(g,"profileLines");function Ce(e){const{map:t}=e;S(n(t.old.scope,"memory"),n(t.old.root,"user","memory"),e);const s=N(e);if(s)try{for(const[r,a]of W(s)){const d=n(t.old.root,"apps",a,"memory","nodes",r);S(n(t.old.root,"apps",a,"nodes",r,"context","memory"),d,e),S(n(t.old.canvas,"nodes",r,"context","memory"),d,e)}}finally{s.close()}const p=X(e);g(p,e);for(const{source:r,target:a,files:d,extras:i}of p.folders){if(!a){S(r,_(d,e),e,!0);continue}for(const c of i)S(n(r,c),_(n(d,c),e),e);S(n(r,"memory"),_(a.dir,e),e),S(n(r,"env.json"),_(a.env,e),e),K(n(r,"home"),_(a.home,e),n(d,"home"),e);for(const c of E(r))L(n(r,c));F(r),e.moved++,e.changes.push(`${r} (removed)`)}for(const r of p.junk)L(r);for(const r of p.aside)x(r,"profiles",e);const o=n(t.old.scope,"profiles");if(u(o)){const r=n(o,".locks");if(u(r)){for(const a of E(r))L(n(r,a));F(r)}F(o)}}h(Ce,"memoryAndProfiles");function le(e,t,s,p){if(u(e)){if(!$(e).isFile())throw new Error(`session path is not a file: ${e}`);if(B(b(t),{recursive:!0}),u(t)){if($(t).isFile()&&O(e,t))return;const o=x(t,"replaced",s,k(s.map.old.root,t));s.resolutions.push(`stray-destination: ${t} predates the migration; moved it to ${o} and put ${e} in its place`)}if(p){const o=n(b(t),`.${A(t)}.migrating`);u(o)&&L(o),ne(e,o);const r=ae(o,"r");try{ce(r)}finally{re(r)}if(!O(e,o))throw new Error(`session copy verification failed: ${e}`);M(o,t),s.moved++,s.changes.push(`${e} -> ${t} (source retained)`);return}M(e,t),s.moved++,s.changes.push(`${e} -> ${t}`)}}h(le,"moveSession");function fe(e,t,s){const p=new Set(t.prepare("SELECT s.transcript_path AS path FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.unbound_at IS NULL AND n.status IN ('active', 'idle') AND s.transcript_path IS NOT NULL").all().map(r=>r.path)),o=e.dryRun?null:t.prepare("UPDATE sessions SET transcript_path = NULL WHERE transcript_path = ?");for(const r of s)if(!(u(r.source)||u(_(r.destination,e)))){if(p.has(r.transcript_path)){e.resolutions.push(`lost-transcript: ${r.transcript_path} is missing but is a live node's current session; kept its path`);continue}o?.run(r.transcript_path),e.resolutions.push(`lost-transcript: ${r.transcript_path} is missing from both paths; cleared the session's transcript path`)}}h(fe,"lostTranscripts");function ue(e){const t=N(e,!0);if(t)try{const s=W(t),p=t.prepare("SELECT session_id, node_id, transcript_path FROM sessions WHERE transcript_path IS NOT NULL ORDER BY session_id, (unbound_at IS NULL) DESC, created_at DESC, rowid DESC").all(),o=new Map,r=new Map,a=new Map;for(const c of p){o.has(c.session_id)||o.set(c.session_id,c.node_id),a.set(c.transcript_path,(a.get(c.transcript_path)??0)+1);const w=r.get(c.transcript_path)??new Set;w.add(c.session_id),r.set(c.transcript_path,w)}const d=new Set,i=[];for(const{session_id:c,node_id:w,transcript_path:f}of p){if(d.has(f))continue;if(d.add(f),r.get(f).size!==1)throw new Error(`two conversations share a transcript: ${f}`);const y=a.get(f)>1?o.get(c):w,R=s.get(y);if(!R)throw new Error(`session belongs to unknown node: ${y}`);if(!Z(f))throw new Error(`session path is not absolute: ${f}`);const l=n(e.map.old.targetRoot,"apps",R,"conversations",y,A(f));if(f===l)continue;const v=f===e.map.old.storedAgent||f.startsWith(e.map.old.storedAgent+P),m=v?n(e.map.old.agent,k(e.map.old.storedAgent,f)):f;i.push({transcript_path:f,destination:l,source:m,retain:process.platform==="linux"&&v})}fe(e,t,i);for(const{transcript_path:c,destination:w}of i)e.map.add(c,w);if(e.dryRun)return;for(const{destination:c,source:w,retain:f}of i)le(w,_(c,e),e,f)}finally{t.close()}}h(ue,"conversations");function De(e){if(process.platform!=="linux")return;const t=N(e);if(t)try{const s=t.prepare("SELECT node_id, path, repo_root FROM worktrees").all(),p=W(t);for(const o of s){const r=e.map.mapPath(o.repo_root);if(r===o.repo_root)continue;const a=p.get(o.node_id);if(!a)throw new Error(`worktree belongs to unknown node: ${o.node_id}`);const d=_(n(e.map.old.targetRoot,"apps",a,"nodes",o.node_id,"worktree"),e);if(!u(d))continue;D(_(r,e),["worktree","repair",d]);const i=o.path.startsWith(e.map.old.storedCanvas+P)?n(e.map.old.canvas,k(e.map.old.storedCanvas,o.path)):o.path;I(i,d,e)}}finally{t.close()}}h(De,"repairMovedRepositories");function I(e,t,s){const p=h(o=>{for(const r of E(o)){const a=n(o,r);if(r===".git"&&a!==n(t,".git")&&$(a).isFile()){const d=T(a,"utf8");if(!d.startsWith("gitdir: "))throw new Error(`invalid submodule git link: ${a}`);const i=d.slice(8).trim(),c=C(b(a),i),w=n(e,k(t,a)),f=C(b(w),i),y=u(c)?c:f;if(!u(y))throw new Error(`submodule git directory missing: ${w}`);const R=s?.map.mapPath(y)??y,l=s&&R!==y?_(R,s):y;if(!u(l))throw new Error(`moved submodule git directory missing: ${l}`);c!==l&&J(a,`gitdir: ${k(b(a),l)}
|
|
2
|
-
`);const v=n(l,"config"),m=T(v,"utf8");if(!/^\s*worktree\s*=.*$/m.test(m))throw new Error(`submodule has no worktree setting: ${v}`);const oe=JSON.stringify(k(l,b(a))),U=m.replace(/^(\s*worktree\s*=).*$/m,`$1 ${oe}`);U!==m&&J(v,U)}else r!==".git"&&$(a).isDirectory()&&p(a)}},"visit");p(t)}h(I,"repairSubmoduleLinks");function he(e,t){return Y("git",["-c",`safe.directory=${e}`,"-C",e,...t],{stdio:"pipe",encoding:"utf8"})}h(he,"gitOut");function ee(e){try{return pe(e)}catch{return C(e)}}h(ee,"real");function we(e,t){try{const s=ee(t);return he(e,["worktree","list","--porcelain"]).split(`
|
|
3
|
-
`).some(p=>p.startsWith("worktree ")&&ee(p.slice(9))===s)}catch{return!1}}h(we,"registered");function ye(e,t){if(!u(e))return!1;try{const s=T(n(t,".git"),"utf8");return s.startsWith("gitdir: ")?u(C(t,s.slice(8).trim())):!1}catch{return!1}}h(ye,"repairable");function te(e,t,s){s.dryRun||t.state!=="open"&&t.cleanup_state==="complete"||e.prepare("UPDATE worktrees SET state = CASE WHEN state = 'open' THEN 'closed' ELSE state END, cleanup_state = 'complete', closed_at = COALESCE(closed_at, ?) WHERE node_id = ?").run(new Date().toISOString(),t.node_id)}h(te,"closeRow");function _e(e){const t=N(e,!0);if(t){try{const s=W(t),p=t.prepare("SELECT node_id, state, cleanup_state, path, repo_root FROM worktrees").all();for(const o of p){const r=s.get(o.node_id);if(!r)throw new Error(`worktree belongs to unknown node: ${o.node_id}`);if(!Z(o.path))throw new Error(`worktree path is not absolute: ${o.path}`);const a=n(e.map.old.targetRoot,"apps",r,"nodes",o.node_id,"worktree");if(o.path===a)continue;const d=o.path===e.map.old.storedCanvas||o.path.startsWith(e.map.old.storedCanvas+P)?n(e.map.old.canvas,k(e.map.old.storedCanvas,o.path)):o.path,i=_(a,e);if(!u(d)){e.map.add(o.path,a),u(i)?!e.dryRun&&u(o.repo_root)&&(D(o.repo_root,["worktree","repair",i]),I(d,i)):o.state!=="open"&&o.cleanup_state==="complete"||(te(t,o,e),e.resolutions.push(`missing-worktree: ${o.path} (node ${o.node_id}) is gone; closed its row`));continue}if(!we(o.repo_root,d))if(o.state==="open"&&ye(o.repo_root,d))e.resolutions.push(`unregistered-worktree: ${o.path} (node ${o.node_id}) is not registered in ${o.repo_root}; relinked it with git worktree repair`),e.dryRun||D(o.repo_root,["worktree","repair",d]);else{const c=H(e,"worktrees",A(d));e.resolutions.push(`unregistered-worktree: ${o.path} (node ${o.node_id}${o.state==="open"?"":`, ${o.state}`}) is not a worktree of ${u(o.repo_root)?o.repo_root:`the missing repository ${o.repo_root}`}; ${o.state==="open"?"closed its row and ":""}moved the folder to ${c}`),e.map.redirect(o.path,n(e.map.old.targetRoot,k(e.map.old.root,c))),e.dryRun||(x(d,"worktrees",e),te(t,o,e));continue}if(e.map.add(o.path,a),u(i)){const c=H(e,"replaced",k(e.map.old.root,i));e.resolutions.push(`stray-destination: ${i} predates the migration; moved it to ${c} and put the worktree ${d} in its place`),e.dryRun||x(i,"replaced",e,k(e.map.old.root,i))}if(!e.dryRun){B(b(i),{recursive:!0});try{D(o.repo_root,["worktree","move",d,i])}catch(c){if(!String(c.stderr??"").includes("submodule"))throw c;M(d,i),D(o.repo_root,["worktree","repair",i])}I(d,i),e.moved++,e.changes.push(`${d} -> ${i} (git worktree move)`)}}}finally{t.close()}e.dryRun||$e(e)}}h(_e,"worktrees");function $e(e){const t=n(e.map.old.canvas,"nodes");if(u(t)){for(const s of E(t)){const p=n(t,s);$(p).isDirectory()&&E(p).length===0&&F(p)}E(t).length===0&&F(t)}}h($e,"pruneOldNodeFolders");function Ae(e){_e(e);const t=X(e);g(t,e);for(const{source:s,target:p,files:o}of t.folders)p&&Q(n(s,"home"),_(p.home,e),n(o,"home"),e);ue(e),de(e)}h(Ae,"previewStores");export{ue as conversations,Ce as memoryAndProfiles,Ae as previewStores,X as profileFolders,De as repairMovedRepositories,_e as worktrees};
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { type PersonSnapshot } from './person-store.js';
|
|
2
|
-
/** Conversion is intentionally explicit. Deployment coordination must prove all legacy writers at these shared roots are stopped before calling it. */
|
|
3
|
-
export declare function convertLegacyScopedStore(input: {
|
|
4
|
-
kind: 'user' | 'project' | 'provider';
|
|
5
|
-
root: string;
|
|
6
|
-
}): void;
|
|
7
|
-
/** Converts legacy provider pools only after the activation owner has stopped every writer sharing this agent directory. */
|
|
8
|
-
export declare function convertLegacyProviderStore(agentDir: string): Promise<void>;
|
|
9
|
-
export declare function personStoresCopied(): Promise<boolean>;
|
|
10
|
-
/** Copy this install's files into the person's rows, once: profiles, scope settings and bookkeeping, the plugin and marketplace
|
|
11
|
-
* lists, managed model accounts with their cooldowns, rotation settings, the OpenAI device id, `auth.json` API keys and the profile, app and deployment env files (sealed into `env_vars`). One
|
|
12
|
-
* transaction, skipping any key a row already holds, ending with `canvas_meta.person_stores_copied`. The files stay, unread. */
|
|
13
|
-
export declare function copyPersonStoresToRows(person: string, legacyUserSnapshot: PersonSnapshot | null, agentDir: string): Promise<void>;
|
|
14
|
-
/** The install's person just became known: copy the old local files into their rows once, then load their snapshot. */
|
|
15
|
-
export declare function adoptInstallPerson(person: string): Promise<void>;
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
var K=Object.defineProperty;var p=(e,t)=>K(e,"name",{value:t,configurable:!0});import{prepared as E}from"../sqlite-statements.js";import{randomUUID as Y}from"node:crypto";import{chmodSync as R,copyFileSync as G,existsSync as y,mkdirSync as g,readFileSync as S,readdirSync as b,statSync as I}from"node:fs";import{basename as B,dirname as j,join as m,relative as X}from"node:path";import q from"proper-lockfile";import{CONFIG_FILE as F,PROFILE_DIR as z,STATE_FILE as k}from"../../types.js";import{LockedJsonFile as Q}from"../locked-file.js";import{assertScopedStoreReady as Z,createScopedStore as C,openScopedStore as $,discardIncompleteScopedStore as ee,legacyScopedStorePaths as D,PROFILE_ID_SHAPE as te,scopedStoreExists as v,withProjectStateLock as re,writeOwnerRoot as oe}from"./db.js";import{canonicalRoot as ae,providerStore as h,projectStore as ie,userStore as ne}from"./paths.js";import{profileSpace as P,appSpace as se}from"../layout.js";import{createScopedSchema as x}from"./schema.js";import{openDb as ce,withCanvasWrite as le}from"../canvas/db.js";import{loadSecretsKey as fe,seal as de}from"../secrets/index.js";import{putEnvRowIfAbsent as pe}from"../secrets/env-rows.js";import{DEPLOYMENT_ID as ue}from"../secrets/environment-secrets.js";import{isReservedEnvName as V,validateEnvVarName as me}from"../env-name.js";import{insertAccount as _e,upsertModelCooldown as ye}from"../subscription-state.js";import{userScopeRoot as Ee}from"../scope.js";import{secretsDir as U}from"../layout.js";import{readLegacyUserSnapshot as we}from"./legacy-profiles.js";import{revisionOf as ve}from"./person-store.js";import{loadPersonSettings as Se,applyOpsToRows as he,readSnapshotFromRows as ge}from"./person-rows.js";function w(e){return JSON.parse(S(e,"utf8"))}p(w,"json");function W(e){return e.some(y)}p(W,"existsLegacy");function O(e,t){const o=m(e,".legacy-scoped-state");try{g(o,{mode:448})}catch(a){if(a.code!=="EEXIST"||!I(o).isDirectory())throw a}R(o,448);for(const a of t)if(y(a)&&I(a).isFile()){const i=X(e,a);if(i===""||i.startsWith(".."))throw new Error(`legacy state is outside its owning root: ${a}`);const r=m(o,i);j(r)!==o&&g(j(r),{recursive:!0,mode:448}),G(a,r),R(r,384)}}p(O,"preserve");function Ie(e){const t=e.kind==="user"?ne(e.root):e.kind==="project"?ie(e.root):h(e.root);if(e.kind!=="project"&&v(t))return;if(e.kind==="provider")throw new Error("provider conversion requires convertLegacyProviderStore() under coordinated shared-agent-dir activation");const o=D(t),a=p(()=>{e.kind==="project"&&ee(t),!v(t)&&(e.kind==="project"&&W(o)&&O(t.root,o),C(t,i=>{x(i,e.kind);const r=e.kind==="user"?"user":"project";oe(i,r,t.root),e.kind==="user"?Ae(i,t.root):N(i,r,m(t.root,k))}),e.kind==="user"&&W(o)&&O(t.root,o))},"convert");e.kind==="project"?re(t.root,()=>{a(),Z(t)}):a()}p(Ie,"convertLegacyScopedStore");function ke(e){if(!y(e))return[];const t=JSON.parse(S(e,"utf8"));if(!Array.isArray(t))throw new Error(`legacy subscription pool is malformed: ${e}`);const o=new Set;return t.map((a,i)=>{if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`legacy subscription pool entry ${i+1} is malformed: ${e}`);const r=a,l=typeof r.label=="string"?r.label.trim():"",d=typeof r.refresh=="string"?r.refresh.trim():"",n=typeof r.access=="string"?r.access.trim():"",s=Number(r.expires);if(!l||!d||!n||!Number.isFinite(s))throw new Error(`legacy subscription pool entry ${i+1} is incomplete: ${e}`);const c=l.toLowerCase();if(o.has(c))throw new Error(`legacy subscription pool has duplicate label "${l}": ${e}`);o.add(c);const f=p(u=>Number.isFinite(Number(r[u]))?Number(r[u]):0,"timing"),_=typeof r.accountId=="string"&&r.accountId.trim()!==""?r.accountId.trim():void 0;return{label:l,refresh:d,access:n,expires:s,rateLimitedUntil:f("rateLimitedUntil"),lastAttemptAt:f("lastAttemptAt"),lastRateLimitedAt:f("lastRateLimitedAt"),...r.authFailure==="invalid_grant"?{authFailure:"invalid_grant"}:{},..._?{accountId:_}:{}}})}p(ke,"parseLegacyProviderPool");function Oe(e){if(!y(e))return{};const t=JSON.parse(S(e,"utf8"));if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`legacy provider rotation settings are malformed: ${e}`);const o=t;return{...o.defaultFallbackStrength==="ultra"||o.defaultFallbackStrength==="strong"||o.defaultFallbackStrength==="medium"||o.defaultFallbackStrength==="light"?{defaultFallbackStrength:o.defaultFallbackStrength}:{},...typeof o.revertWhenAvailable=="boolean"?{revertWhenAvailable:o.revertWhenAvailable}:{}}}p(Oe,"parseLegacyRotation");async function Ne(e,t){const o=[];try{for(const a of e)y(a)&&o.push(await q.lock(a,{realpath:!1,retries:0,stale:3e4,update:1e4}));return await t()}finally{await Promise.allSettled(o.reverse().map(a=>a()))}}p(Ne,"withLegacyProviderLocks");async function rt(e){const t=h(e);if(v(t))return;const o=D(t);await Ne(o,async()=>{if(v(t))return;const a=new Map(o.slice(0,2).map((r,l)=>[l===0?"anthropic":"openai-codex",ke(r)])),i=Oe(o[2]);g(t.root,{recursive:!0,mode:448}),O(t.root,o);for(const[r,l]of a){const d=Object.fromEntries(l.map(s=>[Y(),{refresh:s.refresh,access:s.access,expires:s.expires,...s.accountId?{accountId:s.accountId}:{}}]));await new Q(m(t.root,`${r}-credentials.json`),!0,`{"version":1,"accounts":{}}
|
|
2
|
-
`).withLockAsync(async(s,c,f)=>(f(`${JSON.stringify({version:1,accounts:d})}
|
|
3
|
-
`),{result:void 0}))}C(t,r=>{x(r,"provider");for(const[l,d]of a){const n=JSON.parse(S(m(t.root,`${l}-credentials.json`),"utf8")),s=Object.keys(n.accounts),c=E(r,"INSERT INTO managed_accounts(provider_id,id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure) VALUES(?,?,?,?,?,?,?,?,?)");d.forEach((f,_)=>c.run(l,s[_],f.label,f.label.toLowerCase(),_,f.lastAttemptAt,f.lastRateLimitedAt,f.rateLimitedUntil,f.authFailure??null))}(i.defaultFallbackStrength!==void 0||i.revertWhenAvailable!==void 0)&&E(r,"INSERT INTO rotation_settings(singleton,default_fallback_strength,revert_when_available) VALUES(1,?,?)").run(i.defaultFallbackStrength??null,i.revertWhenAvailable===void 0?null:i.revertWhenAvailable?1:0)})})}p(rt,"convertLegacyProviderStore");function M(e,t,o){if(!y(o))return;const a=w(o);if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`legacy config is malformed: ${o}`);E(e,"INSERT INTO scope_settings(owner_key,raw_json) VALUES(?,?)").run(t,JSON.stringify(a))}p(M,"importSettings");function N(e,t,o){if(!y(o))return;const a=w(o);if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`legacy state is malformed: ${o}`);const i=a;E(e,"INSERT INTO scope_bookkeeping(owner_key,last_self_check,active_canvas) VALUES(?,?,?)").run(t,i.last_self_check??null,i.activeCanvas??null);const r=E(e,"INSERT INTO scope_marketplaces(owner_key,name,last_updated) VALUES(?,?,?)");for(const[d,n]of Object.entries(i.marketplaces??{}))r.run(t,d,n.last_updated??null);const l=E(e,"INSERT INTO scope_plugins(owner_key,name,last_updated,etag,checked_at) VALUES(?,?,?,?,?)");for(const[d,n]of Object.entries(i.plugins??{}))l.run(t,d,n.last_updated??null,n.etag??null,n.checked_at??null)}p(N,"importState");function Ae(e,t){M(e,"user",m(t,F)),N(e,"user",m(t,k));const o=m(t,z);if(y(o))for(const i of b(o,{withFileTypes:!0})){if(!i.isDirectory()||!te.test(i.name))continue;const r=i.name,l=m(o,r),d=m(l,"profile.json");if(!y(d))throw new Error(`legacy profile manifest is missing: ${d}`);const n=w(d);if(!n||typeof n!="object"||!Array.isArray(n.projects)||typeof n.name!="string"||typeof n.created_at!="string")throw new Error(`legacy profile manifest is malformed: ${d}`);E(e,"INSERT INTO profiles(id,name,created_at,last_used_at,paused_at,default_kind,grantee,metadata_json) VALUES(?,?,?,?,?,?,?,?)").run(r,n.name,n.created_at,n.last_used_at??null,n.paused_at??null,n.default_kind??null,n.grantee??null,JSON.stringify(n.metadata??{})),E(e,"INSERT INTO scope_owners(owner_key,kind,root,profile_id) VALUES(?,?,?,?)").run(`profile:${r}`,"profile",ae(P(n.grantee??"app:terminal",r).dir),r);const s=E(e,"INSERT INTO profile_projects(profile_id,path,position) VALUES(?,?,?)"),c=E(e,"INSERT INTO legacy_project_caps(profile_id,path,memory) VALUES(?,?,?)");n.projects.forEach((f,_)=>{s.run(r,f.path,_),f.memory!==void 0&&f.memory!=="content"&&c.run(r,f.path,f.memory)}),M(e,`profile:${r}`,m(l,F)),N(e,`profile:${r}`,m(l,k))}const a=m(t,"profile-defaults.json");if(y(a)){const i=w(a);if(i===null||typeof i!="object"||Array.isArray(i))throw new Error(`legacy profile defaults are malformed: ${a}`);const r=E(e,"INSERT INTO profile_defaults(directory,profile_id) VALUES(?,?)");for(const[l,d]of Object.entries(i)){if(typeof d!="string")throw new Error(`legacy profile default is malformed: ${a}`);r.run(l,d)}}}p(Ae,"importUser");const A="person_stores_copied",L={anthropic:"anthropic-credentials.json","openai-codex":"openai-codex-credentials.json",openai:"openai-credentials.json"};async function Le(){return await(await ce()).prepare("SELECT value FROM canvas_meta WHERE key = ?").get(A)!==void 0}p(Le,"personStoresCopied");function Te(e){const t=h(e);if(!v(t))return[];const o=$(t),a=[];for(const i of Object.keys(L)){const r=m(e,L[i]);if(!y(r))continue;const l=w(r),d=E(o,"SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM managed_account_model_cooldowns WHERE provider_id=?").all(i);for(const n of E(o,"SELECT id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure FROM managed_accounts WHERE provider_id=? ORDER BY position").all(i)){const s=l.accounts?.[n.id];s!==void 0&&a.push({provider:i,id:n.id,row:{providerId:i,id:n.id,label:n.label,labelKey:n.label_key,position:n.position,lastAttemptAt:n.last_attempt_at,lastRateLimitedAt:n.last_rate_limited_at,rateLimitedUntil:n.rate_limited_until,...n.auth_failure?{authFailure:n.auth_failure}:{}},tokens:{refresh:s.refresh,access:s.access,expires:s.expires,...s.accountId?{accountId:s.accountId}:{},...s.clientId?{clientId:s.clientId}:{}},cooldowns:d.filter(c=>c.account_id===n.id).map(c=>({family:c.family,until:c.rate_limited_until,at:c.last_rate_limited_at}))})}}return a}p(Te,"readLegacyAccounts");function T(e,t){if(!y(e)||!I(e).isFile())return{};let o;try{o=w(e)}catch{return{}}const a={};if(o===null||typeof o!="object"||o.vars===null||typeof o.vars!="object"||Array.isArray(o.vars))return a;for(const[i,r]of Object.entries(o.vars))me(i).isValid&&t(i)&&typeof r=="string"&&!r.includes("\0")&&(a[i]=r);return a}p(T,"readLegacyEnvFile");const Re=new Set(["CRTR_FEEDBACK_ENDPOINT","CRTR_FEEDBACK_TOKEN"]);async function be(e,t,o){const a=m(U(),"env");if(!y(a))return;const i=p(async(r,l)=>{for(const[d,n]of Object.entries(l))await pe(e,r,d,n)},"put");for(const r of o)await i({person:t,kind:"profile",id:r.profileId},T(P(r.manifest.grantee??"app:terminal",r.profileId).env,l=>!V(l)));for(const r of b(a,{withFileTypes:!0})){if(!r.isDirectory())continue;const l=`app:${r.name}`;B(se(l).root)===r.name&&await i({person:t,kind:"app",id:l},T(m(a,r.name,"_app"),d=>!V(d)))}await i({person:null,kind:"deployment",id:ue},T(m(a,"_deployment"),r=>Re.has(r)))}p(be,"copyLegacyEnvFiles");async function je(e,t,o){const a=Te(o),i=(()=>{const s=h(o);if(v(s))return E($(s),"SELECT default_fallback_strength,revert_when_available FROM rotation_settings WHERE singleton=1").get()})(),r=m(o,"openai-device-id"),l=y(r)?S(r,"utf8").trim():"",d=m(o,"auth.json"),n=y(d)?Object.entries(w(d)).filter(([s])=>!(s in L)):[];await le(async s=>{if(await s.prepare("SELECT 1 FROM canvas_meta WHERE key = ?").get(A)===void 0){if(t!==null){const c=await ge(s,e),f=[],_=new Set(c.profiles.map(u=>u.profileId));for(const u of t.profiles)_.has(u.profileId)||f.push({op:"profile.insert",profile:u});for(const u of Object.keys(t.settings))c.settings[u]===void 0&&f.push({op:"settings.replace",owner:u,raw:t.settings[u],ifRevision:ve(void 0)});for(const u of Object.keys(t.state)){const H=t.state[u];c.state[u]===void 0&&(u==="user"||_.has(u.replace(/^profile:/,""))||t.profiles.some(J=>`profile:${J.profileId}`===u))&&f.push({op:"state.write",owner:u,state:H})}Object.keys(c.defaults).length===0&&Object.keys(t.defaults).length>0&&f.push({op:"defaults.replace",defaults:t.defaults}),f.length>0&&await he(s,e,f)}for(const c of a)if(await s.prepare("SELECT 1 FROM model_accounts WHERE person=? AND provider_id=? AND (id=? OR label_key=?)").get(e,c.provider,c.id,c.row.labelKey)===void 0){await _e(s,e,c.provider,c.row,c.tokens);for(const _ of c.cooldowns)await ye(s,e,c.provider,c.id,_.family,_.until,_.at)}i!==void 0&&await s.prepare("INSERT INTO model_settings(person,default_fallback_strength,revert_when_available) VALUES(?,?,?) ON CONFLICT(person) DO NOTHING").run(e,i.default_fallback_strength,i.revert_when_available),/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(l)&&await s.prepare("INSERT INTO model_settings(person,openai_device_id) VALUES(?,?) ON CONFLICT(person) DO UPDATE SET openai_device_id=COALESCE(model_settings.openai_device_id,EXCLUDED.openai_device_id)").run(e,l.toLowerCase());for(const[c,f]of n){const{sealed:_,keyId:u}=de(JSON.stringify(f),fe(),`model_api_keys|${e}|${c}`);await s.prepare("INSERT INTO model_api_keys(person,provider_id,credential_sealed,key_id,updated_at) VALUES(?,?,?,?,?) ON CONFLICT(person,provider_id) DO NOTHING").run(e,c,_,u,new Date().toISOString())}await be(s,e,t?.profiles??[]),await s.prepare("INSERT INTO canvas_meta(key,value) VALUES(?,?)").run(A,new Date().toISOString())}})}p(je,"copyPersonStoresToRows");async function ot(e){if(!await Le()){const t=Ee();Ie({kind:"user",root:t}),await je(e,we(t),U())}await Se(e)}p(ot,"adoptInstallPerson");export{ot as adoptInstallPerson,rt as convertLegacyProviderStore,Ie as convertLegacyScopedStore,je as copyPersonStoresToRows,Le as personStoresCopied};
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
export interface BootMigrationResult {
|
|
2
|
-
changed: boolean;
|
|
3
|
-
summary: Record<string, unknown>;
|
|
4
|
-
}
|
|
5
|
-
export interface BootMigration {
|
|
6
|
-
readonly id: string;
|
|
7
|
-
readonly description: string;
|
|
8
|
-
/** Runs unconditionally at every daemon boot. Must be safe to re-run every
|
|
9
|
-
* time (idempotent via its own convergence, not a version gate) and must
|
|
10
|
-
* isolate its own per-item failures — a thrown error here is NOT caught by
|
|
11
|
-
* the boot sequence and would abort daemon startup. */
|
|
12
|
-
apply(): BootMigrationResult | Promise<BootMigrationResult>;
|
|
13
|
-
}
|
|
14
|
-
export declare const BOOT_MIGRATIONS: readonly BootMigration[];
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var c=Object.defineProperty;var o=(e,t)=>c(e,"name",{value:t,configurable:!0});import{migrateLegacyInboxIdentities as p}from"../core/feed/inbox-migrate.js";import{backfillComputedRev as h}from"../core/grants/mirror.js";import{copyBodyFilesToTable as m,repairBodyHashes as f}from"../core/graph/bodies-boot-copy.js";import{listProfiles as u,fillProfileProjectRepo as y}from"../core/profiles/manifest.js";import{reposForCwd as g,warmCheckoutIdentities as b}from"../core/graph/repo-sync/repos.js";import{withCanvasWrite as v}from"../core/canvas/db.js";import{isCloudRole as a}from"../core/canvas/person-state.js";import{emitEvent as n}from"../core/events/emit.js";const F=[{id:"legacy-inbox-identities",description:"normalize pre-cutover inbox entry/operation ids (UUID-spelled or missing) and cursors (ISO-timestamp boundaries) into canonical 32-lowercase-hex identities the strict inbox reader requires.",apply:o(()=>{const e=p();return{changed:e.nodes>0||e.failures>0,summary:{...e}}},"apply")},{id:"grant-computed-rev",description:"mark grant rows a pre-C-D2 build wrote (scopes computed, computed_rev NULL) as computed for their revision, so the terminal grant reads as active before the first directory sync after an upgrade or rollback (NL-550). A cloud role skips it: the directory owns its shared rows.",apply:o(async()=>{if(a())return{changed:!1,summary:{}};try{const e=await h();return{changed:e>0,summary:{rows:e}}}catch(e){return n({level:"warn",event:"daemon.boot_migration.failed",error:e,fields:{migration:"grant-computed-rev"}}),{changed:!1,summary:{}}}},"apply")},{id:"bodies-to-table",description:"copy document text from the old <home>/bodies files into the bodies table (D106). Verifies each file by sha256, skips and reports mismatches, leaves the files for rollback. A cloud role copies nothing.",apply:o(async()=>{if(a())return{changed:!1,summary:{}};const e=await m();return{changed:e.copied>0||e.mismatched.length>0,summary:{...e}}},"apply")},{id:"body-hash-repair",description:"rekey bodies rows PR #822 stored under the hash of the text before NUL became U+FFFD (D106): every revision naming such a hash names the hash of the stored text, and the invalid old-key row is removed. Runs in every role and after bodies-to-table, before readers serve. A mismatch with no intact original (a retained <home>/bodies file or a repo ref body) that becomes exactly the stored text stops the boot and is reported, never rehashed.",apply:o(async()=>{const e=await f();if(e.unresolved.length>0)throw new Error(`body-hash-repair: ${e.unresolved.length} bodies row(s) do not hash to their key and no intact original explains them: ${e.unresolved.join(", ")}`);return{changed:e.rekeyed>0||e.removed>0,summary:{...e}}},"apply")},{id:"profile-project-repos",description:"give each profile folder entry with no repo the repo its checkout identifies as (the nearest enclosing one), so a node with no checkout still gets that repo's documents. A folder no repo identifies keeps its path only. An entry that has a repo is skipped, so a re-run changes nothing. A cloud role skips it: its profiles name repos directly.",apply:o(async()=>{if(a())return{changed:!1,summary:{}};let e=0,t=0;for(const{profileId:s,manifest:d}of u())for(const r of d.projects)if(!(r.path===void 0||r.repo!==void 0))try{await b(r.path);const i=(await v(async l=>await g(l,r.path)))[0];i!==void 0&&await y(s,r.path,i.id)&&e++}catch(i){t++,n({level:"warn",event:"daemon.boot_migration.failed",error:i,fields:{migration:"profile-project-repos",profile:s,path:r.path}})}return{changed:e>0,summary:{filled:e,failed:t}}},"apply")}];export{F as BOOT_MIGRATIONS};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import type { ImportPlan, ImportReport } from './plan.js';
|
|
2
|
-
import type { CanvasDb } from '../../core/canvas/db.js';
|
|
3
|
-
/** The canvas_meta key whose presence means this home's legacy stores were imported. */
|
|
4
|
-
export declare const IMPORT_DONE_KEY = "canvas-import";
|
|
5
|
-
export declare const IMPORT_ID = "004-canvas-documents";
|
|
6
|
-
export declare function readImportRecord(db: CanvasDb): Promise<ImportReport | null>;
|
|
7
|
-
/** Run inside the caller's write transaction; each revision's text is stored in it. Throws on any divergence from the plan. */
|
|
8
|
-
export declare function applyPlan(db: CanvasDb, plan: ImportPlan): Promise<void>;
|