@north-light/api 0.3.759 → 0.3.761

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.
Files changed (39) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/error-codes.d.ts +5 -0
  4. package/dist/api/error-codes.js +2 -0
  5. package/dist/clients/attach/config.js +2 -1
  6. package/dist/commands/api-client.d.ts +0 -5
  7. package/dist/commands/api-client.js +1 -12
  8. package/dist/commands/sys/import/move.d.ts +1 -34
  9. package/dist/commands/sys/import/move.js +5 -205
  10. package/dist/commands/sys/import/start.d.ts +0 -3
  11. package/dist/commands/sys/import/start.js +15 -51
  12. package/dist/commands/sys/signin.js +13 -54
  13. package/dist/core/command-plugins/caller-header.d.ts +3 -1
  14. package/dist/core/command-plugins/caller-header.js +2 -2
  15. package/dist/core/command.d.ts +1 -1
  16. package/dist/core/grants/owner.d.ts +2 -0
  17. package/dist/core/grants/owner.js +6 -0
  18. package/dist/core/graph/reader.d.ts +5 -0
  19. package/dist/core/graph/reader.js +15 -1
  20. package/dist/core/graph/types.d.ts +2 -0
  21. package/dist/core/permissions/evaluator.js +2 -0
  22. package/dist/core/providers/call.js +11 -5
  23. package/dist/core/providers/errors.js +1 -0
  24. package/dist/core/providers/mint.d.ts +19 -0
  25. package/dist/core/providers/mint.js +58 -29
  26. package/dist/core/worktree-mutation-async.js +11 -3
  27. package/dist/core/worktree-scripts.d.ts +13 -0
  28. package/dist/core/worktree-scripts.js +72 -0
  29. package/dist/core/worktree-sweep.js +10 -1
  30. package/dist/daemon/api/reader.d.ts +1 -1
  31. package/dist/daemon/api/reader.js +10 -2
  32. package/dist/daemon/machine-link/config.d.ts +0 -24
  33. package/dist/daemon/machine-link/config.js +1 -27
  34. package/dist/daemon/manage.d.ts +1 -1
  35. package/package.json +1 -1
  36. package/dist/commands/sys/import/retry.d.ts +0 -1
  37. package/dist/commands/sys/import/retry.js +0 -38
  38. package/dist/daemon/machine-link/move-notify.d.ts +0 -4
  39. package/dist/daemon/machine-link/move-notify.js +0 -15
@@ -13,12 +13,13 @@
13
13
  // call on a large repository is not short.
14
14
  import { createHash } from 'node:crypto';
15
15
  import { existsSync, realpathSync } from 'node:fs';
16
- import { isAbsolute, relative, resolve, sep } from 'node:path';
16
+ import { basename, isAbsolute, relative, resolve, sep } from 'node:path';
17
17
  import { completeCleanup, getNode, recordSweepAttempt, resumableNodeCwds } from './canvas/index.js';
18
18
  import { withExclusiveDirectoryLockAsync } from './exclusive-lock.js';
19
19
  import { gitAsync } from './git.js';
20
20
  import { proveBranchContained, upstreamTip } from './worktree-containment.js';
21
21
  import { refDeleteTransactionStdin } from './worktree-landing.js';
22
+ import { runWorktreeScript } from './worktree-scripts.js';
22
23
  import { deleteTrashAsync, removeWorktreeCheckoutAsync } from './worktree-remove.js';
23
24
  import { WORKTREE_LOCK_WAIT_MS, canonicalPath, checkoutPathForBranchInList, samePath, worktreeLockPathForCommonDir } from './worktree.js';
24
25
  /** Escalating recheck interval, in minutes, indexed by consecutive refusal. The
@@ -256,6 +257,14 @@ export async function sweepManagedWorktreeOnHost(wt, guard, dependentCwds) {
256
257
  // before each removal, where spawn admission into the checkout is excluded.
257
258
  if (existsSync(wt.path) && await checkoutHasDependents(dependentCwds, wt.path))
258
259
  return { outcome: CHECKOUT_IN_USE, observed: none };
260
+ // The repository's teardown comes before every Git disposal step, outside the repository lock (it may take minutes). A failure keeps the checkout so a person can rerun it.
261
+ if (existsSync(wt.path)) {
262
+ const teardown = await runWorktreeScript('worktree-teardown', basename(wt.path), wt);
263
+ if (teardown.status === 'failed')
264
+ return { outcome: { status: 'refused', reason: 'teardown_failed', detail: teardown.detail }, observed: none };
265
+ if (!await guard.stillEligible())
266
+ return { outcome: NODE_REVIVED, observed: none };
267
+ }
259
268
  const cwd = existsSync(wt.path) ? wt.path : wt.repo_root;
260
269
  if (!existsSync(cwd)) {
261
270
  return { outcome: { status: 'refused', reason: 'repo_unavailable', detail: `neither the recorded checkout nor repository root exists, so ${wt.branch} cannot be proved absent` }, observed: none };
@@ -3,7 +3,7 @@ import type { ObjectRow, Reader } from '../../core/graph/types.js';
3
3
  import type { RequestContext } from './router.js';
4
4
  import { type CanvasDb } from '../../core/canvas/db.js';
5
5
  /** The graph reader for a request's principal; repos come from the node's cwd. */
