@tnunamak/dalan 0.8.0 → 0.8.2
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/CHANGELOG.md +70 -1
- package/CONTRIBUTING.md +2 -0
- package/PROTOCOL.md +6 -0
- package/README.md +8 -12
- package/bin/dalan.mjs +25 -4
- package/bin/dot-acp-agent.mjs +572 -76
- package/bin/dot-alert.mjs +9 -3
- package/bin/dot-deadman.mjs +3 -1
- package/bin/dot-heartbeat.mjs +14 -7
- package/bin/dot-pr-reviewer.mjs +3 -31
- package/bin/dot-worker.mjs +215 -40
- package/contracts/adapter-qualification.schema.json +94 -7
- package/docs/chatgpt-worker-onboarding.md +1 -1
- package/docs/codex-to-muse.md +2 -2
- package/docs/connect-chatgpt.md +1 -1
- package/docs/connection-longevity.md +2 -2
- package/docs/dalan-upgrade.md +8 -5
- package/docs/deadman.md +4 -0
- package/docs/design/authority-matrix.md +18 -0
- package/docs/design/failure-table.md +87 -0
- package/docs/design/identities.md +22 -0
- package/docs/design/pnpm-prepared-dependencies.md +64 -0
- package/docs/design/reuse-ledger.md +75 -0
- package/docs/design/target-architecture-v2.md +434 -0
- package/docs/local-agent-mcp.md +14 -0
- package/docs/local-agent-requester.md +3 -2
- package/docs/manual-setup.md +1 -1
- package/docs/operations.md +78 -14
- package/docs/pull-workers.md +11 -0
- package/docs/relationships.md +13 -0
- package/docs/service-setup.md +10 -10
- package/docs/t3-integration.md +6 -2
- package/docs/t3-reverse-control.md +5 -5
- package/docs/t3-wake-fence-r4.md +1 -1
- package/docs/test-suite-isolation.md +8 -6
- package/docs/trials/chatgpt-agent.md +47 -0
- package/docs/trials/claude-code-requester.md +68 -0
- package/docs/trials/muse.md +46 -0
- package/docs/usage.md +35 -9
- package/docs/worker-clients.md +1 -1
- package/integrations/t3/acp-kit/src/errors.mjs +6 -2
- package/integrations/t3/acp-kit/src/lock.mjs +46 -17
- package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
- package/package.json +4 -3
- package/packages/job-core/protocol/canonical.mjs +45 -7
- package/packages/job-core/transitions.mjs +4 -2
- package/scripts/upgrade-drain.mjs +96 -8
- package/scripts/worker-bridge-setup.mjs +215 -120
- package/src/ack-ledger.mjs +7 -1
- package/src/acp-bridge.mjs +256 -28
- package/src/admin-socket.mjs +32 -3
- package/src/alerts.mjs +17 -8
- package/src/answer-journal-retention.mjs +82 -0
- package/src/answer-journal.mjs +6 -4
- package/src/as-store.mjs +51 -6
- package/src/as.mjs +27 -5
- package/src/catalog-switch-inventory.mjs +70 -0
- package/src/check-response.mjs +4 -1
- package/src/claim-command-ledger.mjs +3 -2
- package/src/cli-help.mjs +29 -10
- package/src/cli-name.mjs +13 -1
- package/src/connect-cli.mjs +159 -4
- package/src/deadman.mjs +8 -5
- package/src/delivery.mjs +2 -19
- package/src/destinations/index.mjs +75 -14
- package/src/drain-runner.mjs +5 -1
- package/src/follow-current.mjs +3 -1
- package/src/get-summary.mjs +11 -2
- package/src/git-env.mjs +1 -1
- package/src/gozar-routes.mjs +313 -94
- package/src/host-budget-storage.py +56 -6
- package/src/host-budget.mjs +98 -15
- package/src/host-execution-policy.mjs +17 -6
- package/src/inbox.mjs +13 -3
- package/src/legacy-names.mjs +0 -2
- package/src/lifecycle.mjs +104 -11
- package/src/loopback-probe.mjs +46 -0
- package/src/mcp-outcome.mjs +3 -1
- package/src/mcp-sse.mjs +2 -1
- package/src/mcp-stdio.mjs +192 -30
- package/src/patch-apply.mjs +285 -19
- package/src/phase-trace.mjs +73 -0
- package/src/prepared-go-modules.mjs +127 -0
- package/src/prepared-node-modules.mjs +225 -38
- package/src/prepared-pnpm.mjs +276 -0
- package/src/prepared-store-prune.mjs +52 -0
- package/src/projects.mjs +59 -7
- package/src/protocol-artifact-commands.mjs +28 -0
- package/src/protocol-finish.mjs +3 -2
- package/src/publication-authority.mjs +22 -0
- package/src/publish-plan.mjs +2 -2
- package/src/pull-queue.mjs +55 -20
- package/src/read-api.mjs +127 -0
- package/src/redaction.mjs +173 -0
- package/src/rejections.mjs +19 -3
- package/src/route-custody.mjs +90 -0
- package/src/route-publication.mjs +50 -0
- package/src/route-setup.mjs +184 -0
- package/src/schema-subset.mjs +5 -3
- package/src/server.mjs +619 -88
- package/src/service-launchd.mjs +5 -1
- package/src/service-update-lock.mjs +7 -4
- package/src/service-update-runtime.mjs +64 -19
- package/src/service-update.mjs +193 -48
- package/src/service.mjs +276 -77
- package/src/setup.mjs +48 -25
- package/src/signal.mjs +1 -1
- package/src/status-evidence.mjs +18 -5
- package/src/status-summary.mjs +3 -0
- package/src/store.mjs +1086 -127
- package/src/submission-policy.mjs +257 -56
- package/src/t3-control.mjs +1 -1
- package/src/t3.mjs +14 -8
- package/src/terminal-safe.mjs +9 -7
- package/src/tool-registry.mjs +134 -41
- package/src/try-exposure.mjs +53 -86
- package/src/try-hosted.mjs +257 -70
- package/src/try.mjs +48 -22
- package/src/work-order.mjs +11 -6
- package/src/worker-instructions.mjs +26 -4
- package/src/worker-runs.mjs +35 -0
- package/src/workers.mjs +49 -4
- package/src/workspace.mjs +354 -54
- package/systemd/dot-deadman.service +3 -1
- package/docs/dot-pr-reviewer.config.example.json +0 -9
- package/docs/pr-head-reviewer.md +0 -70
- package/src/pr-head-reviewer.mjs +0 -596
- package/systemd/dot-pr-reviewer.service +0 -11
- package/systemd/dot-pr-reviewer.timer +0 -10
package/bin/dot-alert.mjs
CHANGED
|
@@ -3,7 +3,13 @@
|
|
|
3
3
|
// so scheduled agents can alert the owner without handling the notification token themselves.
|
|
4
4
|
// Usage: dalan-alert "title" "message"
|
|
5
5
|
import { publishAlert } from '../src/alerts.mjs';
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
const args = process.argv.slice(2);
|
|
7
|
+
const [title, message] = args;
|
|
8
|
+
if (args.length !== 2 || !title.trim() || !message.trim()) { console.error('usage: dalan-alert TITLE MESSAGE'); process.exit(2); }
|
|
9
|
+
try {
|
|
10
|
+
await publishAlert(title, message, () => {}, { requirePublisher: true });
|
|
11
|
+
} catch (error) {
|
|
12
|
+
console.error('Delivery unconfirmed; do not assume repeating this alert is deduplicated.');
|
|
13
|
+
throw error;
|
|
14
|
+
}
|
|
9
15
|
console.log('sent');
|
package/bin/dot-deadman.mjs
CHANGED
|
@@ -36,7 +36,8 @@ async function heartbeat() {
|
|
|
36
36
|
if (target.search || target.hash) throw new Error('heartbeat base URL cannot include a query or fragment');
|
|
37
37
|
const health = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
38
38
|
const observed = Date.parse(health.observed_at);
|
|
39
|
-
|
|
39
|
+
const now = Date.now();
|
|
40
|
+
if (health.healthy !== true || !Number.isFinite(observed) || now - observed > 90_000 || observed > now + 30_000) {
|
|
40
41
|
throw new Error('bridge health evidence is absent, unhealthy, or stale');
|
|
41
42
|
}
|
|
42
43
|
target.pathname = `${target.pathname.replace(/\/+$/, '')}/heartbeat`;
|
|
@@ -49,6 +50,7 @@ async function heartbeat() {
|
|
|
49
50
|
}
|
|
50
51
|
|
|
51
52
|
try {
|
|
53
|
+
if (command === 'heartbeat' && args.length) throw new Error('usage: dalan-deadman heartbeat');
|
|
52
54
|
loadEnv();
|
|
53
55
|
if (command === 'heartbeat') await heartbeat();
|
|
54
56
|
else if(command==='status') {
|
package/bin/dot-heartbeat.mjs
CHANGED
|
@@ -8,22 +8,29 @@ import { execFile } from 'node:child_process';
|
|
|
8
8
|
import { promisify } from 'node:util';
|
|
9
9
|
import { fileURLToPath } from 'node:url';
|
|
10
10
|
import { bridgeHealth } from '../src/host-health.mjs';
|
|
11
|
+
import { adminSocketPath } from '../src/admin-socket.mjs';
|
|
11
12
|
|
|
12
13
|
const root = defaultPath(os.homedir(),'.local/share/dot-bridge');
|
|
13
14
|
const healthFile = readEnv('DALAN_HEALTH_FILE') || path.join(root, 'health.json');
|
|
14
15
|
const temporary = `${healthFile}.${process.pid}`;
|
|
15
16
|
try {
|
|
16
|
-
const health = await bridgeHealth({ socketPath:
|
|
17
|
+
const health = await bridgeHealth({ socketPath: adminSocketPath(root), drainerFile: readEnv('DALAN_DRAINER_HEALTH_FILE') });
|
|
17
18
|
fs.writeFileSync(temporary, JSON.stringify(health) + '\n', { mode: 0o600 });
|
|
18
19
|
fs.renameSync(temporary, healthFile);
|
|
19
|
-
const { stdout } = await promisify(execFile)(process.execPath, [fileURLToPath(new URL('./dot-deadman.mjs', import.meta.url)), 'heartbeat'], {
|
|
20
|
-
env: { ...process.env, DOT_BRIDGE_HEALTH_FILE: healthFile }, timeout: 10000,
|
|
21
|
-
});
|
|
22
|
-
process.stdout.write(stdout);
|
|
23
20
|
} catch {
|
|
24
21
|
fs.rmSync(temporary, { force: true });
|
|
25
|
-
// Remove stale positive evidence; a failed local check must not ping externally.
|
|
26
22
|
fs.rmSync(healthFile, { force: true });
|
|
27
|
-
console.error('dalan-heartbeat: health check
|
|
23
|
+
console.error('dalan-heartbeat: local health check failed');
|
|
28
24
|
process.exitCode = 1;
|
|
29
25
|
}
|
|
26
|
+
if (!process.exitCode) {
|
|
27
|
+
try {
|
|
28
|
+
const { stdout } = await promisify(execFile)(process.execPath, [fileURLToPath(new URL('./dot-deadman.mjs', import.meta.url)), 'heartbeat'], {
|
|
29
|
+
env: { ...process.env, DOT_BRIDGE_HEALTH_FILE: healthFile }, timeout: 10000,
|
|
30
|
+
});
|
|
31
|
+
process.stdout.write(stdout);
|
|
32
|
+
} catch {
|
|
33
|
+
console.error('dalan-heartbeat: external heartbeat failed');
|
|
34
|
+
process.exitCode = 1;
|
|
35
|
+
}
|
|
36
|
+
}
|
package/bin/dot-pr-reviewer.mjs
CHANGED
|
@@ -1,32 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
//
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
const usage = `usage: dalan-pr-reviewer [--dry-run] [--only OWNER/REPO#N] [--max N] [--ignore-capacity] [--config FILE] [--state-dir DIR]
|
|
6
|
-
--dry-run print what would be submitted; submit and write nothing
|
|
7
|
-
--only OWNER/REPO#N consider only that PR (still deduped and gated)
|
|
8
|
-
--max N submit at most N this run (default: config max_submits_per_run)
|
|
9
|
-
--ignore-capacity with --dry-run only: preview candidates even when no lane is free`;
|
|
10
|
-
const args = process.argv.slice(2), has = f => args.includes(f), opt = f => { const i = args.indexOf(f); return i < 0 ? null : args[i + 1]; };
|
|
11
|
-
try {
|
|
12
|
-
const known = new Set(['--dry-run', '--only', '--max', '--ignore-capacity', '--config', '--state-dir', '--help']);
|
|
13
|
-
const values = new Set(['--only', '--max', '--config', '--state-dir']);
|
|
14
|
-
for (let i = 0; i < args.length; i++) { if (!known.has(args[i])) throw new Error(`unknown argument ${args[i]}`); if (values.has(args[i])) i++; }
|
|
15
|
-
if (has('--help')) { console.log(usage); process.exit(0); }
|
|
16
|
-
const dryRun = has('--dry-run');
|
|
17
|
-
if (has('--ignore-capacity') && !dryRun) throw new Error('--ignore-capacity requires --dry-run');
|
|
18
|
-
let only = null;
|
|
19
|
-
// A present --only with a missing or malformed value must fail, never fall through to every open PR.
|
|
20
|
-
if (args.includes('--only')) only = parseOnly(opt('--only'));
|
|
21
|
-
const max = opt('--max') === null ? null : Number(opt('--max'));
|
|
22
|
-
if (max !== null && !(Number.isInteger(max) && max >= 0)) throw new Error('--max expects a non-negative integer');
|
|
23
|
-
const cfg = loadConfig(opt('--config') ?? paths.config), stateDir = opt('--state-dir') ?? paths.stateDir;
|
|
24
|
-
const release = dryRun ? () => {} : acquireLock(stateDir);
|
|
25
|
-
if (!release) { console.error('dalan-pr-reviewer: another run is active'); process.exit(0); }
|
|
26
|
-
try {
|
|
27
|
-
await run({ cfg, deps: realDeps(cfg), stateDir, dryRun, only, maxSubmits: max, ignoreCapacity: has('--ignore-capacity'), print: line => console.log(line) });
|
|
28
|
-
} finally { release(); }
|
|
29
|
-
} catch (error) {
|
|
30
|
-
console.error(`dalan-pr-reviewer: ${error.message}`);
|
|
31
|
-
process.exit(1);
|
|
32
|
-
}
|
|
2
|
+
// Retired. This stub keeps the `dalan-pr-reviewer` command for one release, so an upgrade leaves no dangling command.
|
|
3
|
+
console.error('dalan-pr-reviewer: the PR-head reviewer was retired from Dalan in this release; fleet tooling owns PR-head reviews.');
|
|
4
|
+
process.exit(2);
|
package/bin/dot-worker.mjs
CHANGED
|
@@ -5,6 +5,9 @@ import http from 'node:http';
|
|
|
5
5
|
import net from 'node:net';
|
|
6
6
|
import { DatabaseSync } from 'node:sqlite';
|
|
7
7
|
import { prepareNodeModules } from '../src/prepared-node-modules.mjs';
|
|
8
|
+
import { prepareGoModules, pruneGoStore } from '../src/prepared-go-modules.mjs';
|
|
9
|
+
import { preparePnpm } from '../src/prepared-pnpm.mjs';
|
|
10
|
+
import { pruneNodeStore } from '../src/prepared-store-prune.mjs';
|
|
8
11
|
import fs from 'node:fs';
|
|
9
12
|
import os from 'node:os';
|
|
10
13
|
import path from 'node:path';
|
|
@@ -23,7 +26,7 @@ import { readLines } from '../src/request-log.mjs';
|
|
|
23
26
|
import { lintChecksFile, formatChecksReport } from '../src/check-lint.mjs';
|
|
24
27
|
import { parseExecution, parseRequiredCapabilities, hostReadiness, hostBackend } from '../src/execution.mjs';
|
|
25
28
|
import { RESOURCE_LIMITS_UNAVAILABLE } from '../src/host-execution-policy.mjs';
|
|
26
|
-
import { summarizeRejections } from '../src/rejections.mjs';
|
|
29
|
+
import { summarizeRejections, formatRejections } from '../src/rejections.mjs';
|
|
27
30
|
import { VERDICT_EXIT, formatVerdict } from '../src/work-order.mjs';
|
|
28
31
|
import { connectCommand } from '../src/connect-cli.mjs';
|
|
29
32
|
import { runAuthCheck } from '../src/auth-check.mjs';
|
|
@@ -31,12 +34,12 @@ import { initAsFiles, rotateKeys } from '../src/as-files.mjs';
|
|
|
31
34
|
import { docsUrl } from '../src/docs-url.mjs';
|
|
32
35
|
import { workerPrompt } from '../src/worker-prompt.mjs';
|
|
33
36
|
import { stoppedTrialFix } from '../src/try-command.mjs';
|
|
34
|
-
import { formatGetSummary, formatWaitLine } from '../src/get-summary.mjs';
|
|
37
|
+
import { formatGetSummary, formatGetEndNote, formatWaitLine } from '../src/get-summary.mjs';
|
|
35
38
|
import { cliCommand } from '../src/cli-name.mjs';
|
|
36
|
-
import { applyPatch } from '../src/patch-apply.mjs';
|
|
39
|
+
import { applyPatch, listPatchFiles, materialize, readMaterializeGrant, patchMatchesWorktree, worktreeRoot } from '../src/patch-apply.mjs';
|
|
37
40
|
import { terminalSafe, jsonTerminalSafe } from '../src/terminal-safe.mjs';
|
|
38
|
-
import { loadOwnerWorkers, parseWorkers, submitTarget, updateWorkerRepoPolicy, writeGenericProfile, writeLegacyMarker, readWorkerRepoHistory, seedWorkerRepos, inspectGrantAudit, AUDIT_INTEGRITY_HINT } from '../src/workers.mjs';
|
|
39
|
-
import { adminSocketPathError } from '../src/admin-socket.mjs';
|
|
41
|
+
import { loadOwnerWorkers, parseWorkers, submitTarget, updateWorkerRepoPolicy, writeGenericProfile, writeLegacyMarker, readWorkerRepoHistory, seedWorkerRepos, inspectGrantAudit, ensureWorkerRelationship, AUDIT_INTEGRITY_HINT } from '../src/workers.mjs';
|
|
42
|
+
import { adminSocketPathError, adminSocketPath } from '../src/admin-socket.mjs';
|
|
40
43
|
import { answerThroughJournal } from '../src/answer-journal.mjs';
|
|
41
44
|
// An answer reply that takes longer than this counts as lost; the journaled envelope is sent again.
|
|
42
45
|
const ANSWER_TIMEOUT_MS=30000;
|
|
@@ -48,7 +51,7 @@ console.error=(...parts)=>writeStderr(...parts.map(part=>typeof part==='string'?
|
|
|
48
51
|
|
|
49
52
|
let endNote=null;
|
|
50
53
|
const args = process.argv.slice(2), command = args.shift(), json = args.includes('--json');
|
|
51
|
-
const home=os.homedir(), root=defaultPath(home,'.local/share/dot-bridge'), socket=
|
|
54
|
+
const home=os.homedir(), root=defaultPath(home,'.local/share/dot-bridge'), socket=adminSocketPath(root), receipts=path.join(root,'receipts');
|
|
52
55
|
function missingProfileWarning(worker,policy) {
|
|
53
56
|
if(policy?.source==='admitted-history')return `worker "${worker}" uses a persisted exact repository list; no identity profile was created`;
|
|
54
57
|
return `worker "${worker}" has no workers.json; repository jobs are denied until an explicit repository allow-list is configured (docs/operations.md#legacy-repository-policy-migration)`;
|
|
@@ -65,8 +68,8 @@ const FIRST_JOB_URL=docsUrl('docs/manual-setup.md','submit-finish-and-read-the-r
|
|
|
65
68
|
// --json output keeps `dalan`, so scripts see the same text as before.
|
|
66
69
|
const cli=json?'dalan':cliCommand(process.argv[1]);
|
|
67
70
|
// Every option a command reads. An option it does not know is refused, so a typo is not ignored in silence.
|
|
68
|
-
const SUBMIT_FLAGS=['--stdin','--json','--review','--wait','--dry-run','--queue-anyway','--refuse-defer','--allow-scope-prune','--fix-scope','--background','--allow-main','--exclude-sensitive'];
|
|
69
|
-
const SUBMIT_VALUES=['--eligible','--policy','--file','--brief','--worker','--thread','--deliver','--timeout','--execution','--require-capability','--objective-key','--revision','--task-kind','--source','--sensitive-scope-override','--defer-if-queued','--producer-thread'];
|
|
71
|
+
const SUBMIT_FLAGS=['--stdin','--json','--review','--wait','--dry-run','--queue-anyway','--refuse-defer','--allow-scope-prune','--fix-scope','--background','--caller-waiting','--allow-main','--exclude-sensitive'];
|
|
72
|
+
const SUBMIT_VALUES=['--eligible','--policy','--file','--brief','--worker','--thread','--deliver','--timeout','--execution','--require-capability','--objective-key','--revision','--task-kind','--source','--revises','--follows','--sensitive-scope-override','--defer-if-queued','--producer-thread'];
|
|
70
73
|
const SUBMIT_OPTIONS=[...SUBMIT_FLAGS,...SUBMIT_VALUES];
|
|
71
74
|
function refuseUnknownOptions(name,{flags=[],values=[]}) {
|
|
72
75
|
for(let i=0;i<args.length;i++) {
|
|
@@ -89,7 +92,7 @@ function bridgeNotRunning(error) {
|
|
|
89
92
|
if(selected) return Object.assign(error,{message:`cannot reach the bridge: no bridge is running for DALAN_HOME=${selected} (${cause})`,fix:[`start the bridge for this home the way you set it up (${docsUrl('docs/manual-setup.md','owner-and-requester-setup')}), then run this command again`]});
|
|
90
93
|
return Object.assign(error,{message:`cannot reach the bridge: DALAN_HOME is not set and no bridge is running in ${home} (${cause})`,fix:[`export DALAN_HOME=DIR for the bridge home you made, or start a trial bridge with: ${cli} try`]});
|
|
91
94
|
}
|
|
92
|
-
function request(route, method = 'GET', payload, headers={}, timeoutMs=
|
|
95
|
+
function request(route, method = 'GET', payload, headers={}, timeoutMs=30000) {
|
|
93
96
|
return new Promise((resolve, reject) => {
|
|
94
97
|
const bytes = payload ? JSON.stringify(payload) : '';
|
|
95
98
|
const transportFailure=error=>reject(Object.assign(error.syscall==='connect'&&['ENOENT','ECONNREFUSED'].includes(error.code)?bridgeNotRunning(error):error,{kind:'transport'}));
|
|
@@ -112,7 +115,40 @@ function request(route, method = 'GET', payload, headers={}, timeoutMs=0) {
|
|
|
112
115
|
});
|
|
113
116
|
}
|
|
114
117
|
|
|
115
|
-
function download(id,output
|
|
118
|
+
function download(id,output,ownerHeaders) {
|
|
119
|
+
return new Promise((resolve,reject)=>{
|
|
120
|
+
const socketPathError=adminSocketPathError(socket);
|
|
121
|
+
if(socketPathError) return reject(socketPathError);
|
|
122
|
+
if(!artifactIdPattern.test(id)) return reject(new Error('invalid artifact ID'));
|
|
123
|
+
const req=http.request({socketPath:socket,path:'/artifact?id='+encodeURIComponent(id),headers:ownerHeaders??{'x-owner-capability':receiptForArtifact(id).token}},res=>{
|
|
124
|
+
if(res.statusCode!==200){
|
|
125
|
+
let body='', tooLarge=false;
|
|
126
|
+
res.on('data',chunk=>{
|
|
127
|
+
if(tooLarge) return;
|
|
128
|
+
body+=chunk;
|
|
129
|
+
if(body.length>8192){ body=''; tooLarge=true; }
|
|
130
|
+
});
|
|
131
|
+
res.on('end',()=>{
|
|
132
|
+
let error;
|
|
133
|
+
try { error=JSON.parse(body)?.error; } catch { /* status fallback */ }
|
|
134
|
+
reject(new Error(typeof error==='string'&&error.trim() ? error : `HTTP ${res.statusCode}`));
|
|
135
|
+
});
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const bytes=[];
|
|
139
|
+
res.on('data',b=>bytes.push(b));
|
|
140
|
+
res.on('end',()=>{
|
|
141
|
+
const data=Buffer.concat(bytes),digest=createHash('sha256').update(data).digest('hex');
|
|
142
|
+
if(digest!==res.headers['x-artifact-sha256']) return reject(new Error('artifact digest mismatch'));
|
|
143
|
+
try { fs.writeFileSync(output,data,{flag:'wx',mode:0o600}); }
|
|
144
|
+
catch (error) { return reject(error); }
|
|
145
|
+
resolve({artifact_id:id,output,bytes:data.length,sha256:digest});
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
req.on('error',reject);
|
|
149
|
+
req.end();
|
|
150
|
+
});
|
|
151
|
+
}
|
|
116
152
|
const artifactIdPattern=/^art_[-\w]{8,128}$/;
|
|
117
153
|
function receiptForArtifact(id) { if(!artifactIdPattern.test(id)) throw new Error('invalid artifact ID');let requestId;try{requestId=fs.readFileSync(path.join(root,'artifact-index',id),'utf8').trim();}catch{throw new Error('artifact owner unknown; run dalan get REQUEST_ID or wait REQUEST_ID first');}return receipt(requestId); }
|
|
118
154
|
function canonical(value) { if(Array.isArray(value)) return value.map(canonical); if(value&&typeof value==='object') return Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])); return value; }
|
|
@@ -134,12 +170,12 @@ function acpReceipt(id) {
|
|
|
134
170
|
if(secret.length<32) return null;
|
|
135
171
|
return {request_id:id,token:createHmac('sha256',secret).update(id).digest('hex'),acp:true};
|
|
136
172
|
}
|
|
137
|
-
function writeReceipt(id, token, body, delivery, review=false, background=false, meta=null, producer=null, routing=null, destinationRevisions=null) {
|
|
173
|
+
function writeReceipt(id, token, body, delivery, review=false, background=false, meta=null, producer=null, routing=null, destinationRevisions=null, revises=null, follows=null, callerWaiting=false) {
|
|
138
174
|
fs.mkdirSync(receipts,{recursive:true,mode:0o700});
|
|
139
175
|
const file=receiptPath(id);
|
|
140
176
|
try {
|
|
141
177
|
const fd=fs.openSync(file,'wx',0o600);
|
|
142
|
-
try { fs.writeSync(fd,JSON.stringify({request_id:id,token,body,delivery,...(delivery.startsWith('t3:')?{thread:delivery.slice(3)}:{}),...(review?{review:true}:{}),...(background?{background:true}:{}),...(meta?{meta}:{}),...(producer?{producer}:{}),...(routing?{routing,destination_revisions:destinationRevisions??{}}:{})})+'\n'); fs.fsyncSync(fd); }
|
|
178
|
+
try { fs.writeSync(fd,JSON.stringify({request_id:id,token,body,delivery,...(delivery.startsWith('t3:')?{thread:delivery.slice(3)}:{}),...(review?{review:true}:{}),...(background?{background:true}:{}),...(meta?{meta}:{}),...(producer?{producer}:{}),...(routing?{routing,destination_revisions:destinationRevisions??{}}:{}),...(revises?{revises}:{}),...(follows?{follows}:{}),...(callerWaiting?{caller_waiting:true}:{})})+'\n'); fs.fsyncSync(fd); }
|
|
143
179
|
finally { fs.closeSync(fd); }
|
|
144
180
|
} catch(e) { if(e.code!=='EEXIST') throw e; }
|
|
145
181
|
const dir=fs.openSync(receipts,'r'); try { fs.fsyncSync(dir); } finally { fs.closeSync(dir); }
|
|
@@ -149,7 +185,7 @@ function operator() { const file=defaultPath(home,'.config/dot-bridge/operator.k
|
|
|
149
185
|
async function waitForAssignment(id, timeout) {
|
|
150
186
|
const seconds=timeout===null?300:Number(timeout);
|
|
151
187
|
if(!Number.isInteger(seconds)||seconds<1||seconds>3600) throw new Error('wait timeout must be an integer from 1 to 3600 seconds');
|
|
152
|
-
return request(`/wait?id=${encodeURIComponent(id)}&timeout=${seconds}`,'GET',null,{'x-owner-capability':receipt(id).token});
|
|
188
|
+
return request(`/wait?id=${encodeURIComponent(id)}&timeout=${seconds}`,'GET',null,{'x-owner-capability':receipt(id).token},0); // The server owns the long-poll deadline.
|
|
153
189
|
}
|
|
154
190
|
// Records which request owns each artifact so `artifact ART_ID` can find the owner receipt. Called by get and wait.
|
|
155
191
|
function indexArtifacts(requestId,result) {
|
|
@@ -224,8 +260,8 @@ function producerReceipts(producer,cache) {
|
|
|
224
260
|
}
|
|
225
261
|
// A failure worth retrying: the bridge restarting (transport) or unavailable (5xx).
|
|
226
262
|
const transient=e=>e.kind==='transport'||e.http_status>=500;
|
|
227
|
-
// /owner-states
|
|
228
|
-
//
|
|
263
|
+
// /owner-states is explicitly non-consuming. A bridge lacking it might also
|
|
264
|
+
// silently ignore /get's peek parameter; do not probe it with an actual receipt.
|
|
229
265
|
async function ownerStates(items,legacy) {
|
|
230
266
|
if(!legacy.on) try {
|
|
231
267
|
let out=null;
|
|
@@ -236,14 +272,7 @@ async function ownerStates(items,legacy) {
|
|
|
236
272
|
return out;
|
|
237
273
|
}
|
|
238
274
|
catch(e) { if(e.http_status!==404) throw e; legacy.on=true; }
|
|
239
|
-
const states=
|
|
240
|
-
for(const x of items) {
|
|
241
|
-
let got; try { got=await request('/get?id='+encodeURIComponent(x.id),'GET',null,{'x-owner-capability':x.token}); }
|
|
242
|
-
catch(e) { if(transient(e)) throw e; states.push({request_id:x.id,error:'unreadable'}); continue; }
|
|
243
|
-
if(typeof got.status!=='string') { states.push({request_id:x.id,error:'unreadable'}); continue; }
|
|
244
|
-
const blockers=(got.progress??[]).map(p=>p.note).filter(n=>/^\s*(?:BLOCKED:|QUESTION:)/im.test(n));
|
|
245
|
-
states.push({request_id:x.id,status:got.status,blocker_count:blockers.length,last_blocker:blockers.at(-1)??null});
|
|
246
|
-
}
|
|
275
|
+
const states=items.map(x=>({request_id:x.id,error:'unreadable'}));
|
|
247
276
|
const s=await request('/status');
|
|
248
277
|
// Only evidence holds refill: a pause or an owner-confirmed break (not an inferred break, not an estimated limit).
|
|
249
278
|
const held=s.paused?'paused':s.worker_break?.active&&s.worker_break.source==='owner'?'worker_break':null;
|
|
@@ -300,8 +329,10 @@ async function waitDrained() {
|
|
|
300
329
|
if(!Number.isInteger(v)||v<0||v>100) throw new Error(`${flag} must be an integer from 0 to 100`);
|
|
301
330
|
limits[key]=v;
|
|
302
331
|
}
|
|
303
|
-
const intervalMs=Number(process.env.DOT_DRAINED_INTERVAL_MS
|
|
304
|
-
|
|
332
|
+
const intervalMs=Number(process.env.DOT_DRAINED_INTERVAL_MS ?? 15000);
|
|
333
|
+
if(!Number.isSafeInteger(intervalMs)||intervalMs<1||intervalMs>2147483647) throw new Error('DOT_DRAINED_INTERVAL_MS must be a positive integer no greater than 2147483647');
|
|
334
|
+
const unreachableMs=Number(process.env.DOT_DRAINED_UNREACHABLE_MS ?? 600000);
|
|
335
|
+
if(!Number.isSafeInteger(unreachableMs)||unreachableMs<1||unreachableMs>2147483647) throw new Error('DOT_DRAINED_UNREACHABLE_MS must be a positive integer no greater than 2147483647');
|
|
305
336
|
// One waiter per producer: a second one exits at once, so the hook and a forgetful agent cannot stack them.
|
|
306
337
|
fs.mkdirSync(drainedDir,{recursive:true,mode:0o700});
|
|
307
338
|
const file=drainedPidfile(producer), mine={pid:process.pid,token:randomBytes(8).toString('hex'),producer,started_at:new Date().toISOString()};
|
|
@@ -352,6 +383,21 @@ async function main() {
|
|
|
352
383
|
else result={config_dir:selectors['--config-root'](),data_dir:root,state_dir:selectors['--state-root'](),workspace_root:workspaceRoot(home),...(json?{warnings}:{})};
|
|
353
384
|
break;
|
|
354
385
|
}
|
|
386
|
+
case 'relationships': {
|
|
387
|
+
const [action,relationshipId,...extra]=args.filter(a=>a!=='--json');
|
|
388
|
+
const headers={'x-operator-key':operator()};
|
|
389
|
+
if(action==='list'&&!relationshipId&&!extra.length) result=await request('/relationships','GET',null,headers);
|
|
390
|
+
else if(action==='publish'&&relationshipId&&(extra.length===1&&extra[0]==='--revoke'||extra.length>=1&&extra.length%2===0&&extra.every((a,i)=>i%2?true:a==='--grant')))
|
|
391
|
+
result=await request('/relationships/publish','POST',{relationship_id:relationshipId,grant:extra[0]==='--revoke'?null:extra.filter((_,i)=>i%2).map(String)},headers);
|
|
392
|
+
else if(action==='end'&&relationshipId&&!extra.length) result=await request('/relationships/end','POST',{relationship_id:relationshipId},headers);
|
|
393
|
+
else throw new Error('usage: dalan relationships list | end RELATIONSHIP_ID | publish RELATIONSHIP_ID (--grant org:NAME|repo:OWNER/NAME)... | publish RELATIONSHIP_ID --revoke [--json]');
|
|
394
|
+
break;
|
|
395
|
+
}
|
|
396
|
+
case 'grants': {
|
|
397
|
+
if(args.some(a=>a!=='--json')) throw new Error('usage: dalan grants [--json]');
|
|
398
|
+
result=await request('/grants','GET',null,{'x-operator-key':operator()});
|
|
399
|
+
break;
|
|
400
|
+
}
|
|
355
401
|
case 'worker': {
|
|
356
402
|
const [action,name,repo,...extra]=args.filter(a=>a!=='--json');
|
|
357
403
|
if(args.filter(a=>a==='--json').length>1) throw new Error('usage: dalan worker allow|deny NAME OWNER/REPO [--json] | worker list [NAME] [--json]');
|
|
@@ -384,12 +430,22 @@ async function main() {
|
|
|
384
430
|
break;
|
|
385
431
|
}
|
|
386
432
|
if(!['allow','deny'].includes(action)||!name||!repo||extra.length) throw new Error('usage: dalan worker allow|deny NAME OWNER/REPO [--json]');
|
|
433
|
+
// Enroll first: a database failure must not leave newly granted repository authority without a relationship.
|
|
434
|
+
if(action==='allow'&&fs.existsSync(path.join(root,'bridge.db'))) {
|
|
435
|
+
const db=new DatabaseSync(path.join(root,'bridge.db'));
|
|
436
|
+
try {
|
|
437
|
+
db.exec('PRAGMA busy_timeout=5000');
|
|
438
|
+
if(db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='relationships'").get()) ensureWorkerRelationship(db,name);
|
|
439
|
+
} finally { db.close(); }
|
|
440
|
+
}
|
|
387
441
|
result=updateWorkerRepoPolicy(file,name,action,repo);
|
|
388
442
|
if(!json) { result=`${name}: ${result.mode}${result.repos?.length?` (${result.repos.join(', ')})`:''}${result.denied?.length?` except ${result.denied.join(', ')}`:''}${result.reset_to_audited?.length?`\nthe audit log failed its checkpoint, so workers.json was reset to the audited grants; allow again: ${result.reset_to_audited.map(item=>`${item.worker}${item.repos.length?` (${item.repos.join(', ')})`:''}`).join('; ')}`:''}`; plainOutput=true; }
|
|
389
443
|
break;
|
|
390
444
|
}
|
|
391
445
|
case 'submit': {
|
|
392
446
|
refuseUnknownOptions('submit',{flags:SUBMIT_FLAGS,values:SUBMIT_VALUES});
|
|
447
|
+
let callerWaiting = args.includes('--caller-waiting');
|
|
448
|
+
if (callerWaiting && args.includes('--background')) throw new Error('--caller-waiting cannot be combined with --background');
|
|
393
449
|
const thread = option('--thread'), requestedDelivery = option('--deliver'), file = option('--file');
|
|
394
450
|
if (thread && requestedDelivery) throw new Error('submit accepts either --thread or --deliver, not both');
|
|
395
451
|
const delivery = requestedDelivery ?? (thread ? `t3:${thread}` : 'none');
|
|
@@ -439,6 +495,13 @@ async function main() {
|
|
|
439
495
|
for(const flag of ['--objective-key','--revision','--task-kind','--source']) if(args.includes(flag)&&(!option(flag)||option(flag).startsWith('--'))) throw new Error(`${flag} requires a value`);
|
|
440
496
|
// Objective identity travels beside the assignment, never inside it; a plain dalan submit is an agent's.
|
|
441
497
|
const given=normalizeMeta({objective_key:option('--objective-key'),revision:option('--revision'),task_kind:option('--task-kind'),source:option('--source')});
|
|
498
|
+
// --revises PRIOR_ID: this job corrects a job this home submitted. It cancels nothing; the prior job's result can no longer be accepted.
|
|
499
|
+
if(args.includes('--revises')&&(!option('--revises')||option('--revises').startsWith('--'))) throw new Error('--revises requires the request ID of the job this one corrects');
|
|
500
|
+
const revisesGiven=option('--revises')??null;
|
|
501
|
+
if(revisesGiven&&routing) throw new Error('--revises needs one worker: it cannot be combined with --eligible or --policy');
|
|
502
|
+
const followsGiven=option('--follows')??null;
|
|
503
|
+
if(args.includes('--follows')&&(!followsGiven||followsGiven.startsWith('--'))) throw new Error('--follows requires a finished predecessor request ID');
|
|
504
|
+
if(followsGiven&&(routing||revisesGiven)) throw new Error('--follows cannot be combined with routing or --revises');
|
|
442
505
|
const dryRun=args.includes('--dry-run'), queueAnyway=args.includes('--queue-anyway'), refuseDefer=args.includes('--refuse-defer');
|
|
443
506
|
if(dryRun&&queueAnyway) throw new Error('--dry-run stores nothing; it cannot be combined with --queue-anyway');
|
|
444
507
|
if(dryRun&&args.includes('--wait')) throw new Error('--dry-run stores nothing; it cannot be combined with --wait');
|
|
@@ -458,18 +521,22 @@ async function main() {
|
|
|
458
521
|
}
|
|
459
522
|
}
|
|
460
523
|
const token=randomBytes(32).toString('hex');
|
|
461
|
-
const write=()=>writeReceipt(id,token,JSON.stringify(body),delivery,review,background,{...given,source:given.source??'agent'},producerId(),routing,destinationRevisions);
|
|
524
|
+
const write=()=>writeReceipt(id,token,JSON.stringify(body),delivery,review,background,{...given,source:given.source??'agent'},producerId(),routing,destinationRevisions,revisesGiven,followsGiven,callerWaiting);
|
|
462
525
|
let saved;
|
|
463
526
|
if(dryRun) {
|
|
464
527
|
try { saved=receipt(id); }
|
|
465
|
-
catch(error) { if(error.code!=='ENOENT') throw error; saved={request_id:id,token,delivery,body:input,...(routing?{routing,destination_revisions:destinationRevisions}:{})}; }
|
|
528
|
+
catch(error) { if(error.code!=='ENOENT') throw error; saved={request_id:id,token,delivery,background,body:input,...(routing?{routing,destination_revisions:destinationRevisions}:{}),...(followsGiven?{follows:followsGiven}:{})}; }
|
|
466
529
|
} else saved=write();
|
|
530
|
+
if (callerWaiting && saved.token !== token && saved.caller_waiting !== true)
|
|
531
|
+
throw Object.assign(new Error('--caller-waiting cannot be added to a saved request; reconcile the saved request before submitting a new request ID'), {local_code:'receipt_conflict'});
|
|
532
|
+
callerWaiting ||= saved.caller_waiting === true;
|
|
533
|
+
if (callerWaiting && background) throw new Error('--caller-waiting cannot be combined with --background');
|
|
467
534
|
if(!routing&&saved.routing) {routing=saved.routing;destinationRevisions=saved.destination_revisions??{};}
|
|
468
535
|
let fresh=!dryRun&&saved.token===token;
|
|
469
536
|
// Receipts written by earlier releases may carry the old spelling of a source; compare the normalized form.
|
|
470
537
|
const savedMeta=()=>{ try { return normalizeMeta(saved.meta); } catch { return {}; } };
|
|
471
538
|
const conflicts=()=>{ const savedDelivery=saved.delivery ?? (saved.thread ? `t3:${saved.thread}` : null);
|
|
472
|
-
return JSON.stringify(canonical(saved.routing??null))!==JSON.stringify(canonical(routing))||JSON.stringify(canonical(saved.destination_revisions??{}))!==JSON.stringify(canonical(destinationRevisions))||JSON.stringify(canonical(JSON.parse(saved.body)))!==JSON.stringify(canonical(body))||savedDelivery!==delivery||!!saved.review!==review||!!saved.background!==background||metaFields.some(k=>savedMeta()[k]!=null&&given[k]!==null&&savedMeta()[k]!==given[k]); };
|
|
539
|
+
return JSON.stringify(canonical(saved.routing??null))!==JSON.stringify(canonical(routing))||JSON.stringify(canonical(saved.destination_revisions??{}))!==JSON.stringify(canonical(destinationRevisions))||JSON.stringify(canonical(JSON.parse(saved.body)))!==JSON.stringify(canonical(body))||savedDelivery!==delivery||!!saved.review!==review||!!saved.background!==background||metaFields.some(k=>savedMeta()[k]!=null&&given[k]!==null&&savedMeta()[k]!==given[k])||saved.revises!=null&&revisesGiven!==null&&saved.revises!==revisesGiven||followsGiven!==null&&(saved.follows??null)!==followsGiven; };
|
|
473
540
|
const conflict=()=>Object.assign(new Error('request_id conflict with local receipt'),{local_code:'receipt_conflict'});
|
|
474
541
|
// A refused submit stores no assignment, so its receipt guards nothing. Replace it instead of refusing a corrected retry.
|
|
475
542
|
if(dryRun&&conflicts()) throw conflict();
|
|
@@ -481,7 +548,9 @@ async function main() {
|
|
|
481
548
|
}
|
|
482
549
|
// A retry inherits what the receipt recorded for any flag it omits, so replaying a drainer request by hand stays one request.
|
|
483
550
|
const meta=Object.fromEntries(metaFields.map(k=>[k,given[k]??savedMeta()[k]??(k==='source'?'agent':null)]));
|
|
484
|
-
const
|
|
551
|
+
const revisesId=revisesGiven??saved.revises??null;
|
|
552
|
+
const followsId=followsGiven??saved.follows??null;
|
|
553
|
+
const send=()=>request(dryRun?'/submit-preview':'/submit', 'POST', { ...(worker?{worker}:{}), ...(routing?{routing,destination_revisions:destinationRevisions}:{}), delivery, assignment: body, owner_token:saved.token, review, ...(background?{background:true}:{}), ...(callerWaiting?{caller_waiting:true}:{}), meta, ...(revisesId?{revises:{prior_id:revisesId,prior_token:receipt(revisesId).token}}:{}), ...(followsId?{follows:{prior_id:followsId,prior_token:receipt(followsId).token}}:{}), ...(args.includes('--sensitive-scope-override')?{sensitive_scope_override:option('--sensitive-scope-override')}:{}), ...(args.includes('--allow-main')?{allow_main:true}:{}), ...(args.includes('--exclude-sensitive')?{exclude_sensitive:true}:{}), ...(execution?{execution}:{}), ...(requiredCapabilities?{required_capabilities:requiredCapabilities}:{}), ...(dryRun?{dry_run:true}:{...(refuseDefer?{refuse_defer:true}:{}),...(queueAnyway?{queue_anyway:true}:{})}), ...(args.includes('--defer-if-queued')?{defer_queued:Number(option('--defer-if-queued'))}:{}) },args.includes('--allow-main')?{'x-operator-key':operator()}:{});
|
|
485
554
|
try {
|
|
486
555
|
try { result=await send(); }
|
|
487
556
|
catch(error) {
|
|
@@ -533,7 +602,7 @@ async function main() {
|
|
|
533
602
|
console.error(`worker activity: ${a.tool_calls} call${a.tool_calls===1?'':'s'}${a.last_tool?`, last ${a.last_tool} at ${a.last_tool_at.slice(11,19)}Z (${age<90?age+'s':age<5400?Math.round(age/60)+'m':Math.round(age/3600)+'h'} ago)`:''}${a.first_workspace_tool_at?'':', no workspace tool'}${a.last_tool_error?`, last error: ${a.last_tool_error}`:''}`); }
|
|
534
603
|
// On a terminal, a person reads the output: show the short human view. Piped output stays the JSON document.
|
|
535
604
|
if(!json&&!id.startsWith('msg_')&&process.stdout.isTTY) { result=formatGetSummary(result,{id,cli}); plainOutput=true; }
|
|
536
|
-
else if(!json&&!id.startsWith('msg_')
|
|
605
|
+
else if(!json&&!id.startsWith('msg_')) endNote=formatGetEndNote(result,{id,cli,decideWords});
|
|
537
606
|
break; }
|
|
538
607
|
case 'cancel-if-queued': { const id=args[0]; if(!id||id.startsWith('-')) throw new Error('cancel-if-queued requires request id'); result=await request('/cancel-if-queued','POST',{id},{'x-owner-capability':receipt(id).token}); break; }
|
|
539
608
|
case 'artifact': { const artifactId=args[0],output=option('--output');if(!artifactId||!output) throw new Error('artifact requires ID --output PATH');result=await download(artifactId,output);break; }
|
|
@@ -602,6 +671,7 @@ async function main() {
|
|
|
602
671
|
break;
|
|
603
672
|
}
|
|
604
673
|
case 'resume': result=await request('/resume','POST',{}, {'x-operator-key':operator()}); break;
|
|
674
|
+
case 'quiesce': { const modes=args.filter(x=>x!=='--json'&&!x.startsWith('-')),mode=modes[0]; if(modes.length!==1||!['on','off','status'].includes(mode)||args.some(x=>x.startsWith('-')&&x!=='--json')) throw new Error('quiesce takes on, off or status (optional --json)'); result=mode==='status'?await request('/quiesce','GET',null,{'x-operator-key':operator()}):await request('/quiesce','POST',{on:mode==='on'},{'x-operator-key':operator()}); break; }
|
|
605
675
|
case 'claims': { if(args.some(a=>a!=='--json')) throw new Error('claims accepts only --json'); result=await request('/claims','GET',null,{'x-operator-key':operator()}); break; }
|
|
606
676
|
case 'abandon': { const id=args[0]; if(!id||id.startsWith('-')) throw new Error('abandon requires request id'); if(args.includes('--reason')&&!option('--reason')) throw new Error('--reason requires text'); result=await request('/abandon','POST',{id,...(args.includes('--reason')?{reason:option('--reason')}:{})},{'x-operator-key':operator()}); break; }
|
|
607
677
|
case 'accept': case 'reject': { const id=args[0]; if(!id||id.startsWith('-')) throw new Error(`${command} requires request id`); if(args.includes('--note')&&!option('--note')) throw new Error('--note requires text'); result=await request(`/${command}`,'POST',{id,...(args.includes('--note')?{note:option('--note')}:{})},{'x-owner-capability':receipt(id).token}); break; }
|
|
@@ -613,21 +683,112 @@ async function main() {
|
|
|
613
683
|
if(!json&&process.stdout.isTTY) { result=`Recorded ${id} as ${decision}.`; plainOutput=true; }
|
|
614
684
|
break;
|
|
615
685
|
}
|
|
686
|
+
case 'materialize': {
|
|
687
|
+
const id=args[0], flags=args.slice(1), parsed=new Map();
|
|
688
|
+
const usage='usage: dalan materialize ID [--dir PATH] [--approve] [--dry-run] [--json]';
|
|
689
|
+
for(let i=0;i<flags.length;i++) {
|
|
690
|
+
const flag=flags[i];
|
|
691
|
+
if(!['--dir','--approve','--dry-run','--json'].includes(flag) || parsed.has(flag)) throw new Error(usage);
|
|
692
|
+
const value=flag==='--dir' ? flags[++i] : true;
|
|
693
|
+
if(!value || (flag==='--dir' && value.startsWith('--'))) throw new Error(usage);
|
|
694
|
+
parsed.set(flag,value);
|
|
695
|
+
}
|
|
696
|
+
if(!/^[-\w]{8,128}$/.test(id??'') || parsed.has('--dry-run') && parsed.has('--approve')) throw new Error(usage);
|
|
697
|
+
readMaterializeGrant(defaultPath(home,'.config/dot-bridge/materialize.json'));
|
|
698
|
+
const headers={'x-owner-capability':receipt(id).token};
|
|
699
|
+
result=await materialize({id, got:await request('/get?id='+encodeURIComponent(id)+'&peek=1','GET',null,headers), grantFile:defaultPath(home,'.config/dot-bridge/materialize.json'),
|
|
700
|
+
dir:path.resolve(parsed.get('--dir')||process.cwd()), dryRun:parsed.has('--dry-run'), approve:parsed.has('--approve'),
|
|
701
|
+
recheck:()=>request('/get?id='+encodeURIComponent(id)+'&peek=1','GET',null,headers),
|
|
702
|
+
download:async art=>{
|
|
703
|
+
const temp=fs.mkdtempSync(path.join(os.tmpdir(),'dalan-download-')), file=path.join(temp,'patch.diff');
|
|
704
|
+
try { await download(art.artifact_id,file,headers); return fs.readFileSync(file); }
|
|
705
|
+
finally { fs.rmSync(temp,{recursive:true,force:true}); }
|
|
706
|
+
}});
|
|
707
|
+
delete result.published; if(!result.pr_url) delete result.branch; delete result.reason;
|
|
708
|
+
if(!json) {
|
|
709
|
+
const message=result.pr_url ? 'Draft pull request: '+result.pr_url : (parsed.has('--dry-run')?'Dry run only: ':'Not published: ')+result.decision.reason+'; branch '+result.decision.branch;
|
|
710
|
+
result=[result.repo+' at '+result.base_sha, message, ...result.files.map(file=>' '+file)].join('\n');
|
|
711
|
+
plainOutput=true;
|
|
712
|
+
}
|
|
713
|
+
break;
|
|
714
|
+
}
|
|
616
715
|
case 'apply': {
|
|
617
|
-
const id=args[0]; if(!id||id.startsWith('-')) throw new Error('apply requires request id (optional --dir PATH, default the current directory)');
|
|
716
|
+
const id=args[0]; if(!id||id.startsWith('-')) throw new Error('apply requires request id (optional --dir PATH, default the current directory; --release gives up an uncertain apply)');
|
|
618
717
|
if(args.includes('--dir')&&!option('--dir')) throw new Error('--dir requires a path');
|
|
619
|
-
const
|
|
718
|
+
const headers={'x-owner-capability':receipt(id).token};
|
|
620
719
|
const got=await request('/get?id='+encodeURIComponent(id),'GET',null,headers); indexArtifacts(id,got);
|
|
720
|
+
const open=got.apply?.state==='applying';
|
|
721
|
+
if(args.includes('--release')) {
|
|
722
|
+
// Gives up an uncertain apply on purpose, without writing or restoring any file. The job stays not applied.
|
|
723
|
+
if(!open) throw new Error(`no apply in progress for ${id}; nothing to release`);
|
|
724
|
+
await request('/decide','POST',{id,decision:'applied',phase:'release',force:true,reason:'released by the owner (dalan apply --release)',via:'apply'},headers);
|
|
725
|
+
result={request_id:id,released:true};
|
|
726
|
+
if(!json) { result=`released the apply in progress for ${id}; it is not applied and no file was changed`; plainOutput=true; }
|
|
727
|
+
break;
|
|
728
|
+
}
|
|
729
|
+
const dir=path.resolve(option('--dir')??process.cwd());
|
|
730
|
+
// A job revised before any reservation is refused here, and again by the bridge when the apply is reserved. An open
|
|
731
|
+
// reservation is not trusted from this read: it may have been released or taken over since, so every run reserves.
|
|
732
|
+
if(got.revised_by&&!open) throw Object.assign(new Error(`${id} was revised by ${got.revised_by.request_id}; its patch is not applied. Apply the patch of ${got.revised_by.request_id} instead (dalan get ${got.revised_by.request_id}).`),{local_code:'stale_revision'});
|
|
621
733
|
const ev=got.report?.workspace_evidence, art=ev?.patch_artifact;
|
|
622
734
|
if(!art?.artifact_id||!art.size) throw new Error('this result has no patch artifact (nothing to apply)');
|
|
623
735
|
const tmp=fs.mkdtempSync(path.join(os.tmpdir(),'dot-apply-')), file=path.join(tmp,'patch.diff');
|
|
736
|
+
const phase=(name,extra={})=>request('/decide','POST',{id,decision:'applied',phase:name,via:'apply',...extra},headers);
|
|
737
|
+
const reserve=async()=>{ try { return await phase('reserve'); } catch(e) { if(e.http_status===400&&/^stale_revision/.test(e.message)) throw e; throw new Error(`not applied: the bridge did not reserve the apply (${e.message}), so ${dir} is unchanged`); } };
|
|
738
|
+
const confirm=async attempt=>{ try { return await phase('confirm',{attempt}); } catch(e) { throw new Error(`the patch is in ${dir}, but the bridge did not confirm it (${e.message}). ${id} still shows an apply in progress. Run dalan apply ${id} again: if the tree still holds the patch it confirms without writing.`); } };
|
|
624
739
|
try {
|
|
625
740
|
await download(art.artifact_id,file);
|
|
626
|
-
const
|
|
627
|
-
|
|
628
|
-
|
|
741
|
+
const patch=fs.readFileSync(file), patchArgs={dir,patch,sha256:art.sha256,baseSha:ev.base_sha??got.assignment?.inputs?.[0]?.base_sha};
|
|
742
|
+
// Two phases, so the bridge never records an effect before it happens, and a fencing token so that only the run that
|
|
743
|
+
// reserved last can write or confirm. Every run reserves, fresh or resumed: the bridge's stale check and the new token
|
|
744
|
+
// share one transaction, so a correction that landed since any earlier read makes it refuse and nothing is written. The
|
|
745
|
+
// patch is written only with a token from this run (every touched file is restored if the write fails), then confirmed.
|
|
746
|
+
// If the tree already holds the patch (a run died after the write), only the confirm is missing.
|
|
747
|
+
let files=[], written=false;
|
|
748
|
+
if(open&&patchMatchesWorktree(dir,patch)) {
|
|
749
|
+
// The tree already holds the patch. The bridge still checks for a correction: a revised job's result is never recorded.
|
|
750
|
+
let reserved;
|
|
751
|
+
try { reserved=await reserve(); }
|
|
752
|
+
catch(e) {
|
|
753
|
+
if(!/^stale_revision/.test(e.message)) throw e;
|
|
754
|
+
const correction=got.revised_by?.request_id??/revised by (\S+?);/.exec(e.message)?.[1]??'(see dalan get '+id+')';
|
|
755
|
+
const keep=path.join(os.tmpdir(),`dalan-revised-${id}.diff`); fs.writeFileSync(keep,patch,{mode:0o600});
|
|
756
|
+
throw Object.assign(new Error(`${e.message}\nThe working tree contains the superseded patch from request ${id}; the correction is ${correction}. Nothing was recorded and the reservation is still open.\n`
|
|
757
|
+
+`To undo it: git -C ${worktreeRoot(dir)??dir} apply -R ${keep}\n`
|
|
758
|
+
+`Or run dalan apply ${id} --release (it changes no file), then revert the files by hand.`),{local_code:'stale_revision'});
|
|
759
|
+
}
|
|
760
|
+
if(reserved.state!=='applied') { const decided=await confirm(reserved.attempt); result={request_id:id,applied:true,dir,files,already_present:true,decision:decided.decision}; }
|
|
761
|
+
else result={request_id:id,applied:true,dir,files,already_present:true,decision:'applied'};
|
|
762
|
+
} else {
|
|
763
|
+
try { applyPatch({...patchArgs,checkOnly:true}); }
|
|
764
|
+
catch(e) {
|
|
765
|
+
// An open reservation and a tree that fits neither the base nor the patch: a run may have died mid-write.
|
|
766
|
+
if(!open||!/git apply --check failed/.test(e.message)) throw e;
|
|
767
|
+
let names; try { names=listPatchFiles(dir,patch); } catch { names=[]; }
|
|
768
|
+
const top=worktreeRoot(dir)??dir;
|
|
769
|
+
const list=names.map(n=>/^[\w@%+=:,./-]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`).join(' ');
|
|
770
|
+
throw new Error(`${id} has an apply in progress from an earlier run, and ${dir} matches neither the patch nor the base it applies to: the checkout may be partly changed (${e.message.replace(/^not applied: /,'')}).\n`
|
|
771
|
+
+`Files the patch touches: ${names.join(', ')||'(not listed)'}.\n`
|
|
772
|
+
+`To recover: (1) inspect them: git -C ${top} diff -- ${list}\n`
|
|
773
|
+
+` (2) restore them: git -C ${top} checkout -- ${list} (this discards edits to those files only; delete any of them that the patch created, and keep unrelated edits)\n`
|
|
774
|
+
+` (3) run: dalan apply ${id} --dir ${dir}\n`
|
|
775
|
+
+`To give up without applying: dalan apply ${id} --release (it changes no file).`);
|
|
776
|
+
}
|
|
777
|
+
const reserved=await reserve();
|
|
778
|
+
if(reserved.state==='applied') { files=applyPatch(patchArgs); written=true; result={request_id:id,applied:true,dir,files,decision:'applied'}; }
|
|
779
|
+
else {
|
|
780
|
+
try { files=applyPatch(patchArgs); written=true; }
|
|
781
|
+
catch(e) {
|
|
782
|
+
let released=true; try { await phase('release',{attempt:reserved.attempt,reason:`apply_failed: ${e.message}`.slice(0,500)}); } catch { released=false; }
|
|
783
|
+
throw Object.assign(new Error(`apply_failed: ${e.message}${released?`. ${id} is not applied and can be applied again.`:`. The bridge could not be told; ${id} still shows an apply in progress: run dalan apply ${id} --release, or run it again.`}`),{local_code:'apply_failed'});
|
|
784
|
+
}
|
|
785
|
+
const decided=await confirm(reserved.attempt);
|
|
786
|
+
result={request_id:id,applied:true,dir,files,already_present:false,decision:decided.decision};
|
|
787
|
+
}
|
|
788
|
+
}
|
|
629
789
|
} finally { fs.rmSync(tmp,{recursive:true,force:true}); }
|
|
630
|
-
if(!json) {
|
|
790
|
+
if(!json&&result.already_present) { result=`the patch was already in ${dir}; recorded decision applied for ${id} without writing`; plainOutput=true; }
|
|
791
|
+
else if(!json) { const {files}=result; result=`applied ${files.length} file${files.length===1?'':'s'} in ${dir}; recorded decision applied for ${id}\n${files.map(f=>' '+f).join('\n')}`; plainOutput=true; }
|
|
631
792
|
break;
|
|
632
793
|
}
|
|
633
794
|
case 'integrate': { const id=args[0]; if(!id||id.startsWith('-')) throw new Error('integrate requires request id'); result=await request('/lifecycle','POST',{id,type:'integrated',...(option('--reason')?{reason:option('--reason')}:{})},{'x-operator-key':operator()}); break; }
|
|
@@ -667,7 +828,7 @@ async function main() {
|
|
|
667
828
|
const { DatabaseSync }=await import('node:sqlite'), db=new DatabaseSync(defaultPath(home,'.local/share/dot-bridge/bridge.db'),{readOnly:true});
|
|
668
829
|
const accepted=db.prepare('SELECT count(*) n FROM assignments WHERE created_at>=?').get(new Date(sinceMs).toISOString()).n; db.close();
|
|
669
830
|
result={since:new Date(sinceMs).toISOString(),accepted,refused:summary.refused,refused_fraction:summary.refused+accepted?Math.round(summary.refused/(summary.refused+accepted)*1000)/1000:null,classes:summary.classes,by_kind:summary.by_kind};
|
|
670
|
-
if(!args.includes('--json')) { result=
|
|
831
|
+
if(!args.includes('--json')) { result=formatRejections(summary,{since:result.since,accepted}); plainOutput=true; }
|
|
671
832
|
break;
|
|
672
833
|
}
|
|
673
834
|
// Built-in authorization server. init writes local files only (no running bridge needed); connect talks to the owner socket.
|
|
@@ -700,9 +861,23 @@ async function main() {
|
|
|
700
861
|
case 'reconcile': { const id=args[0]; if(!id) throw new Error('reconcile requires id'); const adopt=args.includes('--adopt'); let ownerToken; if(adopt) ownerToken=writeReceipt(id,randomBytes(32).toString('hex'),'', '').token; result=await request('/reconcile','POST',{id,adopt,owner_token:ownerToken},{'x-operator-key':operator()}); break; }
|
|
701
862
|
case 'verify-stops': { const id=args.find(a=>a!=='--json'); result=await request('/verify-stops','POST',id?{id}:{},{'x-operator-key':operator()}); break; }
|
|
702
863
|
case 'prepare-deps': {
|
|
703
|
-
const
|
|
704
|
-
if(
|
|
705
|
-
|
|
864
|
+
const usage='usage: dalan prepare-deps SOURCE_DIRECTORY [--go|--pnpm] [--json] [--replace-invalid] | dalan prepare-deps --prune [--keep N] [--json]';
|
|
865
|
+
if(args.includes('--prune')) {
|
|
866
|
+
const at=args.indexOf('--keep'),keep=at<0?4:Number(args[at+1]);
|
|
867
|
+
if(args.some((a,i)=>!['--prune','--json','--keep'].includes(a)&&!(at>=0&&i===at+1))||!Number.isInteger(keep)||keep<1) throw new Error(usage);
|
|
868
|
+
result={...pruneNodeStore({keep}),go:pruneGoStore({keep})};
|
|
869
|
+
break;
|
|
870
|
+
}
|
|
871
|
+
const positional=args.filter(a=>!['--json','--replace-invalid','--go','--pnpm'].includes(a));
|
|
872
|
+
if(positional.length!==1||positional[0].startsWith('-')) throw new Error(usage);
|
|
873
|
+
const replaceInvalid=args.includes('--replace-invalid');
|
|
874
|
+
// --go prepares the Go module cache (and the toolchain go.mod asks for); --pnpm (or a pnpm-lock.yaml without a package-lock.json) the pnpm trees; otherwise the npm tree.
|
|
875
|
+
const source=positional[0],has=name=>fs.existsSync(path.join(source,name));
|
|
876
|
+
if(args.includes('--go')) result=prepareGoModules(source,{replaceInvalid});
|
|
877
|
+
else if(args.includes('--pnpm')||(has('pnpm-lock.yaml')&&!has('package-lock.json'))) result=preparePnpm(source,{replaceInvalid});
|
|
878
|
+
else result=prepareNodeModules(source,{replaceInvalid});
|
|
879
|
+
// Keep the shared store that was just written bounded: the newest entries stay, and nothing under a day old is touched.
|
|
880
|
+
try { if(args.includes('--go')) pruneGoStore({}); else pruneNodeStore({}); } catch {}
|
|
706
881
|
break;
|
|
707
882
|
}
|
|
708
883
|
case 'doctor': {
|