@tnunamak/dalan 0.0.0-stage → 0.6.0
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 +176 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +351 -0
- package/README.md +215 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +43 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +764 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/codex-to-muse.md +175 -0
- package/docs/connect-chatgpt.md +83 -0
- package/docs/connection-longevity.md +43 -0
- package/docs/dalan-upgrade.md +246 -0
- package/docs/deadman.md +61 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +41 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +97 -0
- package/docs/operations.md +799 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +107 -0
- package/docs/pr-head-reviewer.md +70 -0
- package/docs/pr-preflight.md +28 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +94 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +219 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +51 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +443 -0
- package/docs/worker-clients.md +290 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +67 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/dalan-try-selfcheck.mjs +29 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +418 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +538 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +186 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-owner.mjs +26 -0
- package/src/drained-slot.mjs +70 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +79 -0
- package/src/mcp-sse.mjs +62 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/process-inspection.mjs +36 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/pull-queue.mjs +159 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/route-setting.mjs +24 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1468 -0
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +388 -0
- package/src/setup.mjs +63 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3069 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +453 -0
- package/src/try-command.mjs +11 -0
- package/src/try-exposure.mjs +908 -0
- package/src/try-hosted-clients.mjs +46 -0
- package/src/try-hosted.mjs +444 -0
- package/src/try-selfcheck.mjs +168 -0
- package/src/try.mjs +635 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +632 -0
- package/src/workspace.mjs +1065 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// `dalan mcp`: a local MCP server on stdio. It lets an agent on the bridge computer submit jobs, wait for them and read
|
|
2
|
+
// their results as tool calls. It is not the worker-facing endpoint in server.mjs. Each tool runs the matching `dalan`
|
|
3
|
+
// CLI command with --json, so owner receipts, admin-socket access, assignment checks and verdicts stay in one place.
|
|
4
|
+
// Trust is the CLI's: whoever can run `dalan` here (the admin socket) can use these tools.
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import readline from 'node:readline';
|
|
9
|
+
import { redactOutput, redactSinkText } from './redaction.mjs';
|
|
10
|
+
import { safeDiagnostic } from './diagnostic.mjs';
|
|
11
|
+
|
|
12
|
+
export const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
13
|
+
export const RESULT_CAP_BYTES = 32 * 1024;
|
|
14
|
+
const WAIT_DEFAULT = 120, WAIT_MAX = 300;
|
|
15
|
+
const CLI = path.join(import.meta.dirname, '../bin/dalan.mjs');
|
|
16
|
+
const requestId = { type: 'string', pattern: '^[-\\w]{8,128}$', description: 'The request_id of a submitted job.' };
|
|
17
|
+
|
|
18
|
+
export const TOOLS = [
|
|
19
|
+
{ name: 'dalan_submit', title: 'Submit a job',
|
|
20
|
+
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
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['assignment'], properties: {
|
|
22
|
+
assignment: { type: 'object', description: 'The assignment: request_id (8-128 letters, digits, _ or -), brief, inputs (array; [] for none), expected_output, and the other fields `dalan submit` accepts.',
|
|
23
|
+
required: ['request_id'], properties: { request_id: requestId, brief: { type: 'string' }, inputs: { type: 'array' } } },
|
|
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.' },
|
|
26
|
+
dry_run: { type: 'boolean', description: 'Check the assignment and store nothing.' },
|
|
27
|
+
queue_anyway: { type: 'boolean', description: 'Queue even when the bridge would defer or warn.' },
|
|
28
|
+
refuse_defer: { type: 'boolean', description: 'Fail instead of deferring.' } } },
|
|
29
|
+
annotations: { title: 'Submit a job', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false } },
|
|
30
|
+
{ 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.`,
|
|
32
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['request_id'], properties: {
|
|
33
|
+
request_id: requestId,
|
|
34
|
+
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}.` } } },
|
|
35
|
+
annotations: { title: 'Wait for a job', readOnlyHint: true, openWorldHint: false } },
|
|
36
|
+
{ name: 'dalan_result', title: 'Read a job result',
|
|
37
|
+
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
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['request_id'], properties: { request_id: requestId } },
|
|
39
|
+
annotations: { title: 'Read a job result', readOnlyHint: true, openWorldHint: false } },
|
|
40
|
+
{ name: 'dalan_status', title: 'Bridge status',
|
|
41
|
+
description: 'Show the bridge status (`dalan status --json`): queue, workers and health.',
|
|
42
|
+
inputSchema: { type: 'object', additionalProperties: false, properties: {} },
|
|
43
|
+
annotations: { title: 'Bridge status', readOnlyHint: true, openWorldHint: false } }
|
|
44
|
+
];
|
|
45
|
+
|
|
46
|
+
// A SafeError carries a message written by Dalan; any other thrown value is a crash whose text never reaches the client.
|
|
47
|
+
class SafeError extends Error {}
|
|
48
|
+
const fail = (message, detail) => Object.assign(new SafeError(message), { detail });
|
|
49
|
+
// Untrusted names appear in a message only when they are plain identifiers.
|
|
50
|
+
const shown = name => /^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(name) ? `"${name}"` : '(name withheld)';
|
|
51
|
+
|
|
52
|
+
function validate(tool, args) {
|
|
53
|
+
if (args === undefined) args = {};
|
|
54
|
+
if (!args || typeof args !== 'object' || Array.isArray(args)) throw fail('arguments must be an object');
|
|
55
|
+
const { properties = {}, required = [] } = tool.inputSchema;
|
|
56
|
+
for (const key of Object.keys(args)) if (!(key in properties)) throw fail(`unknown argument ${shown(key)} for ${tool.name}`);
|
|
57
|
+
for (const key of required) if (args[key] === undefined) throw fail(`missing required argument "${key}"`);
|
|
58
|
+
for (const [key, value] of Object.entries(args)) {
|
|
59
|
+
const spec = properties[key];
|
|
60
|
+
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}`}`);
|
|
62
|
+
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 -)`);
|
|
64
|
+
if (spec.type === 'string' && value.startsWith('--')) throw fail(`argument "${key}" must not start with --`);
|
|
65
|
+
}
|
|
66
|
+
return args;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Run `dalan <args> --json`. stdout and stderr are collected, never forwarded: stdout of this process is the protocol.
|
|
70
|
+
function runCli(args, { input, timeoutMs = 60_000, env = process.env } = {}) {
|
|
71
|
+
return new Promise(resolve => {
|
|
72
|
+
const child = spawn(process.execPath, [CLI, ...args, '--json'], { env, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
73
|
+
let stdout = '', stderr = '', done = false;
|
|
74
|
+
const finish = value => { if (!done) { done = true; clearTimeout(timer); resolve(value); } };
|
|
75
|
+
const timer = setTimeout(() => { child.kill('SIGKILL'); finish({ code: null, stdout, stderr: `${stderr}dalan did not answer within ${Math.round(timeoutMs / 1000)}s` }); }, timeoutMs);
|
|
76
|
+
child.stdout.on('data', chunk => { stdout += chunk; });
|
|
77
|
+
child.stderr.on('data', chunk => { stderr += chunk; });
|
|
78
|
+
child.on('error', error => finish({ code: null, stdout, stderr: error.message }));
|
|
79
|
+
child.on('close', code => finish({ code, stdout, stderr }));
|
|
80
|
+
child.stdin.on('error', () => {});
|
|
81
|
+
child.stdin.end(input ?? '');
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
const parseJson = text => { try { return JSON.parse(text); } catch { return undefined; } };
|
|
85
|
+
// stderr may hold warnings before the final error JSON line.
|
|
86
|
+
const lastJsonLine = text => text.trim().split('\n').reverse().map(parseJson).find(v => v && typeof v === 'object');
|
|
87
|
+
|
|
88
|
+
export function cliError(run, label) {
|
|
89
|
+
const body = lastJsonLine(run.stderr) ?? lastJsonLine(run.stdout);
|
|
90
|
+
if (body) return { isError: true, value: body };
|
|
91
|
+
return { isError: true, message: `${label} failed${run.code === null ? '' : ` (exit ${run.code})`}: ${safeDiagnostic((run.stderr || run.stdout).trim(), 4000) || 'no output'}` };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function capped(value) {
|
|
95
|
+
const text = JSON.stringify(redactOutput(value));
|
|
96
|
+
if (Buffer.byteLength(text) <= RESULT_CAP_BYTES) return { text, structured: JSON.parse(text) };
|
|
97
|
+
const cut = Buffer.from(text).subarray(0, RESULT_CAP_BYTES).toString('utf8').replace(/�$/, '');
|
|
98
|
+
// The note is part of the frame the client sees, so it is redacted too.
|
|
99
|
+
return { text: `${cut}\n${redactSinkText(`[truncated: output was ${Buffer.byteLength(text)} bytes, cap is ${RESULT_CAP_BYTES}. Read the rest with \`dalan get ${value.request_id ?? 'REQUEST_ID'} --json\` or fetch artifacts with \`dalan artifact\`.]`)}` };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// The one exit for tool results: every message and value is redacted, success or error.
|
|
103
|
+
const asResult = ({ isError, value, message }) => {
|
|
104
|
+
if (message !== undefined) return { content: [{ type: 'text', text: redactSinkText(message) }], isError: true };
|
|
105
|
+
const { text, structured } = capped(value);
|
|
106
|
+
return { content: [{ type: 'text', text }], ...(structured && typeof structured === 'object' ? { structuredContent: structured } : {}), ...(isError ? { isError: true } : {}) };
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const handlers = {
|
|
110
|
+
async dalan_submit(args) {
|
|
111
|
+
const flags = [];
|
|
112
|
+
if (args.worker) flags.push('--worker', args.worker);
|
|
113
|
+
if (args.execution) flags.push('--execution', args.execution);
|
|
114
|
+
for (const [key, flag] of [['dry_run', '--dry-run'], ['queue_anyway', '--queue-anyway'], ['refuse_defer', '--refuse-defer']]) if (args[key]) flags.push(flag);
|
|
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
|
+
},
|
|
121
|
+
async dalan_wait(args) {
|
|
122
|
+
const seconds = Math.min(args.timeout_seconds ?? WAIT_DEFAULT, WAIT_MAX);
|
|
123
|
+
const run = await runCli(['wait', args.request_id, '--timeout', String(Math.max(1, seconds))], { timeoutMs: (seconds + 30) * 1000 });
|
|
124
|
+
// 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);
|
|
126
|
+
return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'wait'));
|
|
127
|
+
},
|
|
128
|
+
async dalan_result(args) {
|
|
129
|
+
const run = await runCli(['get', args.request_id]);
|
|
130
|
+
const value = run.code === 0 ? parseJson(run.stdout) : undefined;
|
|
131
|
+
return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'get'));
|
|
132
|
+
},
|
|
133
|
+
async dalan_status() {
|
|
134
|
+
const run = await runCli(['status']);
|
|
135
|
+
const value = run.code === 0 ? parseJson(run.stdout) : undefined;
|
|
136
|
+
return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'status'));
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
export async function callTool(name, rawArgs) {
|
|
141
|
+
const tool = TOOLS.find(t => t.name === name);
|
|
142
|
+
if (!tool) return null;
|
|
143
|
+
try { return await handlers[name](validate(tool, rawArgs)); }
|
|
144
|
+
catch (error) {
|
|
145
|
+
if (error instanceof SafeError) return asResult({ message: error.message });
|
|
146
|
+
// Python MCP SDK pattern: the client gets the tool name and an error id; the redacted detail goes to the local log.
|
|
147
|
+
const id = randomUUID().slice(0, 8);
|
|
148
|
+
process.stderr.write(`dalan mcp: ${name}: error ${id}: ${safeDiagnostic(error.stack ?? error, 4000)}\n`);
|
|
149
|
+
return asResult({ message: `Error executing tool ${name} (error id ${id}; details are in the dalan mcp log)` });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const rpcError = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message: redactSinkText(message) } });
|
|
154
|
+
|
|
155
|
+
// One JSON-RPC message in, zero or one frame out. Never throws.
|
|
156
|
+
export async function handleFrame(message) {
|
|
157
|
+
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
|
+
const { id, method, params } = message;
|
|
159
|
+
if (id === undefined) return null; // notification
|
|
160
|
+
const ok = result => ({ jsonrpc: '2.0', id, result });
|
|
161
|
+
switch (method) {
|
|
162
|
+
case 'initialize': return ok({ protocolVersion: PROTOCOL_VERSIONS.includes(params?.protocolVersion) ? params.protocolVersion : PROTOCOL_VERSIONS[0],
|
|
163
|
+
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.' });
|
|
165
|
+
case 'ping': return ok({});
|
|
166
|
+
case 'tools/list': return ok({ tools: TOOLS });
|
|
167
|
+
case 'tools/call': {
|
|
168
|
+
if (typeof params?.name !== 'string') return rpcError(id, -32602, 'tools/call requires a tool name');
|
|
169
|
+
const result = await callTool(params.name, params.arguments);
|
|
170
|
+
return result ? ok(result) : rpcError(id, -32602, `unknown tool "${params.name}"`);
|
|
171
|
+
}
|
|
172
|
+
default: return rpcError(id, -32601, `method not found: ${method}`);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export async function main({ input = process.stdin, output = process.stdout } = {}) {
|
|
177
|
+
const inflight = new Set();
|
|
178
|
+
const write = frame => output.write(`${JSON.stringify(frame)}\n`);
|
|
179
|
+
for await (const line of readline.createInterface({ input, crlfDelay: Infinity })) {
|
|
180
|
+
if (!line.trim()) continue;
|
|
181
|
+
let message;
|
|
182
|
+
try { message = JSON.parse(line); }
|
|
183
|
+
catch { write(rpcError(null, -32700, 'parse error')); continue; }
|
|
184
|
+
// Requests run concurrently: a long dalan_wait must not block a ping or another tool.
|
|
185
|
+
const work = handleFrame(message).then(frame => { if (frame) write(frame); }, error => {
|
|
186
|
+
process.stderr.write(`dalan mcp: ${safeDiagnostic(error.stack ?? error, 4000)}\n`); write(rpcError(message?.id ?? null, -32603, 'internal error'));
|
|
187
|
+
}).finally(() => inflight.delete(work));
|
|
188
|
+
inflight.add(work);
|
|
189
|
+
}
|
|
190
|
+
await Promise.all(inflight);
|
|
191
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Kernel ownership and platform-specific settlement for a private mirror fetch.
|
|
2
|
+
|
|
3
|
+
The lock inode is permanent. Never unlink it: another opener may already hold it.
|
|
4
|
+
The single-threaded guardian never reaps a child between enumerating and signaling
|
|
5
|
+
it, so a child PID cannot be recycled in that interval.
|
|
6
|
+
"""
|
|
7
|
+
import ctypes
|
|
8
|
+
import fcntl
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import shutil
|
|
12
|
+
import signal
|
|
13
|
+
import select
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def run():
|
|
20
|
+
request = sys.stdin.buffer.read()
|
|
21
|
+
mirror = json.loads(request)['mirror']
|
|
22
|
+
attempt = mirror + '.fetch-lock'
|
|
23
|
+
fd = os.open(mirror + '.fetch-mutex', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
|
24
|
+
try:
|
|
25
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
26
|
+
except BlockingIOError:
|
|
27
|
+
raise RuntimeError('mirror fetch already in progress (kernel lock held)')
|
|
28
|
+
expected = json.dumps({'version': 1, 'mirror': mirror}).encode()
|
|
29
|
+
receipt_path = mirror + '.fetch-owner.json'
|
|
30
|
+
try:
|
|
31
|
+
with open(receipt_path, 'rb') as source:
|
|
32
|
+
receipt = source.read(4096)
|
|
33
|
+
except FileNotFoundError:
|
|
34
|
+
receipt = None
|
|
35
|
+
if receipt is None and not os.path.exists(attempt):
|
|
36
|
+
# Publish atomically before creating any disposable state. An interrupted
|
|
37
|
+
# publication has no attempt to clean; the next owner can repeat it.
|
|
38
|
+
with open(receipt_path + '.new', 'wb') as target:
|
|
39
|
+
os.chmod(target.fileno(), 0o600)
|
|
40
|
+
target.write(expected)
|
|
41
|
+
target.flush()
|
|
42
|
+
os.fsync(target.fileno())
|
|
43
|
+
os.replace(receipt_path + '.new', receipt_path)
|
|
44
|
+
parent_fd = os.open(os.path.dirname(mirror), os.O_RDONLY | os.O_DIRECTORY)
|
|
45
|
+
os.fsync(parent_fd)
|
|
46
|
+
os.close(parent_fd)
|
|
47
|
+
elif receipt != expected:
|
|
48
|
+
raise RuntimeError('mirror fetch ownership receipt missing or corrupt; private attempt left untouched')
|
|
49
|
+
# Acquiring flock proves all previous cooperating owners have closed it.
|
|
50
|
+
# Set subreaper BEFORE spawning: orphan Git descendants become our children.
|
|
51
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
52
|
+
if sys.platform == 'linux' and libc.prctl(36, 1, 0, 0, 0) != 0: # PR_SET_CHILD_SUBREAPER
|
|
53
|
+
raise OSError(ctypes.get_errno(), 'cannot establish mirror fetch subreaper')
|
|
54
|
+
# The live anchor and actual Git stderr descriptors retain this separate
|
|
55
|
+
# barrier even if both the guardian and Node die. Never clean a live writer.
|
|
56
|
+
settle(mirror, nonblocking=True)
|
|
57
|
+
if os.path.exists(attempt):
|
|
58
|
+
shutil.rmtree(attempt)
|
|
59
|
+
child = subprocess.Popen([sys.argv[1], sys.argv[2], '--owned-fetch', str(fd)],
|
|
60
|
+
stdin=subprocess.PIPE, pass_fds=(fd,),
|
|
61
|
+
start_new_session=sys.platform == 'darwin')
|
|
62
|
+
child.stdin.write(request)
|
|
63
|
+
child.stdin.close()
|
|
64
|
+
if sys.platform == 'darwin':
|
|
65
|
+
# NOTE_EXIT observes without waitpid/reaping. Our unreaped direct child
|
|
66
|
+
# pins the PGID until the final signal, including synchronous Git calls.
|
|
67
|
+
queue = select.kqueue()
|
|
68
|
+
event = select.kevent(child.pid, filter=select.KQ_FILTER_PROC,
|
|
69
|
+
flags=select.KQ_EV_ADD | select.KQ_EV_ONESHOT,
|
|
70
|
+
fflags=select.KQ_NOTE_EXIT)
|
|
71
|
+
queue.control([event], 1, None)
|
|
72
|
+
queue.close()
|
|
73
|
+
try:
|
|
74
|
+
os.killpg(child.pid, signal.SIGKILL)
|
|
75
|
+
except (ProcessLookupError, PermissionError):
|
|
76
|
+
# Darwin returns EPERM for an all-zombie group. This signal is
|
|
77
|
+
# best effort; inherited flock descriptions remain the cleanup
|
|
78
|
+
# authority even if a member cannot be signaled.
|
|
79
|
+
pass
|
|
80
|
+
code = child.wait()
|
|
81
|
+
settle(mirror)
|
|
82
|
+
# Node may have been SIGKILLed with detached Git grandchildren still writing.
|
|
83
|
+
# Keep flock until every descendant is reaped, including orphan grandchildren.
|
|
84
|
+
deadline = time.monotonic() + 5
|
|
85
|
+
warned = False
|
|
86
|
+
while sys.platform == 'linux':
|
|
87
|
+
try:
|
|
88
|
+
while os.waitpid(-1, os.WNOHANG)[0]:
|
|
89
|
+
pass
|
|
90
|
+
except ChildProcessError:
|
|
91
|
+
break
|
|
92
|
+
children = open(f'/proc/self/task/{os.getpid()}/children').read().split()
|
|
93
|
+
for pid in children:
|
|
94
|
+
os.kill(int(pid), signal.SIGKILL)
|
|
95
|
+
if time.monotonic() > deadline and not warned:
|
|
96
|
+
print('mirror fetch children still settling; kernel lock remains held', file=sys.stderr)
|
|
97
|
+
warned = True
|
|
98
|
+
time.sleep(.01)
|
|
99
|
+
os.close(fd)
|
|
100
|
+
return code if code >= 0 else 1
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def settle(mirror, nonblocking=False):
|
|
104
|
+
fd = os.open(mirror + '.fetch-writers', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
|
105
|
+
try:
|
|
106
|
+
fcntl.flock(fd, fcntl.LOCK_EX | (fcntl.LOCK_NB if nonblocking else 0))
|
|
107
|
+
except BlockingIOError:
|
|
108
|
+
raise RuntimeError('mirror fetch already in progress (writers still settling)')
|
|
109
|
+
finally:
|
|
110
|
+
os.close(fd)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def anchor():
|
|
114
|
+
"""One fetch group on either supported OS, anchored until its final group-wide SIGKILL.
|
|
115
|
+
|
|
116
|
+
Only Node retains the control pipe's write end; Git receives /dev/null.
|
|
117
|
+
The anchor survives loss of Node and its guardian and detects pipe EOF.
|
|
118
|
+
Git's stderr IS the writer lock's open description, not a PID receipt.
|
|
119
|
+
"""
|
|
120
|
+
mirror, timeout, inherited = sys.argv[2:5]
|
|
121
|
+
fd = os.open(mirror + '.fetch-writers', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
|
122
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
123
|
+
os.ftruncate(fd, 0)
|
|
124
|
+
child = None
|
|
125
|
+
try:
|
|
126
|
+
child = subprocess.Popen(sys.argv[5:], stdin=subprocess.DEVNULL,
|
|
127
|
+
stdout=subprocess.DEVNULL, stderr=fd,
|
|
128
|
+
pass_fds=(int(inherited), fd))
|
|
129
|
+
deadline = time.monotonic() + float(timeout) / 1000
|
|
130
|
+
timed_out = False
|
|
131
|
+
while child.poll() is None:
|
|
132
|
+
if select.select([0], [], [], .02)[0] and not os.read(0, 1):
|
|
133
|
+
return
|
|
134
|
+
if time.monotonic() >= deadline:
|
|
135
|
+
timed_out = True
|
|
136
|
+
break
|
|
137
|
+
# Output is a result, not settlement authority. The caller must acquire
|
|
138
|
+
# the independent writer barrier after this anchor has killed its group.
|
|
139
|
+
os.lseek(fd, max(0, os.lseek(fd, 0, os.SEEK_END) - 8192), os.SEEK_SET)
|
|
140
|
+
print(json.dumps({'code': child.returncode, 'timedOut': timed_out,
|
|
141
|
+
'stderr': os.read(fd, 8192).decode(errors='replace')}), flush=True)
|
|
142
|
+
finally:
|
|
143
|
+
# Our live PID pins the group identity. Do not reap/exit this anchor and
|
|
144
|
+
# later signal a recorded PGID, which could have been reused.
|
|
145
|
+
os.killpg(os.getpid(), signal.SIGKILL)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
try:
|
|
149
|
+
if sys.platform not in ('linux', 'darwin'):
|
|
150
|
+
raise RuntimeError('mirror fetch requires Linux or macOS')
|
|
151
|
+
if sys.argv[1] == '--check':
|
|
152
|
+
if sys.version_info < (3, 8):
|
|
153
|
+
raise RuntimeError('Python 3.8 or newer required')
|
|
154
|
+
sys.exit(0)
|
|
155
|
+
if sys.argv[1] == '--settle':
|
|
156
|
+
settle(sys.argv[2])
|
|
157
|
+
sys.exit(0)
|
|
158
|
+
if sys.argv[1] == '--anchor':
|
|
159
|
+
anchor()
|
|
160
|
+
else:
|
|
161
|
+
sys.exit(run())
|
|
162
|
+
except Exception as error:
|
|
163
|
+
print(str(error), file=sys.stderr)
|
|
164
|
+
sys.exit(1)
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// A fetch owns a private object store. Publish complete objects before refs so
|
|
2
|
+
// reference clones and live worktrees never depend on disposable attempt files.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
7
|
+
import { gitEnv } from './git-env.mjs';
|
|
8
|
+
|
|
9
|
+
const file = fileURLToPath(import.meta.url);
|
|
10
|
+
const guardianFile = fileURLToPath(new URL('./mirror-fetch-lock.py', import.meta.url));
|
|
11
|
+
let lockFd;
|
|
12
|
+
const inheritedLock = () => lockFd === undefined ? [] : Array.from({ length: lockFd - 2 }, (_, i) => i + 3 === lockFd ? lockFd : 'ignore');
|
|
13
|
+
const retention = ['-c', 'gc.auto=0', '-c', 'maintenance.auto=false', '-c', 'gc.autoDetach=false'];
|
|
14
|
+
const corrupt = /unresolved deltas|unpack-objects failed|index-pack failed|missing (?:blob|tree|commit) object|did not send all necessary objects|bad object|is corrupt/i;
|
|
15
|
+
|
|
16
|
+
export function fetchMirror(mirror, url, env, timeoutMs = 900000, revisions = null, { refetch = false } = {}) {
|
|
17
|
+
if(revisions!==null&&(!Array.isArray(revisions)||!revisions.length||revisions.some(sha=>typeof sha!=='string'||!/^[a-f0-9]{40}$/.test(sha)))) throw new Error('full pinned revisions required');
|
|
18
|
+
const result = spawnSync(process.execPath, [file, '--fetch'], {
|
|
19
|
+
input: JSON.stringify({ mirror, url, timeoutMs, revisions, refetch: refetch === true }), env: gitEnv(env), encoding: 'utf8', maxBuffer: 1024 * 1024,
|
|
20
|
+
});
|
|
21
|
+
// Repair notices must survive a later fetch failure as well as success.
|
|
22
|
+
for (const line of String(result.stderr || '').split('\n')) {
|
|
23
|
+
if (line.startsWith('mirror repair: ')) console.error(line);
|
|
24
|
+
}
|
|
25
|
+
if (result.error || result.status !== 0) {
|
|
26
|
+
const message = String(result.stderr || result.error?.message || 'fetch supervisor failed').replace(/https:\/\/[^/@\s]+@/g, 'https://<redacted>@');
|
|
27
|
+
throw new Error(`git failed: ${message.slice(0, 1000)}`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function git(args, input) {
|
|
32
|
+
const result = spawnSync('git', [...retention, ...args], { input, stdio: ['pipe', 'pipe', 'pipe', ...inheritedLock()], encoding: 'utf8', timeout: 30000, maxBuffer: 12 * 1024 * 1024 });
|
|
33
|
+
if (result.error || result.status !== 0) throw new Error(result.stderr || result.error?.message || 'git failed');
|
|
34
|
+
return result.stdout;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function fetch(args, timeoutMs, state) {
|
|
38
|
+
const mirror = path.dirname(args[1]).slice(0, -'.fetch-lock'.length);
|
|
39
|
+
const child = spawn('python3', [guardianFile, '--anchor', mirror, String(timeoutMs), String(lockFd), 'git', ...retention, ...args], {
|
|
40
|
+
detached: true, stdio: ['pipe', 'pipe', 'pipe', ...inheritedLock()],
|
|
41
|
+
});
|
|
42
|
+
// Keep this pipe open for exactly Node's lifetime. Git cannot inherit it.
|
|
43
|
+
child.stdin.on('error', () => {});
|
|
44
|
+
let output = '', errors = '';
|
|
45
|
+
child.stdout.on('data', data => { output += data; });
|
|
46
|
+
child.stderr.on('data', data => { errors = (errors + data).slice(-8192); });
|
|
47
|
+
await new Promise((resolve, reject) => { child.once('error', reject); child.once('close', resolve); });
|
|
48
|
+
const barrier = spawnSync('python3', [guardianFile, '--settle', mirror], { timeout: 5000, encoding: 'utf8' });
|
|
49
|
+
if (barrier.error || barrier.status !== 0) {
|
|
50
|
+
state.settled = false;
|
|
51
|
+
throw new Error('fetch writers still settling; attempt retained');
|
|
52
|
+
}
|
|
53
|
+
let result;
|
|
54
|
+
try { result = JSON.parse(output); } catch { throw new Error(errors || 'fetch anchor failed'); }
|
|
55
|
+
if (result.timedOut) throw new Error('mirror fetch timed out');
|
|
56
|
+
if (result.code !== 0) throw new Error(result.stderr || `fetch exited ${result.code}`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function publishObjects(source, target) {
|
|
60
|
+
for (const dir of fs.readdirSync(source)) {
|
|
61
|
+
if (dir !== 'pack' && !/^[a-f0-9]{2}$/.test(dir)) continue;
|
|
62
|
+
fs.mkdirSync(path.join(target, dir), { recursive: true });
|
|
63
|
+
for (const name of fs.readdirSync(path.join(source, dir))) {
|
|
64
|
+
if (dir === 'pack' && !/^pack-[a-f0-9]+\.(pack|idx|rev)$/.test(name)) continue;
|
|
65
|
+
if (dir !== 'pack' && !/^[a-f0-9]{38}$/.test(name)) continue;
|
|
66
|
+
try { fs.linkSync(path.join(source, dir, name), path.join(target, dir, name)); }
|
|
67
|
+
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Returns the listing of the refs that remain, in `for-each-ref` format.
|
|
73
|
+
function removeMissingRefs(mirror, refs) {
|
|
74
|
+
const entries = refs.split('\n').filter(Boolean).map(line => {
|
|
75
|
+
const match = /^([a-f0-9]{40}) (refs\/[^\t\n]+)\t([^\t\n]*)$/.exec(line);
|
|
76
|
+
if (!match) throw new Error('invalid mirror ref listing');
|
|
77
|
+
return { oid: match[1], ref: match[2], symbolic: Boolean(match[3]), line: match[1] + ' ' + match[2] };
|
|
78
|
+
});
|
|
79
|
+
if (!entries.length) return '';
|
|
80
|
+
const result = git(['-C', mirror, 'cat-file', '--batch-check=%(objectname) %(objecttype)'],
|
|
81
|
+
entries.map(entry => entry.oid).join('\n') + '\n').trimEnd().split('\n');
|
|
82
|
+
if (result.length !== entries.length) throw new Error('incomplete mirror object check');
|
|
83
|
+
const missing = new Set();
|
|
84
|
+
const healthy = [];
|
|
85
|
+
entries.forEach((entry, index) => {
|
|
86
|
+
if (result[index] === entry.oid + ' missing') { if (!entry.symbolic) missing.add(entry.ref); }
|
|
87
|
+
else if (new RegExp('^' + entry.oid + ' (commit|tree|blob|tag)$').test(result[index])) healthy.push(entry.line);
|
|
88
|
+
else throw new Error('unexpected mirror object check result');
|
|
89
|
+
});
|
|
90
|
+
if (missing.size) {
|
|
91
|
+
const commands = ['start'];
|
|
92
|
+
for (const entry of entries) if (missing.has(entry.ref)) commands.push(`delete ${entry.ref} ${entry.oid}`);
|
|
93
|
+
commands.push('prepare', 'commit', '');
|
|
94
|
+
git(['-C', mirror, 'update-ref', '--stdin'], commands.join('\n'));
|
|
95
|
+
console.error(`mirror repair: deleted ${missing.size} missing-object refs`);
|
|
96
|
+
for (const ref of [...missing].slice(0, 20)) console.error('mirror repair: deleted missing-object ref ' + JSON.stringify(ref));
|
|
97
|
+
if (missing.size > 20) console.error(`mirror repair: ... and ${missing.size - 20} more`);
|
|
98
|
+
}
|
|
99
|
+
return healthy.length ? healthy.join('\n') + '\n' : '';
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function prepare({ mirror, url, timeoutMs, revisions = null, refetch = false }) {
|
|
103
|
+
if(revisions!==null&&(!Array.isArray(revisions)||!revisions.length||revisions.some(sha=>typeof sha!=='string'||!/^[a-f0-9]{40}$/.test(sha)))) throw new Error('full pinned revisions required');
|
|
104
|
+
const deadline=performance.now()+timeoutMs;
|
|
105
|
+
const remaining=()=>{const ms=Math.floor(deadline-performance.now());if(ms<=0)throw new Error('mirror fetch timed out');return ms;};
|
|
106
|
+
const lock = mirror + '.fetch-lock';
|
|
107
|
+
fs.mkdirSync(lock, { mode: 0o700 });
|
|
108
|
+
const state = { settled: true };
|
|
109
|
+
try {
|
|
110
|
+
fs.writeFileSync(path.join(lock, 'owner.json'), JSON.stringify({ pid: process.pid, guardian: process.ppid, mirror }), { mode: 0o600 });
|
|
111
|
+
// A mirror directory that lost HEAD or config is not a repository to git, but its objects and refs are intact.
|
|
112
|
+
// `git init --bare` on an existing directory only adds what is missing, so it repairs the mirror in place.
|
|
113
|
+
if (!fs.existsSync(mirror) || !fs.existsSync(path.join(mirror, 'HEAD')) || !fs.existsSync(path.join(mirror, 'config'))) {
|
|
114
|
+
const repairing = fs.existsSync(mirror);
|
|
115
|
+
git(['init', '--bare', mirror]);
|
|
116
|
+
if (repairing) console.error('mirror repair: re-initialised a mirror without HEAD or config');
|
|
117
|
+
}
|
|
118
|
+
if (git(['-C', mirror, 'remote']).trim().split('\n').includes('origin')) git(['-C', mirror, 'remote', 'remove', 'origin']);
|
|
119
|
+
for (const [key, value] of [['gc.auto', '0'], ['maintenance.auto', 'false'], ['gc.autoDetach', 'false']]) git(['-C', mirror, 'config', '--local', key, value]);
|
|
120
|
+
const stage = path.join(lock, 'repo.git');
|
|
121
|
+
git(['init', '--bare', stage]);
|
|
122
|
+
// Carry bridge-owned settings (notably fetch.unpackLimit) into the attempt.
|
|
123
|
+
// Local retention settings also protect consumers between bridge invocations.
|
|
124
|
+
fs.copyFileSync(path.join(mirror, 'config'), path.join(stage, 'config'));
|
|
125
|
+
fs.writeFileSync(path.join(stage, 'objects/info/alternates'), path.join(mirror, 'objects') + '\n');
|
|
126
|
+
// A ref whose object is missing makes every fetch fail connectivity checks with "bad object".
|
|
127
|
+
// Delete only those refs, in the mirror itself and under the fetch lock: Git also advertises refs
|
|
128
|
+
// from the alternate object store, not only the stage's packed-refs. The fetch below restores
|
|
129
|
+
// whatever the caller needs.
|
|
130
|
+
const refs = removeMissingRefs(mirror, git(['-C', mirror, 'for-each-ref', '--format=%(objectname) %(refname)%09%(symref)']));
|
|
131
|
+
fs.writeFileSync(path.join(stage, 'packed-refs'), '# pack-refs with: sorted\n' + refs);
|
|
132
|
+
// A job names immutable commits, not every branch/tag/PR in the repository.
|
|
133
|
+
// Keep prior refs seeded above; only the requested pins may change here.
|
|
134
|
+
const selection=revisions===null?['--prune',url,'+refs/heads/*:refs/heads/*','+refs/tags/*:refs/tags/*','+refs/pull/*/head:refs/pull/*/head']:['--no-tags',url,...[...new Set(revisions)].map(sha=>`+${sha}:refs/dot-bridge/pins/${sha}`)];
|
|
135
|
+
// refetch: the caller proved the mirror lacks objects under a pin; ignore what it claims to have.
|
|
136
|
+
const args = ['-C', stage, 'fetch', '--no-auto-maintenance', ...(refetch === true ? ['--refetch'] : []), ...selection];
|
|
137
|
+
try { await fetch(args, remaining(), state); }
|
|
138
|
+
catch (error) {
|
|
139
|
+
if (!state.settled || refetch === true || !corrupt.test(error.message)) throw error;
|
|
140
|
+
await fetch([...args.slice(0, 3), '--refetch', ...args.slice(3)], remaining(), state);
|
|
141
|
+
}
|
|
142
|
+
publishObjects(path.join(stage, 'objects'), path.join(mirror, 'objects'));
|
|
143
|
+
const after = git(['-C', stage, 'for-each-ref', '--format=%(objectname) %(refname)']);
|
|
144
|
+
const old = new Map(refs.split('\n').filter(Boolean).map(line => { const [sha, ref] = line.split(' '); return [ref, sha]; }));
|
|
145
|
+
const commands = ['start'];
|
|
146
|
+
for (const line of after.split('\n').filter(Boolean)) {
|
|
147
|
+
const [sha, ref] = line.split(' ');
|
|
148
|
+
commands.push(`update ${ref} ${sha} ${old.get(ref) || '0'.repeat(40)}`); old.delete(ref);
|
|
149
|
+
}
|
|
150
|
+
for (const [ref, sha] of old) commands.push(`delete ${ref} ${sha}`);
|
|
151
|
+
commands.push('prepare', 'commit', '');
|
|
152
|
+
git(['-C', mirror, 'update-ref', '--stdin'], commands.join('\n'));
|
|
153
|
+
} finally {
|
|
154
|
+
if (state.settled) fs.rmSync(lock, { recursive: true, force: true });
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (process.argv[1] === file && process.argv[2] === '--fetch') {
|
|
159
|
+
const check = spawnSync('python3', [guardianFile, '--check'], { encoding: 'utf8' });
|
|
160
|
+
if (check.error || check.status !== 0) {
|
|
161
|
+
console.error('Mirror fetch requires Python 3.8+ on Linux or macOS. Install Python 3 and put python3 on the bridge service PATH, then retry. ' + (check.stderr || check.error?.message || ''));
|
|
162
|
+
process.exit(1);
|
|
163
|
+
}
|
|
164
|
+
const result = spawnSync('python3', [guardianFile, process.execPath, file], {
|
|
165
|
+
input: fs.readFileSync(0), stdio: ['pipe', 'inherit', 'inherit'],
|
|
166
|
+
});
|
|
167
|
+
if (result.error) console.error(result.error.message);
|
|
168
|
+
process.exitCode = result.status ?? 1;
|
|
169
|
+
}
|
|
170
|
+
if (process.argv[1] === file && process.argv[2] === '--owned-fetch') {
|
|
171
|
+
lockFd = Number(process.argv[3]);
|
|
172
|
+
try { await prepare(JSON.parse(fs.readFileSync(0, 'utf8'))); }
|
|
173
|
+
catch (error) { console.error(error.message); process.exitCode = 1; }
|
|
174
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
const META_KEY='dot-bridge/idempotencyKey';
|
|
7
|
+
|
|
8
|
+
// Validate before argument auditing; metadata never enters argument summaries.
|
|
9
|
+
export function notifyKey(meta) {
|
|
10
|
+
if(meta===undefined||meta===null) return undefined;
|
|
11
|
+
if(typeof meta!=='object'||Array.isArray(meta)) throw new Error('invalid notification metadata');
|
|
12
|
+
if(!Object.hasOwn(meta,META_KEY)) return undefined;
|
|
13
|
+
const key=meta[META_KEY];
|
|
14
|
+
if(typeof key!=='string'||!key.trim()||key.length>256) throw new Error('invalid notification idempotency key');
|
|
15
|
+
return key;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Positive results only; outside J3, with no cross-process or crash exactly-once claim.
|
|
19
|
+
export class NotifyLedger {
|
|
20
|
+
constructor(file) {
|
|
21
|
+
fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});
|
|
22
|
+
if(!fs.existsSync(file)) { const fd=fs.openSync(file,'wx',0o600); fs.closeSync(fd); }
|
|
23
|
+
const stat=fs.lstatSync(file);
|
|
24
|
+
if(!stat.isFile()||(stat.mode&0o777)!==0o600) throw new Error('notification ledger must be a regular mode 0600 file');
|
|
25
|
+
this.db=new DatabaseSync(file);
|
|
26
|
+
this.inFlight=new Map();
|
|
27
|
+
try {
|
|
28
|
+
this.db.exec('PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS sent(key_sha256 TEXT PRIMARY KEY,result_json TEXT,state TEXT NOT NULL DEFAULT \'delivered\',sent_at INTEGER NOT NULL,reconcile_evidence TEXT) WITHOUT ROWID;');
|
|
29
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('sent') WHERE name='state'").get()) this.db.exec("ALTER TABLE sent ADD COLUMN state TEXT NOT NULL DEFAULT 'delivered'");
|
|
30
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('sent') WHERE name='reconcile_evidence'").get()) this.db.exec('ALTER TABLE sent ADD COLUMN reconcile_evidence TEXT');
|
|
31
|
+
if(this.db.prepare('PRAGMA integrity_check').get().integrity_check!=='ok') throw new Error('integrity check failed');
|
|
32
|
+
} catch(error) { this.db.close(); throw new Error('notification ledger unavailable',{cause:error}); }
|
|
33
|
+
}
|
|
34
|
+
pending() { return this.db.prepare("SELECT key_sha256,sent_at FROM sent WHERE state='pending' ORDER BY sent_at,key_sha256").all().map(row=>({key_sha256:row.key_sha256,reserved_at:row.sent_at})); }
|
|
35
|
+
reconcile({key_sha256,outcome,evidence}) {
|
|
36
|
+
if(typeof key_sha256!=='string'||!/^[a-f0-9]{64}$/.test(key_sha256)||!['sent','unsent'].includes(outcome)||typeof evidence!=='string'||!evidence.trim()||evidence.length>2000) throw new Error('invalid notification reconciliation');
|
|
37
|
+
if(this.inFlight.has(key_sha256)) throw new Error('notification still in flight');
|
|
38
|
+
const evidenceHash=createHash('sha256').update(evidence.trim()).digest('hex');
|
|
39
|
+
const result=outcome==='sent'
|
|
40
|
+
? this.db.prepare("UPDATE sent SET state='delivered',result_json=?,sent_at=?,reconcile_evidence=? WHERE key_sha256=? AND state='pending'").run(JSON.stringify({notified:true}),Date.now(),evidenceHash,key_sha256)
|
|
41
|
+
: this.db.prepare("UPDATE sent SET state='retryable',result_json='{}',reconcile_evidence=? WHERE key_sha256=? AND state='pending'").run(evidenceHash,key_sha256);
|
|
42
|
+
if(result.changes!==1) throw new Error('notification is not pending');
|
|
43
|
+
return {key_sha256,outcome,state:outcome==='sent'?'delivered':'retryable'};
|
|
44
|
+
}
|
|
45
|
+
async send(worker,text,key,publish) {
|
|
46
|
+
const hash=createHash('sha256').update(JSON.stringify([worker,key===undefined?'payload':'caller',key===undefined?text:key])).digest('hex');
|
|
47
|
+
const pending=this.inFlight.get(hash);
|
|
48
|
+
if(pending) return pending;
|
|
49
|
+
// Set the promise before running any cache or network work.
|
|
50
|
+
const promise=Promise.resolve().then(async()=>{
|
|
51
|
+
const row=this.db.prepare('SELECT result_json,state FROM sent WHERE key_sha256=?').get(hash);
|
|
52
|
+
if(row?.state==='pending') throw new Error('uncertain notification: reconcile receiver acceptance before retry');
|
|
53
|
+
if(row?.state==='delivered') {
|
|
54
|
+
const result=JSON.parse(row.result_json);
|
|
55
|
+
if(result?.notified!==true||Object.keys(result).length!==1) throw new Error('invalid notification ledger result');
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
58
|
+
if(row?.state==='retryable') {
|
|
59
|
+
const changed=this.db.prepare("UPDATE sent SET state='pending',result_json='{}',sent_at=?,reconcile_evidence=NULL WHERE key_sha256=? AND state='retryable'").run(Date.now(),hash);
|
|
60
|
+
if(changed.changes!==1) throw new Error('uncertain notification: another sender reserved this key');
|
|
61
|
+
} else {
|
|
62
|
+
const reservation=this.db.prepare("INSERT INTO sent(key_sha256,result_json,state,sent_at) VALUES(?,'{}','pending',?) ON CONFLICT(key_sha256) DO NOTHING").run(hash,Date.now());
|
|
63
|
+
if(reservation.changes!==1) throw new Error('uncertain notification: another sender reserved this key');
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
const published=await publish(hash);
|
|
67
|
+
if(published===false) throw Object.assign(new Error('notification was not accepted'),{notifyOutcome:'not_accepted'});
|
|
68
|
+
const result={notified:true};
|
|
69
|
+
// One synchronous autocommit; never a transaction held across publish.
|
|
70
|
+
this.db.prepare("UPDATE sent SET result_json=?,state='delivered',sent_at=?,reconcile_evidence=NULL WHERE key_sha256=? AND state='pending'").run(JSON.stringify(result),Date.now(),hash);
|
|
71
|
+
return result;
|
|
72
|
+
} catch(error) {
|
|
73
|
+
if(error?.notifyOutcome==='not_accepted') this.db.prepare("UPDATE sent SET state='retryable',reconcile_evidence=? WHERE key_sha256=? AND state='pending'").run(String(error.message).slice(0,2000),hash);
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
this.inFlight.set(hash,promise);
|
|
78
|
+
try { return await promise; }
|
|
79
|
+
finally { if(this.inFlight.get(hash)===promise) this.inFlight.delete(hash); }
|
|
80
|
+
}
|
|
81
|
+
close() { this.db.close(); }
|
|
82
|
+
}
|