6
- export declare function readerFor(db: CanvasDb, ctx: Pick<RequestContext, 'principal'>): Promise<Reader>;
6
+ export declare function readerFor(db: CanvasDb, ctx: Pick<RequestContext, 'principal'> & Partial<Pick<RequestContext, 'query' | 'body'>>): Promise<Reader>;
7
7
  /** Run the git lookups a node caller's reader needs (its cwd and its profile's project paths, and the `cwd` a request names for `--owner repo`) before a canvas write opens, so
8
8
  * `readerFor` inside the write hits the identity cache instead of spawning git while the write holds a pooled connection. */
9
9
  export declare function warmReaderRepos(principal: RequestContext['principal'], requestCwd?: string): Promise<void>;
@@ -1,5 +1,6 @@
1
1
  import { ApiError } from '../../api/index.js';
2
- import { readerFor as graphReaderFor, warmNodeRepos } from '../../core/graph/reader.js';
2
+ import { parsePrincipal } from '@north-light/identity';
3
+ import { actingReaderFor, readerFor as graphReaderFor, warmNodeRepos } from '../../core/graph/reader.js';
3
4
  import { canRead } from '../../core/graph/access.js';
4
5
  import { ownersByHandle, resolveName, viewOf } from '../../core/graph/names.js';
5
6
  import { ensureOwner, ownerForGrantee, profileHandle } from '../../core/graph/objects.js';
@@ -10,7 +11,14 @@ import { filterAsync, mapAsync } from '../../core/async-array.js';
10
11
  import { personId } from '../../core/canvas/person.js';
11
12
  /** The graph reader for a request's principal; repos come from the node's cwd. */
12
13
  export async function readerFor(db, ctx) {
13
- return await graphReaderFor(db, ctx.principal, async (cwd, person) => await checkoutsForCwd(db, cwd, person));
14
+ const reposFn = async (cwd, person) => await checkoutsForCwd(db, cwd, person);
15
+ const body = ctx.body;
16
+ const as = ctx.query?.get('as') ?? (typeof body === 'object' && body !== null && typeof body.as === 'string' ? body.as : null);
17
+ if (as === null)
18
+ return await graphReaderFor(db, ctx.principal, reposFn);
19
+ if (parsePrincipal(as) === null)
20
+ throw new ApiError(400, 'invalid_request', 'as must be a principal like user:<id> or app:<id>/<path>');
21
+ return await actingReaderFor(db, ctx.principal, reposFn, as);
14
22
  }
15
23
  /** Run the git lookups a node caller's reader needs (its cwd and its profile's project paths, and the `cwd` a request names for `--owner repo`) before a canvas write opens, so
16
24
  * `readerFor` inside the write hits the identity cache instead of spawning git while the write holds a pooled connection. */
@@ -1,4 +1,3 @@
1
- import { CrtrError } from '../../core/errors.js';
2
1
  /** The Northlight account, as the directory names it (`account` of the sign-in poll). */
