@north-light/api 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 +0 -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 +0 -1
- package/dist/build-root.d.ts +0 -3
- package/dist/build-root.js +0 -9
- package/dist/commands/sys/branch.js +1 -1
- package/dist/commands/sys/daemon.js +1 -1
- package/dist/commands/sys.js +1 -2
- package/dist/core/canvas/executions.d.ts +0 -3
- package/dist/core/canvas/executions.js +1 -17
- package/dist/core/canvas/pid.d.ts +0 -10
- package/dist/core/canvas/pid.js +0 -16
- package/dist/core/directory/join.js +18 -1
- package/dist/core/grants/mirror.d.ts +0 -5
- package/dist/core/grants/mirror.js +0 -7
- package/dist/core/grants/sync.js +2 -2
- package/dist/core/human/page-schema.d.ts +1 -1
- package/dist/core/io.js +0 -5
- package/dist/core/layout.d.ts +0 -2
- package/dist/core/layout.js +2 -19
- package/dist/daemon/api/map.d.ts +1 -6
- package/dist/daemon/api/map.js +0 -16
- package/dist/daemon/api/operations.js +0 -1
- package/dist/daemon/control.d.ts +0 -8
- package/dist/daemon/manage.js +1 -1
- package/package.json +1 -1
- package/dist/commands/sys/migrate.d.ts +0 -1
- package/dist/commands/sys/migrate.js +0 -79
- package/dist/core/layout-migrate/index.d.ts +0 -38
- package/dist/core/layout-migrate/index.js +0 -523
- package/dist/core/layout-migrate/paths.d.ts +0 -30
- package/dist/core/layout-migrate/paths.js +0 -118
- package/dist/core/layout-migrate/stored-paths.d.ts +0 -9
- package/dist/core/layout-migrate/stored-paths.js +0 -424
- package/dist/core/layout-migrate/stores.d.ts +0 -30
- package/dist/core/layout-migrate/stores.js +0 -543
- package/dist/core/locked-file.d.ts +0 -27
- package/dist/core/locked-file.js +0 -121
- package/dist/core/scoped-state/db.d.ts +0 -17
- package/dist/core/scoped-state/db.js +0 -271
- package/dist/core/scoped-state/legacy-profiles.d.ts +0 -11
- package/dist/core/scoped-state/legacy-profiles.js +0 -65
- package/dist/core/scoped-state/migrate.d.ts +0 -15
- package/dist/core/scoped-state/migrate.js +0 -332
- package/dist/core/scoped-state/schema.d.ts +0 -14
- package/dist/core/scoped-state/schema.js +0 -52
- package/dist/migrations/004-canvas-documents/apply.d.ts +0 -8
- package/dist/migrations/004-canvas-documents/apply.js +0 -113
- package/dist/migrations/004-canvas-documents/index.d.ts +0 -16
- package/dist/migrations/004-canvas-documents/index.js +0 -89
- package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +0 -16
- package/dist/migrations/004-canvas-documents/legacy/discover.js +0 -251
- package/dist/migrations/004-canvas-documents/legacy/history.d.ts +0 -5
- package/dist/migrations/004-canvas-documents/legacy/history.js +0 -37
- package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +0 -7
- package/dist/migrations/004-canvas-documents/legacy/nested.js +0 -37
- package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +0 -14
- package/dist/migrations/004-canvas-documents/legacy/parse.js +0 -24
- package/dist/migrations/004-canvas-documents/legacy/types.d.ts +0 -91
- package/dist/migrations/004-canvas-documents/legacy/types.js +0 -3
- package/dist/migrations/004-canvas-documents/plan.d.ts +0 -102
- package/dist/migrations/004-canvas-documents/plan.js +0 -410
- package/dist/migrations/004-canvas-documents/pointers.d.ts +0 -23
- package/dist/migrations/004-canvas-documents/pointers.js +0 -95
- package/dist/migrations/activation.d.ts +0 -17
- package/dist/migrations/activation.js +0 -46
|
@@ -1,332 +0,0 @@
|
|
|
1
|
-
import { prepared as cachedStatement } from '../sqlite-statements.js';
|
|
2
|
-
import { randomUUID } from 'node:crypto';
|
|
3
|
-
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
|
4
|
-
import { basename, dirname, join, relative } from 'node:path';
|
|
5
|
-
import lockfile from 'proper-lockfile';
|
|
6
|
-
import { CONFIG_FILE, PROFILE_DIR, STATE_FILE } from '../../types.js';
|
|
7
|
-
import { LockedJsonFile } from '../locked-file.js';
|
|
8
|
-
import { assertScopedStoreReady, createScopedStore, openScopedStore, discardIncompleteScopedStore, legacyScopedStorePaths, PROFILE_ID_SHAPE, scopedStoreExists, withProjectStateLock, writeOwnerRoot } from './db.js';
|
|
9
|
-
import { canonicalRoot, providerStore, projectStore, userStore } from './paths.js';
|
|
10
|
-
import { profileSpace, appSpace } from '../layout.js';
|
|
11
|
-
import { createScopedSchema } from './schema.js';
|
|
12
|
-
import { openDb, withCanvasWrite } from '../canvas/db.js';
|
|
13
|
-
import { loadSecretsKey, seal } from '../secrets/index.js';
|
|
14
|
-
import { putEnvRowIfAbsent } from '../secrets/env-rows.js';
|
|
15
|
-
import { DEPLOYMENT_ID } from '../secrets/environment-secrets.js';
|
|
16
|
-
import { isReservedEnvName, validateEnvVarName } from '../env-name.js';
|
|
17
|
-
import { insertAccount, upsertModelCooldown } from '../subscription-state.js';
|
|
18
|
-
import { userScopeRoot } from '../scope.js';
|
|
19
|
-
import { secretsDir } from '../layout.js';
|
|
20
|
-
import { readLegacyUserSnapshot } from './legacy-profiles.js';
|
|
21
|
-
import { revisionOf } from './person-store.js';
|
|
22
|
-
import { loadPersonSettings, applyOpsToRows, readSnapshotFromRows } from './person-rows.js';
|
|
23
|
-
function json(path) { return JSON.parse(readFileSync(path, 'utf8')); }
|
|
24
|
-
function existsLegacy(paths) { return paths.some(existsSync); }
|
|
25
|
-
function preserve(root, paths) { const target = join(root, '.legacy-scoped-state'); try {
|
|
26
|
-
mkdirSync(target, { mode: 0o700 });
|
|
27
|
-
}
|
|
28
|
-
catch (error) {
|
|
29
|
-
if (error.code !== 'EEXIST' || !statSync(target).isDirectory())
|
|
30
|
-
throw error;
|
|
31
|
-
} chmodSync(target, 0o700); for (const path of paths)
|
|
32
|
-
if (existsSync(path) && statSync(path).isFile()) {
|
|
33
|
-
const fromRoot = relative(root, path);
|
|
34
|
-
if (fromRoot === '' || fromRoot.startsWith('..'))
|
|
35
|
-
throw new Error(`legacy state is outside its owning root: ${path}`);
|
|
36
|
-
const destination = join(target, fromRoot);
|
|
37
|
-
if (dirname(destination) !== target)
|
|
38
|
-
mkdirSync(dirname(destination), { recursive: true, mode: 0o700 });
|
|
39
|
-
copyFileSync(path, destination);
|
|
40
|
-
chmodSync(destination, 0o600);
|
|
41
|
-
} }
|
|
42
|
-
/** Conversion is intentionally explicit. Deployment coordination must prove all legacy writers at these shared roots are stopped before calling it. */
|
|
43
|
-
export function convertLegacyScopedStore(input) {
|
|
44
|
-
const store = input.kind === 'user' ? userStore(input.root) : input.kind === 'project' ? projectStore(input.root) : providerStore(input.root);
|
|
45
|
-
if (input.kind !== 'project' && scopedStoreExists(store))
|
|
46
|
-
return;
|
|
47
|
-
if (input.kind === 'provider')
|
|
48
|
-
throw new Error('provider conversion requires convertLegacyProviderStore() under coordinated shared-agent-dir activation');
|
|
49
|
-
const paths = legacyScopedStorePaths(store);
|
|
50
|
-
const convert = () => {
|
|
51
|
-
if (input.kind === 'project')
|
|
52
|
-
discardIncompleteScopedStore(store);
|
|
53
|
-
if (scopedStoreExists(store))
|
|
54
|
-
return;
|
|
55
|
-
if (input.kind === 'project' && existsLegacy(paths))
|
|
56
|
-
preserve(store.root, paths);
|
|
57
|
-
createScopedStore(store, (db) => {
|
|
58
|
-
createScopedSchema(db, input.kind);
|
|
59
|
-
const owner = input.kind === 'user' ? 'user' : 'project';
|
|
60
|
-
writeOwnerRoot(db, owner, store.root);
|
|
61
|
-
if (input.kind === 'user')
|
|
62
|
-
importUser(db, store.root);
|
|
63
|
-
else
|
|
64
|
-
importState(db, owner, join(store.root, STATE_FILE));
|
|
65
|
-
});
|
|
66
|
-
if (input.kind === 'user' && existsLegacy(paths))
|
|
67
|
-
preserve(store.root, paths);
|
|
68
|
-
};
|
|
69
|
-
if (input.kind === 'project')
|
|
70
|
-
withProjectStateLock(store.root, () => { convert(); assertScopedStoreReady(store); });
|
|
71
|
-
else
|
|
72
|
-
convert();
|
|
73
|
-
}
|
|
74
|
-
function parseLegacyProviderPool(path) {
|
|
75
|
-
if (!existsSync(path))
|
|
76
|
-
return [];
|
|
77
|
-
const raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
78
|
-
if (!Array.isArray(raw))
|
|
79
|
-
throw new Error(`legacy subscription pool is malformed: ${path}`);
|
|
80
|
-
const labels = new Set();
|
|
81
|
-
return raw.map((item, position) => {
|
|
82
|
-
if (item === null || typeof item !== 'object' || Array.isArray(item))
|
|
83
|
-
throw new Error(`legacy subscription pool entry ${position + 1} is malformed: ${path}`);
|
|
84
|
-
const value = item;
|
|
85
|
-
const label = typeof value.label === 'string' ? value.label.trim() : '';
|
|
86
|
-
const refresh = typeof value.refresh === 'string' ? value.refresh.trim() : '';
|
|
87
|
-
const access = typeof value.access === 'string' ? value.access.trim() : '';
|
|
88
|
-
const expires = Number(value.expires);
|
|
89
|
-
if (!label || !refresh || !access || !Number.isFinite(expires))
|
|
90
|
-
throw new Error(`legacy subscription pool entry ${position + 1} is incomplete: ${path}`);
|
|
91
|
-
const labelKey = label.toLowerCase();
|
|
92
|
-
if (labels.has(labelKey))
|
|
93
|
-
throw new Error(`legacy subscription pool has duplicate label "${label}": ${path}`);
|
|
94
|
-
labels.add(labelKey);
|
|
95
|
-
const timing = (field) => Number.isFinite(Number(value[field])) ? Number(value[field]) : 0;
|
|
96
|
-
const accountId = typeof value.accountId === 'string' && value.accountId.trim() !== '' ? value.accountId.trim() : undefined;
|
|
97
|
-
return { label, refresh, access, expires, rateLimitedUntil: timing('rateLimitedUntil'), lastAttemptAt: timing('lastAttemptAt'), lastRateLimitedAt: timing('lastRateLimitedAt'), ...(value.authFailure === 'invalid_grant' ? { authFailure: 'invalid_grant' } : {}), ...(accountId ? { accountId } : {}) };
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
function parseLegacyRotation(path) {
|
|
101
|
-
if (!existsSync(path))
|
|
102
|
-
return {};
|
|
103
|
-
const raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
104
|
-
if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
|
|
105
|
-
throw new Error(`legacy provider rotation settings are malformed: ${path}`);
|
|
106
|
-
const value = raw;
|
|
107
|
-
return { ...(value.defaultFallbackStrength === 'ultra' || value.defaultFallbackStrength === 'strong' || value.defaultFallbackStrength === 'medium' || value.defaultFallbackStrength === 'light' ? { defaultFallbackStrength: value.defaultFallbackStrength } : {}), ...(typeof value.revertWhenAvailable === 'boolean' ? { revertWhenAvailable: value.revertWhenAvailable } : {}) };
|
|
108
|
-
}
|
|
109
|
-
async function withLegacyProviderLocks(paths, run) {
|
|
110
|
-
const releases = [];
|
|
111
|
-
try {
|
|
112
|
-
for (const path of paths)
|
|
113
|
-
if (existsSync(path))
|
|
114
|
-
releases.push(await lockfile.lock(path, { realpath: false, retries: 0, stale: 30_000, update: 10_000 }));
|
|
115
|
-
return await run();
|
|
116
|
-
}
|
|
117
|
-
finally {
|
|
118
|
-
await Promise.allSettled(releases.reverse().map((release) => release()));
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
/** Converts legacy provider pools only after the activation owner has stopped every writer sharing this agent directory. */
|
|
122
|
-
export async function convertLegacyProviderStore(agentDir) {
|
|
123
|
-
const store = providerStore(agentDir);
|
|
124
|
-
if (scopedStoreExists(store))
|
|
125
|
-
return;
|
|
126
|
-
const paths = legacyScopedStorePaths(store);
|
|
127
|
-
await withLegacyProviderLocks(paths, async () => {
|
|
128
|
-
if (scopedStoreExists(store))
|
|
129
|
-
return;
|
|
130
|
-
const pools = new Map(paths.slice(0, 2).map((path, index) => [index === 0 ? 'anthropic' : 'openai-codex', parseLegacyProviderPool(path)]));
|
|
131
|
-
const rotation = parseLegacyRotation(paths[2]);
|
|
132
|
-
mkdirSync(store.root, { recursive: true, mode: 0o700 });
|
|
133
|
-
preserve(store.root, paths);
|
|
134
|
-
for (const [provider, pool] of pools) {
|
|
135
|
-
const accounts = Object.fromEntries(pool.map((entry) => { const id = randomUUID(); return [id, { refresh: entry.refresh, access: entry.access, expires: entry.expires, ...(entry.accountId ? { accountId: entry.accountId } : {}) }]; }));
|
|
136
|
-
const file = new LockedJsonFile(join(store.root, `${provider}-credentials.json`), true, '{"version":1,"accounts":{}}\n');
|
|
137
|
-
await file.withLockAsync(async (_current, _held, publish) => { publish(`${JSON.stringify({ version: 1, accounts })}\n`); return { result: undefined }; });
|
|
138
|
-
}
|
|
139
|
-
createScopedStore(store, (db) => {
|
|
140
|
-
createScopedSchema(db, 'provider');
|
|
141
|
-
for (const [provider, pool] of pools) {
|
|
142
|
-
const accounts = JSON.parse(readFileSync(join(store.root, `${provider}-credentials.json`), 'utf8'));
|
|
143
|
-
const ids = Object.keys(accounts.accounts);
|
|
144
|
-
const insert = cachedStatement(db, 'INSERT INTO managed_accounts(provider_id,id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure) VALUES(?,?,?,?,?,?,?,?,?)');
|
|
145
|
-
pool.forEach((entry, position) => insert.run(provider, ids[position], entry.label, entry.label.toLowerCase(), position, entry.lastAttemptAt, entry.lastRateLimitedAt, entry.rateLimitedUntil, entry.authFailure ?? null));
|
|
146
|
-
}
|
|
147
|
-
if (rotation.defaultFallbackStrength !== undefined || rotation.revertWhenAvailable !== undefined)
|
|
148
|
-
cachedStatement(db, 'INSERT INTO rotation_settings(singleton,default_fallback_strength,revert_when_available) VALUES(1,?,?)').run(rotation.defaultFallbackStrength ?? null, rotation.revertWhenAvailable === undefined ? null : rotation.revertWhenAvailable ? 1 : 0);
|
|
149
|
-
});
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
function importSettings(db, owner, path) { if (!existsSync(path))
|
|
153
|
-
return; const raw = json(path); if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
|
|
154
|
-
throw new Error(`legacy config is malformed: ${path}`); cachedStatement(db, 'INSERT INTO scope_settings(owner_key,raw_json) VALUES(?,?)').run(owner, JSON.stringify(raw)); }
|
|
155
|
-
function importState(db, owner, path) { if (!existsSync(path))
|
|
156
|
-
return; const raw = json(path); if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
|
|
157
|
-
throw new Error(`legacy state is malformed: ${path}`); const state = raw; cachedStatement(db, 'INSERT INTO scope_bookkeeping(owner_key,last_self_check,active_canvas) VALUES(?,?,?)').run(owner, state.last_self_check ?? null, state.activeCanvas ?? null); const market = cachedStatement(db, 'INSERT INTO scope_marketplaces(owner_key,name,last_updated) VALUES(?,?,?)'); for (const [name, value] of Object.entries(state.marketplaces ?? {}))
|
|
158
|
-
market.run(owner, name, value.last_updated ?? null); const plugins = cachedStatement(db, 'INSERT INTO scope_plugins(owner_key,name,last_updated,etag,checked_at) VALUES(?,?,?,?,?)'); for (const [name, value] of Object.entries(state.plugins ?? {}))
|
|
159
|
-
plugins.run(owner, name, value.last_updated ?? null, value.etag ?? null, value.checked_at ?? null); }
|
|
160
|
-
function importUser(db, root) {
|
|
161
|
-
importSettings(db, 'user', join(root, CONFIG_FILE));
|
|
162
|
-
importState(db, 'user', join(root, STATE_FILE));
|
|
163
|
-
const profiles = join(root, PROFILE_DIR);
|
|
164
|
-
if (existsSync(profiles))
|
|
165
|
-
for (const entry of readdirSync(profiles, { withFileTypes: true })) {
|
|
166
|
-
if (!entry.isDirectory() || !PROFILE_ID_SHAPE.test(entry.name))
|
|
167
|
-
continue;
|
|
168
|
-
const id = entry.name;
|
|
169
|
-
const profileRoot = join(profiles, id);
|
|
170
|
-
const path = join(profileRoot, 'profile.json');
|
|
171
|
-
if (!existsSync(path))
|
|
172
|
-
throw new Error(`legacy profile manifest is missing: ${path}`);
|
|
173
|
-
const manifest = json(path);
|
|
174
|
-
if (!manifest || typeof manifest !== 'object' || !Array.isArray(manifest.projects) || typeof manifest.name !== 'string' || typeof manifest.created_at !== 'string')
|
|
175
|
-
throw new Error(`legacy profile manifest is malformed: ${path}`);
|
|
176
|
-
cachedStatement(db, 'INSERT INTO profiles(id,name,created_at,last_used_at,paused_at,default_kind,grantee,metadata_json) VALUES(?,?,?,?,?,?,?,?)').run(id, manifest.name, manifest.created_at, manifest.last_used_at ?? null, manifest.paused_at ?? null, manifest.default_kind ?? null, manifest.grantee ?? null, JSON.stringify(manifest.metadata ?? {}));
|
|
177
|
-
cachedStatement(db, 'INSERT INTO scope_owners(owner_key,kind,root,profile_id) VALUES(?,?,?,?)').run(`profile:${id}`, 'profile', canonicalRoot(profileSpace(manifest.grantee ?? 'app:terminal', id).dir), id);
|
|
178
|
-
const project = cachedStatement(db, 'INSERT INTO profile_projects(profile_id,path,position) VALUES(?,?,?)');
|
|
179
|
-
const cap = cachedStatement(db, 'INSERT INTO legacy_project_caps(profile_id,path,memory) VALUES(?,?,?)');
|
|
180
|
-
manifest.projects.forEach((p, position) => { project.run(id, p.path, position); if (p.memory !== undefined && p.memory !== 'content')
|
|
181
|
-
cap.run(id, p.path, p.memory); });
|
|
182
|
-
importSettings(db, `profile:${id}`, join(profileRoot, CONFIG_FILE));
|
|
183
|
-
importState(db, `profile:${id}`, join(profileRoot, STATE_FILE));
|
|
184
|
-
}
|
|
185
|
-
const defaults = join(root, 'profile-defaults.json');
|
|
186
|
-
if (existsSync(defaults)) {
|
|
187
|
-
const raw = json(defaults);
|
|
188
|
-
if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
|
|
189
|
-
throw new Error(`legacy profile defaults are malformed: ${defaults}`);
|
|
190
|
-
const insert = cachedStatement(db, 'INSERT INTO profile_defaults(directory,profile_id) VALUES(?,?)');
|
|
191
|
-
for (const [directory, id] of Object.entries(raw)) {
|
|
192
|
-
if (typeof id !== 'string')
|
|
193
|
-
throw new Error(`legacy profile default is malformed: ${defaults}`);
|
|
194
|
-
insert.run(directory, id);
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
// ------------------------------------------------------------------ the one-time boot copy into the person's rows
|
|
199
|
-
const COPIED_KEY = 'person_stores_copied';
|
|
200
|
-
const CREDENTIAL_FILES = { anthropic: 'anthropic-credentials.json', 'openai-codex': 'openai-codex-credentials.json', openai: 'openai-credentials.json' };
|
|
201
|
-
export async function personStoresCopied() {
|
|
202
|
-
const row = await (await openDb()).prepare('SELECT value FROM canvas_meta WHERE key = ?').get(COPIED_KEY);
|
|
203
|
-
return row !== undefined;
|
|
204
|
-
}
|
|
205
|
-
function readLegacyAccounts(agentDir) {
|
|
206
|
-
const store = providerStore(agentDir);
|
|
207
|
-
if (!scopedStoreExists(store))
|
|
208
|
-
return [];
|
|
209
|
-
const db = openScopedStore(store);
|
|
210
|
-
const out = [];
|
|
211
|
-
for (const provider of Object.keys(CREDENTIAL_FILES)) {
|
|
212
|
-
const path = join(agentDir, CREDENTIAL_FILES[provider]);
|
|
213
|
-
if (!existsSync(path))
|
|
214
|
-
continue;
|
|
215
|
-
const file = json(path);
|
|
216
|
-
const cooldowns = cachedStatement(db, 'SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM managed_account_model_cooldowns WHERE provider_id=?').all(provider);
|
|
217
|
-
for (const r of cachedStatement(db, '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(provider)) {
|
|
218
|
-
const tokens = file.accounts?.[r.id];
|
|
219
|
-
if (tokens === undefined)
|
|
220
|
-
continue;
|
|
221
|
-
out.push({
|
|
222
|
-
provider, id: r.id,
|
|
223
|
-
row: { providerId: provider, id: r.id, label: r.label, labelKey: r.label_key, position: r.position, lastAttemptAt: r.last_attempt_at, lastRateLimitedAt: r.last_rate_limited_at, rateLimitedUntil: r.rate_limited_until, ...(r.auth_failure ? { authFailure: r.auth_failure } : {}) },
|
|
224
|
-
tokens: { refresh: tokens.refresh, access: tokens.access, expires: tokens.expires, ...(tokens.accountId ? { accountId: tokens.accountId } : {}), ...(tokens.clientId ? { clientId: tokens.clientId } : {}) },
|
|
225
|
-
cooldowns: cooldowns.filter((c) => c.account_id === r.id).map((c) => ({ family: c.family, until: c.rate_limited_until, at: c.last_rate_limited_at })),
|
|
226
|
-
});
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
return out;
|
|
230
|
-
}
|
|
231
|
-
/** The old `{vars}` env file at `path`, with the filters its reader applied: a valid name, a string value without NUL, and the names `admits` allows. */
|
|
232
|
-
function readLegacyEnvFile(path, admits) {
|
|
233
|
-
if (!existsSync(path) || !statSync(path).isFile())
|
|
234
|
-
return {};
|
|
235
|
-
let raw;
|
|
236
|
-
try {
|
|
237
|
-
raw = json(path);
|
|
238
|
-
}
|
|
239
|
-
catch {
|
|
240
|
-
return {};
|
|
241
|
-
} // the old reader gave a corrupt file no values; the file stays for the person
|
|
242
|
-
const out = {};
|
|
243
|
-
if (raw === null || typeof raw !== 'object' || raw.vars === null || typeof raw.vars !== 'object' || Array.isArray(raw.vars))
|
|
244
|
-
return out;
|
|
245
|
-
for (const [name, value] of Object.entries(raw.vars))
|
|
246
|
-
if (validateEnvVarName(name).isValid && admits(name) && typeof value === 'string' && !value.includes('\0'))
|
|
247
|
-
out[name] = value;
|
|
248
|
-
return out;
|
|
249
|
-
}
|
|
250
|
-
const LEGACY_DEPLOYMENT_NAMES = new Set(['CRTR_FEEDBACK_ENDPOINT', 'CRTR_FEEDBACK_TOKEN']);
|
|
251
|
-
/** Seal every legacy env file into `env_vars` rows: each profile's file, each app's `_app` file and the deployment-wide `_deployment` file under `<secrets>/env`. */
|
|
252
|
-
async function copyLegacyEnvFiles(db, person, profiles) {
|
|
253
|
-
const envRoot = join(secretsDir(), 'env');
|
|
254
|
-
if (!existsSync(envRoot))
|
|
255
|
-
return;
|
|
256
|
-
const put = async (owner, vars) => { for (const [name, value] of Object.entries(vars))
|
|
257
|
-
await putEnvRowIfAbsent(db, owner, name, value); };
|
|
258
|
-
for (const profile of profiles)
|
|
259
|
-
await put({ person, kind: 'profile', id: profile.profileId }, readLegacyEnvFile(profileSpace(profile.manifest.grantee ?? 'app:terminal', profile.profileId).env, (name) => !isReservedEnvName(name)));
|
|
260
|
-
for (const entry of readdirSync(envRoot, { withFileTypes: true })) {
|
|
261
|
-
if (!entry.isDirectory())
|
|
262
|
-
continue;
|
|
263
|
-
const app = `app:${entry.name}`;
|
|
264
|
-
if (basename(appSpace(app).root) !== entry.name)
|
|
265
|
-
continue;
|
|
266
|
-
await put({ person, kind: 'app', id: app }, readLegacyEnvFile(join(envRoot, entry.name, '_app'), (name) => !isReservedEnvName(name)));
|
|
267
|
-
}
|
|
268
|
-
await put({ person: null, kind: 'deployment', id: DEPLOYMENT_ID }, readLegacyEnvFile(join(envRoot, '_deployment'), (name) => LEGACY_DEPLOYMENT_NAMES.has(name)));
|
|
269
|
-
}
|
|
270
|
-
/** Copy this install's files into the person's rows, once: profiles, scope settings and bookkeeping, the plugin and marketplace
|
|
271
|
-
* 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
|
|
272
|
-
* transaction, skipping any key a row already holds, ending with `canvas_meta.person_stores_copied`. The files stay, unread. */
|
|
273
|
-
export async function copyPersonStoresToRows(person, legacyUserSnapshot, agentDir) {
|
|
274
|
-
const accounts = readLegacyAccounts(agentDir);
|
|
275
|
-
const rotation = (() => { const store = providerStore(agentDir); if (!scopedStoreExists(store))
|
|
276
|
-
return undefined; return cachedStatement(openScopedStore(store), 'SELECT default_fallback_strength,revert_when_available FROM rotation_settings WHERE singleton=1').get(); })();
|
|
277
|
-
const deviceIdPath = join(agentDir, 'openai-device-id');
|
|
278
|
-
const deviceId = existsSync(deviceIdPath) ? readFileSync(deviceIdPath, 'utf8').trim() : '';
|
|
279
|
-
const authPath = join(agentDir, 'auth.json');
|
|
280
|
-
const apiKeys = existsSync(authPath) ? Object.entries(json(authPath)).filter(([id]) => !(id in CREDENTIAL_FILES)) : [];
|
|
281
|
-
await withCanvasWrite(async (db) => {
|
|
282
|
-
if (await db.prepare('SELECT 1 FROM canvas_meta WHERE key = ?').get(COPIED_KEY) !== undefined)
|
|
283
|
-
return;
|
|
284
|
-
if (legacyUserSnapshot !== null) {
|
|
285
|
-
const have = await readSnapshotFromRows(db, person);
|
|
286
|
-
const ops = [];
|
|
287
|
-
const known = new Set(have.profiles.map((p) => p.profileId));
|
|
288
|
-
for (const profile of legacyUserSnapshot.profiles)
|
|
289
|
-
if (!known.has(profile.profileId))
|
|
290
|
-
ops.push({ op: 'profile.insert', profile });
|
|
291
|
-
for (const owner of Object.keys(legacyUserSnapshot.settings))
|
|
292
|
-
if (have.settings[owner] === undefined)
|
|
293
|
-
ops.push({ op: 'settings.replace', owner, raw: legacyUserSnapshot.settings[owner], ifRevision: revisionOf(undefined) });
|
|
294
|
-
for (const owner of Object.keys(legacyUserSnapshot.state)) {
|
|
295
|
-
const st = legacyUserSnapshot.state[owner];
|
|
296
|
-
if (have.state[owner] === undefined && (owner === 'user' || known.has(owner.replace(/^profile:/, '')) || legacyUserSnapshot.profiles.some((p) => `profile:${p.profileId}` === owner)))
|
|
297
|
-
ops.push({ op: 'state.write', owner, state: st });
|
|
298
|
-
}
|
|
299
|
-
if (Object.keys(have.defaults).length === 0 && Object.keys(legacyUserSnapshot.defaults).length > 0)
|
|
300
|
-
ops.push({ op: 'defaults.replace', defaults: legacyUserSnapshot.defaults });
|
|
301
|
-
if (ops.length > 0)
|
|
302
|
-
await applyOpsToRows(db, person, ops);
|
|
303
|
-
}
|
|
304
|
-
for (const a of accounts) {
|
|
305
|
-
const present = await db.prepare('SELECT 1 FROM model_accounts WHERE person=? AND provider_id=? AND (id=? OR label_key=?)').get(person, a.provider, a.id, a.row.labelKey);
|
|
306
|
-
if (present !== undefined)
|
|
307
|
-
continue;
|
|
308
|
-
await insertAccount(db, person, a.provider, a.row, a.tokens);
|
|
309
|
-
for (const c of a.cooldowns)
|
|
310
|
-
await upsertModelCooldown(db, person, a.provider, a.id, c.family, c.until, c.at);
|
|
311
|
-
}
|
|
312
|
-
if (rotation !== undefined)
|
|
313
|
-
await db.prepare('INSERT INTO model_settings(person,default_fallback_strength,revert_when_available) VALUES(?,?,?) ON CONFLICT(person) DO NOTHING').run(person, rotation.default_fallback_strength, rotation.revert_when_available);
|
|
314
|
-
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(deviceId))
|
|
315
|
-
await db.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(person, deviceId.toLowerCase());
|
|
316
|
-
for (const [providerId, credential] of apiKeys) {
|
|
317
|
-
const { sealed, keyId } = seal(JSON.stringify(credential), loadSecretsKey(), `model_api_keys|${person}|${providerId}`);
|
|
318
|
-
await db.prepare('INSERT INTO model_api_keys(person,provider_id,credential_sealed,key_id,updated_at) VALUES(?,?,?,?,?) ON CONFLICT(person,provider_id) DO NOTHING').run(person, providerId, sealed, keyId, new Date().toISOString());
|
|
319
|
-
}
|
|
320
|
-
await copyLegacyEnvFiles(db, person, legacyUserSnapshot?.profiles ?? []);
|
|
321
|
-
await db.prepare('INSERT INTO canvas_meta(key,value) VALUES(?,?)').run(COPIED_KEY, new Date().toISOString());
|
|
322
|
-
});
|
|
323
|
-
}
|
|
324
|
-
/** The install's person just became known: copy the old local files into their rows once, then load their snapshot. */
|
|
325
|
-
export async function adoptInstallPerson(person) {
|
|
326
|
-
if (!(await personStoresCopied())) {
|
|
327
|
-
const root = userScopeRoot();
|
|
328
|
-
convertLegacyScopedStore({ kind: 'user', root });
|
|
329
|
-
await copyPersonStoresToRows(person, readLegacyUserSnapshot(root), secretsDir());
|
|
330
|
-
}
|
|
331
|
-
await loadPersonSettings(person);
|
|
332
|
-
}
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import type { DatabaseSync } from 'node:sqlite';
|
|
2
|
-
export declare const SCOPED_SCHEMA_VERSION = 5;
|
|
3
|
-
export declare const PROVIDER_SCHEMA_VERSION = 1;
|
|
4
|
-
/** `profiles.environment_id` (null = the machine environment) is additive to version 5: a store written before it gains the
|
|
5
|
-
* column on open (`upgradeScopedStore`), and an older generation sharing the store names its columns and never reads it, so
|
|
6
|
-
* the version stays 5 and a runtime rollback keeps opening the store. */
|
|
7
|
-
export declare const PROFILE_ENVIRONMENT_COLUMN = "environment_id";
|
|
8
|
-
/** `profile_projects.repo` and the `profile_project_repos` table (a repo with no folder) are additive to version 5, like `PROFILE_ENVIRONMENT_COLUMN`:
|
|
9
|
-
* a store written before them gains both on open (`upgradeScopedStore`), and an older generation never reads them. One position
|
|
10
|
-
* counter covers both tables. */
|
|
11
|
-
export declare const PROFILE_PROJECT_REPO_COLUMN = "repo";
|
|
12
|
-
/** Adds the model-cooldown table to a provider store that predates it; a no-op (no write) once present. */
|
|
13
|
-
export declare function ensureProviderModelCooldowns(db: DatabaseSync): void;
|
|
14
|
-
export declare function createScopedSchema(db: DatabaseSync, kind: 'user' | 'project' | 'provider'): void;
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { prepared as cachedStatement } from '../sqlite-statements.js';
|
|
2
|
-
export const SCOPED_SCHEMA_VERSION = 5;
|
|
3
|
-
export const PROVIDER_SCHEMA_VERSION = 1;
|
|
4
|
-
/** `profiles.environment_id` (null = the machine environment) is additive to version 5: a store written before it gains the
|
|
5
|
-
* column on open (`upgradeScopedStore`), and an older generation sharing the store names its columns and never reads it, so
|
|
6
|
-
* the version stays 5 and a runtime rollback keeps opening the store. */
|
|
7
|
-
export const PROFILE_ENVIRONMENT_COLUMN = 'environment_id';
|
|
8
|
-
/** `profile_projects.repo` and the `profile_project_repos` table (a repo with no folder) are additive to version 5, like `PROFILE_ENVIRONMENT_COLUMN`:
|
|
9
|
-
* a store written before them gains both on open (`upgradeScopedStore`), and an older generation never reads them. One position
|
|
10
|
-
* counter covers both tables. */
|
|
11
|
-
export const PROFILE_PROJECT_REPO_COLUMN = 'repo';
|
|
12
|
-
const SCOPE_SCHEMA = `
|
|
13
|
-
CREATE TABLE scope_owners (owner_key TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK(kind IN ('user','profile','project')), root TEXT NOT NULL UNIQUE, profile_id TEXT UNIQUE);
|
|
14
|
-
CREATE TABLE profiles (id TEXT PRIMARY KEY, name TEXT NOT NULL, created_at TEXT NOT NULL, last_used_at TEXT, paused_at TEXT, default_kind TEXT, grantee TEXT, metadata_json TEXT NOT NULL CHECK(json_valid(metadata_json)), delivery_limits_json TEXT NOT NULL DEFAULT '{}' CHECK(json_valid(delivery_limits_json)), environment_id TEXT);
|
|
15
|
-
CREATE TABLE profile_projects (profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE, path TEXT NOT NULL, position INTEGER NOT NULL, repo TEXT, PRIMARY KEY(profile_id,path), UNIQUE(profile_id,position));
|
|
16
|
-
CREATE TABLE profile_project_repos (profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE, repo TEXT NOT NULL, position INTEGER NOT NULL, PRIMARY KEY(profile_id,repo));
|
|
17
|
-
-- Pre-canvas per-project memory caps awaiting the canvas import, which turns them into delivery_limits and deletes the rows.
|
|
18
|
-
CREATE TABLE legacy_project_caps (profile_id TEXT NOT NULL, path TEXT NOT NULL, memory TEXT NOT NULL CHECK(memory IN ('none','name','preview')), PRIMARY KEY(profile_id,path));
|
|
19
|
-
CREATE TABLE profile_defaults (directory TEXT PRIMARY KEY, profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE);
|
|
20
|
-
CREATE TABLE scope_settings (owner_key TEXT PRIMARY KEY REFERENCES scope_owners(owner_key), raw_json TEXT NOT NULL CHECK(json_valid(raw_json)));
|
|
21
|
-
CREATE TABLE scope_bookkeeping (owner_key TEXT PRIMARY KEY REFERENCES scope_owners(owner_key), last_self_check TEXT, active_canvas TEXT);
|
|
22
|
-
CREATE TABLE scope_marketplaces (owner_key TEXT NOT NULL REFERENCES scope_owners(owner_key), name TEXT NOT NULL, last_updated TEXT, PRIMARY KEY(owner_key,name));
|
|
23
|
-
CREATE TABLE scope_plugins (owner_key TEXT NOT NULL REFERENCES scope_owners(owner_key), name TEXT NOT NULL, last_updated TEXT, etag TEXT, checked_at TEXT, PRIMARY KEY(owner_key,name));`;
|
|
24
|
-
// A subscription 429 on one model family's window (Anthropic `seven_day_opus` /
|
|
25
|
-
// `seven_day_sonnet`) cools only that family on that account. Additive to v1: a
|
|
26
|
-
// store written before this table existed gains it on open (ensureProviderModelCooldowns),
|
|
27
|
-
// and older crtr generations sharing the store simply never read it, so the provider
|
|
28
|
-
// schema version stays 1 and a runtime rollback keeps opening the store.
|
|
29
|
-
const MODEL_COOLDOWNS_TABLE = 'CREATE TABLE IF NOT EXISTS managed_account_model_cooldowns (provider_id TEXT NOT NULL, account_id TEXT NOT NULL, family TEXT NOT NULL, rate_limited_until INTEGER NOT NULL, last_rate_limited_at INTEGER NOT NULL, PRIMARY KEY(provider_id,account_id,family));';
|
|
30
|
-
/** Adds the model-cooldown table to a provider store that predates it; a no-op (no write) once present. */
|
|
31
|
-
export function ensureProviderModelCooldowns(db) {
|
|
32
|
-
const present = db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='managed_account_model_cooldowns'").get();
|
|
33
|
-
if (present === undefined)
|
|
34
|
-
db.exec(MODEL_COOLDOWNS_TABLE);
|
|
35
|
-
}
|
|
36
|
-
const PROVIDER_SCHEMA = `
|
|
37
|
-
CREATE TABLE managed_accounts (provider_id TEXT NOT NULL, id TEXT NOT NULL, label TEXT NOT NULL, label_key TEXT NOT NULL, position INTEGER NOT NULL, last_attempt_at INTEGER NOT NULL, last_rate_limited_at INTEGER NOT NULL, rate_limited_until INTEGER NOT NULL, auth_failure TEXT CHECK(auth_failure IS NULL OR auth_failure='invalid_grant'), PRIMARY KEY(provider_id,id), UNIQUE(provider_id,label_key));
|
|
38
|
-
CREATE INDEX managed_accounts_order ON managed_accounts(provider_id,position);
|
|
39
|
-
CREATE TABLE rotation_settings (singleton INTEGER PRIMARY KEY CHECK(singleton=1), default_fallback_strength TEXT, revert_when_available INTEGER CHECK(revert_when_available IN (0,1)));
|
|
40
|
-
CREATE TABLE provider_revision (singleton INTEGER PRIMARY KEY CHECK(singleton=1), revision INTEGER NOT NULL);
|
|
41
|
-
${MODEL_COOLDOWNS_TABLE}`;
|
|
42
|
-
export function createScopedSchema(db, kind) {
|
|
43
|
-
db.exec(kind === 'provider' ? PROVIDER_SCHEMA : SCOPE_SCHEMA);
|
|
44
|
-
if (kind !== 'provider') {
|
|
45
|
-
const ownerKey = kind === 'user' ? 'user' : 'project';
|
|
46
|
-
cachedStatement(db, 'INSERT INTO scope_owners(owner_key, kind, root, profile_id) VALUES (?, ?, ?, NULL)').run(ownerKey, kind, '');
|
|
47
|
-
}
|
|
48
|
-
else {
|
|
49
|
-
cachedStatement(db, 'INSERT INTO provider_revision(singleton, revision) VALUES (1, 0)').run();
|
|
50
|
-
}
|
|
51
|
-
db.exec(`PRAGMA user_version = ${kind === 'provider' ? PROVIDER_SCHEMA_VERSION : SCOPED_SCHEMA_VERSION}`);
|
|
52
|
-
}
|
|
@@ -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>;
|
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
// Writes an import plan into canvas.db: owners, documents with their revisions and
|
|
2
|
-
// their bodies (content-addressed rows in `bodies`), links, the
|
|
3
|
-
// authors' acted-on edges and watches, and the done-record, in one transaction.
|
|
4
|
-
// Publishes nothing: the import is history, not activity.
|
|
5
|
-
import { put as putBody } from '../../core/graph/bodies.js';
|
|
6
|
-
import { importDocument } from '../../core/graph/documents.js';
|
|
7
|
-
import { linksIn } from '../../core/graph/documents.js';
|
|
8
|
-
import { recordActedOn, setLinks } from '../../core/graph/edges.js';
|
|
9
|
-
import { resolveName } from '../../core/graph/names.js';
|
|
10
|
-
import { ensureOwner, nodeObject, ownerForGrantee } from '../../core/graph/objects.js';
|
|
11
|
-
import { ensureRepo } from '../../core/graph/repo-sync/repos.js';
|
|
12
|
-
import { recordWatch } from '../../core/graph/watches.js';
|
|
13
|
-
import { mapAsync } from '../../core/async-array.js';
|
|
14
|
-
import { personId } from '../../core/canvas/person.js';
|
|
15
|
-
/** The canvas_meta key whose presence means this home's legacy stores were imported. */
|
|
16
|
-
export const IMPORT_DONE_KEY = 'canvas-import';
|
|
17
|
-
export const IMPORT_ID = '004-canvas-documents';
|
|
18
|
-
export async function readImportRecord(db) {
|
|
19
|
-
const row = await db.prepareUncached('SELECT value FROM canvas_meta WHERE key = ?').get(IMPORT_DONE_KEY);
|
|
20
|
-
if (row === undefined)
|
|
21
|
-
return null;
|
|
22
|
-
const report = JSON.parse(row.value).report;
|
|
23
|
-
return { ...report, resolutions: report.resolutions ?? [] };
|
|
24
|
-
}
|
|
25
|
-
/** Run inside the caller's write transaction; each revision's text is stored in it. Throws on any divergence from the plan. */
|
|
26
|
-
export async function applyPlan(db, plan) {
|
|
27
|
-
const hashes = new Map();
|
|
28
|
-
for (const d of plan.documents)
|
|
29
|
-
for (const r of d.revisions)
|
|
30
|
-
if (!hashes.has(r.body))
|
|
31
|
-
hashes.set(r.body, await putBody(db, r.body));
|
|
32
|
-
const planned = new Map(plan.owners.map((o) => [o.key, o]));
|
|
33
|
-
const rows = new Map();
|
|
34
|
-
const ownerRow = async (o) => {
|
|
35
|
-
const known = rows.get(o.key);
|
|
36
|
-
if (known)
|
|
37
|
-
return known;
|
|
38
|
-
let row;
|
|
39
|
-
switch (o.type) {
|
|
40
|
-
case 'person':
|
|
41
|
-
row = await ownerForGrantee(db, personId());
|
|
42
|
-
break;
|
|
43
|
-
case 'app':
|
|
44
|
-
row = await ensureOwner(db, 'app', 'app', `app:${o.handle}`, o.handle);
|
|
45
|
-
break;
|
|
46
|
-
case 'profile': {
|
|
47
|
-
const app = planned.get(o.ownerKey);
|
|
48
|
-
if (!app)
|
|
49
|
-
throw new Error(`import: profile ${o.key} names unplanned app ${o.ownerKey}`);
|
|
50
|
-
row = await ensureOwner(db, 'profile', 'profile', o.key.slice('profile:'.length), o.handle, await ownerRow(app));
|
|
51
|
-
break;
|
|
52
|
-
}
|
|
53
|
-
case 'repo':
|
|
54
|
-
row = await ensureRepo(db, { scheme: o.scheme, externalId: o.externalId, handleHint: o.handle }, o.handle);
|
|
55
|
-
break;
|
|
56
|
-
case 'node':
|
|
57
|
-
row = await nodeObject(db, o.handle);
|
|
58
|
-
break;
|
|
59
|
-
}
|
|
60
|
-
if (o.type !== 'node' && row.name !== o.handle)
|
|
61
|
-
throw new Error(`import: owner ${o.key} holds handle ${row.name}, planned ${o.handle}`);
|
|
62
|
-
rows.set(o.key, row);
|
|
63
|
-
return row;
|
|
64
|
-
};
|
|
65
|
-
const person = await ownerRow(planned.get('person') ?? { key: 'person', type: 'person', handle: 'user' });
|
|
66
|
-
const reader = { class: 'person', person };
|
|
67
|
-
const nodes = new Map();
|
|
68
|
-
const node = async (id) => {
|
|
69
|
-
let row = nodes.get(id);
|
|
70
|
-
if (!row)
|
|
71
|
-
nodes.set(id, (row = await nodeObject(db, id)));
|
|
72
|
-
return row;
|
|
73
|
-
};
|
|
74
|
-
const imported = [];
|
|
75
|
-
for (const d of plan.documents) {
|
|
76
|
-
const owner = await ownerRow(planned.get(d.ownerKey));
|
|
77
|
-
const doc = await importDocument(db, {
|
|
78
|
-
owner, name: d.name, kind: d.kind, preview: d.preview, privacy: d.privacy,
|
|
79
|
-
summary: d.summary, whyItExists: d.whyItExists, unlisted: d.unlisted, rules: d.rules,
|
|
80
|
-
lintIgnore: d.lintIgnore, extensions: d.extensions,
|
|
81
|
-
revisions: (await mapAsync(d.revisions, async (r) => ({
|
|
82
|
-
body_hash: hashes.get(r.body), author: r.authorNodeId === null ? null : await node(r.authorNodeId),
|
|
83
|
-
rationale: r.rationale, created_at: r.createdAt,
|
|
84
|
-
}))),
|
|
85
|
-
});
|
|
86
|
-
const authors = new Set(d.revisions.flatMap((r) => (r.authorNodeId === null ? [] : [r.authorNodeId])));
|
|
87
|
-
imported.push({ doc, owner, body: d.revisions[d.revisions.length - 1].body, authors });
|
|
88
|
-
}
|
|
89
|
-
// Links resolve after every document exists; a bare name prefers the linking document's owner.
|
|
90
|
-
for (const { doc, owner, body, authors } of imported) {
|
|
91
|
-
const links = [];
|
|
92
|
-
for (const name of linksIn(body)) {
|
|
93
|
-
const candidates = name.includes('/') ? [name] : [`${owner.type === 'node' ? owner.id : owner.name}/${name}`, name];
|
|
94
|
-
for (const c of candidates) {
|
|
95
|
-
const hit = await resolveName(db, reader, c);
|
|
96
|
-
if ('object' in hit) {
|
|
97
|
-
links.push({ written_as: name, dst: hit.object });
|
|
98
|
-
break;
|
|
99
|
-
}
|
|
100
|
-
if ('deleted' in hit) {
|
|
101
|
-
links.push({ written_as: name, dst: hit.deleted });
|
|
102
|
-
break;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
await setLinks(db, doc, links);
|
|
107
|
-
for (const id of authors) {
|
|
108
|
-
await recordActedOn(db, await node(id), doc);
|
|
109
|
-
await recordWatch(db, await node(id), doc, 'write');
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
await db.prepareUncached('INSERT INTO canvas_meta (key, value) VALUES (?, ?)').run(IMPORT_DONE_KEY, JSON.stringify({ id: IMPORT_ID, report: plan.report }));
|
|
113
|
-
}
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import { type ImportBlocker, type ImportReport } from './plan.js';
|
|
2
|
-
export type { ImportBlocker, ImportReport } from './plan.js';
|
|
3
|
-
export interface CanvasImportResult {
|
|
4
|
-
report: ImportReport;
|
|
5
|
-
blockers: ImportBlocker[];
|
|
6
|
-
dryRun: boolean;
|
|
7
|
-
/** True while this home still has to be imported (always false after a write run succeeds). */
|
|
8
|
-
pending: boolean;
|
|
9
|
-
}
|
|
10
|
-
/** Whether this home's import has already been recorded. */
|
|
11
|
-
export declare function canvasImportDone(): Promise<boolean>;
|
|
12
|
-
/** Plan and (unless `dryRun` or blocked) apply the import. On an imported home a dry run
|
|
13
|
-
* returns the recorded report; a write run does nothing and returns empty counts. */
|
|
14
|
-
export declare function runCanvasImport(opts: {
|
|
15
|
-
dryRun: boolean;
|
|
16
|
-
}): Promise<CanvasImportResult>;
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
// 004-canvas-documents — the one cut: every pre-canvas memory store, node
|
|
2
|
-
// context folder and report file becomes canvas documents. The daemon runs it
|
|
3
|
-
// at startup and resolves every clash itself, reporting each resolution; only
|
|
4
|
-
// a runtime that skipped the previous release's store migrations blocks it,
|
|
5
|
-
// holding startup in `blocked` until `crtr sys migrate` finds a clean plan.
|
|
6
|
-
import { projectPaths } from '../../api/dto/profiles.js';
|
|
7
|
-
import { existsSync } from 'node:fs';
|
|
8
|
-
import { join } from 'node:path';
|
|
9
|
-
import { openDb, withCanvasWrite } from '../../core/canvas/db.js';
|
|
10
|
-
import { nodeAgentDir, nodeRecordDir, onDiskMigrationMarkerPath } from '../../core/canvas/paths.js';
|
|
11
|
-
import { identifyCheckout } from '../../core/graph/repo-sync/identity.js';
|
|
12
|
-
import { profileSpace, userRoot } from '../../core/layout.js';
|
|
13
|
-
import { deleteLegacyProjectCaps, listLegacyProjectCaps, readLegacyUserSnapshot } from '../../core/scoped-state/legacy-profiles.js';
|
|
14
|
-
import { personIdAsync } from '../../core/canvas/person.js';
|
|
15
|
-
import { userStore } from '../../core/scoped-state/paths.js';
|
|
16
|
-
import { userScopeRoot } from '../../core/scope.js';
|
|
17
|
-
import { LEGACY_LOCAL_PERSON } from '../../core/canvas/legacy-person.js';
|
|
18
|
-
import { applyPlan, readImportRecord } from './apply.js';
|
|
19
|
-
import { readLegacyCorpus, readMarkerIds } from './legacy/discover.js';
|
|
20
|
-
import { planImport } from './plan.js';
|
|
21
|
-
const emptyReport = () => ({ stores: [], counts: {}, rewrites: [], droppedFields: [], skipped: [], resolutions: [] });
|
|
22
|
-
async function legacyRoots() {
|
|
23
|
-
const scope = userScopeRoot();
|
|
24
|
-
const stored = readLegacyUserSnapshot(scope)?.profiles ?? [];
|
|
25
|
-
const caps = listLegacyProjectCaps(scope);
|
|
26
|
-
const manifestStore = userStore(scope).path;
|
|
27
|
-
const profiles = stored.map(({ profileId, manifest }) => {
|
|
28
|
-
const app = manifest.grantee ?? 'app:terminal';
|
|
29
|
-
const mine = new Map(caps.filter((c) => c.profileId === profileId).map((c) => [c.path, c.memory]));
|
|
30
|
-
return {
|
|
31
|
-
id: profileId, name: manifest.name, app, memory: profileSpace(app, profileId).dir,
|
|
32
|
-
projects: projectPaths(manifest.projects),
|
|
33
|
-
raw: { projects: projectPaths(manifest.projects).map((path) => (mine.has(path) ? { path, memory: mine.get(path) } : { path })) },
|
|
34
|
-
manifestPath: `${manifestStore}#${profileId}`,
|
|
35
|
-
};
|
|
36
|
-
});
|
|
37
|
-
const rows = await (await openDb()).prepareUncached('SELECT node_id, cwd, grantee FROM node_rows ORDER BY created').all();
|
|
38
|
-
const nodes = rows.map((r) => {
|
|
39
|
-
// An app node's folder is in its app space; any other node's is its record folder.
|
|
40
|
-
// Stage L placed a legacy-local-person row's folders in the terminal app, as migration v49 assigns it.
|
|
41
|
-
const app = r.grantee === LEGACY_LOCAL_PERSON ? 'app:terminal' : r.grantee;
|
|
42
|
-
const agent = app?.startsWith('app:') ? nodeAgentDir(r.node_id, app) : null;
|
|
43
|
-
const dir = agent !== null && (existsSync(join(agent, 'context')) || existsSync(join(agent, 'reports'))) ? agent : nodeRecordDir(r.node_id);
|
|
44
|
-
return { id: r.node_id, dir };
|
|
45
|
-
});
|
|
46
|
-
return {
|
|
47
|
-
// The layout migration moved the old user store to user/memory.
|
|
48
|
-
roots: { userMemory: join(userRoot(), 'memory'), profiles, nodeCwds: [...new Set(rows.map((r) => r.cwd))], nodes },
|
|
49
|
-
stored,
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
async function plan() {
|
|
53
|
-
const { roots, stored } = await legacyRoots();
|
|
54
|
-
const corpus = readLegacyCorpus(roots);
|
|
55
|
-
const existingOwners = await (await openDb()).prepareUncached(`SELECT o.type, o.name AS handle, i.external_id AS externalId FROM objects o
|
|
56
|
-
LEFT JOIN identities i ON i.object = o.id WHERE o.type IN ('person','app','repo','profile')`).all();
|
|
57
|
-
return planImport(corpus, {
|
|
58
|
-
roots,
|
|
59
|
-
markerIds: readMarkerIds(onDiskMigrationMarkerPath()),
|
|
60
|
-
repoIdentity: identifyCheckout,
|
|
61
|
-
existingOwners,
|
|
62
|
-
storedProfiles: stored.map((p) => ({ id: p.profileId, deliveryLimits: { ...(p.manifest.delivery_limits ?? {}) } })),
|
|
63
|
-
});
|
|
64
|
-
}
|
|
65
|
-
/** Whether this home's import has already been recorded. */
|
|
66
|
-
export async function canvasImportDone() {
|
|
67
|
-
return await readImportRecord(await openDb()) !== null;
|
|
68
|
-
}
|
|
69
|
-
/** Plan and (unless `dryRun` or blocked) apply the import. On an imported home a dry run
|
|
70
|
-
* returns the recorded report; a write run does nothing and returns empty counts. */
|
|
71
|
-
export async function runCanvasImport(opts) {
|
|
72
|
-
const recorded = await readImportRecord(await openDb());
|
|
73
|
-
if (recorded !== null)
|
|
74
|
-
return { report: opts.dryRun ? recorded : emptyReport(), blockers: [], dryRun: opts.dryRun, pending: false };
|
|
75
|
-
const p = await plan();
|
|
76
|
-
if (opts.dryRun || p.blockers.length > 0)
|
|
77
|
-
return { report: p.report, blockers: p.blockers, dryRun: opts.dryRun, pending: true };
|
|
78
|
-
// Scoped-state caps convert first: a crash after it leaves the canvas import still pending,
|
|
79
|
-
// and a re-plan reads the converted limits instead of the (deleted) cap rows.
|
|
80
|
-
const person = await personIdAsync();
|
|
81
|
-
await withCanvasWrite(async (db) => {
|
|
82
|
-
for (const l of p.profileLimits)
|
|
83
|
-
if ((await db.prepare('UPDATE profiles SET delivery_limits_json = ? WHERE id = ? AND person = ?').run(JSON.stringify(l.deliveryLimits), l.profileId, person)).changes !== 1)
|
|
84
|
-
throw new Error(`no stored profile ${l.profileId}`);
|
|
85
|
-
});
|
|
86
|
-
deleteLegacyProjectCaps(userScopeRoot());
|
|
87
|
-
await withCanvasWrite(async (db) => await applyPlan(db, p));
|
|
88
|
-
return { report: p.report, blockers: [], dryRun: false, pending: false };
|
|
89
|
-
}
|