@tnunamak/dalan 0.8.1 → 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 +59 -2
- package/CONTRIBUTING.md +2 -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 +121 -34
- 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 +2 -1
- package/docs/manual-setup.md +1 -1
- package/docs/operations.md +77 -14
- package/docs/pull-workers.md +11 -1
- package/docs/service-setup.md +10 -10
- package/docs/t3-integration.md +4 -2
- package/docs/t3-reverse-control.md +5 -5
- package/docs/test-suite-isolation.md +7 -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 +21 -7
- 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/cli-help.mjs +14 -3
- 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/legacy-names.mjs +0 -2
- package/src/lifecycle.mjs +44 -9
- 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 +212 -7
- 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 +503 -98
- 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/store.mjs +876 -120
- 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 +34 -7
- 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/src/mcp-stdio.mjs
CHANGED
|
@@ -5,30 +5,63 @@
|
|
|
5
5
|
import { spawn } from 'node:child_process';
|
|
6
6
|
import { randomUUID } from 'node:crypto';
|
|
7
7
|
import path from 'node:path';
|
|
8
|
-
import readline from 'node:readline';
|
|
9
8
|
import { redactOutput, redactSinkText } from './redaction.mjs';
|
|
10
9
|
import { safeDiagnostic } from './diagnostic.mjs';
|
|
10
|
+
import { MAX_ANSWER_BYTES } from './answer-journal.mjs';
|
|
11
11
|
|
|
12
12
|
export const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
13
13
|
export const RESULT_CAP_BYTES = 32 * 1024;
|
|
14
|
+
export const MAX_INPUT_FRAME_BYTES = 1024 * 1024 + 1;
|
|
14
15
|
const WAIT_DEFAULT = 120, WAIT_MAX = 300;
|
|
16
|
+
const SUBMIT_NEXT = 'Check dalan_status or dalan_result later, or read the inbox.';
|
|
15
17
|
const CLI = path.join(import.meta.dirname, '../bin/dalan.mjs');
|
|
16
|
-
const requestId = { type: 'string', pattern: '
|
|
18
|
+
const requestId = { type: 'string', pattern: '^\\w[-\\w]{7,127}$', description: 'The request_id of a submitted job; it cannot start with a dash.' };
|
|
19
|
+
|
|
20
|
+
const submitProperties = {
|
|
21
|
+
assignment: { type: 'object', description: 'The assignment: request_id (8-128 letters, digits, _ or -; cannot start with a dash), brief, inputs (array; [] for none), expected_output, and the other fields `dalan submit` accepts.',
|
|
22
|
+
required: ['request_id'], properties: { request_id: requestId, brief: { type: 'string' }, inputs: { type: 'array' } } },
|
|
23
|
+
task: { type: 'string', description: 'Task text; maps to assignment.brief. Omit when assignment contains brief, objective or stop_rule.' },
|
|
24
|
+
priority_class: { type: 'string', enum: ['normal', 'background'], description: 'Queue priority (default normal).' },
|
|
25
|
+
requirements: { type: 'array', items: { type: 'string' }, description: 'Required supported backend or adapter capability names.' },
|
|
26
|
+
repo: { type: 'string', description: 'GitHub owner/repo; supply with base and an empty assignment.inputs.' },
|
|
27
|
+
base: { type: 'string', description: 'Full pushed commit SHA; supply with repo.' },
|
|
28
|
+
worker: { type: 'string', description: 'Name of the worker to queue for. Optional with a one-worker profile.' },
|
|
29
|
+
execution: { type: 'string', enum: ['none', 'worker', 'host'], description: 'Execution capability for the job.' }
|
|
30
|
+
};
|
|
17
31
|
|
|
18
32
|
export const TOOLS = [
|
|
19
33
|
{ name: 'dalan_submit', title: 'Submit a job',
|
|
20
34
|
description: 'Queue a bounded job for a Dalan worker (same checks as `dalan submit`). Returns the request_id and the bridge verdict. A clarify or reject verdict comes back as an error result with the reasons; fix the assignment and submit again. Resubmitting the same assignment is safe.',
|
|
21
35
|
inputSchema: { type: 'object', additionalProperties: false, required: ['assignment'], properties: {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
worker: { type: 'string', description: 'Name of the worker to queue for. Optional with a one-worker profile.' },
|
|
25
|
-
execution: { type: 'string', enum: ['none', 'worker', 'host'], description: 'Execution capability for the job.' },
|
|
36
|
+
...submitProperties,
|
|
37
|
+
follows: { ...requestId, description: 'A finished predecessor this bridge home owns. Its result is not copied.' },
|
|
26
38
|
dry_run: { type: 'boolean', description: 'Check the assignment and store nothing.' },
|
|
27
39
|
queue_anyway: { type: 'boolean', description: 'Queue even when the bridge would defer or warn.' },
|
|
28
40
|
refuse_defer: { type: 'boolean', description: 'Fail instead of deferring.' } } },
|
|
29
41
|
annotations: { title: 'Submit a job', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false } },
|
|
42
|
+
{ name: 'dalan_forecast', title: 'Forecast a job',
|
|
43
|
+
description: 'Check a bounded job and estimate its admission without submitting it or reserving capacity. Returns the same verdict as a submit dry run, plus available queue and worker estimates.',
|
|
44
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['assignment'], properties: submitProperties },
|
|
45
|
+
annotations: { title: 'Forecast a job', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } },
|
|
46
|
+
{ name: 'dalan_cancel', title: 'Cancel a job',
|
|
47
|
+
description: 'Stop a queued job or ask the worker on a claimed job to stop. The reply states the job’s state.',
|
|
48
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['request_id'], properties: {
|
|
49
|
+
request_id: requestId,
|
|
50
|
+
reason: { type: 'string', description: 'Optional reason for cancelling the job.' } } },
|
|
51
|
+
annotations: { title: 'Cancel a job', readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false } },
|
|
52
|
+
{ name: 'dalan_accept', title: 'Accept or reject a job result',
|
|
53
|
+
description: 'Record an accept or reject verdict for a job result as its requester, using the existing CLI checks.',
|
|
54
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['request_id', 'verdict'], properties: {
|
|
55
|
+
request_id: requestId, verdict: { type: 'string', enum: ['accept', 'reject'] },
|
|
56
|
+
note: { type: 'string', description: 'Optional note explaining the verdict.' } } },
|
|
57
|
+
annotations: { title: 'Accept or reject a job result', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false } },
|
|
58
|
+
{ name: 'dalan_correct', title: 'Correct an earlier job',
|
|
59
|
+
description: 'Submit a new job to correct an earlier job you submitted. This cancels nothing; the earlier job’s result can no longer be accepted. Returns the new request_id and verdict.',
|
|
60
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['revises', 'assignment'], properties: {
|
|
61
|
+
revises: requestId, ...submitProperties } },
|
|
62
|
+
annotations: { title: 'Correct an earlier job', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false } },
|
|
30
63
|
{ name: 'dalan_wait', title: 'Wait for a job',
|
|
31
|
-
description: `Wait for a job to reach a stop (finished, blocker, question, cancelled, worker_break). Returns after at most timeout_seconds (default ${WAIT_DEFAULT}, maximum ${WAIT_MAX}) with the current state; status "timeout" means it is still running, so call again.`,
|
|
64
|
+
description: `Wait for a job to reach a stop (finished, blocker, question, cancelled, worker_break). Returns after at most timeout_seconds (default ${WAIT_DEFAULT}, maximum ${WAIT_MAX}) with the current state; status "timeout" means it is still running, so call again. If dalan_wait reports a waiting question: call dalan_questions, then dalan_answer, then dalan_wait again.`,
|
|
32
65
|
inputSchema: { type: 'object', additionalProperties: false, required: ['request_id'], properties: {
|
|
33
66
|
request_id: requestId,
|
|
34
67
|
timeout_seconds: { type: 'integer', minimum: 1, maximum: WAIT_MAX, default: WAIT_DEFAULT, description: `Seconds to wait; values above ${WAIT_MAX} are lowered to ${WAIT_MAX}.` } } },
|
|
@@ -37,6 +70,17 @@ export const TOOLS = [
|
|
|
37
70
|
description: `Read the current state of a job, with the worker's report once it has finished. Secrets are redacted and output is capped at ${RESULT_CAP_BYTES / 1024} KiB.`,
|
|
38
71
|
inputSchema: { type: 'object', additionalProperties: false, required: ['request_id'], properties: { request_id: requestId } },
|
|
39
72
|
annotations: { title: 'Read a job result', readOnlyHint: true, openWorldHint: false } },
|
|
73
|
+
{ name: 'dalan_questions', title: 'Read job questions',
|
|
74
|
+
description: 'Read identified questions with the local owner receipt. Several can be open at once; answer each by its question_id, then wait again. Human-only questions still require operator action.',
|
|
75
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['id'], properties: { id: requestId } },
|
|
76
|
+
annotations: { title: 'Read job questions', readOnlyHint: true, openWorldHint: false } },
|
|
77
|
+
{ name: 'dalan_answer', title: 'Answer a job question',
|
|
78
|
+
description: 'Answer an identified clarification through the CLI answer journal. Exact retries reuse the saved envelope; different text for the same saved attempt is refused. Then call dalan_wait again. This cannot answer human-only questions with owner authority alone.',
|
|
79
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['id', 'question_id', 'text'], properties: {
|
|
80
|
+
id: requestId,
|
|
81
|
+
question_id: { type: 'string', pattern: '^(?!-)[A-Za-z0-9_.:-]{1,128}$' },
|
|
82
|
+
text: { type: 'string', description: `Nonblank answer, at most ${MAX_ANSWER_BYTES} UTF-8 bytes. Text beginning with a dash is not supported by the CLI.` } } },
|
|
83
|
+
annotations: { title: 'Answer a job question', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false } },
|
|
40
84
|
{ name: 'dalan_status', title: 'Bridge status',
|
|
41
85
|
description: 'Show the bridge status (`dalan status --json`): queue, workers and health.',
|
|
42
86
|
inputSchema: { type: 'object', additionalProperties: false, properties: {} },
|
|
@@ -58,9 +102,10 @@ function validate(tool, args) {
|
|
|
58
102
|
for (const [key, value] of Object.entries(args)) {
|
|
59
103
|
const spec = properties[key];
|
|
60
104
|
if (spec.type === 'object' ? !value || typeof value !== 'object' || Array.isArray(value)
|
|
61
|
-
: spec.type === 'integer' ? !Number.isInteger(value) : typeof value !== spec.type) throw fail(`argument "${key}" must be ${spec.type === 'object' ? 'an object' : `a ${spec.type}`}`);
|
|
105
|
+
: spec.type === 'integer' ? !Number.isInteger(value) : spec.type === 'array' ? !Array.isArray(value) : typeof value !== spec.type) throw fail(`argument "${key}" must be ${spec.type === 'object' ? 'an object' : `a ${spec.type}`}`);
|
|
106
|
+
if (spec.type === 'array' && value.some(item => typeof item !== 'string' || !item || item.includes(',') || item.includes('\u0000'))) throw fail(`argument "${key}" must contain nonempty capability names`);
|
|
62
107
|
if (spec.enum && !spec.enum.includes(value)) throw fail(`argument "${key}" must be one of ${spec.enum.join(', ')}`);
|
|
63
|
-
if (spec.pattern && !new RegExp(spec.pattern).test(value)) throw fail(`argument "${key}" is not a valid request id (8-128 letters, digits, _ or
|
|
108
|
+
if (spec.pattern && !new RegExp(spec.pattern).test(value)) throw fail(`argument "${key}" is not a valid request id (8-128 letters, digits, _ or -; cannot start with a dash)`);
|
|
64
109
|
if (spec.type === 'string' && value.startsWith('--')) throw fail(`argument "${key}" must not start with --`);
|
|
65
110
|
}
|
|
66
111
|
return args;
|
|
@@ -69,14 +114,19 @@ function validate(tool, args) {
|
|
|
69
114
|
// Run `dalan <args> --json`. stdout and stderr are collected, never forwarded: stdout of this process is the protocol.
|
|
70
115
|
function runCli(args, { input, timeoutMs = 60_000, env = process.env } = {}) {
|
|
71
116
|
return new Promise(resolve => {
|
|
72
|
-
|
|
117
|
+
let child;
|
|
118
|
+
try { child = spawn(process.execPath, [CLI, ...args, '--json'], { env, stdio: ['pipe', 'pipe', 'pipe'] }); }
|
|
119
|
+
catch { resolve({ code: null, termination: 'exec_failed' }); return; }
|
|
73
120
|
let stdout = '', stderr = '', done = false;
|
|
74
121
|
const finish = value => { if (!done) { done = true; clearTimeout(timer); resolve(value); } };
|
|
75
|
-
const timer = setTimeout(() => {
|
|
122
|
+
const timer = setTimeout(() => {
|
|
123
|
+
finish({ code: null, termination: 'deadline', timeoutMs });
|
|
124
|
+
child.kill('SIGKILL');
|
|
125
|
+
}, timeoutMs);
|
|
76
126
|
child.stdout.on('data', chunk => { stdout += chunk; });
|
|
77
127
|
child.stderr.on('data', chunk => { stderr += chunk; });
|
|
78
|
-
child.on('error',
|
|
79
|
-
child.on('close', code => finish({ code, stdout, stderr }));
|
|
128
|
+
child.on('error', () => finish({ code: null, termination: 'exec_failed' }));
|
|
129
|
+
child.on('close', (code, signal) => finish({ code, signal, stdout, stderr }));
|
|
80
130
|
child.stdin.on('error', () => {});
|
|
81
131
|
child.stdin.end(input ?? '');
|
|
82
132
|
});
|
|
@@ -85,10 +135,19 @@ const parseJson = text => { try { return JSON.parse(text); } catch { return unde
|
|
|
85
135
|
// stderr may hold warnings before the final error JSON line.
|
|
86
136
|
const lastJsonLine = text => text.trim().split('\n').reverse().map(parseJson).find(v => v && typeof v === 'object');
|
|
87
137
|
|
|
138
|
+
const RETRYABLE_CLI_READS = new Set(['forecast', 'wait', 'get', 'questions', 'status']);
|
|
88
139
|
export function cliError(run, label) {
|
|
89
|
-
|
|
140
|
+
if (run.termination === 'deadline') {
|
|
141
|
+
return { isError: true, value: { code: 'cli_deadline', retryable: RETRYABLE_CLI_READS.has(label),
|
|
142
|
+
error: `dalan ${label} did not answer within ${Math.round(run.timeoutMs / 1000)}s` } };
|
|
143
|
+
}
|
|
144
|
+
if (run.termination === 'exec_failed') {
|
|
145
|
+
return { isError: true, value: { code: 'cli_exec_failed', retryable: false, error: `could not start dalan ${label}` } };
|
|
146
|
+
}
|
|
147
|
+
const body = run.code === null ? undefined : lastJsonLine(run.stderr) ?? lastJsonLine(run.stdout);
|
|
90
148
|
if (body) return { isError: true, value: body };
|
|
91
|
-
|
|
149
|
+
const exit = run.signal ? ` (signal ${run.signal})` : run.code === null ? '' : ` (exit ${run.code})`;
|
|
150
|
+
return { isError: true, message: `${label} failed${exit}: ${safeDiagnostic((run.stderr || run.stdout).trim(), 4000) || 'no output'}` };
|
|
92
151
|
}
|
|
93
152
|
|
|
94
153
|
function capped(value) {
|
|
@@ -106,23 +165,73 @@ const asResult = ({ isError, value, message }) => {
|
|
|
106
165
|
return { content: [{ type: 'text', text }], ...(structured && typeof structured === 'object' ? { structuredContent: structured } : {}), ...(isError ? { isError: true } : {}) };
|
|
107
166
|
};
|
|
108
167
|
|
|
168
|
+
const pick = (value, keys) => Object.fromEntries(keys.filter(key => Object.hasOwn(value, key)).map(key => [key, value[key]]));
|
|
169
|
+
const claimDurationProjection = value => pick(value, ['source', 'n', 'min_samples', 'p50_ms']);
|
|
170
|
+
const sessionLengthProjection = value => pick(value, ['source', 'n', 'min_samples', 'window_days', 'p50_ms']);
|
|
171
|
+
const recordProjection = record => ({ ...pick(record, ['worker', 'kind', 'window_days', 'n', 'accepted', 'check_passed']),
|
|
172
|
+
...(record.claim_to_report ? { claim_to_report: claimDurationProjection(record.claim_to_report) } : {}),
|
|
173
|
+
...(record.session_length ? { session_length: sessionLengthProjection(record.session_length) } : {}),
|
|
174
|
+
...(record.outcomes ? { outcomes: pick(record.outcomes, ['landed', 'check_passed', 'checks_failed', 'refused_by_provider', 'unable_to_run', 'owner_cancelled', 'finished_unchecked']) } : {}) });
|
|
175
|
+
export function projectAdmission(admission) {
|
|
176
|
+
const answer = pick(admission, ['start', 'worker_state', 'until', 'until_source', 'at']);
|
|
177
|
+
if (admission.ahead) answer.ahead = pick(admission.ahead, ['count', 'oldest_age_ms']);
|
|
178
|
+
if (admission.latency) {
|
|
179
|
+
const latency = admission.latency;
|
|
180
|
+
answer.latency = pick(latency, ['worker', 'kind', 'window_days', 'min_samples']);
|
|
181
|
+
if (latency.censored) answer.latency.censored = pick(latency.censored, ['expired_unclaimed', 'cancelled_unclaimed', 'claimed_not_started', 'finished_unobserved_start']);
|
|
182
|
+
for (const key of ['claimed', 'started']) if (latency[key]) answer.latency[key] = pick(latency[key], ['n', 'p50_ms', 'p90_ms', 'insufficient_history']);
|
|
183
|
+
}
|
|
184
|
+
if (admission.track_record) answer.track_record = recordProjection(admission.track_record);
|
|
185
|
+
if (admission.claim_to_report) answer.claim_to_report = claimDurationProjection(admission.claim_to_report);
|
|
186
|
+
if (admission.session_length) answer.session_length = sessionLengthProjection(admission.session_length);
|
|
187
|
+
return answer;
|
|
188
|
+
}
|
|
189
|
+
const projectAnswer = value => ({ ...value, ...(value.admission ? { admission: projectAdmission(value.admission) } : {}),
|
|
190
|
+
...(value.track_record ? { track_record: recordProjection(value.track_record) } : {}) });
|
|
191
|
+
|
|
192
|
+
const forecastAnswer = value => Object.fromEntries(['verdict', 'reasons', 'admission', 'track_record']
|
|
193
|
+
.filter(key => Object.hasOwn(value, key)).map(key => [key, value[key]]));
|
|
194
|
+
|
|
195
|
+
async function submit(args, extraFlags = [], {forecast = false} = {}) {
|
|
196
|
+
if (args.worker?.startsWith('-') || args.worker?.includes('\u0000')) throw fail('worker name must not start with a dash or contain NUL');
|
|
197
|
+
if ((args.repo === undefined) !== (args.base === undefined)) throw fail('repo and base must be supplied together');
|
|
198
|
+
if (args.task !== undefined && ['brief', 'objective', 'stop_rule'].some(field => args.assignment[field] !== undefined)) throw fail('supply task or assignment brief/objective/stop_rule, not both');
|
|
199
|
+
if (args.repo !== undefined && (!Array.isArray(args.assignment.inputs) || args.assignment.inputs.length)) throw fail('repo and base require empty assignment.inputs');
|
|
200
|
+
const assignment = { ...args.assignment, ...(args.task !== undefined ? { brief: args.task } : {}),
|
|
201
|
+
...(args.repo !== undefined ? { inputs: [{ github_repo: args.repo, base_sha: args.base, head_sha: args.base }] } : {}) };
|
|
202
|
+
const flags = [...extraFlags, ...(forecast ? ['--dry-run'] : [])];
|
|
203
|
+
if (args.worker) flags.push('--worker', args.worker);
|
|
204
|
+
if (args.execution) flags.push('--execution', args.execution);
|
|
205
|
+
if (args.priority_class === 'background') flags.push('--background');
|
|
206
|
+
if (args.requirements?.length) flags.push('--require-capability', args.requirements.join(','));
|
|
207
|
+
for (const [key, flag] of [['dry_run', '--dry-run'], ['queue_anyway', '--queue-anyway'], ['refuse_defer', '--refuse-defer']]) if (!forecast && args[key]) flags.push(flag);
|
|
208
|
+
const run = await runCli(['submit', '--stdin', ...flags], { input: JSON.stringify(assignment) });
|
|
209
|
+
const value = run.code === null ? undefined : parseJson(run.stdout);
|
|
210
|
+
// A dry run exits non-zero for clarify, reject and defer but still prints the verdict on stdout.
|
|
211
|
+
if (value !== undefined) return asResult({ value: projectAnswer(forecast ? forecastAnswer(value) : { ...value, next: SUBMIT_NEXT }), isError: run.code !== 0 && (value.verdict ? value.verdict !== 'admissible' : true) });
|
|
212
|
+
const error = cliError(run, forecast ? 'forecast' : 'submit');
|
|
213
|
+
if (error.value !== undefined) error.value = projectAnswer(forecast && error.value.verdict ? forecastAnswer(error.value) : error.value);
|
|
214
|
+
return asResult(error);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function ownerTransition(command, id, flag, text) {
|
|
218
|
+
if (text?.startsWith('-') || text?.includes('\u0000')) throw fail(flag.slice(2) + ' text must not start with a dash or contain NUL');
|
|
219
|
+
const run = await runCli([command, id, ...(text === undefined ? [] : [flag, text])]);
|
|
220
|
+
const value = run.code === 0 ? parseJson(run.stdout) : undefined;
|
|
221
|
+
return value !== undefined ? asResult({ value }) : asResult(cliError(run, command));
|
|
222
|
+
}
|
|
223
|
+
|
|
109
224
|
const handlers = {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const run = await runCli(['submit', '--stdin', ...flags], { input: JSON.stringify(args.assignment) });
|
|
116
|
-
const value = parseJson(run.stdout);
|
|
117
|
-
// A dry run exits non-zero for clarify, reject and defer but still prints the verdict on stdout.
|
|
118
|
-
if (value !== undefined) return asResult({ value, isError: run.code !== 0 && (value.verdict ? value.verdict !== 'admissible' : true) });
|
|
119
|
-
return asResult(cliError(run, 'submit'));
|
|
120
|
-
},
|
|
225
|
+
dalan_submit: args => submit(args, args.follows ? ['--follows', args.follows] : []),
|
|
226
|
+
dalan_forecast: args => submit(args, [], {forecast: true}),
|
|
227
|
+
dalan_correct: args => submit(args, ['--revises', args.revises]),
|
|
228
|
+
dalan_cancel: args => ownerTransition('cancel', args.request_id, '--reason', args.reason),
|
|
229
|
+
dalan_accept: args => ownerTransition(args.verdict, args.request_id, '--note', args.note),
|
|
121
230
|
async dalan_wait(args) {
|
|
122
231
|
const seconds = Math.min(args.timeout_seconds ?? WAIT_DEFAULT, WAIT_MAX);
|
|
123
232
|
const run = await runCli(['wait', args.request_id, '--timeout', String(Math.max(1, seconds))], { timeoutMs: (seconds + 30) * 1000 });
|
|
124
233
|
// wait exits 3, 4, 5 and 124 for non-finished states; the JSON on stdout is the state, not a failure.
|
|
125
|
-
const value = parseJson(run.stdout);
|
|
234
|
+
const value = run.code === null ? undefined : parseJson(run.stdout);
|
|
126
235
|
return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'wait'));
|
|
127
236
|
},
|
|
128
237
|
async dalan_result(args) {
|
|
@@ -130,6 +239,21 @@ const handlers = {
|
|
|
130
239
|
const value = run.code === 0 ? parseJson(run.stdout) : undefined;
|
|
131
240
|
return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'get'));
|
|
132
241
|
},
|
|
242
|
+
async dalan_questions(args) {
|
|
243
|
+
const run = await runCli(['questions', args.id]);
|
|
244
|
+
const value = run.code === 0 ? parseJson(run.stdout) : undefined;
|
|
245
|
+
return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'questions'));
|
|
246
|
+
},
|
|
247
|
+
async dalan_answer(args) {
|
|
248
|
+
if (!args.text.trim()) throw fail('answer text must not be blank');
|
|
249
|
+
if (Buffer.byteLength(args.text) > MAX_ANSWER_BYTES) throw fail(`answer text exceeds ${MAX_ANSWER_BYTES} UTF-8 bytes; nothing was sent or saved`);
|
|
250
|
+
// The CLI treats leading dashes as options and argv cannot carry NUL.
|
|
251
|
+
if (args.text.startsWith('-') || args.text.includes('\u0000')) throw fail('answer text must not start with a dash or contain NUL');
|
|
252
|
+
if (args.question_id.startsWith('-') || args.question_id.includes('\u0000')) throw fail('question_id must not start with a dash or contain NUL');
|
|
253
|
+
const run = await runCli(['answer', args.id, args.question_id, args.text]);
|
|
254
|
+
const value = run.code === 0 ? parseJson(run.stdout) : undefined;
|
|
255
|
+
return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'answer'));
|
|
256
|
+
},
|
|
133
257
|
async dalan_status() {
|
|
134
258
|
const run = await runCli(['status']);
|
|
135
259
|
const value = run.code === 0 ? parseJson(run.stdout) : undefined;
|
|
@@ -154,6 +278,9 @@ const rpcError = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, me
|
|
|
154
278
|
|
|
155
279
|
// One JSON-RPC message in, zero or one frame out. Never throws.
|
|
156
280
|
export async function handleFrame(message) {
|
|
281
|
+
const candidateId = message?.id;
|
|
282
|
+
if (candidateId !== undefined && candidateId !== null && typeof candidateId !== 'string' &&
|
|
283
|
+
(typeof candidateId !== 'number' || !Number.isFinite(candidateId))) return rpcError(null, -32600, 'invalid request');
|
|
157
284
|
if (!message || typeof message !== 'object' || Array.isArray(message) || message.jsonrpc !== '2.0' || typeof message.method !== 'string') return rpcError(message?.id ?? null, -32600, 'invalid request');
|
|
158
285
|
const { id, method, params } = message;
|
|
159
286
|
if (id === undefined) return null; // notification
|
|
@@ -161,7 +288,7 @@ export async function handleFrame(message) {
|
|
|
161
288
|
switch (method) {
|
|
162
289
|
case 'initialize': return ok({ protocolVersion: PROTOCOL_VERSIONS.includes(params?.protocolVersion) ? params.protocolVersion : PROTOCOL_VERSIONS[0],
|
|
163
290
|
capabilities: { tools: {} }, serverInfo: { name: 'dalan-mcp', version: '1' },
|
|
164
|
-
instructions: 'Local requester tools for a Dalan bridge: dalan_submit queues a job, dalan_wait waits for it, dalan_result reads the report, dalan_status shows the bridge.' });
|
|
291
|
+
instructions: 'Local requester tools for a Dalan bridge: dalan_submit queues a job, dalan_wait waits for it; on a waiting question call dalan_questions, dalan_answer, then dalan_wait again. dalan_result reads the report, dalan_status shows the bridge.' });
|
|
165
292
|
case 'ping': return ok({});
|
|
166
293
|
case 'tools/list': return ok({ tools: TOOLS });
|
|
167
294
|
case 'tools/call': {
|
|
@@ -173,10 +300,45 @@ export async function handleFrame(message) {
|
|
|
173
300
|
}
|
|
174
301
|
}
|
|
175
302
|
|
|
176
|
-
|
|
303
|
+
// One reusable bounded byte buffer; don't decode a frame that exceeded the
|
|
304
|
+
// limit. The extra byte admits CRLF without charging the CR to the JSON body.
|
|
305
|
+
async function* inputFrames(input, limit) {
|
|
306
|
+
const frame = Buffer.allocUnsafe(limit + 1);
|
|
307
|
+
let used = 0, discard = false;
|
|
308
|
+
const read = () => {
|
|
309
|
+
const size = used && frame[used - 1] === 13 ? used - 1 : used;
|
|
310
|
+
return discard || size > limit ? null : frame.subarray(0, size).toString('utf8');
|
|
311
|
+
};
|
|
312
|
+
for await (const chunk of input) {
|
|
313
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
314
|
+
for (let offset = 0; offset < bytes.length;) {
|
|
315
|
+
const newline = bytes.indexOf(10, offset);
|
|
316
|
+
const end = newline === -1 ? bytes.length : newline;
|
|
317
|
+
if (!discard) {
|
|
318
|
+
if (end - offset > frame.length - used) discard = true;
|
|
319
|
+
else {
|
|
320
|
+
bytes.copy(frame, used, offset, end);
|
|
321
|
+
used += end - offset;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (newline === -1) break;
|
|
325
|
+
yield read();
|
|
326
|
+
used = 0;
|
|
327
|
+
discard = false;
|
|
328
|
+
offset = newline + 1;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
if (used || discard) yield read();
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export async function main({ input = process.stdin, output = process.stdout, maxFrameBytes = MAX_INPUT_FRAME_BYTES } = {}) {
|
|
335
|
+
if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0 || maxFrameBytes > MAX_INPUT_FRAME_BYTES) {
|
|
336
|
+
throw new RangeError('invalid stdio frame limit');
|
|
337
|
+
}
|
|
177
338
|
const inflight = new Set();
|
|
178
339
|
const write = frame => output.write(`${JSON.stringify(frame)}\n`);
|
|
179
|
-
for await (const line of
|
|
340
|
+
for await (const line of inputFrames(input, maxFrameBytes)) {
|
|
341
|
+
if (line === null) { write(rpcError(null, -32600, 'request frame exceeds byte limit')); continue; }
|
|
180
342
|
if (!line.trim()) continue;
|
|
181
343
|
let message;
|
|
182
344
|
try { message = JSON.parse(line); }
|
package/src/patch-apply.mjs
CHANGED
|
@@ -4,13 +4,204 @@ import { spawnSync } from 'node:child_process';
|
|
|
4
4
|
import { createHash } from 'node:crypto';
|
|
5
5
|
import fs from 'node:fs';
|
|
6
6
|
import path from 'node:path';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import { workGrantProblem } from './publication-authority.mjs';
|
|
9
|
+
import { writableScope } from './workspace.mjs';
|
|
7
10
|
|
|
8
|
-
const git = (dir, args, input, env) => spawnSync('git', ['-C', dir, ...args], { input, encoding
|
|
11
|
+
const git = (dir, args, input, env, encoding = "utf8") => spawnSync((env ?? process.env).DALAN_GIT || 'git', ['-C', dir, ...args], { input, encoding, maxBuffer: 64 * 1024 * 1024, env });
|
|
12
|
+
|
|
13
|
+
const materializeName = '[A-Za-z0-9][A-Za-z0-9_.-]*';
|
|
14
|
+
const materializeRepo = new RegExp('^' + materializeName + '/' + materializeName + '$');
|
|
15
|
+
const materializeEntry = new RegExp('^(?:org:' + materializeName + '|repo:' + materializeName + '/' + materializeName + ')$');
|
|
16
|
+
const grantError = (local_code, message) => Object.assign(new Error(local_code + ': ' + message), {local_code});
|
|
17
|
+
|
|
18
|
+
export function readMaterializeGrant(file) {
|
|
19
|
+
let fd;
|
|
20
|
+
try {
|
|
21
|
+
fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
22
|
+
} catch (error) {
|
|
23
|
+
if (error.code === 'ENOENT') return null;
|
|
24
|
+
throw grantError('materialize_grant_unsafe', 'cannot safely open the owner grant file');
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
const state = fs.fstatSync(fd);
|
|
28
|
+
if (!state.isFile() || typeof process.getuid !== 'function' || state.uid !== process.getuid() || (state.mode & 0o7777) !== 0o600) {
|
|
29
|
+
throw grantError('materialize_grant_unsafe', 'the owner grant must be a regular owner-owned mode 0600 file');
|
|
30
|
+
}
|
|
31
|
+
let parsed;
|
|
32
|
+
try {
|
|
33
|
+
if (state.size > 16 * 1024) throw new Error('too large');
|
|
34
|
+
parsed = JSON.parse(fs.readFileSync(fd, 'utf8'));
|
|
35
|
+
} catch {
|
|
36
|
+
throw grantError('materialize_grant_invalid', 'expected a small JSON grant document');
|
|
37
|
+
}
|
|
38
|
+
if (!parsed || typeof parsed !== 'object' || Object.keys(parsed).length !== 2 ||
|
|
39
|
+
!['standing', 'per_pr'].includes(parsed.mode) || !Array.isArray(parsed.grant) ||
|
|
40
|
+
!parsed.grant.every(entry => typeof entry === 'string' && materializeEntry.test(entry))) {
|
|
41
|
+
throw grantError('materialize_grant_invalid', 'expected mode standing or per_pr and exact org: or repo: entries');
|
|
42
|
+
}
|
|
43
|
+
return parsed;
|
|
44
|
+
} finally { fs.closeSync(fd); }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function materializeDecision(grant, repo, requestId, authority) {
|
|
48
|
+
if (typeof repo !== 'string' || !materializeRepo.test(repo) || !/^[-\w]{8,128}$/.test(requestId)) {
|
|
49
|
+
throw grantError('materialize_result_invalid', 'expected one exact repository and a valid request ID');
|
|
50
|
+
}
|
|
51
|
+
const [org] = repo.toLowerCase().split('/');
|
|
52
|
+
const installed = !!grant?.grant.some(entry => ['org:' + org, 'repo:' + repo.toLowerCase()].includes(entry.toLowerCase()));
|
|
53
|
+
// The install file may only narrow what the work's own grant allows; it cannot stand in for it.
|
|
54
|
+
const workProblem = installed ? workGrantProblem(authority, repo) : null;
|
|
55
|
+
const eligible = installed && !workProblem;
|
|
56
|
+
const push = eligible && grant.mode === 'standing';
|
|
57
|
+
const needs_approval = eligible && grant.mode === 'per_pr';
|
|
58
|
+
return { push, draft_pr: push, needs_approval, branch: 'dalan/' + requestId,
|
|
59
|
+
reason: push ? 'standing_grant' : needs_approval ? 'per_pr_approval_required' : workProblem ?? 'no_standing_grant' };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
// Shared owner-side publication path. Approval and formatting belong to the caller.
|
|
64
|
+
export async function materialize({id, got, dir, grantFile, download, recheck,
|
|
65
|
+
dryRun=false, approve=false, standingOnly=false, fetchBase=false}) {
|
|
66
|
+
const grant=readMaterializeGrant(grantFile);
|
|
67
|
+
if(got.status!=='finished'||got.revised_by) throw new Error('materialize needs a current, finished result');
|
|
68
|
+
const ev=got.report?.workspace_evidence, art=ev?.patch_artifact, inputs=got.assignment?.inputs;
|
|
69
|
+
if(!Array.isArray(inputs)||inputs.length!==1||!art?.artifact_id||!art.size||!/^[a-f0-9]{64}$/.test(art.sha256??'')) {
|
|
70
|
+
throw new Error('materialize needs one repository and a sealed patch');
|
|
71
|
+
}
|
|
72
|
+
const repo=inputs[0].github_repo, base_sha=ev.base_sha??inputs[0].base_sha;
|
|
73
|
+
if(!/^[a-f0-9]{40}$/.test(base_sha??'')) throw new Error('materialize needs a pinned base commit');
|
|
74
|
+
const decision=materializeDecision(grant,repo,id,got.publication_authority);
|
|
75
|
+
const result={request_id:id,repo,base_sha,files:[],decision,published:false,branch:decision.branch,reason:decision.reason};
|
|
76
|
+
if(standingOnly && !decision.push) return result;
|
|
77
|
+
const temp=fs.mkdtempSync(path.join(os.tmpdir(),'dalan-materialize-'));
|
|
78
|
+
try {
|
|
79
|
+
const body=Buffer.from(await download(art));
|
|
80
|
+
if(createHash('sha256').update(body).digest('hex')!==art.sha256||body.length!==art.size) throw new Error('materialize patch does not match the report');
|
|
81
|
+
result.files=listPatchFiles(temp,body);
|
|
82
|
+
// The patch may touch only what the work was allowed to change. Anything else is kept as a patch and never pushed.
|
|
83
|
+
const inScope=got.assignment?.execution_scope?writableScope(got.assignment):null;
|
|
84
|
+
const outside=inScope?result.files.filter(file=>!inScope(file)):[];
|
|
85
|
+
if(outside.length) {
|
|
86
|
+
result.decision={...decision,push:false,draft_pr:false,needs_approval:false,reason:'patch_outside_scope',outside_scope:outside};
|
|
87
|
+
result.reason='patch_outside_scope';
|
|
88
|
+
return result;
|
|
89
|
+
}
|
|
90
|
+
if(!dryRun && (decision.push || decision.needs_approval && approve)) {
|
|
91
|
+
const title=String(got.assignment?.title ?? 'Dalan patch '+id).split(/\r?\n/,1)[0].trim().slice(0,240) || 'Dalan patch '+id;
|
|
92
|
+
const summary=String(got.report?.summary ?? 'Patch for Dalan assignment '+id+'.').slice(0,30000);
|
|
93
|
+
Object.assign(result,await materializePatch({dir,temp,body,sha256:art.sha256,baseSha:base_sha,
|
|
94
|
+
repo,branch:decision.branch,title,summary,fetchBase,recheck:async(phase='push')=>{
|
|
95
|
+
const current=await recheck();
|
|
96
|
+
const after=phase==='pr' ? 'the branch was pushed, so it exists, but no draft pull request was opened' : 'nothing pushed';
|
|
97
|
+
if(current.status!=='finished'||current.revised_by||current.report?.workspace_evidence?.patch_artifact?.sha256!==art.sha256) {
|
|
98
|
+
throw new Error('materialize result changed before publication; '+after);
|
|
99
|
+
}
|
|
100
|
+
const currentDecision=materializeDecision(readMaterializeGrant(grantFile),repo,id,current.publication_authority);
|
|
101
|
+
if(!currentDecision.push && !(currentDecision.needs_approval && approve)) {
|
|
102
|
+
throw new Error('materialize authority changed before publication ('+currentDecision.reason+'); '+after);
|
|
103
|
+
}
|
|
104
|
+
}}));
|
|
105
|
+
}
|
|
106
|
+
result.published=!!result.pr_url;
|
|
107
|
+
return result;
|
|
108
|
+
} finally { fs.rmSync(temp,{recursive:true,force:true}); }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Only a matching GitHub push URL is eligible. Match the exact path, not a substring
|
|
112
|
+
// or an arbitrary remote helper. Do not use an implicit push refspec or default remote.
|
|
113
|
+
function githubPushRepo(url) {
|
|
114
|
+
const ssh = /^git@github\.com:([a-z0-9_.-]+\/[a-z0-9_.-]+)$/i.exec(url);
|
|
115
|
+
const absolute = /^(?:https:\/\/github\.com|ssh:\/\/git@github\.com)\/([a-z0-9_.-]+\/[a-z0-9_.-]+)$/i.exec(url);
|
|
116
|
+
return (ssh?.[1] ?? absolute?.[1])?.replace(/\.git$/i, '').toLowerCase();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function materializePatch({dir, temp, body, sha256, baseSha, repo, branch, title, summary, recheck, fetchBase=false}) {
|
|
120
|
+
if(typeof dir!=='string' || !path.isAbsolute(dir)) throw new Error('materialize requires a checkout directory');
|
|
121
|
+
const ref = 'refs/heads/' + branch;
|
|
122
|
+
if (!materializeRepo.test(repo) || !/^dalan\/[-\w]{8,128}$/.test(branch) || !/^[a-f0-9]{40}$/.test(baseSha)) {
|
|
123
|
+
throw new Error('materialize needs a pinned GitHub repo and a scoped branch');
|
|
124
|
+
}
|
|
125
|
+
const run = (program, cwd, args, label) => {
|
|
126
|
+
const r = spawnSync(program, args, {cwd, encoding:'utf8', maxBuffer:1024*1024});
|
|
127
|
+
if(r.error || r.status!==0) throw new Error('materialize: '+label+' failed'+(r.status==null?'':' (exit '+r.status+')'));
|
|
128
|
+
return r.stdout.trim();
|
|
129
|
+
};
|
|
130
|
+
const gitCmd = (cwd, args, label) => run(process.env.DALAN_GIT || 'git',cwd,['-c','core.hooksPath=/dev/null', ...args],label);
|
|
131
|
+
const ghRepo = 'github.com/' + repo;
|
|
132
|
+
const ghCmd = (args, label) => run(process.env.DALAN_GH || 'gh',dir,args,label);
|
|
133
|
+
// Require a real checkout, including when it is a linked worktree.
|
|
134
|
+
gitCmd(dir,['rev-parse','--show-toplevel'],'verify checkout');
|
|
135
|
+
const urls = new Map();
|
|
136
|
+
for(const remote of gitCmd(dir,['remote'],'list remotes').split(/\r?\n/).filter(Boolean)) {
|
|
137
|
+
const values = gitCmd(dir,['remote','get-url','--push','--all','--',remote],'read push URL').split(/\r?\n/);
|
|
138
|
+
if (values.length === 1 && githubPushRepo(values[0]) === repo.toLowerCase()) urls.set(remote,values[0]);
|
|
139
|
+
}
|
|
140
|
+
if (urls.size !== 1) throw new Error('materialize requires one matching GitHub push URL');
|
|
141
|
+
const [[, remote]] = urls;
|
|
142
|
+
if(fetchBase && git(dir,['cat-file','-e',baseSha+'^{commit}']).status!==0) {
|
|
143
|
+
// Fetch only from the already matched push URL, even if the remote's fetch URL differs.
|
|
144
|
+
gitCmd(dir,['fetch','--no-tags',remote,baseSha],'fetch pinned base commit');
|
|
145
|
+
}
|
|
146
|
+
const targetBase = ghCmd(['repo','view',ghRepo,'--json','defaultBranchRef','--jq','.defaultBranchRef.name'],'read repository default branch');
|
|
147
|
+
if(!targetBase || targetBase===branch) throw new Error('materialize cannot target the default branch for a push');
|
|
148
|
+
gitCmd(dir,['check-ref-format','refs/heads/'+targetBase],'verify repository default branch');
|
|
149
|
+
const worktree = path.join(temp,'checkout');
|
|
150
|
+
gitCmd(dir,['worktree','add','--detach',worktree,baseSha],'create detached worktree');
|
|
151
|
+
let failure;
|
|
152
|
+
try {
|
|
153
|
+
applyPatch({dir:worktree, patch:body, sha256, baseSha});
|
|
154
|
+
gitCmd(worktree,['add','-A','--','.'],'stage patch');
|
|
155
|
+
gitCmd(worktree,['commit','--no-gpg-sign','-m','Materialize '+branch],'commit patch with local identity');
|
|
156
|
+
const tip = gitCmd(worktree,['ls-remote','--heads',remote,ref],'inspect scoped remote branch');
|
|
157
|
+
if(tip) {
|
|
158
|
+
const cols=tip.split(/\s+/);
|
|
159
|
+
if(cols.length!==2 || !/^[a-f0-9]{40}$/.test(cols[0]) || cols[1]!==ref) throw new Error('materialize received an invalid remote ref');
|
|
160
|
+
gitCmd(worktree,['fetch','--no-tags','--no-write-fetch-head',remote,cols[0]],'read the existing scoped branch');
|
|
161
|
+
const existing=gitCmd(worktree,['show','-s','--format=%P %T',cols[0]],'read existing branch tree');
|
|
162
|
+
const candidate=gitCmd(worktree,['show','-s','--format=%P %T','HEAD'],'read candidate tree');
|
|
163
|
+
if(existing!==candidate) throw new Error('materialize will not replace the existing branch with different content');
|
|
164
|
+
}
|
|
165
|
+
await recheck('push');
|
|
166
|
+
// Expect absence at the server, even if another publisher races this push.
|
|
167
|
+
if(!tip) gitCmd(worktree,['push','--no-follow-tags','--force-with-lease='+ref+':',remote,'HEAD:'+ref],'create scoped remote branch');
|
|
168
|
+
let pr_url;
|
|
169
|
+
try {
|
|
170
|
+
// The push can finish after the owner changes or withdraws approval.
|
|
171
|
+
await recheck('pr');
|
|
172
|
+
try {
|
|
173
|
+
pr_url=ghCmd(['pr','create','--repo',ghRepo,'--draft','--base',targetBase,'--head',branch,
|
|
174
|
+
'--title',title,'--body',summary],'open draft pull request');
|
|
175
|
+
} catch(error) {
|
|
176
|
+
// A create call can fail after the draft was opened, and a replay can find the draft
|
|
177
|
+
// the first publication opened. Look for it before reporting failure.
|
|
178
|
+
try {
|
|
179
|
+
pr_url=ghCmd(['pr','list','--repo',ghRepo,'--state','open','--base',targetBase,'--head',branch,
|
|
180
|
+
'--json','url,isDraft','--jq','.[] | select(.isDraft) | .url'],'find existing draft pull request');
|
|
181
|
+
} catch { throw error; }
|
|
182
|
+
if(!pr_url) throw error;
|
|
183
|
+
}
|
|
184
|
+
const prefix='https://github.com/'+repo.toLowerCase()+'/pull/';
|
|
185
|
+
if(!pr_url.toLowerCase().startsWith(prefix) || !/^[1-9]\d*$/.test(pr_url.slice(prefix.length))) {
|
|
186
|
+
throw new Error('materialize did not receive the draft pull request URL');
|
|
187
|
+
}
|
|
188
|
+
} catch(error) {
|
|
189
|
+
throw new Error('materialize branch '+branch+' exists; draft pull request not confirmed. '+error.message);
|
|
190
|
+
}
|
|
191
|
+
return {branch,pr_url};
|
|
192
|
+
} catch(error) {
|
|
193
|
+
failure=error;
|
|
194
|
+
throw error;
|
|
195
|
+
} finally {
|
|
196
|
+
try {gitCmd(dir,['worktree','remove','--force',worktree],'remove temporary worktree');}
|
|
197
|
+
catch(error) { if(!failure) throw error; }
|
|
198
|
+
}
|
|
199
|
+
}
|
|
9
200
|
|
|
10
201
|
// git apply from a subdirectory can silently skip root-relative paths.
|
|
11
202
|
export function worktreeRoot(dir, env) {
|
|
12
|
-
const root = git(dir, ['rev-parse', '--show-toplevel'], undefined, env);
|
|
13
|
-
return root.status === 0 ? root.stdout.replace(/\r?\n$/, '') : null;
|
|
203
|
+
const root = git(dir, ['rev-parse', '--show-toplevel'], undefined, env, 'buffer');
|
|
204
|
+
return root.status === 0 ? decodePatchPathOutput(root.stdout).replace(/\r?\n$/, '') : null;
|
|
14
205
|
}
|
|
15
206
|
|
|
16
207
|
// What the patch can touch, read before it runs: each named file's bytes, mode or link target, or its absence, and the
|
|
@@ -69,11 +260,18 @@ export function baseProblem(dir, baseSha, env) {
|
|
|
69
260
|
return anc.status === 0 ? null : `could not compare base and HEAD: ${anc.stderr.trim()}`;
|
|
70
261
|
}
|
|
71
262
|
|
|
263
|
+
// Refuse ambiguous byte sequences while inspection is still read-only.
|
|
264
|
+
export function decodePatchPathOutput(bytes) {
|
|
265
|
+
const decoded = bytes.toString('utf8');
|
|
266
|
+
if (!Buffer.from(decoded, 'utf8').equals(bytes)) throw new Error('not applied: patch path inspection is not valid UTF-8');
|
|
267
|
+
return decoded;
|
|
268
|
+
}
|
|
269
|
+
|
|
72
270
|
// The files a patch names, renames as old and new, read from the patch alone (no check against the tree).
|
|
73
|
-
|
|
74
|
-
const numstat = git(dir, ['apply', '--numstat', '-z', '-'], body, env);
|
|
75
|
-
if (numstat.error || numstat.status !== 0) throw new Error(`git apply --numstat failed: ${(numstat.stderr || numstat.error?.message || '').trim().slice(0, 300)}`);
|
|
76
|
-
const records = numstat.stdout.split('\0');
|
|
271
|
+
function patchPaths(dir, body, env, direction) {
|
|
272
|
+
const numstat = git(dir, ['apply', '--numstat', '-z', ...direction, '-'], body, env, 'buffer');
|
|
273
|
+
if (numstat.error || numstat.status !== 0) throw new Error(`git apply --numstat failed: ${(numstat.stderr?.toString('utf8') || numstat.error?.message || '').trim().slice(0, 300)}`);
|
|
274
|
+
const records = decodePatchPathOutput(numstat.stdout).split('\0');
|
|
77
275
|
const files = [];
|
|
78
276
|
for (let index = 0; index < records.length; index++) {
|
|
79
277
|
const record = records[index];
|
|
@@ -92,6 +290,13 @@ export function listPatchFiles(dir, body, env) {
|
|
|
92
290
|
return files;
|
|
93
291
|
}
|
|
94
292
|
|
|
293
|
+
export function listPatchFiles(dir, body, env) {
|
|
294
|
+
// Some git apply versions report only the destination in forward numstat.
|
|
295
|
+
// Ask the same parser in reverse too, so rollback captures both endpoints
|
|
296
|
+
// without interpreting a human-readable rename summary or its quoting.
|
|
297
|
+
return [...new Set([...patchPaths(dir, body, env, []), ...patchPaths(dir, body, env, ['--reverse'])])];
|
|
298
|
+
}
|
|
299
|
+
|
|
95
300
|
// Checks the digest, the base and `git apply --check`, then applies. Preflight failures touch nothing; a failed apply
|
|
96
301
|
// process restores the files it touched (a restore that itself fails is named in the error). Returns the list of touched file names. With checkOnly, it stops after
|
|
97
302
|
// the checks and the file list and writes nothing, so a caller can take an authorization between the check and the write.
|