3
2
  export interface NorthlightAccount {
4
3
  id: string;
@@ -20,29 +19,6 @@ export declare function readMachineConfig(): MachineConfig | undefined;
20
19
  export declare function writeMachineConfig(config: MachineConfig): void;
21
20
  export declare function readMachineCredential(): string;
22
21
  export declare function writeMachineCredential(secret: string): void;
23
- /** A move to Northlight in progress. `running`: the cloud run has not reached `done`, so a failure undoes the move. `committed`: the account holds the
24
- * records and only the switch-over (machine credential, `machine.json`, restart) is left. `activated`: the machine-role daemon is up, so the switch-over is
25
- * complete and commands run; the record stays only until `notified` — the asking node's message is stored in the account — is true, then it is deleted. */
26
- export interface MoveRecord {
27
- runId: string;
28
- apiUrl: string;
29
- directoryUrl: string;
30
- account: NorthlightAccount;
31
- notify: string | null;
32
- state: 'running' | 'committed' | 'activated';
33
- notified: boolean;
34
- /** The exporter's process, so a later `crtr sys signin` can tell a running move from one whose exporter was killed. */
35
- pid: number;
36
- }
37
- export declare const moveRecordPath: () => string;
38
- /** The move record, or undefined when no move is running or unfinished. A present but malformed file throws. */
39
- export declare function readMoveRecord(): MoveRecord | undefined;
40
- export declare function writeMoveRecord(record: MoveRecord): void;
41
- export declare function deleteMoveRecord(): void;
42
- /** Whether a move's records are in the Northlight account but this computer has not switched over (the record says `committed`). */
43
- export declare const isMoveCommitted: () => boolean;
44
- /** The one `move_unfinished` error: every command, `crtr sys import resume` and a move whose switch-over failed answer it alike (exit code USAGE, as `not_signed_in`). */
45
- export declare const moveUnfinishedError: (reason?: string) => CrtrError;
46
22
  /** This computer's install id, kept under `runtime/` so it exists before any daemon: the machine registration names it, and a reinstall that keeps `runtime/` registers the same machine again. */
47
23
  export declare const installIdPath: () => string;
48
24
  export declare function readOrCreateInstallId(): string;
@@ -3,14 +3,11 @@
3
3
  // `runtime/secrets/machine-credential` (mode 0600). A Mac with no `machine.json` is a local control plane, not a machine.
4
4
  // Also the move record `runtime/import/move.json` (0600): where a move to Northlight that `crtr sys signin` started stands, from before the drain until the
5
5
  // computer has switched over (design-crtr-northlight-signin component 4).
6
- import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
6
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
7
7
  import { randomBytes } from 'node:crypto';
8
8
  import { dirname, join } from 'node:path';
9
9
  import { runtimeRoot, secretsDir } from '../../core/layout.js';
10
10
  import { joinedIssuer } from '../../core/directory/join.js';
11
- import { CrtrError } from '../../core/errors.js';
12
- import { atomicWriteJson } from '../../core/fs-utils.js';
13
- import { ExitCode } from '../../types.js';
14
11
  export const machineConfigPath = () => join(runtimeRoot(), 'machine.json');
15
12
  export const machineCredentialPath = () => join(secretsDir(), 'machine-credential');
16
13
  /** The machine config, or undefined when this install is not an imported machine. A present but malformed file throws. */
@@ -40,29 +37,6 @@ export function writeMachineCredential(secret) {
40
37
  writeFileSync(path, `${secret}\n`, { mode: 0o600 });
41
38
  chmodSync(path, 0o600);
42
39
  }
43
- export const moveRecordPath = () => join(runtimeRoot(), 'import', 'move.json');
44
- /** The move record, or undefined when no move is running or unfinished. A present but malformed file throws. */
45
- export function readMoveRecord() {
46
- const path = moveRecordPath();
47
- if (!existsSync(path))
48
- return undefined;
49
- const raw = JSON.parse(readFileSync(path, 'utf8'));
50
- if (typeof raw.runId !== 'string' || typeof raw.apiUrl !== 'string' || typeof raw.directoryUrl !== 'string' || (raw.state !== 'running' && raw.state !== 'committed' && raw.state !== 'activated')
51
- || typeof raw.account?.id !== 'string' || typeof raw.account.display !== 'string')
52
- throw new Error(`${path} is not a move record`);
53
- return { runId: raw.runId, apiUrl: raw.apiUrl, directoryUrl: raw.directoryUrl, account: { id: raw.account.id, display: raw.account.display },
54
- notify: typeof raw.notify === 'string' ? raw.notify : null, state: raw.state, notified: raw.notified === true, pid: typeof raw.pid === 'number' ? raw.pid : 0 };
55
- }
56
- export function writeMoveRecord(record) {
57
- atomicWriteJson(moveRecordPath(), record, { mode: 0o600 });
58
- }
59
- export function deleteMoveRecord() {
60
- rmSync(moveRecordPath(), { force: true });
61
- }
62
- /** Whether a move's records are in the Northlight account but this computer has not switched over (the record says `committed`). */
63
- export const isMoveCommitted = () => readMoveRecord()?.state === 'committed';
64
- /** The one `move_unfinished` error: every command, `crtr sys import resume` and a move whose switch-over failed answer it alike (exit code USAGE, as `not_signed_in`). */
65
- export const moveUnfinishedError = (reason) => new CrtrError('move_unfinished', `crtr's records are already in your Northlight account, but this computer has not switched over${reason === undefined ? '.' : `: ${reason}`}`, ExitCode.USAGE, { next: 'Run `crtr sys signin` to finish.' });
66
40
  /** This computer's install id, kept under `runtime/` so it exists before any daemon: the machine registration names it, and a reinstall that keeps `runtime/` registers the same machine again. */
67
41
  export const installIdPath = () => join(runtimeRoot(), 'install-id');
68
42
  export function readOrCreateInstallId() {
@@ -48,7 +48,7 @@ export interface DaemonExportSqliteResult {
48
48
  userVersion: number;
49
49
  }
50
50
  /** Run the selected generation's `crtrd-cli import-dump`: the row files of the running canvas into `out`/rows. */
51
- export declare function runDaemonImportDump(out: string, kind: 'machine' | 'hosted'): Promise<DumpResult>;
51
+ export declare function runDaemonImportDump(out: string, kind: 'hosted'): Promise<DumpResult>;
52
52
  /** Run `crtrd-cli import-dump <out> bodies`: every `bodies` row into `out`/rows/bodies (the pre-pause dump; the later `runDaemonImportDump` adds the rows written since). */
53
53
  export declare function runDaemonBodiesDump(out: string): Promise<{
54
54
  parts: string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.759",
3
+ "version": "0.3.761",
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 +0,0 @@
1
- export declare const retry: import("../../../core/command.js").LeafDef;
@@ -1,38 +0,0 @@
1
- // `crtr sys import retry <run_id>`: loads a failed import again from the bundle its failure kept.
2
- import { defineLeaf } from '../../../core/command.js';
3
- import { usage } from '../../../core/errors.js';
4
- import { ImportCloud } from '../../../core/import/export/cloud.js';
5
- import { controlPlaneUrl, personBearer } from '../../../core/directory/person-credential.js';
6
- import { awaitRunOutcome, defaultDirectoryUrl } from './move.js';
7
- export const retry = defineLeaf({
8
- name: 'retry',
9
- description: 'load a failed import again from the bundle it already uploaded',
10
- whenToUse: 'an import failed while Northlight was loading it (a refused or conflicting row) and the cause is fixed: no new upload and no new confirm code',
11
- help: {
12
- name: 'sys import retry',
13
- summary: 're-queue a failed run so Northlight loads its kept upload again, then wait for the outcome',
14
- guide: 'Works for a run that failed before its copy committed and whose upload is under 7 days old (Northlight deletes older ones; run the import again then). The bundle is what was uploaded, so rows this computer changed since are not in it. Prints the final state, or the new failure.',
15
- params: [
16
- { kind: 'positional', name: 'run_id', type: 'string', required: true, constraint: 'The failed import run (`imp_…`).' },
17
- { kind: 'flag', name: 'api-url', type: 'string', required: false, constraint: 'Control plane base URL; default is the one the sign-in is for.' },
18
- ],
19
- output: [
20
- { name: 'run_id', type: 'string', required: true, constraint: 'The import run.' },
21
- { name: 'state', type: 'string', required: true, constraint: 'Final state of the run, `done`.' },
22
- ],
23
- outputKind: 'object',
24
- effects: ['Moves the run from `failed` back to `loading` on the control plane; nothing local changes.'],
25
- },
26
- run: async (input) => {
27
- const runId = String(input['run_id'] ?? '');
28
- if (runId === '')
29
- throw usage('name the failed run: crtr sys import retry <run_id>');
30
- const directoryUrl = defaultDirectoryUrl();
31
- const apiUrl = input.apiUrl === undefined ? await controlPlaneUrl(directoryUrl) : String(input.apiUrl);
32
- const cloud = new ImportCloud(apiUrl, () => personBearer(directoryUrl));
33
- await cloud.retry(runId);
34
- await awaitRunOutcome(cloud, runId, undefined);
35
- return { run_id: runId, state: 'done' };
36
- },
37
- render: (r) => `<import run="${r['run_id']}" state="${r['state']}"/>`,
38
- });
@@ -1,4 +0,0 @@
1
- import { type MoveRecord } from './config.js';
2
- /** Tell the node that asked for the move that it finished, through the control plane with the person's bearer (`POST /v1/nodes/:id/messages`): the node
3
- * now lives in the account, so the message is stored there as mail and wakes it once the machine link is up. Then the record says `notified`. */
4
- export declare function notifyMoveFinished(move: MoveRecord): Promise<MoveRecord>;
@@ -1,15 +0,0 @@
1
- // src/daemon/machine-link/move-notify.ts — telling the node that asked for a move to Northlight that it finished (design-crtr-northlight-signin component 4).
2
- import { CrtrClient } from '../../api/index.js';
3
- import { northlightFetch } from '../../core/directory/person-credential.js';
4
- import { writeMoveRecord } from './config.js';
5
- /** Tell the node that asked for the move that it finished, through the control plane with the person's bearer (`POST /v1/nodes/:id/messages`): the node
6
- * now lives in the account, so the message is stored there as mail and wakes it once the machine link is up. Then the record says `notified`. */
7
- export async function notifyMoveFinished(move) {
8
- if (move.notified || move.notify === null)
9
- return move;
10
- await new CrtrClient({ baseUrl: move.apiUrl, fetch: northlightFetch(move.directoryUrl, move.apiUrl) }).sendMessage(move.notify, { from: null,
11
- body: `The move to Northlight finished; crtr on this computer now runs with the account ${move.account.display}. Retry the command that needed the account and carry on.` });
12
- const notified = { ...move, notified: true };
13
- writeMoveRecord(notified);
14
- return notified;
15
- }