@north-light/cli 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.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/error-codes.d.ts +5 -0
- package/dist/api/error-codes.js +1 -1
- package/dist/builtin-memory/crouter-sdk/release-notes.md +4 -0
- package/dist/builtin-memory/internal/nodes-and-canvas.md +1 -1
- package/dist/builtin-memory/internal/storage-tiers.md +1 -1
- package/dist/cli.js +5 -5
- package/dist/clients/attach/config.js +1 -1
- package/dist/clients/attach/viewer.js +467 -467
- package/dist/commands/api-client.d.ts +0 -5
- package/dist/commands/api-client.js +3 -3
- package/dist/commands/daemon-generation.js +1 -1
- package/dist/commands/sys/import/move.d.ts +1 -34
- package/dist/commands/sys/import/move.js +5 -9
- package/dist/commands/sys/import/start.d.ts +0 -3
- package/dist/commands/sys/import/start.js +1 -1
- package/dist/commands/sys/signin.js +2 -2
- package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -0
- package/dist/core/canvas/managed-worktree-sweep-candidates.js +6 -4
- package/dist/core/command-plugins/caller-header.d.ts +3 -1
- package/dist/core/command-plugins/caller-header.js +1 -1
- package/dist/core/command.d.ts +1 -1
- package/dist/core/grants/owner.d.ts +2 -0
- package/dist/core/grants/owner.js +1 -1
- package/dist/core/graph/reader.d.ts +5 -0
- package/dist/core/graph/reader.js +3 -3
- package/dist/core/graph/types.d.ts +2 -0
- package/dist/core/permissions/evaluator.js +2 -2
- package/dist/core/providers/call.js +1 -1
- package/dist/core/providers/errors.js +1 -1
- package/dist/core/providers/mint.d.ts +19 -0
- package/dist/core/providers/mint.js +1 -1
- package/dist/core/runtime/front-door.js +9 -10
- package/dist/core/user-settings.d.ts +2 -2
- package/dist/core/worktree-mutation-async.js +5 -5
- package/dist/core/worktree-scripts.d.ts +13 -0
- package/dist/core/worktree-scripts.js +5 -0
- package/dist/core/worktree-sweep.js +4 -4
- package/dist/daemon/api/handlers/daemon.js +1 -1
- package/dist/daemon/api/handlers/memory.js +5 -5
- package/dist/daemon/api/handlers/plugin-app-token.js +1 -1
- package/dist/daemon/api/reader.d.ts +1 -1
- package/dist/daemon/api/reader.js +1 -1
- package/dist/daemon/crtrd.js +11 -11
- package/dist/daemon/import-dump-run.js +4 -4
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/config.d.ts +0 -24
- package/dist/daemon/machine-link/config.js +4 -4
- package/dist/daemon/manage.d.ts +1 -1
- package/docs/sdk/release-notes.md +4 -0
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/error-codes.js +2 -0
- package/packages/crouter-api/dist/clients/attach/config.js +2 -1
- package/packages/crouter-api/dist/commands/api-client.js +1 -12
- package/packages/crouter-api/dist/commands/sys/import/move.js +5 -205
- package/packages/crouter-api/dist/commands/sys/import/start.js +15 -51
- package/packages/crouter-api/dist/commands/sys/signin.js +13 -54
- package/packages/crouter-api/dist/core/command-plugins/caller-header.js +2 -2
- package/packages/crouter-api/dist/core/grants/owner.js +6 -0
- package/packages/crouter-api/dist/core/graph/reader.js +15 -1
- package/packages/crouter-api/dist/core/permissions/evaluator.js +2 -0
- package/packages/crouter-api/dist/core/providers/call.js +11 -5
- package/packages/crouter-api/dist/core/providers/errors.js +1 -0
- package/packages/crouter-api/dist/core/providers/mint.js +58 -29
- package/packages/crouter-api/dist/core/worktree-mutation-async.js +11 -3
- package/packages/crouter-api/dist/core/worktree-scripts.js +72 -0
- package/packages/crouter-api/dist/core/worktree-sweep.js +10 -1
- package/packages/crouter-api/dist/daemon/api/reader.js +10 -2
- package/packages/crouter-api/dist/daemon/machine-link/config.js +1 -27
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/commands/sys/import/retry.d.ts +0 -1
- package/dist/commands/sys/import/retry.js +0 -1
- package/dist/daemon/machine-link/move-notify.d.ts +0 -4
- package/dist/daemon/machine-link/move-notify.js +0 -1
- package/packages/crouter-api/dist/commands/sys/import/retry.js +0 -38
- package/packages/crouter-api/dist/daemon/machine-link/move-notify.js +0 -15
|
@@ -19,6 +19,7 @@ import { createHash } from 'node:crypto';
|
|
|
19
19
|
import { directoryIssuer } from '../directory/issuer.js';
|
|
20
20
|
import { emitEvent } from '../events/emit.js';
|
|
21
21
|
import { OutboundError } from '../events/outbound.js';
|
|
22
|
+
import { sameNamespace } from '../grants/owner.js';
|
|
22
23
|
import { grantSyncStateFor } from '../grants/mirror.js';
|
|
23
24
|
import { assertion, machineRevokedMessage, requestGrantSync, runtimeClient } from '../grants/sync.js';
|
|
24
25
|
import { isUnsandboxedMachine } from '../runtime/unsandboxed.js';
|
|
@@ -105,24 +106,13 @@ async function syncIfNewer(request, refused, options) {
|
|
|
105
106
|
// The sync logs its own failure; the caller already has its answer.
|
|
106
107
|
void Promise.resolve().then(() => sync({ fresh: true })).catch(() => { });
|
|
107
108
|
}
|
|
108
|
-
/**
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
const endpoint = `${issuer}/token`;
|
|
109
|
+
/** POST a form to the directory's token endpoint (each attempt signs its own assertion: the directory accepts a `jti` once). A 502, 503 or 504 is the directory
|
|
110
|
+
* briefly down, not a refusal: ask again before failing. Unreachable or too slow is a retryable `server_error`. */
|
|
111
|
+
async function postToken(endpoint, form, options) {
|
|
112
112
|
const client = runtimeClient();
|
|
113
113
|
const attempt = async () => {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
grant_type: 'client_credentials',
|
|
117
|
-
client_id: client.client_id,
|
|
118
|
-
client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
|
|
119
|
-
client_assertion: assertion(client, endpoint),
|
|
120
|
-
audience: request.audience,
|
|
121
|
-
sub: request.sub,
|
|
122
|
-
grantee: request.grantee,
|
|
123
|
-
scope: [...new Set(request.scope)].sort().join(' '),
|
|
124
|
-
initiating_app: request.initiating_app,
|
|
125
|
-
});
|
|
114
|
+
const body = new URLSearchParams({ client_id: client.client_id, client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
|
|
115
|
+
client_assertion: assertion(client, endpoint), ...form(client) });
|
|
126
116
|
const timeout = AbortSignal.timeout(MINT_TIMEOUT_MS);
|
|
127
117
|
const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
|
|
128
118
|
const response = await (options.fetch ?? fetch)(endpoint, { method: 'POST', body, signal, headers: { Accept: 'application/json' } });
|
|
@@ -131,7 +121,6 @@ export async function mintOutboundToken(request, options = {}) {
|
|
|
131
121
|
let response;
|
|
132
122
|
let text;
|
|
133
123
|
try {
|
|
134
|
-
// A 502, 503 or 504 is the directory briefly down, not a refusal of this request: ask again before failing the call.
|
|
135
124
|
for (let tries = 0;; tries++) {
|
|
136
125
|
({ response, text } = await attempt());
|
|
137
126
|
const delay = MINT_RETRY_DELAYS_MS[tries];
|
|
@@ -153,16 +142,10 @@ export async function mintOutboundToken(request, options = {}) {
|
|
|
153
142
|
catch {
|
|
154
143
|
parsed = null;
|
|
155
144
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
emitEvent({ level: 'error', event: 'daemon.grants.machine_revoked', fields: { audience: request.audience } });
|
|
161
|
-
emitEvent({ level: 'info', event: 'daemon.providers.mint_refused', fields: { audience: request.audience, grantee: request.grantee, code: error.code, directory_error: typeof json['error'] === 'string' ? json['error'] : null, status: response.status } });
|
|
162
|
-
if (grantRefusal)
|
|
163
|
-
await syncIfNewer(request, refusedGrantState(json), options);
|
|
164
|
-
throw error;
|
|
165
|
-
}
|
|
145
|
+
return { response, json: parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {} };
|
|
146
|
+
}
|
|
147
|
+
/** The cacheable token a successful token response carries. The directory names who is charged; a token without the claim (an older directory) is charged to `payerFallback`. */
|
|
148
|
+
function tokenOf(json, payerFallback, options) {
|
|
166
149
|
const accessToken = json['access_token'];
|
|
167
150
|
if (typeof accessToken !== 'string' || !accessToken) {
|
|
168
151
|
throw new ProviderError('server_error', 'the directory token response has no access_token', { origin: 'directory' });
|
|
@@ -178,10 +161,28 @@ export async function mintOutboundToken(request, options = {}) {
|
|
|
178
161
|
if (exp === null)
|
|
179
162
|
throw new ProviderError('server_error', 'the directory token response names no expiry', { origin: 'directory' });
|
|
180
163
|
const jti = typeof payload.jti === 'string' && payload.jti ? payload.jti : createHash('sha256').update(accessToken).digest('hex');
|
|
181
|
-
|
|
182
|
-
const payer = typeof payload.payer === 'string' && payload.payer ? payload.payer : request.sub;
|
|
164
|
+
const payer = typeof payload.payer === 'string' && payload.payer ? payload.payer : payerFallback;
|
|
183
165
|
return { access_token: accessToken, jti, exp, payer };
|
|
184
166
|
}
|
|
167
|
+
/** Mint one outbound token (no cache). Throws a mapped `ProviderError`. */
|
|
168
|
+
export async function mintOutboundToken(request, options = {}) {
|
|
169
|
+
const issuer = issuerOf(options);
|
|
170
|
+
const endpoint = `${issuer}/token`;
|
|
171
|
+
const { response, json } = await postToken(endpoint, () => ({
|
|
172
|
+
grant_type: 'client_credentials', audience: request.audience, sub: request.sub, grantee: request.grantee,
|
|
173
|
+
scope: [...new Set(request.scope)].sort().join(' '), initiating_app: request.initiating_app,
|
|
174
|
+
}), options);
|
|
175
|
+
if (!response.ok) {
|
|
176
|
+
const { error, grantRefusal } = refusal(response.status, json, request, issuer);
|
|
177
|
+
if (error.code === 'machine_revoked')
|
|
178
|
+
emitEvent({ level: 'error', event: 'daemon.grants.machine_revoked', fields: { audience: request.audience } });
|
|
179
|
+
emitEvent({ level: 'info', event: 'daemon.providers.mint_refused', fields: { audience: request.audience, grantee: request.grantee, code: error.code, directory_error: typeof json['error'] === 'string' ? json['error'] : null, status: response.status } });
|
|
180
|
+
if (grantRefusal)
|
|
181
|
+
await syncIfNewer(request, refusedGrantState(json), options);
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
return tokenOf(json, request.sub, options);
|
|
185
|
+
}
|
|
185
186
|
// Concurrent calls for one key share one mint.
|
|
186
187
|
const inflight = new Map();
|
|
187
188
|
/** The outbound token for `request`: the cached one while `now < exp − 30 s`
|
|
@@ -217,3 +218,31 @@ function abortable(work, signal) {
|
|
|
217
218
|
work.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));
|
|
218
219
|
});
|
|
219
220
|
}
|
|
221
|
+
/** Exchange a node's call token for one whose `sub` is `request.as` and whose `act` is the node (the directory's token exchange). A refusal is 403
|
|
222
|
+
* `not_granted` or `scope_missing`; any other failure is a `server_error`. Nothing is cached: the token is for this call. */
|
|
223
|
+
export async function exchangeForOwner(request, options = {}) {
|
|
224
|
+
const { response, json } = await postToken(`${issuerOf(options)}/token`, () => ({
|
|
225
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange', subject_token: request.subjectToken,
|
|
226
|
+
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token', requested_subject: request.as, audience: request.audience,
|
|
227
|
+
scope: [...new Set(request.scope)].sort().join(' '),
|
|
228
|
+
}), options);
|
|
229
|
+
if (!response.ok) {
|
|
230
|
+
const reason = typeof json['error_description'] === 'string' ? json['error_description'] : undefined;
|
|
231
|
+
const details = { directory_status: response.status, ...(typeof json['error'] === 'string' ? { directory_error: json['error'] } : {}), ...(reason ? { directory_description: reason } : {}) };
|
|
232
|
+
if (json['error'] === 'invalid_grant' && reason === 'not_granted')
|
|
233
|
+
throw new ProviderError('not_granted', `${request.as} has not granted this caller access`, { origin: 'directory', details });
|
|
234
|
+
if (json['error'] === 'invalid_grant' && reason === 'scope_missing')
|
|
235
|
+
throw new ProviderError('scope_missing', `the grant from ${request.as} does not cover ${request.scope.join(' ')}`, { origin: 'directory', details, ...(request.scope.length === 1 ? { scope: request.scope[0] } : {}) });
|
|
236
|
+
throw new ProviderError('server_error', `the directory refused the token exchange (${response.status}${reason ? ` ${reason}` : ''})`, { origin: 'directory', details });
|
|
237
|
+
}
|
|
238
|
+
return tokenOf(json, request.as, options);
|
|
239
|
+
}
|
|
240
|
+
/** The token a node presents to act for `as`: its own call token (minted as its `sub` and `grantee`), exchanged at the directory. In the node's own namespace
|
|
241
|
+
* the node mints directly as `as` (an owner link) and no exchange runs. */
|
|
242
|
+
export async function actingToken(node, as, call, options = {}) {
|
|
243
|
+
if (sameNamespace(as, node.grantee))
|
|
244
|
+
return await outboundToken({ ...call, sub: as, grantee: node.grantee, initiating_app: node.grantee }, options);
|
|
245
|
+
const subject = await outboundToken({ ...call, sub: node.sub, grantee: node.grantee, initiating_app: node.grantee }, options);
|
|
246
|
+
const token = await exchangeForOwner({ subjectToken: subject.access_token, as, audience: call.audience, scope: call.scope }, options);
|
|
247
|
+
return { ...token, key: `exchange:${token.jti}` };
|
|
248
|
+
}
|
|
@@ -8,6 +8,7 @@ import { withExclusiveDirectoryLockAsync } from './exclusive-lock.js';
|
|
|
8
8
|
import { gitAsync } from './git.js';
|
|
9
9
|
import { WORKTREE_LOCK_WAIT_MS, canonicalPath, checkoutPathForBranchInList, isManagedWorktreeBase, managedWorktreesRoot, managedWorktreePath, persistClosedWorktreeState, worktreeLockPathForCommonDir, WorktreeError, branchIsPushedAtCurrentTip } from './worktree.js';
|
|
10
10
|
import { proveBranchContained } from './worktree-containment.js';
|
|
11
|
+
import { runWorktreeScript } from './worktree-scripts.js';
|
|
11
12
|
import { refDeleteTransactionStdin } from './worktree-landing.js';
|
|
12
13
|
import { deleteTrashAsync, removeWorktreeCheckoutAsync } from './worktree-remove.js';
|
|
13
14
|
// A function, not a constant: `runtime/nodes.ts` imports this module and sits in an import cycle with `worktree.ts`, so a module-level read of its exports would run before they exist.
|
|
@@ -116,7 +117,7 @@ export async function createManagedWorktreeAsync(cwd, nodeId, baseRef = 'main')
|
|
|
116
117
|
throw new WorktreeError('managed_worktree_base', `cwd ${repoRoot} is a managed worktree and cannot be used as a managed worktree base`, 'Pass `--cwd` pointing at the repository’s primary checkout and keep `--worktree` set to the desired existing local base branch, including the parent branch.');
|
|
117
118
|
}
|
|
118
119
|
const commonDir = await commonGitDir(repoRoot);
|
|
119
|
-
|
|
120
|
+
const wt = await withExclusiveDirectoryLockAsync(worktreeLockPathForCommonDir(commonDir), async () => {
|
|
120
121
|
const baseSha = await resolveLandableBase(repoRoot, baseRef);
|
|
121
122
|
const path = managedWorktreePath(nodeId);
|
|
122
123
|
const branch = `crtr/${nodeId}`;
|
|
@@ -124,7 +125,7 @@ export async function createManagedWorktreeAsync(cwd, nodeId, baseRef = 'main')
|
|
|
124
125
|
throw new WorktreeError('worktree_path_exists', `managed worktree path already exists: ${path}`, 'Remove the stale path or choose a fresh node id.');
|
|
125
126
|
if ((await gitAsync(['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], repoRoot)).status === 0)
|
|
126
127
|
throw new WorktreeError('worktree_branch_exists', `managed worktree branch already exists: ${branch}`, 'Remove the stale branch or choose a fresh node id.');
|
|
127
|
-
const
|
|
128
|
+
const created = { state: 'open', path, branch, repo_root: repoRoot, base_ref: baseRef, base_sha: baseSha, created: new Date().toISOString() };
|
|
128
129
|
await runGit(repoRoot, ['branch', branch, baseSha], 'worktree_branch_create_failed', 'Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.');
|
|
129
130
|
const added = await gitAsync(['worktree', 'add', path, branch], repoRoot);
|
|
130
131
|
if (added.status !== 0) {
|
|
@@ -132,8 +133,15 @@ export async function createManagedWorktreeAsync(cwd, nodeId, baseRef = 'main')
|
|
|
132
133
|
throw new WorktreeError('worktree_add_failed', 'git worktree add failed', 'Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.', detailOf(added));
|
|
133
134
|
}
|
|
134
135
|
seedExclude(repoRoot, commonDir);
|
|
135
|
-
return
|
|
136
|
+
return created;
|
|
136
137
|
}, { timeoutMs: lockWaitMs(), timeoutError: () => new WorktreeError('worktree_lock_timeout', `timed out waiting to create a managed worktree in ${commonDir}`, 'Wait for the other managed-worktree operation to finish, then retry.') });
|
|
138
|
+
// Outside the repository lock: a script may take minutes. A failed setup fails creation and the half-prepared checkout is removed the normal way.
|
|
139
|
+
const setup = await runWorktreeScript('worktree-setup', basename(wt.path), wt);
|
|
140
|
+
if (setup.status === 'failed') {
|
|
141
|
+
await rollbackManagedWorktreeAsync(wt);
|
|
142
|
+
throw new WorktreeError('worktree_setup_failed', '.dev/worktree-setup failed', 'Fix the repository\'s .dev/worktree-setup on its base branch, then retry spawning with --worktree.', setup.detail);
|
|
143
|
+
}
|
|
144
|
+
return wt;
|
|
137
145
|
}
|
|
138
146
|
async function cleanTip(wt) {
|
|
139
147
|
if (wt.state !== 'open' || !existsSync(wt.path))
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// A repository's optional `.dev/worktree-setup` and `.dev/worktree-teardown` executables.
|
|
2
|
+
//
|
|
3
|
+
// crtr decides WHEN they run (after a managed worktree is created, and as the first step of its sweep); the
|
|
4
|
+
// repository decides WHAT they do. Each script is read from the worktree's base branch in the primary checkout,
|
|
5
|
+
// never from the worktree itself, so a node's own commits cannot change what crtr executes. A missing file is no step.
|
|
6
|
+
// Async only: the sweep runs on the daemon's event loop.
|
|
7
|
+
import { spawn } from 'node:child_process';
|
|
8
|
+
import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
9
|
+
import { tmpdir } from 'node:os';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { gitAsync } from './git.js';
|
|
12
|
+
/** Fixed, not configurable. */
|
|
13
|
+
export const WORKTREE_SCRIPT_TIMEOUT_MS = 5 * 60_000;
|
|
14
|
+
const STDERR_TAIL_LINES = 20;
|
|
15
|
+
function tail(text) {
|
|
16
|
+
return text.trim().split('\n').slice(-STDERR_TAIL_LINES).join('\n');
|
|
17
|
+
}
|
|
18
|
+
export async function runWorktreeScript(script, nodeId, wt, timeoutMs = WORKTREE_SCRIPT_TIMEOUT_MS) {
|
|
19
|
+
const ref = `refs/heads/${wt.base_ref}`;
|
|
20
|
+
const spec = `${ref}:.dev/${script}`;
|
|
21
|
+
const exists = await gitAsync(['cat-file', '-e', spec], wt.repo_root);
|
|
22
|
+
if (exists.status !== 0)
|
|
23
|
+
return { status: 'absent' };
|
|
24
|
+
const body = await gitAsync(['show', spec], wt.repo_root);
|
|
25
|
+
if (body.status !== 0)
|
|
26
|
+
return { status: 'failed', detail: `could not read .dev/${script} from ${ref}: ${body.stderr.trim()}` };
|
|
27
|
+
const dir = await mkdtemp(join(tmpdir(), 'crtr-worktree-script-'));
|
|
28
|
+
try {
|
|
29
|
+
const file = join(dir, script);
|
|
30
|
+
await writeFile(file, body.stdout);
|
|
31
|
+
await chmod(file, 0o755);
|
|
32
|
+
return await new Promise((resolve) => {
|
|
33
|
+
const child = spawn(file, [], {
|
|
34
|
+
cwd: wt.path,
|
|
35
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
36
|
+
env: {
|
|
37
|
+
...process.env,
|
|
38
|
+
CRTR_NODE_ID: nodeId,
|
|
39
|
+
CRTR_WORKTREE_PATH: wt.path,
|
|
40
|
+
CRTR_REPO_ROOT: wt.repo_root,
|
|
41
|
+
CRTR_BASE_REF: wt.base_ref,
|
|
42
|
+
COMPOSE_PROJECT_NAME: `crtr-${nodeId}`,
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
let stderr = '';
|
|
46
|
+
let timedOut = false;
|
|
47
|
+
let settled = false;
|
|
48
|
+
const finish = (result) => {
|
|
49
|
+
if (settled)
|
|
50
|
+
return;
|
|
51
|
+
settled = true;
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
resolve(result);
|
|
54
|
+
};
|
|
55
|
+
const timer = setTimeout(() => {
|
|
56
|
+
timedOut = true;
|
|
57
|
+
child.kill('SIGKILL');
|
|
58
|
+
finish({ status: 'failed', detail: `.dev/${script} timed out after ${Math.round(timeoutMs / 1000)}s\n${tail(stderr)}`.trim() });
|
|
59
|
+
}, timeoutMs);
|
|
60
|
+
child.stderr.on('data', (chunk) => { stderr = (stderr + chunk.toString('utf8')).slice(-16_384); });
|
|
61
|
+
child.on('error', (err) => finish({ status: 'failed', detail: `could not run .dev/${script}: ${err.message}` }));
|
|
62
|
+
child.on('close', (code, signal) => {
|
|
63
|
+
if (timedOut)
|
|
64
|
+
return;
|
|
65
|
+
finish(code === 0 ? { status: 'ok' } : { status: 'failed', detail: `.dev/${script} exited ${code ?? `by ${signal}`}\n${tail(stderr)}`.trim() });
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
await rm(dir, { recursive: true, force: true });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -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 };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ApiError } from '../../api/index.js';
|
|
2
|
-
import {
|
|
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
|
-
|
|
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. */
|
|
@@ -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,
|
|
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() {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
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,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.761",
|
|
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.761",
|
|
31
|
+
"@north-light/identity": "0.3.761"
|
|
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.761",
|
|
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.761",
|
|
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.761",
|
|
32
|
+
"@north-light/plugin": "0.3.761",
|
|
33
33
|
"cron-parser": "^5.6.0",
|
|
34
34
|
"esbuild": "0.28.2",
|
|
35
35
|
"jose": "^6.2.12",
|
|
@@ -11902,17 +11902,17 @@
|
|
|
11902
11902
|
},
|
|
11903
11903
|
"packages/crouter-api": {
|
|
11904
11904
|
"name": "@north-light/api",
|
|
11905
|
-
"version": "0.3.
|
|
11905
|
+
"version": "0.3.761",
|
|
11906
11906
|
"license": "UNLICENSED"
|
|
11907
11907
|
},
|
|
11908
11908
|
"packages/crouter-env-docker": {
|
|
11909
11909
|
"name": "@north-light/env-docker",
|
|
11910
|
-
"version": "0.3.
|
|
11910
|
+
"version": "0.3.761",
|
|
11911
11911
|
"license": "UNLICENSED"
|
|
11912
11912
|
},
|
|
11913
11913
|
"packages/crouter-identity": {
|
|
11914
11914
|
"name": "@north-light/identity",
|
|
11915
|
-
"version": "0.3.
|
|
11915
|
+
"version": "0.3.761",
|
|
11916
11916
|
"license": "UNLICENSED",
|
|
11917
11917
|
"dependencies": {
|
|
11918
11918
|
"jose": "^6.2.1"
|
|
@@ -11920,21 +11920,21 @@
|
|
|
11920
11920
|
},
|
|
11921
11921
|
"packages/crouter-plugin": {
|
|
11922
11922
|
"name": "@north-light/plugin",
|
|
11923
|
-
"version": "0.3.
|
|
11923
|
+
"version": "0.3.761",
|
|
11924
11924
|
"license": "UNLICENSED",
|
|
11925
11925
|
"dependencies": {
|
|
11926
|
-
"@north-light/api": "0.3.
|
|
11927
|
-
"@north-light/identity": "0.3.
|
|
11926
|
+
"@north-light/api": "0.3.761",
|
|
11927
|
+
"@north-light/identity": "0.3.761"
|
|
11928
11928
|
}
|
|
11929
11929
|
},
|
|
11930
11930
|
"packages/crouter-sdk": {
|
|
11931
11931
|
"name": "@north-light/sdk",
|
|
11932
|
-
"version": "0.3.
|
|
11932
|
+
"version": "0.3.761",
|
|
11933
11933
|
"license": "UNLICENSED",
|
|
11934
11934
|
"dependencies": {
|
|
11935
|
-
"@north-light/api": "0.3.
|
|
11936
|
-
"@north-light/identity": "0.3.
|
|
11937
|
-
"@north-light/plugin": "0.3.
|
|
11935
|
+
"@north-light/api": "0.3.761",
|
|
11936
|
+
"@north-light/identity": "0.3.761",
|
|
11937
|
+
"@north-light/plugin": "0.3.761",
|
|
11938
11938
|
"jose": "^6.2.1"
|
|
11939
11939
|
},
|
|
11940
11940
|
"bin": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const retry: import("../../../core/command.js").LeafDef;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var a=Object.defineProperty;var r=(e,t)=>a(e,"name",{value:t,configurable:!0});import{defineLeaf as d}from"../../../core/command.js";import{usage as s}from"../../../core/errors.js";import{ImportCloud as u}from"../../../core/import/export/cloud.js";import{controlPlaneUrl as l,personBearer as p}from"../../../core/directory/person-credential.js";import{awaitRunOutcome as m,defaultDirectoryUrl as f}from"./move.js";const _=d({name:"retry",description:"load a failed import again from the bundle it already uploaded",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",help:{name:"sys import retry",summary:"re-queue a failed run so Northlight loads its kept upload again, then wait for the outcome",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.",params:[{kind:"positional",name:"run_id",type:"string",required:!0,constraint:"The failed import run (`imp_\u2026`)."},{kind:"flag",name:"api-url",type:"string",required:!1,constraint:"Control plane base URL; default is the one the sign-in is for."}],output:[{name:"run_id",type:"string",required:!0,constraint:"The import run."},{name:"state",type:"string",required:!0,constraint:"Final state of the run, `done`."}],outputKind:"object",effects:["Moves the run from `failed` back to `loading` on the control plane; nothing local changes."]},run:r(async e=>{const t=String(e.run_id??"");if(t==="")throw s("name the failed run: crtr sys import retry <run_id>");const n=f(),i=e.apiUrl===void 0?await l(n):String(e.apiUrl),o=new u(i,()=>p(n));return await o.retry(t),await m(o,t,void 0),{run_id:t,state:"done"}},"run"),render:r(e=>`<import run="${e.run_id}" state="${e.state}"/>`,"render")});export{_ as retry};
|
|
@@ -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 +0,0 @@
|
|
|
1
|
-
var i=Object.defineProperty;var n=(t,r)=>i(t,"name",{value:r,configurable:!0});import{CrtrClient as o}from"../../api/index.js";import{northlightFetch as e}from"../../core/directory/person-credential.js";import{writeMoveRecord as c}from"./config.js";async function l(t){if(t.notified||t.notify===null)return t;await new o({baseUrl:t.apiUrl,fetch:e(t.directoryUrl,t.apiUrl)}).sendMessage(t.notify,{from:null,body:`The move to Northlight finished; crtr on this computer now runs with the account ${t.account.display}. Retry the command that needed the account and carry on.`});const r={...t,notified:!0};return c(r),r}n(l,"notifyMoveFinished");export{l as notifyMoveFinished};
|
|
@@ -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,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
|
-
}
|