@north-light/cli 0.3.755 → 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/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/scoped-state/db.js +2 -2
- package/dist/daemon/api/handlers/daemon.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/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/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
|
@@ -304,22 +304,6 @@ export function makeBootIdCache(read, now = Date.now, negativeTtlMs = BOOT_ID_NE
|
|
|
304
304
|
};
|
|
305
305
|
}
|
|
306
306
|
const bootIdBase = makeBootIdCache(readKernelBootId);
|
|
307
|
-
/** Is `identity` a LEGACY (pre-boot-scoped) baseline — a `<lstart>#<ticks>` row
|
|
308
|
-
* whose base is NOT a boot_id UUID but which DOES carry ticks? These are the
|
|
309
|
-
* rows the one-time startup migration re-records once this platform can
|
|
310
|
-
* compose boot-scoped identities (see `migrateLegacyPidIdentities`). */
|
|
311
|
-
export function isLegacyTicksIdentity(identity) {
|
|
312
|
-
const { base, ticks } = splitIdentity(identity);
|
|
313
|
-
return ticks !== undefined && !BOOT_ID_RE.test(base);
|
|
314
|
-
}
|
|
315
|
-
/** Is `identity` a NEW-format boot-scoped baseline — `<bootId>#<ticks>` with a
|
|
316
|
-
* real boot_id UUID base AND ticks? The startup migration only re-records a
|
|
317
|
-
* legacy row when the pid's CURRENT identity comes out in this shape (i.e. the
|
|
318
|
-
* platform now composes new-format), never otherwise. */
|
|
319
|
-
export function isBootScopedIdentity(identity) {
|
|
320
|
-
const { base, ticks } = splitIdentity(identity);
|
|
321
|
-
return ticks !== undefined && BOOT_ID_RE.test(base);
|
|
322
|
-
}
|
|
323
307
|
/** Compose the stable, BOOT-SCOPED process-identity fingerprint used
|
|
324
308
|
* everywhere in this module. ALWAYS used to build an identity string, never a
|
|
325
309
|
* raw field directly, so every identity captured anywhere (launch-time
|
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
// It writes no settings (the daemon applies them at its start); the private key never leaves this computer.
|
|
4
4
|
import { createHash, generateKeyPairSync, randomUUID } from 'node:crypto';
|
|
5
5
|
import { existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs';
|
|
6
|
+
import { request } from 'node:http';
|
|
6
7
|
import { hostname } from 'node:os';
|
|
7
8
|
import { join } from 'node:path';
|
|
8
9
|
import { InputError } from '../io.js';
|
|
9
10
|
import { network } from '../errors.js';
|
|
10
11
|
import { secretsDir } from '../layout.js';
|
|
11
12
|
import { apiSocketPath } from '../canvas/paths.js';
|
|
12
|
-
import { daemonAnswers } from '../layout-migrate/index.js';
|
|
13
13
|
import { atomicWriteJson, readJsonIfExists } from '../fs-utils.js';
|
|
14
14
|
import { launcherPresent } from '../grants/sandboxes.js';
|
|
15
15
|
import { crtrVersion } from '../../shared/crtr-version.js';
|
|
@@ -151,6 +151,23 @@ async function registerAndStore(directory, credential, name, retry) {
|
|
|
151
151
|
}
|
|
152
152
|
return { ...joined, registered };
|
|
153
153
|
}
|
|
154
|
+
/** True when a daemon answers /healthz on the socket (a blocked daemon still answers and owns its files). */
|
|
155
|
+
function daemonAnswers(socketPath) {
|
|
156
|
+
return new Promise(resolve => {
|
|
157
|
+
const req = request({ socketPath, path: '/healthz', method: 'GET', timeout: 1000 }, res => {
|
|
158
|
+
res.resume();
|
|
159
|
+
resolve(true);
|
|
160
|
+
});
|
|
161
|
+
req.on('timeout', () => req.destroy(new Error('daemon probe timed out')));
|
|
162
|
+
req.on('error', error => {
|
|
163
|
+
if (error.code === 'ENOENT' || error.code === 'ECONNREFUSED')
|
|
164
|
+
resolve(false);
|
|
165
|
+
else
|
|
166
|
+
resolve(true); // Uncertain probe: do not touch an owned volume.
|
|
167
|
+
});
|
|
168
|
+
req.end();
|
|
169
|
+
});
|
|
170
|
+
}
|
|
154
171
|
/** A hosted runtime's first boot: register with the provisioning enrollment token before any daemon exists. Refuses `daemon_running` when one answers. */
|
|
155
172
|
export async function joinDirectory(directory, token, name = hostname()) {
|
|
156
173
|
const socket = apiSocketPath();
|
|
@@ -417,13 +417,6 @@ export async function dropLocalGrantMirror(db) {
|
|
|
417
417
|
await db.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run();
|
|
418
418
|
return Number((await db.prepare('DELETE FROM grants').run()).changes);
|
|
419
419
|
}
|
|
420
|
-
/** Mark rows a build older than C-D2 wrote as computed for their revision. That build computed every column locally in the same
|
|
421
|
-
* write but never set `computed_rev`, so its rows are complete; left NULL they read as no grant until the next successful
|
|
422
|
-
* sync rewrites them, and the terminal grant then refuses every launch (NL-550). A directory-written row with lagging
|
|
423
|
-
* columns has NULL scopes, so it is never matched. Returns the rows changed. */
|
|
424
|
-
export async function backfillComputedRev() {
|
|
425
|
-
return await withCanvasWrite(async (db) => Number((await db.prepare('UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL').run()).changes));
|
|
426
|
-
}
|
|
427
420
|
/** The `teams` a grant sync answer carried; absent (an unjoined install, an older directory) reads as none. Team
|
|
428
421
|
* membership is advisory next to the grants the same answer carries, so an entry that is not a directory team
|
|
429
422
|
* (`team:<id>`, e.g. a canvas group row echoed back) is dropped rather than failing the sync. */
|
|
@@ -8,9 +8,9 @@ import { isUnsandboxedMachine } from '../runtime/unsandboxed.js';
|
|
|
8
8
|
import { emitEvent } from '../events/emit.js';
|
|
9
9
|
import { describeOutboundFailure, outboundFetch, outboundJson, outboundRefusal } from '../events/outbound.js';
|
|
10
10
|
import { dependenciesOf, endpointPays, inferenceEndpointOf, principalPayer, replaceGrants, teamsOf } from './mirror.js';
|
|
11
|
+
import { loadPersonSettings } from '../scoped-state/person-rows.js';
|
|
11
12
|
import { onGrantSync } from './on-sync.js';
|
|
12
13
|
import { hostedEndpointOf, paymentSetupUrlOf, storeHostedEndpoint } from './hosted-endpoint.js';
|
|
13
|
-
import { adoptInstallPerson } from '../scoped-state/migrate.js';
|
|
14
14
|
import { PersonOutsideRequestError, PersonUnresolvedError, personId, resolvePerson, retireLocalPerson, setPersonId } from '../canvas/person.js';
|
|
15
15
|
export const GRANT_SYNC_INTERVAL_S = 300;
|
|
16
16
|
/** A `private_key_jwt` client assertion for `endpoint` (the directory's token endpoint), signed by the runtime client key. */
|
|
@@ -135,7 +135,7 @@ async function pullPerson() {
|
|
|
135
135
|
/** Bind a person resolved on a hosted first boot and run the boot one-shot. */
|
|
136
136
|
async function bindLatePerson(resolved) {
|
|
137
137
|
setPersonId(resolved.id);
|
|
138
|
-
await
|
|
138
|
+
await loadPersonSettings(resolved.id);
|
|
139
139
|
const result = await retireLocalPerson();
|
|
140
140
|
// The boot reconcile was skipped while the person was unresolved.
|
|
141
141
|
await withCanvasWrite(async (db) => await reconcilePackages(db));
|
|
@@ -300,11 +300,6 @@ export function apiErrorToCliError(err, next, options = {}) {
|
|
|
300
300
|
next: 'crtrd is now on the new generation — retry the command.',
|
|
301
301
|
});
|
|
302
302
|
}
|
|
303
|
-
if (err.code === 'layout_migration_required') {
|
|
304
|
-
return new CrtrError('layout_migration_required', err.message, ExitCode.NETWORK, {
|
|
305
|
-
next: 'Run `crtr sys migrate` while the runtime is offline, then restart it.',
|
|
306
|
-
});
|
|
307
|
-
}
|
|
308
303
|
if (err.code === 'daemon_unavailable') {
|
|
309
304
|
return new CrtrError('daemon_unavailable', err.message, ExitCode.NETWORK, {
|
|
310
305
|
next: 'Start it with `crtr sys daemon start`, then retry.',
|
|
@@ -102,26 +102,9 @@ export function assertSupportedLayoutMarker(path) {
|
|
|
102
102
|
throw new Error(`unsupported runtime layout version: ${path} holds ${describeLayoutMarker(bytes)}; expected "${LAYOUT_VERSION}"`);
|
|
103
103
|
}
|
|
104
104
|
}
|
|
105
|
-
/** A missing version on an occupied volume is never initialized by daemon startup. */
|
|
106
|
-
export function layoutNeedsMigration() {
|
|
107
|
-
if (process.env['CRTR_LAYOUT_REFUSE'] === '1')
|
|
108
|
-
return true;
|
|
109
|
-
if (existsSync(layoutVersionFile())) {
|
|
110
|
-
assertSupportedLayoutMarker(layoutVersionFile());
|
|
111
|
-
return false;
|
|
112
|
-
}
|
|
113
|
-
const root = layoutRoot();
|
|
114
|
-
const volume = process.platform === 'linux' && root === '/' && existsSync('/volume') ? '/volume' : root;
|
|
115
|
-
if (existsSync(join(volume, 'canvas')) || existsSync(join(volume, 'canvas.db')))
|
|
116
|
-
return true;
|
|
117
|
-
// A moved canvas.db without a layout version is an unfinished offline
|
|
118
|
-
// migration. Node records move before the DB, so the old or moved DB always
|
|
119
|
-
// accompanies them; entrypoint-created directories are a fresh volume.
|
|
120
|
-
return existsSync(join(runtimeRoot(), 'canvas.db'));
|
|
121
|
-
}
|
|
122
105
|
export function initializeEmptyLayout() {
|
|
123
|
-
if (
|
|
124
|
-
|
|
106
|
+
if (existsSync(layoutVersionFile()))
|
|
107
|
+
assertSupportedLayoutMarker(layoutVersionFile());
|
|
125
108
|
for (const dir of [runtimeRoot(), userRoot(), appsRoot(), secretsDir()]) {
|
|
126
109
|
// mkdir returns the first directory it had to create; every entry from there down to
|
|
127
110
|
// `dir` is new, and so is the entry for the first one in its (existing) parent.
|
|
@@ -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;
|