@north-light/cli 0.3.678 → 0.3.680
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 +0 -8
- package/dist/api/client.js +3 -3
- package/dist/api/routes.d.ts +0 -2
- package/dist/api/routes.js +1 -1
- package/dist/api/server-timing.d.ts +3 -0
- package/dist/api/server-timing.js +1 -0
- package/dist/clients/attach/viewer.js +447 -447
- package/dist/commands/sys.js +1 -1
- package/dist/core/checkout-identities.js +3 -3
- package/dist/core/conversation-store/client.d.ts +9 -0
- package/dist/core/conversation-store/client.js +2 -2
- package/dist/core/conversation-store/index.d.ts +10 -2
- package/dist/core/conversation-store/index.js +1 -1
- package/dist/core/conversation-store/patch.js +1 -1
- package/dist/core/conversation-store/row-store.js +9 -9
- package/dist/core/graph/objects.d.ts +0 -3
- package/dist/core/graph/objects.js +10 -10
- package/dist/core/runtime/broker.d.ts +3 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/front-door.js +4 -4
- package/dist/core/runtime/runner/blaxel/image-build.js +3 -3
- package/dist/core/runtime/runner/blaxel/release-image.js +2 -2
- package/dist/core/runtime/runner/machine/call.d.ts +5 -0
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/core/runtime/runner/machine/ops.d.ts +2 -0
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/step-timings.d.ts +13 -0
- package/dist/core/step-timings.js +1 -0
- package/dist/core/timing.d.ts +2 -0
- package/dist/core/timing.js +2 -2
- package/dist/daemon/api/handlers/conversations.js +1 -1
- package/dist/daemon/api/handlers/nodes.d.ts +1 -0
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/docs/ci-runner.md +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +4 -8
- package/packages/crouter-api/dist/api/routes.js +0 -2
- package/packages/crouter-api/dist/api/server-timing.js +11 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +1 -1
- package/packages/crouter-api/dist/commands/node-context.js +1 -1
- package/packages/crouter-api/dist/commands/sys.js +1 -2
- package/packages/crouter-api/dist/core/checkout-identities.js +4 -1
- package/packages/crouter-api/dist/core/conversation-store/client.js +8 -1
- package/packages/crouter-api/dist/core/conversation-store/index.js +1 -0
- package/packages/crouter-api/dist/core/conversation-store/patch.js +1 -2
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +2 -2
- package/packages/crouter-api/dist/core/graph/objects.js +0 -15
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +2 -2
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/release-image.js +1 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +7 -0
- package/packages/crouter-api/dist/core/runtime/spawn.js +30 -8
- package/packages/crouter-api/dist/core/step-timings.js +37 -0
- package/packages/crouter-api/dist/core/timing.js +14 -0
- package/packages/crouter-api/dist/daemon/api/operations.js +0 -2
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/sandbox-bootstrap.sh +1 -4
- package/dist/api/dto/repo-import.d.ts +0 -25
- package/dist/api/dto/repo-import.js +0 -0
- package/dist/commands/sys/repo-docs.d.ts +0 -1
- package/dist/commands/sys/repo-docs.js +0 -2
- package/dist/core/graph/repo-sync/exchange.d.ts +0 -25
- package/dist/core/graph/repo-sync/exchange.js +0 -1
- package/dist/core/graph/repo-sync/ref-format.d.ts +0 -51
- package/dist/core/graph/repo-sync/ref-format.js +0 -1
- package/dist/daemon/api/handlers/repo-import.d.ts +0 -2
- package/dist/daemon/api/handlers/repo-import.js +0 -2
- package/packages/crouter-api/dist/api/dto/repo-import.js +0 -5
- package/packages/crouter-api/dist/commands/sys/repo-docs.js +0 -96
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { appsRoot } from '../layout.js';
|
|
2
2
|
import { apiSocketPath } from '../canvas/paths.js';
|
|
3
3
|
import { createStoreClient } from './client.js';
|
|
4
|
+
export { setConversationRequestMark } from './client.js';
|
|
4
5
|
import { currentNodeToken } from '../runtime/broker/node-token.js';
|
|
5
6
|
export class ConversationNotFoundError extends Error {
|
|
6
7
|
code = 'not_found';
|
|
@@ -49,8 +49,7 @@ export function installSessionManagerStorePatch(nodeId, store = conversationClie
|
|
|
49
49
|
const [header, ...entries] = manager.fileEntries;
|
|
50
50
|
if (!header || header.type !== 'session')
|
|
51
51
|
throw new Error('conversation has no session header');
|
|
52
|
-
store.create(nodeId, header, entries);
|
|
53
|
-
manager.sessionFile = store.header(header.id).path;
|
|
52
|
+
manager.sessionFile = store.create(nodeId, header, entries).path;
|
|
54
53
|
manager.sessionDir = dirname(manager.sessionFile);
|
|
55
54
|
manager.flushed = true;
|
|
56
55
|
}
|
|
@@ -164,7 +164,7 @@ export function createRowStore() {
|
|
|
164
164
|
await tx.prepare('UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE session_id = ? AND node_id = ?').run(entries.at(-1)?.id ?? null, JSON.stringify(pending), id, nodeId);
|
|
165
165
|
}
|
|
166
166
|
});
|
|
167
|
-
return id;
|
|
167
|
+
return { conversation_id: id, path };
|
|
168
168
|
},
|
|
169
169
|
async append(id, entries) {
|
|
170
170
|
if (!entries.length)
|
|
@@ -276,7 +276,7 @@ export function createRowStore() {
|
|
|
276
276
|
manager.createBranchedSession(leafId);
|
|
277
277
|
entries = manager.getEntries();
|
|
278
278
|
}
|
|
279
|
-
return await store.create(nodeId ?? (await initial(id, await openDb())).binding?.node_id ?? legacy.get(id).node, { ...source.header, id: randomUUID(), timestamp: at(), cwd: cwd ?? source.header.cwd, parentSession: source.path }, entries);
|
|
279
|
+
return (await store.create(nodeId ?? (await initial(id, await openDb())).binding?.node_id ?? legacy.get(id).node, { ...source.header, id: randomUUID(), timestamp: at(), cwd: cwd ?? source.header.cwd, parentSession: source.path }, entries)).conversation_id;
|
|
280
280
|
},
|
|
281
281
|
async delete(id, knownPath) {
|
|
282
282
|
const db = await openDb();
|
|
@@ -275,18 +275,3 @@ export async function searchObjects(db, reader, query) {
|
|
|
275
275
|
await flush();
|
|
276
276
|
return hits;
|
|
277
277
|
}
|
|
278
|
-
/** One-time cutover (`crtr sys repo-docs rename`): give the live repo object holding handle `from` the handle `to`.
|
|
279
|
-
* Refuses with `conflict` before changing anything when another live repo holds `to`. The id never changes (I4). */
|
|
280
|
-
export async function renameRepoObject(db, from, to) {
|
|
281
|
-
const own = await db.prepare(`SELECT * FROM objects WHERE name = ? AND type = 'repo' AND deleted_at IS NULL AND home_machine IS NULL`).get(from);
|
|
282
|
-
if (!own)
|
|
283
|
-
throw new CrtrError('not_found', `no repo named "${from}"`, ExitCode.GENERAL, { handle: from });
|
|
284
|
-
const holder = await db.prepare(`SELECT id FROM objects WHERE name = ? AND type = 'repo' AND deleted_at IS NULL AND home_machine IS NULL AND id <> ?`).get(to, own.id);
|
|
285
|
-
if (holder) {
|
|
286
|
-
throw new CrtrError('conflict', `handle "${to}" is already held by repo object ${holder.id}; cannot rename repo ${from} to it`, ExitCode.GENERAL, { handle: to, holder: holder.id });
|
|
287
|
-
}
|
|
288
|
-
if (own.name === to)
|
|
289
|
-
return false;
|
|
290
|
-
await setObjectName(db, own, to);
|
|
291
|
-
return true;
|
|
292
|
-
}
|
|
@@ -57,7 +57,7 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
|
|
|
57
57
|
out.push(guarded('setup script', `bash /tmp/${SETUP_SCRIPT_FILE}`));
|
|
58
58
|
out.push(guarded('finalize', `echo ${Math.trunc(revision)} > /work/.crtr/recipe-revision && chown -R ${RUN_USER} /work /home/${RUN_USER} /var/lib/crtr`));
|
|
59
59
|
out.push('', ...base);
|
|
60
|
-
//
|
|
60
|
+
// Blaxel keeps the ownership set in the Dockerfile only for an image that declares a final USER (an image without one is built all root-owned); the final USER is below.
|
|
61
61
|
for (const dir of ['/work', `/home/${RUN_USER}`, '/var/lib/crtr'])
|
|
62
62
|
out.push(`COPY --from=build --chown=${RUN_USER}:${RUN_USER} ${dir} ${dir}`);
|
|
63
63
|
for (const dir of ['/usr/local', '/usr', '/etc', '/lib'])
|
|
@@ -67,7 +67,7 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
|
|
|
67
67
|
out.push('RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi');
|
|
68
68
|
if (packagesToken)
|
|
69
69
|
out.push(`RUN rm -f /work/.npmrc /home/${RUN_USER}/.npmrc`);
|
|
70
|
-
out.push('WORKDIR /work', 'ENTRYPOINT ["/usr/local/bin/sandbox-api"]', '');
|
|
70
|
+
out.push(`USER ${RUN_USER}`, 'WORKDIR /work', 'ENTRYPOINT ["/usr/local/bin/sandbox-api"]', '');
|
|
71
71
|
return out.join('\n');
|
|
72
72
|
}
|
|
73
73
|
const runGit = (args, env, cwd) => new Promise((resolve, reject) => {
|
|
@@ -51,6 +51,7 @@ export function releaseImageDockerfile(version, sha256) {
|
|
|
51
51
|
`COPY --from=${SANDBOX_API_IMAGE} /sandbox-api /usr/local/bin/sandbox-api`,
|
|
52
52
|
`RUN adduser -D -h /home/${RUN_USER} -s /bin/sh ${RUN_USER} && mkdir -p /run/crtr /var/lib/crtr /work/.crtr && chown -R ${RUN_USER} /run/crtr /var/lib/crtr /work`,
|
|
53
53
|
'COPY --from=release /opt/crtr /opt/crtr',
|
|
54
|
+
`USER ${RUN_USER}`,
|
|
54
55
|
'WORKDIR /work',
|
|
55
56
|
'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',
|
|
56
57
|
'',
|
|
@@ -16,6 +16,13 @@ export const MACHINE_CALL_TIMEOUT_S = {
|
|
|
16
16
|
'repo.identify': 15,
|
|
17
17
|
};
|
|
18
18
|
const REREAD_MS = 1000;
|
|
19
|
+
/** When a call was queued and when its holder settled it (epoch ms), for the create request's step timings. Null when the row is gone or unsettled. */
|
|
20
|
+
export async function callTimes(callId) {
|
|
21
|
+
const row = await (await openDb()).prepare('SELECT created_at, finished_at FROM machine_calls WHERE call_id = ?').get(callId);
|
|
22
|
+
if (row === undefined || row.finished_at === null)
|
|
23
|
+
return null;
|
|
24
|
+
return { createdAt: Date.parse(row.created_at), finishedAt: Date.parse(row.finished_at) };
|
|
25
|
+
}
|
|
19
26
|
/** Write the `pending` call row and notify the link's holder, in the caller's transaction when it has one (the notification is delivered at its commit,
|
|
20
27
|
* so a call queued by a transaction that rolls back is never sent). No live link → MachineOfflineError, nothing written. Returns the call id for `awaitMachineCall`. */
|
|
21
28
|
export async function enqueueMachineCall(environmentId, op, args) {
|
|
@@ -48,7 +48,8 @@ import { personIdAsync } from '../canvas/person.js';
|
|
|
48
48
|
import { recordLaunch } from '../canvas/canvas.js';
|
|
49
49
|
import { setExecutionLaunchJson } from '../canvas/executions.js';
|
|
50
50
|
import { acceptedRelease, remoteMachineEnvironmentOf } from '../../daemon/reconcilers/node-lifecycle/remote-wake.js';
|
|
51
|
-
import { enqueueMachineCall, awaitMachineCall } from './runner/machine/call.js';
|
|
51
|
+
import { enqueueMachineCall, awaitMachineCall, callTimes } from './runner/machine/call.js';
|
|
52
|
+
import { addStepTiming, timedStep } from '../step-timings.js';
|
|
52
53
|
import { MachineLostError, MachineOfflineError } from './runner/machine/ops.js';
|
|
53
54
|
import { isDrained } from '../../daemon/drain.js';
|
|
54
55
|
import { ensureDaemon } from '../../daemon/manage.js';
|
|
@@ -270,6 +271,16 @@ export function resolveSpawner(parent, ctxNodeId, root) {
|
|
|
270
271
|
}
|
|
271
272
|
return spawner;
|
|
272
273
|
}
|
|
274
|
+
/** Record how long the `start` call took from being queued to being answered (both times are written once, by the queuer and by the link
|
|
275
|
+
* holder that settles it), and the steps the Mac reported inside `executor.start`. The row keeps no time for when the holder sent the call, so
|
|
276
|
+
* the enqueue-to-sent and sent-to-answer halves are not reported; the Mac's own steps show its share. */
|
|
277
|
+
async function recordStartCallTimings(callId, answer) {
|
|
278
|
+
const times = await callTimes(callId);
|
|
279
|
+
if (times !== null)
|
|
280
|
+
addStepTiming('start_enqueue_to_answer', times.finishedAt - times.createdAt);
|
|
281
|
+
for (const [name, ms] of Object.entries(answer?.timings ?? {}))
|
|
282
|
+
addStepTiming(`mac_${name}`, ms);
|
|
283
|
+
}
|
|
273
284
|
/** Launch a just-born node on its remote machine in two transactions: the node and execution rows are committed (as a birth always does), then one
|
|
274
285
|
* transaction renders the start data, mints the token and queues the `start` call; the call is awaited after that commit. The bundle's network work
|
|
275
286
|
* (GitHub token, blob store) runs before that transaction opens. 'failed': nothing started, the caller freezes the node for the lifecycle tick to wake.
|
|
@@ -298,10 +309,10 @@ async function startOnMachine(meta, environmentId, inv) {
|
|
|
298
309
|
const launchJson = await brokerLaunchJson(meta.node_id, inv, meta.cwd);
|
|
299
310
|
await setExecutionLaunchJson(executionId, launchJson);
|
|
300
311
|
const execId = executionId;
|
|
301
|
-
await warmNodeRepos(await openDb(), meta.node_id);
|
|
312
|
+
await timedStep('warm_repos', async () => await warmNodeRepos(await openDb(), meta.node_id));
|
|
302
313
|
const sub = meta.sub ?? await personIdAsync();
|
|
303
|
-
const bundle = await buildStartBundle({ nodeId: meta.node_id, app: meta.grantee ?? 'app:terminal', sub, launchJson, runner: 'machine' });
|
|
304
|
-
callId = await withCanvasWrite(async (db) => {
|
|
314
|
+
const bundle = await timedStep('start_bundle', () => buildStartBundle({ nodeId: meta.node_id, app: meta.grantee ?? 'app:terminal', sub, launchJson, runner: 'machine' }));
|
|
315
|
+
callId = await timedStep('render_transaction', () => withCanvasWrite(async (db) => {
|
|
305
316
|
// The reader is built here, after the goal and every birth write have landed, so the rendered bearings see them.
|
|
306
317
|
const start = await renderCarriedStart(meta.node_id);
|
|
307
318
|
const nodeToken = await mintNodeToken(db, execId, meta.node_id, new Date().toISOString());
|
|
@@ -309,15 +320,16 @@ async function startOnMachine(meta, environmentId, inv) {
|
|
|
309
320
|
executionId: execId, nodeId: meta.node_id, attempt: 1, sandboxName: null, release: acceptedRelease(), launchJson, cwd: meta.cwd, resuming: false,
|
|
310
321
|
nodeToken, bundle, start,
|
|
311
322
|
});
|
|
312
|
-
});
|
|
323
|
+
}));
|
|
313
324
|
}
|
|
314
325
|
catch (error) {
|
|
315
326
|
emitEvent({ level: 'warn', event: 'broker.create_start_failed', node_id: meta.node_id, error });
|
|
316
327
|
await abortExecution(executionId, { reason: 'launch_failed' });
|
|
317
328
|
return 'failed';
|
|
318
329
|
}
|
|
330
|
+
let startAnswer;
|
|
319
331
|
try {
|
|
320
|
-
await awaitMachineCall(environmentId, 'start', callId);
|
|
332
|
+
startAnswer = await awaitMachineCall(environmentId, 'start', callId);
|
|
321
333
|
}
|
|
322
334
|
catch (error) {
|
|
323
335
|
emitEvent({ level: 'warn', event: 'broker.create_start_failed', node_id: meta.node_id, error });
|
|
@@ -327,9 +339,16 @@ async function startOnMachine(meta, environmentId, inv) {
|
|
|
327
339
|
await abortExecution(executionId, { reason: 'launch_failed' });
|
|
328
340
|
return 'failed';
|
|
329
341
|
}
|
|
330
|
-
// The Mac has confirmed the start:
|
|
342
|
+
// The Mac has confirmed the start: timing marks are diagnostics only and never change the outcome.
|
|
343
|
+
try {
|
|
344
|
+
await recordStartCallTimings(callId, startAnswer);
|
|
345
|
+
}
|
|
346
|
+
catch (error) {
|
|
347
|
+
emitEvent({ level: 'warn', event: 'broker.create_start_timing_failed', node_id: meta.node_id, error });
|
|
348
|
+
}
|
|
349
|
+
// A failure to record it must not end a running execution.
|
|
331
350
|
try {
|
|
332
|
-
await recordLaunch(meta.node_id, new Date().toISOString());
|
|
351
|
+
await timedStep('record_launch', () => recordLaunch(meta.node_id, new Date().toISOString()));
|
|
333
352
|
}
|
|
334
353
|
catch (error) {
|
|
335
354
|
emitEvent({ level: 'warn', event: 'broker.create_start_record_failed', node_id: meta.node_id, error });
|
|
@@ -337,6 +356,7 @@ async function startOnMachine(meta, environmentId, inv) {
|
|
|
337
356
|
return 'started';
|
|
338
357
|
}
|
|
339
358
|
export async function spawnChildPrepared(opts, beforeBrokerLaunch, afterNodeCreated) {
|
|
359
|
+
const birthStart = performance.now();
|
|
340
360
|
try {
|
|
341
361
|
ensureDaemon();
|
|
342
362
|
}
|
|
@@ -567,6 +587,8 @@ export async function spawnChildPrepared(opts, beforeBrokerLaunch, afterNodeCrea
|
|
|
567
587
|
// Mac needs, so the node is never left dormant for the lifecycle tick to wake.
|
|
568
588
|
const machine = opts.start === true ? await remoteMachineEnvironmentOf(meta.profile_id ?? null) : null;
|
|
569
589
|
if (machine !== null) {
|
|
590
|
+
// Billing admission, node creation, goal write, birth hooks and the broker invocation are done; the start steps follow.
|
|
591
|
+
addStepTiming('birth', performance.now() - birthStart);
|
|
570
592
|
const started = await startOnMachine(meta, machine, inv);
|
|
571
593
|
if (started === 'started' || started === 'uncertain')
|
|
572
594
|
return { node: meta, frozen: false, window: null, session: null };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// step-timings.ts — step durations of one control plane request, returned to its caller in a `Server-Timing` header.
|
|
2
|
+
// The client prints them through `markServerTiming` in timing.ts.
|
|
3
|
+
//
|
|
4
|
+
// The control plane's logs may not be readable by the person who made a request, so the steps of one request are returned to them in a
|
|
5
|
+
// `Server-Timing` response header. A request opts in by running inside `collectStepTimings`; `timedStep` / `addStepTiming` record nothing
|
|
6
|
+
// outside one. Names and durations only: never a token, secret, env value or document body.
|
|
7
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
8
|
+
const stepTimings = new AsyncLocalStorage();
|
|
9
|
+
/** Run `fn`, collecting the steps recorded beneath it. */
|
|
10
|
+
export async function collectStepTimings(fn) {
|
|
11
|
+
const steps = [];
|
|
12
|
+
const value = await stepTimings.run({ steps, start: performance.now() }, fn);
|
|
13
|
+
return { value, steps };
|
|
14
|
+
}
|
|
15
|
+
/** Record a step's duration in ms, when a request is collecting. */
|
|
16
|
+
export function addStepTiming(name, ms) {
|
|
17
|
+
stepTimings.getStore()?.steps.push([name, ms]);
|
|
18
|
+
}
|
|
19
|
+
/** ms since the collection began (0 outside one). */
|
|
20
|
+
export function sinceCollectionStart() {
|
|
21
|
+
const store = stepTimings.getStore();
|
|
22
|
+
return store === undefined ? 0 : performance.now() - store.start;
|
|
23
|
+
}
|
|
24
|
+
/** Run `fn` and record how long it took under `name`, whether it returns or throws. */
|
|
25
|
+
export async function timedStep(name, fn) {
|
|
26
|
+
const start = performance.now();
|
|
27
|
+
try {
|
|
28
|
+
return await fn();
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
addStepTiming(name, performance.now() - start);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** The `Server-Timing` header value for these steps: `name;dur=<ms>` joined by commas. */
|
|
35
|
+
export function serverTimingHeader(steps) {
|
|
36
|
+
return steps.map(([name, ms]) => `${name};dur=${ms.toFixed(1)}`).join(', ');
|
|
37
|
+
}
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
//
|
|
19
19
|
// Off by default and effectively free when off: one env read, one comparison.
|
|
20
20
|
// Output goes to stderr only — never stdout, which is the CLI's data contract.
|
|
21
|
+
import { onServerTiming } from '../api/server-timing.js';
|
|
21
22
|
const FLAG = 'CRTR_TIMING';
|
|
22
23
|
const ORIGIN = 'CRTR_TIMING_T0';
|
|
23
24
|
/** Wall-clock epoch ms with sub-ms precision, comparable across processes. */
|
|
@@ -92,3 +93,16 @@ export function mark(phase, fields) {
|
|
|
92
93
|
// what lets its markers be merged into the cli/viewer timeline after the fact.
|
|
93
94
|
process.stderr.write(`[timing] +${fmt(since)}ms Δ${fmt(delta)}ms up=${fmt(up)}ms t=${abs.toFixed(1)} ${name}/${process.pid} ${phase}${tail}\n`);
|
|
94
95
|
}
|
|
96
|
+
// The server side that produces the `Server-Timing` header is in step-timings.ts (it needs node:async_hooks, which the API client must not import).
|
|
97
|
+
/** Print each step of a response's `Server-Timing` header as a phase marker (`server.<name>`). */
|
|
98
|
+
export function markServerTiming(header) {
|
|
99
|
+
if (!enabled)
|
|
100
|
+
return;
|
|
101
|
+
for (const part of header.split(',')) {
|
|
102
|
+
const [name, ...params] = part.trim().split(';');
|
|
103
|
+
const dur = params.find((p) => p.startsWith('dur='))?.slice(4);
|
|
104
|
+
if (name !== undefined && name !== '' && dur !== undefined)
|
|
105
|
+
mark(`server.${name}`, { dur_ms: dur });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
onServerTiming(markServerTiming);
|
|
@@ -64,8 +64,6 @@ export const OPERATIONS = [
|
|
|
64
64
|
{ name: 'custom-objects.receive', method: 'GET', path: '/v1/custom-objects/:ref/deliveries', classes: ['anonymous', 'person', 'app', 'broker', 'cron'], resource: 'objects', stream: true, stage: 'objects' },
|
|
65
65
|
{ name: 'custom-objects.ack', method: 'POST', path: '/v1/custom-objects/:ref/deliveries/ack', classes: ['anonymous', 'person', 'app', 'broker', 'cron'], resource: 'objects', stage: 'objects' },
|
|
66
66
|
{ name: 'objects.edges', method: 'GET', path: '/v1/objects/:ref/edges', classes: ['person', 'app', 'broker', 'cron'], resource: 'objects', stage: 'objects' },
|
|
67
|
-
{ name: 'repos.import', method: 'POST', path: '/v1/repos/:repo/import', classes: ['person'], resource: 'objects', stage: 'objects' },
|
|
68
|
-
{ name: 'repos.rename', method: 'POST', path: '/v1/repos/:repo/rename', classes: ['person'], resource: 'objects', stage: 'objects' },
|
|
69
67
|
{ name: 'docs.write', method: 'POST', path: '/v1/docs', classes: ['person', 'app', 'broker', 'cron'], resource: 'objects', stage: 'objects' },
|
|
70
68
|
{ name: 'docs.edit', method: 'PATCH', path: '/v1/docs/:ref', classes: ['person', 'app', 'broker', 'cron'], resource: 'objects', stage: 'objects' },
|
|
71
69
|
{ name: 'docs.move', method: 'POST', path: '/v1/docs/:ref/move', classes: ['person', 'app', 'broker', 'cron'], resource: 'objects', stage: 'objects' },
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.680",
|
|
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.680",
|
|
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.680",
|
|
31
|
+
"@north-light/identity": "0.3.680"
|
|
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.680",
|
|
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.680",
|
|
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.680",
|
|
32
|
+
"@north-light/plugin": "0.3.680",
|
|
33
33
|
"cron-parser": "^5.6.0",
|
|
34
34
|
"esbuild": "0.28.2",
|
|
35
35
|
"jose": "^6.2.12",
|
|
@@ -10667,17 +10667,17 @@
|
|
|
10667
10667
|
},
|
|
10668
10668
|
"packages/crouter-api": {
|
|
10669
10669
|
"name": "@north-light/api",
|
|
10670
|
-
"version": "0.3.
|
|
10670
|
+
"version": "0.3.680",
|
|
10671
10671
|
"license": "UNLICENSED"
|
|
10672
10672
|
},
|
|
10673
10673
|
"packages/crouter-env-docker": {
|
|
10674
10674
|
"name": "@north-light/env-docker",
|
|
10675
|
-
"version": "0.3.
|
|
10675
|
+
"version": "0.3.680",
|
|
10676
10676
|
"license": "UNLICENSED"
|
|
10677
10677
|
},
|
|
10678
10678
|
"packages/crouter-identity": {
|
|
10679
10679
|
"name": "@north-light/identity",
|
|
10680
|
-
"version": "0.3.
|
|
10680
|
+
"version": "0.3.680",
|
|
10681
10681
|
"license": "UNLICENSED",
|
|
10682
10682
|
"dependencies": {
|
|
10683
10683
|
"jose": "^6.2.1"
|
|
@@ -10685,21 +10685,21 @@
|
|
|
10685
10685
|
},
|
|
10686
10686
|
"packages/crouter-plugin": {
|
|
10687
10687
|
"name": "@north-light/plugin",
|
|
10688
|
-
"version": "0.3.
|
|
10688
|
+
"version": "0.3.680",
|
|
10689
10689
|
"license": "UNLICENSED",
|
|
10690
10690
|
"dependencies": {
|
|
10691
|
-
"@north-light/api": "0.3.
|
|
10692
|
-
"@north-light/identity": "0.3.
|
|
10691
|
+
"@north-light/api": "0.3.680",
|
|
10692
|
+
"@north-light/identity": "0.3.680"
|
|
10693
10693
|
}
|
|
10694
10694
|
},
|
|
10695
10695
|
"packages/crouter-sdk": {
|
|
10696
10696
|
"name": "@north-light/sdk",
|
|
10697
|
-
"version": "0.3.
|
|
10697
|
+
"version": "0.3.680",
|
|
10698
10698
|
"license": "UNLICENSED",
|
|
10699
10699
|
"dependencies": {
|
|
10700
|
-
"@north-light/api": "0.3.
|
|
10701
|
-
"@north-light/identity": "0.3.
|
|
10702
|
-
"@north-light/plugin": "0.3.
|
|
10700
|
+
"@north-light/api": "0.3.680",
|
|
10701
|
+
"@north-light/identity": "0.3.680",
|
|
10702
|
+
"@north-light/plugin": "0.3.680",
|
|
10703
10703
|
"jose": "^6.2.1"
|
|
10704
10704
|
},
|
|
10705
10705
|
"bin": {
|
|
@@ -41,10 +41,7 @@ if ! id "$RUN_USER" >/dev/null 2>&1; then
|
|
|
41
41
|
fi
|
|
42
42
|
mkdir -p /run/crtr /var/lib/crtr /work "$RELEASES"
|
|
43
43
|
chown "$RUN_USER" /run/crtr /var/lib/crtr /work
|
|
44
|
-
|
|
45
|
-
# (`/work/.crtr`, the home) is root-owned in the sandbox, and the start script, running as `crtr`, could not write `/work/.crtr/plugins-revision`.
|
|
46
|
-
# These are the small trees the image creates; they are handed over here on every boot.
|
|
47
|
-
for dir in /work/.crtr "/home/$RUN_USER"; do [ ! -e "$dir" ] || chown -R "$RUN_USER" "$dir"; done
|
|
44
|
+
[ ! -d "/home/$RUN_USER" ] || chown "$RUN_USER" "/home/$RUN_USER"
|
|
48
45
|
# pi's grep tool wants ripgrep; the release image has it, and installing it once per sandbox avoids a GitHub download at the first grep.
|
|
49
46
|
rg=present
|
|
50
47
|
if ! command -v rg >/dev/null 2>&1; then
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
export interface RepoImportRequest {
|
|
2
|
-
/** `docs/<id>.json` → file text, as read from the ref. */
|
|
3
|
-
tree: Record<string, string>;
|
|
4
|
-
/** Legacy markdown files: `name` is the path under the legacy dir without `.md`; `text` the whole file. */
|
|
5
|
-
legacy?: Array<{
|
|
6
|
-
name: string;
|
|
7
|
-
text: string;
|
|
8
|
-
}>;
|
|
9
|
-
}
|
|
10
|
-
export interface RepoImportDTO {
|
|
11
|
-
repo: string;
|
|
12
|
-
created: number;
|
|
13
|
-
revisions: number;
|
|
14
|
-
deleted: number;
|
|
15
|
-
needs_merge: string[];
|
|
16
|
-
refused: Array<{
|
|
17
|
-
path: string;
|
|
18
|
-
reason: string;
|
|
19
|
-
}>;
|
|
20
|
-
legacy_imported: string[];
|
|
21
|
-
legacy_skipped: Array<{
|
|
22
|
-
name: string;
|
|
23
|
-
reason: string;
|
|
24
|
-
}>;
|
|
25
|
-
}
|
|
File without changes
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const sysRepoDocsBranch: import("../../core/command.js").BranchDef;
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var u=Object.defineProperty;var n=(e,r)=>u(e,"name",{value:r,configurable:!0});import{execFileSync as g}from"node:child_process";import{readdirSync as y,readFileSync as w,statSync as $}from"node:fs";import{join as S,relative as k}from"node:path";import{defineBranch as v,defineLeaf as p}from"../../core/command.js";import{general as j,usage as b}from"../../core/errors.js";import{cliClient as m,rethrowAsCliError as l}from"../api-client.js";const f="refs/crtr/docs",d=n((e,r)=>g("git",r,{cwd:e,encoding:"utf8",maxBuffer:512*1024*1024,stdio:["ignore","pipe","pipe"]}),"git");function h(e,r=[]){for(const i of y(e)){const o=S(e,i);$(o).isDirectory()?h(o,r):i.endsWith(".md")&&r.push(o)}return r}n(h,"walk");const q=p({name:"import",tier:"hidden",description:"one-time: upload refs/crtr/docs (and legacy files) into a repo object",help:{name:"sys repo-docs import",summary:"fetch `refs/crtr/docs` from this checkout's origin and upload it into the repo object, keeping document ids and revision history",params:[{kind:"flag",name:"repo",type:"string",required:!0,constraint:"The repo object handle to import into (you need edit on it)."},{kind:"flag",name:"legacy-dir",type:"string",required:!1,constraint:"A directory of legacy markdown files (e.g. the old memory folder); files whose name is neither on the ref nor in the canvas are uploaded too."}],output:[{name:"summary",type:"string",required:!0,constraint:"Counts of what landed and what was refused."}],outputKind:"object",effects:["Runs `git fetch origin refs/crtr/docs` in the current directory, posts the tree to `POST /v1/repos/:repo/import`; re-running changes nothing already imported."]},run:n(async e=>{const r=typeof e.repo=="string"?e.repo:"";if(r==="")throw b("--repo <handle> is required");const i=process.cwd();try{d(i,["fetch","--quiet","origin",`+${f}:refs/crtr/import-tip`])}catch(t){throw j(`could not fetch ${f} from origin: ${t.message.slice(0,300)}`)}const o={};for(const t of d(i,["ls-tree","-r","--name-only","refs/crtr/import-tip"]).split(`
|
|
2
|
-
`).filter(c=>c.startsWith("docs/")&&c.endsWith(".json")))o[t]=d(i,["show",`refs/crtr/import-tip:${t}`]);const s=typeof e.legacyDir=="string"?e.legacyDir:void 0,a=s===void 0?void 0:h(s).map(t=>({name:k(s,t).replace(/\.md$/,"").replace(/\/INDEX$/,"/index"),text:w(t,"utf8")}));try{return{...await m().importRepoDocs(r,{tree:o,...a!==void 0?{legacy:a}:{}}),files:Object.keys(o).length}}catch(t){l(t)}},"run"),render:n(e=>`<repo-docs-import repo="${String(e.repo)}" files="${String(e.files)}" created="${String(e.created)}" revisions="${String(e.revisions)}" deleted="${String(e.deleted)}" refused="${e.refused.length}" legacy-imported="${e.legacy_imported.length}" legacy-skipped="${e.legacy_skipped.length}">${JSON.stringify({refused:e.refused,legacy_skipped:e.legacy_skipped})}</repo-docs-import>`,"render")}),D=p({name:"rename",tier:"hidden",description:"one-time: change a repo object's handle",help:{name:"sys repo-docs rename",summary:"give the repo object `<old>` the handle `<new>`; its id and documents are unchanged",params:[{kind:"positional",name:"old",required:!0,constraint:"The current repo handle."},{kind:"positional",name:"new",required:!0,constraint:"The new handle; refused when another live repo holds it."}],output:[{name:"id",type:"string",required:!0,constraint:"The repo object id."},{name:"name",type:"string",required:!0,constraint:"Its handle now."}],outputKind:"object",effects:["Renames the repo object. Links are edges to ids, so they keep resolving."]},run:n(async e=>{try{return{...await m().renameRepo(String(e.old),String(e.new))}}catch(r){l(r)}},"run"),render:n(e=>`<repo id="${String(e.id)}" name="${String(e.name)}" renamed="${String(e.renamed)}"/>`,"render")}),E=v({name:"repo-docs",tier:"hidden",description:"one-time repo-document cutover",whenToUse:"the production cutover of repo documents from the git ref into the canvas",help:{name:"sys repo-docs",summary:"import `refs/crtr/docs` into a repo object, or rename a repo handle (removed after the cutover)",model:"Hidden, temporary commands."},children:[q,D]});export{E as sysRepoDocsBranch};
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import type { ReposFn } from '../reader.js';
|
|
2
|
-
import type { ObjectRow } from '../types.js';
|
|
3
|
-
import { type CanvasDb } from '../../canvas/db.js';
|
|
4
|
-
export interface ImportResult {
|
|
5
|
-
created: number;
|
|
6
|
-
revisions: number;
|
|
7
|
-
deleted: number;
|
|
8
|
-
needsMerge: string[];
|
|
9
|
-
refused: Array<{
|
|
10
|
-
path: string;
|
|
11
|
-
reason: string;
|
|
12
|
-
}>;
|
|
13
|
-
}
|
|
14
|
-
/**
|
|
15
|
-
* Apply the difference between two trees (the one last imported and the new one) to the
|
|
16
|
-
* repo's documents, in one transaction. Per changed file: a file that does not parse, is not
|
|
17
|
-
* public, or names an id held by an object outside this repo is refused and reported; a new
|
|
18
|
-
* document is created with its id; arriving revisions are added (author NULL); changed record
|
|
19
|
-
* fields and a rename are applied; a tombstone or a removed file deletes. Each document
|
|
20
|
-
* publishes once: `created`, `edited` (with `heads` and `needs_merge`) or `deleted`. A
|
|
21
|
-
* document that fails is rolled back alone and reported in `refused`.
|
|
22
|
-
*/
|
|
23
|
-
export declare function importTree(db: CanvasDb, repo: ObjectRow, before: Map<string, string>, after: Map<string, string>, reposFn?: ReposFn): Promise<ImportResult>;
|
|
24
|
-
/** Whether any link target in a serialized ref file is one of `arrived`. */
|
|
25
|
-
export declare function namesArrived(text: string, arrived: ReadonlySet<string>): boolean;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var A=Object.defineProperty;var m=(t,n)=>A(t,"name",{value:n,configurable:!0});import{put as $}from"../bodies.js";import{setLinks as j,setUnresolved as M}from"../edges.js";import{collectUnlinked as U,deleteDocument as x,documentRecord as H,heads as D,importDocument as L,insertImportedRevisions as W,moveDocument as J,restoreDocument as P,setDocumentRecord as B}from"../documents.js";import{CrtrError as z}from"../../errors.js";import{publish as O}from"../events.js";import{getById as v,setObjectKind as G}from"../objects.js";import{parseDoc as k}from"./ref-format.js";import{withCanvasWrite as I}from"../../canvas/db.js";import{mapAsync as K}from"../../async-array.js";function V(t){if(t.type!=="repo")throw new Error(`${t.type} ${t.id} is not a repo object`)}m(V,"assertRepoRefSpace");function q(t){return[...t].sort((n,a)=>n.position-a.position).map(n=>({on:n.on,deliver:n.deliver,...n.match!==null&&n.match!==void 0?{match:n.match}:{},...n.match_frontmatter!==null&&n.match_frontmatter!==void 0?{matchFrontmatter:n.match_frontmatter}:{},...n.if!==null&&n.if!==void 0?{if:n.if}:{}}))}m(q,"toRuleSpecs");const Q=m((t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null),"same");function N(t,n){const a={},i=m(p=>!t||!Q(t[p],n[p]),"differs");return i("preview")&&(a.preview=n.preview),i("summary")&&(a.summary=n.summary),i("why_it_exists")&&(a.whyItExists=n.why_it_exists),i("unlisted")&&(a.unlisted=n.unlisted),i("lint_ignore")&&(a.lintIgnore=n.lint_ignore),i("extensions")&&(a.extensions=n.extensions),i("rules")&&(a.rules=q(n.rules)),a}m(N,"changedFields");async function me(t,n,a,i,p){V(n);const c={created:0,revisions:0,deleted:0,needsMerge:[],refused:[]},l=[];for(const[r,s]of i){if(a.get(r)===s)continue;const e=k(r,s);if(!e.ok){c.refused.push({path:r,reason:e.reason});continue}const f=a.has(r)?k(r,a.get(r)):null;l.push({path:r,prior:f?.ok?f.doc:null,doc:e.doc})}for(const[r,s]of a){if(i.has(r))continue;const e=k(r,s);e.ok&&l.push({path:r,prior:e.doc,doc:null,priorId:e.doc.id})}const _=[];return await I(async()=>{for(const s of l)for(const e of s.doc?.revisions??[])await $(t,e.body,e.body_hash);let r=l;for(;;){const s=[];for(const e of r){const f={created:0,revisions:0,deleted:0,needsMerge:[],refused:[]};try{const u=[];await I(async()=>await ee(t,n,e.prior,e.doc,e.priorId??e.doc.id,f,p,u),{savepoint:!0}),_.push(...u),c.created+=f.created,c.revisions+=f.revisions,c.deleted+=f.deleted,c.needsMerge.push(...f.needsMerge)}catch(u){b(u)?s.push({w:e,error:u}):c.refused.push({path:e.path,reason:u.message})}}if(s.length===0)break;if(s.length===r.length){for(const e of s)c.refused.push({path:e.w.path,reason:e.error.message});break}r=s.map(e=>e.w)}await X(t,i,new Set(_),new Set(l.map(s=>s.path)))},{savepoint:!0}),c}m(me,"importTree");async function X(t,n,a,i){if(a.size===0)return;const p=t.prepare("INSERT INTO edges (type, src, dst, written_as, created_at) VALUES ('links-to', ?, ?, ?, ?) ON CONFLICT DO NOTHING"),c=new Date().toISOString();for(const[l,_]of n){if(!i.has(l)&&!Z(_,a))continue;const r=k(l,_);if(!r.ok||r.doc.deleted_at)continue;const s=await v(t,r.doc.id);if(!s||s.type!=="document"||s.deleted_at)continue;const e=(await D(t,s))[0],f=r.doc.revisions.find(u=>u.rev_id===e?.rev_id)?.links??[];for(const u of f){const h=await v(t,u.dst);h&&h.id!==s.id&&await p.run(s.id,h.id,u.written_as,c)}}}m(X,"completeLinks");const Y=/"dst":\s*"((?:[^"\\]|\\.)*)"/g;function Z(t,n){for(const a of t.matchAll(Y))if(n.has(F(a[1])))return!0;return!1}m(Z,"namesArrived");function F(t){if(!t.includes("\\"))return t;try{return JSON.parse(`"${t}"`)}catch{return t}}m(F,"decodeJsonString");function b(t){return t instanceof z&&t.code==="conflict"&&t.details?.holder!==void 0}m(b,"isNameConflict");async function ee(t,n,a,i,p,c,l,_){const r=await v(t,p);if(r&&(r.type!=="document"||r.owner!==n.id))throw new Error(`id ${p} is held by ${r.type} ${r.name} outside ${n.name}`);if(!i){r&&!r.deleted_at&&(await x(t,null,r,l),c.deleted++);return}const s=t.prepare("SELECT count(*) AS n FROM revisions WHERE document = ?");let e,f=!1,u=!1,h=0,y=0;if(r){e=r,h=(await H(t,e)).revision,e.created_at!==i.created_at&&(await t.prepare("UPDATE objects SET created_at = ? WHERE id = ?").run(i.created_at,e.id),e=await v(t,e.id));const o=i.kind;(a?a.kind!==o:e.kind!==o)&&await G(t,e,o),u=!!e.deleted_at&&i.deleted_at===null&&(a===null||a.deleted_at!=null);let d=N(u?null:a,i);if(i.deleted_at&&e.deleted_at){const{rules:g,...E}=d;d=E}u&&(e=await P(t,e,i.name,l),_?.push(e.id)),Object.keys(d).length>0&&(e=await B(t,null,e,d)),i.name!==e.name&&!e.deleted_at&&(e=await J(t,null,e,{name:i.name},l))}else{const d=i.revisions.filter(g=>g.parents.length===0).sort((g,E)=>g.number-E.number||g.rev_id.localeCompare(E.rev_id))[0];if(!d)throw new Error(`${i.name}: no root revision`);e=await L(t,{id:i.id,owner:n,name:i.name,kind:i.kind,preview:i.preview,privacy:"public",...N(null,i),revisions:[{rev_id:d.rev_id,body_hash:d.body_hash,author:null,rationale:d.rationale,created_at:d.created_at}]},l),e.created_at!==i.created_at&&(await t.prepare("UPDATE objects SET created_at = ? WHERE id = ?").run(i.created_at,e.id),e=await v(t,e.id)),f=!0,_?.push(e.id),y=1}const C=(await s.get(e.id)).n,{headCount:S}=await W(t,e,i.revisions.map(o=>({rev_id:o.rev_id,parents:o.parents,body_hash:o.body_hash,rationale:o.rationale,created_at:o.created_at})));y+=(await s.get(e.id)).n-C,c.revisions+=y;const w=(await D(t,e))[0],R=new Map(i.revisions.map(o=>[o.rev_id,o]));if(y>0||u){const o=(await K(R.get(w.rev_id)?.links??[],async d=>({written_as:d.written_as,dst:await v(t,d.dst)}))).filter(d=>d.dst!==null);await U(t,await j(t,e,o),l),await M(t,e,[])}if(S>1&&c.needsMerge.push(e.id),i.deleted_at&&!e.deleted_at){await x(t,null,e,l,i.deleted_at),c.deleted++;return}if(i.deleted_at&&e.deleted_at&&e.deleted_at!==i.deleted_at&&await t.prepare("UPDATE objects SET deleted_at = ? WHERE id = ?").run(i.deleted_at,e.id),f){c.created++,await O(t,{event:"created",object:e,actor:null,attrs:{revision:w.number},pointer:w.rev_id},l);return}if(u){c.created++,await O(t,{event:"created",object:e,actor:null,attrs:{revision:w.number},pointer:w.rev_id},l);return}if(y===0)return;const T=i.revisions.filter(o=>!a?.revisions.some(d=>d.rev_id===o.rev_id)).sort((o,d)=>d.number-o.number||d.created_at.localeCompare(o.created_at))[0]??R.get(w.rev_id);await O(t,{event:"edited",object:e,actor:null,pointer:w.rev_id,attrs:{revision:w.number,from_revision:h,rationale:T?.rationale??null,author:T?.author??null,heads:S,needs_merge:S>1}},l)}m(ee,"importOne");export{me as importTree,Z as namesArrived};
|
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
import type { RuleOn } from '../types.js';
|
|
2
|
-
export interface RefRule {
|
|
3
|
-
position: number;
|
|
4
|
-
on: RuleOn;
|
|
5
|
-
match: unknown;
|
|
6
|
-
match_frontmatter: unknown;
|
|
7
|
-
if: unknown;
|
|
8
|
-
deliver: 'name' | 'preview' | 'content';
|
|
9
|
-
}
|
|
10
|
-
export interface RefRevision {
|
|
11
|
-
rev_id: string;
|
|
12
|
-
number: number;
|
|
13
|
-
parents: string[];
|
|
14
|
-
body: string;
|
|
15
|
-
body_hash: string;
|
|
16
|
-
/** Object id of the author on the runtime that wrote it; null when unknown. */
|
|
17
|
-
author: string | null;
|
|
18
|
-
rationale: string | null;
|
|
19
|
-
created_at: string;
|
|
20
|
-
links: Array<{
|
|
21
|
-
written_as: string;
|
|
22
|
-
dst: string;
|
|
23
|
-
}>;
|
|
24
|
-
}
|
|
25
|
-
export interface RefDocument {
|
|
26
|
-
id: string;
|
|
27
|
-
name: string;
|
|
28
|
-
kind: string;
|
|
29
|
-
privacy: 'public';
|
|
30
|
-
preview: string;
|
|
31
|
-
summary: string | null;
|
|
32
|
-
why_it_exists: string | null;
|
|
33
|
-
unlisted: boolean;
|
|
34
|
-
lint_ignore: unknown;
|
|
35
|
-
extensions: unknown;
|
|
36
|
-
created_at: string;
|
|
37
|
-
deleted_at: string | null;
|
|
38
|
-
rules: RefRule[];
|
|
39
|
-
revisions: RefRevision[];
|
|
40
|
-
}
|
|
41
|
-
export declare const docPath: (id: string) => string;
|
|
42
|
-
/** Parse one ref file. Refuses anything not public, a body whose hash disagrees, or an id that is not the file name.
|
|
43
|
-
* Each body is checked against the hash it arrived with, then held as `canonical` makes it (NUL → U+FFFD, hash of that text), so every consumer of a
|
|
44
|
-
* parsed file — prior export, import, merge — sees the one representation the database stores. */
|
|
45
|
-
export declare function parseDoc(path: string, text: string): {
|
|
46
|
-
ok: true;
|
|
47
|
-
doc: RefDocument;
|
|
48
|
-
} | {
|
|
49
|
-
ok: false;
|
|
50
|
-
reason: string;
|
|
51
|
-
};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var y=Object.defineProperty;var a=(o,t)=>y(o,"name",{value:t,configurable:!0});import{canonical as u,hashOf as p}from"../bodies.js";const h=a(o=>`docs/${o}.json`,"docPath"),m=new Set(["boot","workspace-open","file-read","document-read","command","pre-command","slash-command"]),b=new Set(["name","preview","content"]),s=a(o=>typeof o=="string","isStr"),i=a(o=>o===null||typeof o=="string","isStrOrNull");function _(o,t){let n;try{n=JSON.parse(t)}catch(e){return{ok:!1,reason:`not JSON: ${e.message}`}}if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,reason:"not an object"};const r=n;if(r.privacy!=="public")return{ok:!1,reason:`privacy is ${String(r.privacy)}; a repo holds only public documents`};if(!s(r.id)||h(r.id)!==o)return{ok:!1,reason:`id ${String(r.id)} does not match file ${o}`};for(const e of["name","kind","preview","created_at"])if(!s(r[e]))return{ok:!1,reason:`${e} is not a string`};for(const e of["summary","why_it_exists","deleted_at"])if(!i(r[e]))return{ok:!1,reason:`${e} is not a string or null`};if(typeof r.unlisted!="boolean")return{ok:!1,reason:"unlisted is not a boolean"};if(!Array.isArray(r.rules))return{ok:!1,reason:"rules is not an array"};for(const e of r.rules)if(!e||typeof e.position!="number"||!m.has(e.on)||!b.has(e.deliver))return{ok:!1,reason:"malformed rule"};if(!Array.isArray(r.revisions)||r.revisions.length===0)return{ok:!1,reason:"no revisions"};const d=new Set;for(const e of r.revisions){if(!e||!s(e.rev_id)||typeof e.number!="number"||!s(e.body)||!s(e.body_hash)||!s(e.created_at)||!i(e.author)||!i(e.rationale)||!Array.isArray(e.parents)||!e.parents.every(s)||!Array.isArray(e.links))return{ok:!1,reason:"malformed revision"};if(d.has(e.rev_id))return{ok:!1,reason:`revision ${e.rev_id} appears twice`};if(d.add(e.rev_id),p(e.body)!==e.body_hash)return{ok:!1,reason:`revision ${e.rev_id} body does not match body_hash`}}const l=r.revisions.map(e=>{const{text:f,hash:c}=u(e.body,e.body_hash);return f===e.body?e:{...e,body:f,body_hash:c}});return{ok:!0,doc:{...r,revisions:l}}}a(_,"parseDoc");export{h as docPath,_ as parseDoc};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var N=Object.defineProperty;var l=(e,o)=>N(e,"name",{value:o,configurable:!0});import{randomUUID as b}from"node:crypto";import{ApiError as s}from"../../../api/errors.js";import{withCanvasWrite as v}from"../../../core/canvas/db.js";import{parseFrontmatterGeneric as I}from"../../../core/frontmatter.js";import{importTree as L}from"../../../core/graph/repo-sync/exchange.js";import{parseDoc as D}from"../../../core/graph/repo-sync/ref-format.js";import{check as g}from"../../../core/permissions/evaluator.js";import{documentFields as O}from"../../../migrations/004-canvas-documents/fields.js";import{hashOf as R}from"../../../core/graph/bodies.js";import{renameRepoObject as k}from"../../../core/graph/objects.js";import{asApiError as $}from"./schemas.js";import{readerFor as E}from"../reader.js";const U=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;async function j(e){if(e.principal.class!=="person")throw new s(403,"forbidden","the import is run by the person");const o=e.body;if(!o||typeof o.tree!="object"||o.tree===null)throw new s(400,"invalid_request","`tree` must map file paths to text");const i=decodeURIComponent(e.params.repo);return await v(async r=>{const a=await r.prepare("SELECT * FROM objects WHERE type = 'repo' AND name = ? AND deleted_at IS NULL AND home_machine IS NULL").get(i);if(!a)throw new s(404,"not_found",`no repo named '${i}'`);const f=await E(r,e);if(!await g(r,f,"edit",a.id))throw new s(403,"forbidden",`you may not edit repo ${i}`);const u=new Map(Object.entries(o.tree)),h=new Set;for(const[t,m]of u){const n=D(t,m);n.ok&&h.add(n.doc.name)}for(const t of await r.prepare("SELECT name FROM objects WHERE type = 'document' AND owner = ?").all(a.id))h.add(t.name);const y=[],d=[];for(const t of o.legacy??[]){if(!U.test(t.name)){d.push({name:t.name,reason:"not a valid document name"});continue}if(h.has(t.name)){d.push({name:t.name,reason:"already on the ref or in the canvas"});continue}let m;try{m=I(t.text)}catch(p){d.push({name:t.name,reason:`unreadable frontmatter: ${p.message}`});continue}const n=O(m.data,m.body,{missingPrivacy:"public"});if(n.privacy!=="public"){d.push({name:t.name,reason:"private; a repo holds only public documents"});continue}const w=new Date().toISOString(),_=b(),A={id:_,name:t.name,kind:n.kind==="preference"?"preference":"knowledge",privacy:"public",preview:n.preview,summary:n.summary,why_it_exists:n.whyItExists,unlisted:n.unlisted,lint_ignore:n.lintIgnore,extensions:n.extensions,created_at:w,deleted_at:null,rules:n.rules.map((p,S)=>({position:S,on:p.on,match:p.match??null,match_frontmatter:p.matchFrontmatter??null,if:p.if??null,deliver:p.deliver})),revisions:[{rev_id:b(),number:1,parents:[],body:m.body,body_hash:R(m.body),author:null,rationale:"imported from legacy files",created_at:w,links:[]}]};u.set(`docs/${_}.json`,`${JSON.stringify(A)}
|
|
2
|
-
`),y.push(t.name)}const c=await L(r,a,new Map,u);return{repo:a.id,created:c.created,revisions:c.revisions,deleted:c.deleted,needs_merge:c.needsMerge,refused:c.refused,legacy_imported:y,legacy_skipped:d}})}l(j,"run");async function F(e){if(e.principal.class!=="person")throw new s(403,"forbidden","the rename is run by the person");const o=e.body?.to;if(typeof o!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(o))throw new s(400,"invalid_request","`to` must be a handle");const i=decodeURIComponent(e.params.repo);try{return await v(async r=>{const a=await r.prepare("SELECT * FROM objects WHERE type = 'repo' AND name = ? AND deleted_at IS NULL AND home_machine IS NULL").get(i);if(!a)throw new s(404,"not_found",`no repo named '${i}'`);if(!await g(r,await E(r,e),"share",a.id))throw new s(403,"forbidden",`only the owner of repo ${i} may rename it`);const f=await k(r,i,o);return{id:a.id,name:o,renamed:f}})}catch(r){throw $(r)}}l(F,"rename");const K=[{method:"POST",pattern:"/v1/repos/:repo/rename",handler:l(async e=>({status:200,body:await F(e)}),"handler")},{method:"POST",pattern:"/v1/repos/:repo/import",maxBodyBytes:256*1024*1024,handler:l(async e=>({status:200,body:await j(e)}),"handler")}];export{K as repoImportRoutes};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// `POST /v1/repos/:repo/import` — the one-time upload of a repo's `refs/crtr/docs` tree (and, optionally, legacy
|
|
2
|
-
// legacy markdown files) into its repo object. Removed after the production cutover.
|
|
3
|
-
//
|
|
4
|
-
// PURITY (spec §3.1): Node built-ins + `src/api/*` only.
|
|
5
|
-
export {};
|