@tnunamak/dalan 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/CONTRIBUTING.md +2 -0
  3. package/PROTOCOL.md +6 -0
  4. package/README.md +8 -12
  5. package/bin/dalan.mjs +25 -4
  6. package/bin/dot-acp-agent.mjs +572 -76
  7. package/bin/dot-alert.mjs +9 -3
  8. package/bin/dot-deadman.mjs +3 -1
  9. package/bin/dot-heartbeat.mjs +14 -7
  10. package/bin/dot-pr-reviewer.mjs +3 -31
  11. package/bin/dot-worker.mjs +215 -40
  12. package/contracts/adapter-qualification.schema.json +94 -7
  13. package/docs/chatgpt-worker-onboarding.md +1 -1
  14. package/docs/codex-to-muse.md +2 -2
  15. package/docs/connect-chatgpt.md +1 -1
  16. package/docs/connection-longevity.md +2 -2
  17. package/docs/dalan-upgrade.md +8 -5
  18. package/docs/deadman.md +4 -0
  19. package/docs/design/authority-matrix.md +18 -0
  20. package/docs/design/failure-table.md +87 -0
  21. package/docs/design/identities.md +22 -0
  22. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  23. package/docs/design/reuse-ledger.md +75 -0
  24. package/docs/design/target-architecture-v2.md +434 -0
  25. package/docs/local-agent-mcp.md +14 -0
  26. package/docs/local-agent-requester.md +3 -2
  27. package/docs/manual-setup.md +1 -1
  28. package/docs/operations.md +78 -14
  29. package/docs/pull-workers.md +11 -0
  30. package/docs/relationships.md +13 -0
  31. package/docs/service-setup.md +10 -10
  32. package/docs/t3-integration.md +6 -2
  33. package/docs/t3-reverse-control.md +5 -5
  34. package/docs/t3-wake-fence-r4.md +1 -1
  35. package/docs/test-suite-isolation.md +8 -6
  36. package/docs/trials/chatgpt-agent.md +47 -0
  37. package/docs/trials/claude-code-requester.md +68 -0
  38. package/docs/trials/muse.md +46 -0
  39. package/docs/usage.md +35 -9
  40. package/docs/worker-clients.md +1 -1
  41. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  42. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  43. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  44. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  45. package/package.json +4 -3
  46. package/packages/job-core/protocol/canonical.mjs +45 -7
  47. package/packages/job-core/transitions.mjs +4 -2
  48. package/scripts/upgrade-drain.mjs +96 -8
  49. package/scripts/worker-bridge-setup.mjs +215 -120
  50. package/src/ack-ledger.mjs +7 -1
  51. package/src/acp-bridge.mjs +256 -28
  52. package/src/admin-socket.mjs +32 -3
  53. package/src/alerts.mjs +17 -8
  54. package/src/answer-journal-retention.mjs +82 -0
  55. package/src/answer-journal.mjs +6 -4
  56. package/src/as-store.mjs +51 -6
  57. package/src/as.mjs +27 -5
  58. package/src/catalog-switch-inventory.mjs +70 -0
  59. package/src/check-response.mjs +4 -1
  60. package/src/claim-command-ledger.mjs +3 -2
  61. package/src/cli-help.mjs +29 -10
  62. package/src/cli-name.mjs +13 -1
  63. package/src/connect-cli.mjs +159 -4
  64. package/src/deadman.mjs +8 -5
  65. package/src/delivery.mjs +2 -19
  66. package/src/destinations/index.mjs +75 -14
  67. package/src/drain-runner.mjs +5 -1
  68. package/src/follow-current.mjs +3 -1
  69. package/src/get-summary.mjs +11 -2
  70. package/src/git-env.mjs +1 -1
  71. package/src/gozar-routes.mjs +313 -94
  72. package/src/host-budget-storage.py +56 -6
  73. package/src/host-budget.mjs +98 -15
  74. package/src/host-execution-policy.mjs +17 -6
  75. package/src/inbox.mjs +13 -3
  76. package/src/legacy-names.mjs +0 -2
  77. package/src/lifecycle.mjs +104 -11
  78. package/src/loopback-probe.mjs +46 -0
  79. package/src/mcp-outcome.mjs +3 -1
  80. package/src/mcp-sse.mjs +2 -1
  81. package/src/mcp-stdio.mjs +192 -30
  82. package/src/patch-apply.mjs +285 -19
  83. package/src/phase-trace.mjs +73 -0
  84. package/src/prepared-go-modules.mjs +127 -0
  85. package/src/prepared-node-modules.mjs +225 -38
  86. package/src/prepared-pnpm.mjs +276 -0
  87. package/src/prepared-store-prune.mjs +52 -0
  88. package/src/projects.mjs +59 -7
  89. package/src/protocol-artifact-commands.mjs +28 -0
  90. package/src/protocol-finish.mjs +3 -2
  91. package/src/publication-authority.mjs +22 -0
  92. package/src/publish-plan.mjs +2 -2
  93. package/src/pull-queue.mjs +55 -20
  94. package/src/read-api.mjs +127 -0
  95. package/src/redaction.mjs +173 -0
  96. package/src/rejections.mjs +19 -3
  97. package/src/route-custody.mjs +90 -0
  98. package/src/route-publication.mjs +50 -0
  99. package/src/route-setup.mjs +184 -0
  100. package/src/schema-subset.mjs +5 -3
  101. package/src/server.mjs +619 -88
  102. package/src/service-launchd.mjs +5 -1
  103. package/src/service-update-lock.mjs +7 -4
  104. package/src/service-update-runtime.mjs +64 -19
  105. package/src/service-update.mjs +193 -48
  106. package/src/service.mjs +276 -77
  107. package/src/setup.mjs +48 -25
  108. package/src/signal.mjs +1 -1
  109. package/src/status-evidence.mjs +18 -5
  110. package/src/status-summary.mjs +3 -0
  111. package/src/store.mjs +1086 -127
  112. package/src/submission-policy.mjs +257 -56
  113. package/src/t3-control.mjs +1 -1
  114. package/src/t3.mjs +14 -8
  115. package/src/terminal-safe.mjs +9 -7
  116. package/src/tool-registry.mjs +134 -41
  117. package/src/try-exposure.mjs +53 -86
  118. package/src/try-hosted.mjs +257 -70
  119. package/src/try.mjs +48 -22
  120. package/src/work-order.mjs +11 -6
  121. package/src/worker-instructions.mjs +26 -4
  122. package/src/worker-runs.mjs +35 -0
  123. package/src/workers.mjs +49 -4
  124. package/src/workspace.mjs +354 -54
  125. package/systemd/dot-deadman.service +3 -1
  126. package/docs/dot-pr-reviewer.config.example.json +0 -9
  127. package/docs/pr-head-reviewer.md +0 -70
  128. package/src/pr-head-reviewer.mjs +0 -596
  129. package/systemd/dot-pr-reviewer.service +0 -11
  130. package/systemd/dot-pr-reviewer.timer +0 -10
@@ -0,0 +1,276 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { hash, failure, markUsed, addScratchMountpoints, repairScratchMountpoints, readRegular, checkDirectory, checkParents, validateTree, freezeTree, thawTree, shellQuote, prepareInChild, preparedNodeStore } from './prepared-node-modules.mjs';
7
+
8
+ // A pnpm repository's dependencies are prepared on the host (with network) from its lock alone, then mounted read-only like an npm
9
+ // workspace tree set: the root node_modules plus each importer's own node_modules. `pnpm fetch` fills a stage-private store from
10
+ // pnpm-lock.yaml; an offline frozen install with copy import then assembles the trees (copy, not hardlinks: freezeTree must not change
11
+ // store inodes). The sandbox has no network and no pnpm. Same trust rule as npm: the key is file hashes, never a worker's edits.
12
+ const recovery = source => `dalan prepare-deps ${shellQuote(path.resolve(source))} --pnpm`;
13
+ const SAFE_SEGMENT = /^[A-Za-z0-9_@.+-]+$/;
14
+ const safeImporter = value => typeof value === 'string' && value.split('/').every(part => SAFE_SEGMENT.test(part) && part !== '.' && part !== '..' && part !== 'node_modules' && part !== '.git');
15
+ // Repository files that make pnpm read repo-controlled settings or run repository code during install.
16
+ const SETTINGS_FILES = ['.npmrc', '.pnpmfile.cjs', '.pnpmfile.mjs', 'pnpmfile.cjs'];
17
+ // pnpm-workspace.yaml is an allow-list, not a deny-list: pnpm reads any top-level key as a setting, and quoted or flow-style spellings of
18
+ // registry, pnpmfile or configDependencies keys are real settings that run repository code or reach other hosts. A key that is not here,
19
+ // or any YAML shape this line reader does not understand, makes the repository unsupported.
20
+ const WORKSPACE_KEYS = new Set(['packages', 'catalog', 'catalogs', 'overrides', 'publicHoistPattern', 'hoistPattern', 'childConcurrency', 'allowBuilds', 'onlyBuiltDependencies', 'ignoredBuiltDependencies', 'neverBuiltDependencies', 'minimumReleaseAge', 'minimumReleaseAgeExclude']);
21
+ // package.json#pnpm: the same rule for the root manifest's `pnpm` block.
22
+ const MANIFEST_PNPM_KEYS = new Set(['overrides', 'onlyBuiltDependencies', 'ignoredBuiltDependencies', 'neverBuiltDependencies', 'allowBuilds', 'peerDependencyRules']);
23
+ export function workspaceYamlReason(yaml) {
24
+ for (const line of String(yaml).split('\n')) {
25
+ if (/^\s*(#|$)/.test(line) || /^[ \t]/.test(line) || /^-(\s|$)/.test(line)) continue; // comments, blank lines, indented values, unindented sequence items
26
+ if (/^---\s*$/.test(line)) continue;
27
+ const key = /^(?:'([^']+)'|"([^"]+)"|([A-Za-z][A-Za-z0-9_]*))\s*:(?:\s|$)/.exec(line);
28
+ if (!key) return 'pnpm-workspace.yaml has a shape this reader does not understand';
29
+ if (!WORKSPACE_KEYS.has(key[1] ?? key[2] ?? key[3])) return `pnpm-workspace.yaml sets ${key[1] ?? key[2] ?? key[3]}, which is unsupported`;
30
+ }
31
+ return null;
32
+ }
33
+
34
+ // importers: keys of the lock's `importers:` block, and the link:/file: specs inside it. A small fail-closed line parser: any shape it
35
+ // does not recognise yields null (unsupported) rather than a guess.
36
+ export function parseLock(lockText) {
37
+ // pnpm 11+ writes two YAML documents: the environment lock (the pinned pnpm itself), then the project lock. Only the last is the project's.
38
+ const text = String(lockText), lines = text.slice(text.lastIndexOf('\n---\n') + 1).split('\n');
39
+ const version = lines.find(line => /^lockfileVersion:/.test(line));
40
+ if (!version || !/^lockfileVersion:\s*['"]?9\.\d+['"]?\s*$/.test(version)) return { error: 'only pnpm lockfiles of version 9 are supported' };
41
+ const start = lines.findIndex(line => /^importers:\s*$/.test(line));
42
+ if (start < 0) return { error: 'the pnpm lock has no importers block' };
43
+ const importers = [], links = [];
44
+ let current = null;
45
+ for (const line of lines.slice(start + 1)) {
46
+ if (/^\S/.test(line)) break; // the next top-level block ends importers
47
+ const key = /^ {2}(?:'([^']+)'|"([^"]+)"|([^\s'"#][^:]*)):\s*(?:\{\s*\})?\s*$/.exec(line);
48
+ if (key) { current = key[1] ?? key[2] ?? key[3]; importers.push(current); continue; }
49
+ const spec = /^\s+(?:version|specifier):\s*['"]?(link|file|portal):(\S*?)['"]?\s*$/.exec(line);
50
+ if (spec && current !== null) links.push({ importer: current, kind: spec[1], target: spec[2] });
51
+ }
52
+ // Any line, in any block or flow layout, that names a tarball URL, a git repository, a directory or a downloaded binary runtime.
53
+ const rest = lines.filter(line => /(?:^|[\s{,])(?:tarball|directory|repo|commit|url):\s/.test(line) || /\btype:\s*['"]?(?:git|directory|binary|variations)\b/.test(line));
54
+ return { importers, links, localResolutions: rest.length, patched: lines.some(line => /^patchedDependencies:/.test(line)) };
55
+ }
56
+
57
+ // Workspace package directories come from the `packages:` globs of pnpm-workspace.yaml. A workspace package with no dependencies has no
58
+ // importer block in the lock, yet others link to it, so the globs (not only the importers) say which directories a link may name.
59
+ export function workspaceGlobs(yaml) {
60
+ const globs = [], lines = String(yaml).split('\n');
61
+ const start = lines.findIndex(line => /^packages:\s*$/.test(line));
62
+ if (start < 0) return globs;
63
+ for (const line of lines.slice(start + 1)) {
64
+ if (/^\S/.test(line)) break;
65
+ const item = /^\s+-\s*(?:'([^']*)'|"([^"]*)"|([^\s#]+))\s*(?:#.*)?$/.exec(line);
66
+ if (item) globs.push(item[1] ?? item[2] ?? item[3]);
67
+ }
68
+ return globs;
69
+ }
70
+ const globRegex = glob => new RegExp('^' + glob.replace(/^\.\//, '').replace(/\/$/, '').split('/').map(part => part === '**' ? '.*' : part.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]+')).join('/') + '$');
71
+ export function inWorkspaceGlobs(globs, target) {
72
+ const include = globs.filter(glob => !glob.startsWith('!')), exclude = globs.filter(glob => glob.startsWith('!'));
73
+ return include.some(glob => globRegex(glob).test(target)) && !exclude.some(glob => globRegex(glob.slice(1)).test(target));
74
+ }
75
+ // Real (non-link) directories with a package.json under the globs, to a bounded depth.
76
+ function workspaceDirectories(root, globs) {
77
+ const found = [], walk = (rel, depth) => {
78
+ if (depth > 4) return;
79
+ let names; try { names = fs.readdirSync(path.join(root, rel), { withFileTypes: true }); } catch { return; }
80
+ for (const entry of names) {
81
+ if (!entry.isDirectory() || entry.isSymbolicLink() || ['node_modules', '.git'].includes(entry.name)) continue;
82
+ const child = rel ? `${rel}/${entry.name}` : entry.name;
83
+ if (safeImporter(child) && inWorkspaceGlobs(globs, child) && fs.existsSync(path.join(root, child, 'package.json'))) found.push(child);
84
+ walk(child, depth + 1);
85
+ }
86
+ };
87
+ walk('', 0);
88
+ return found;
89
+ }
90
+
91
+ const manager = manifest => { const match = /^pnpm@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?:\+.*)?$/.exec(String(JSON.parse(manifest).packageManager ?? '')); return match ? match[1] : null; };
92
+ const safeEnv = env => Object.fromEntries(Object.entries(env).filter(([name]) => /^(PATH|HOME|LANG|TMPDIR|XDG_.*|NODE_EXTRA_CA_CERTS|SSL_CERT_FILE|(npm|pnpm)_config_(registry|fetch_retries|fetch_retry_.*)|(https?|no)_proxy)$/i.test(name)));
93
+ const versions = new Map(), FAILED_VERSION_TTL_MS = 60e3;
94
+ // The version `pnpm` reports for a package.json that pins `packageManager` (pnpm switches to the pinned release when it has it). Run in a
95
+ // scratch directory, not the repository, so no repository setting is read. null when pnpm is missing or reports another version.
96
+ function hostPnpmVersion(pinned, env, timeout = 5000) {
97
+ const key = `${pinned}\0${env.PATH ?? ''}`;
98
+ const known = versions.get(key);
99
+ if (known && (known.reported !== null || Date.now() - known.at < FAILED_VERSION_TTL_MS)) return known.reported;
100
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dalan-pnpm-version-'));
101
+ try {
102
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'v', packageManager: `pnpm@${pinned}` }));
103
+ const run = spawnSync('pnpm', ['--version'], { cwd: dir, env: { ...safeEnv(env), COREPACK_ENABLE_AUTO_PIN: '0' }, encoding: 'utf8', timeout }); // callers on the claim path keep the 5 s default (spawnSync blocks the bridge); `dalan prepare-deps` allows a download. A failure is remembered for a minute only
104
+ const reported = run.status === 0 ? run.stdout.trim() : null;
105
+ versions.set(key, { reported, at: Date.now() });
106
+ return reported;
107
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
108
+ }
109
+
110
+ // Pure verdict from file contents (`read(name)` returns a Buffer or null); null means supported or nothing to prepare. Shared by the offer filter,
111
+ // which reads the pinned base commit, and by inputs(), which reads the checkout.
112
+ export function pnpmUnsupportedReason(read) {
113
+ const lock = read('pnpm-lock.yaml');
114
+ if (!lock) return null;
115
+ const manifest = read('package.json');
116
+ if (!manifest) return 'a pnpm lock needs a root package.json';
117
+ if (read('package-lock.json')) return 'both package-lock.json and pnpm-lock.yaml are present';
118
+ let pinned, packageJson;
119
+ try { packageJson = JSON.parse(manifest); pinned = manager(manifest); } catch { return 'package.json is not valid JSON'; }
120
+ if (!pinned) return 'package.json must pin packageManager to an exact pnpm version';
121
+ const parsed = parseLock(lock.toString('utf8'));
122
+ if (parsed.error) return parsed.error;
123
+ if (parsed.patched) return 'patchedDependencies are unsupported';
124
+ if (parsed.localResolutions) return 'local file or directory, git and URL dependencies (and downloaded runtimes) are unsupported';
125
+ const importers = new Set(parsed.importers);
126
+ if (!importers.has('.')) return 'the pnpm lock has no root importer';
127
+ for (const name of importers) if (name !== '.' && !safeImporter(name)) return 'an importer path is unsupported';
128
+ const yaml = read('pnpm-workspace.yaml')?.toString('utf8') ?? '', globs = workspaceGlobs(yaml);
129
+ for (const link of parsed.links) {
130
+ const target = link.kind === 'link' ? path.posix.normalize(path.posix.join(link.importer, link.target)) : null;
131
+ if (!target || !(importers.has(target) || (safeImporter(target) && inWorkspaceGlobs(globs, target)))) return 'link or file dependencies that are not workspace packages are unsupported';
132
+ }
133
+ for (const name of SETTINGS_FILES) if (read(name)) return `a repository ${name} is unsupported`;
134
+ const yamlReason = workspaceYamlReason(yaml);
135
+ if (yamlReason) return yamlReason;
136
+ for (const name of Object.keys(packageJson.pnpm ?? {})) if (!MANIFEST_PNPM_KEYS.has(name)) return `package.json sets pnpm.${name}, which is unsupported`;
137
+ return null;
138
+ }
139
+ // For the offer filter: version check included, memoised per packageManager.
140
+ export function pnpmUnsupported(read, env = process.env) {
141
+ const reason = pnpmUnsupportedReason(read);
142
+ if (reason || !read('pnpm-lock.yaml')) return reason;
143
+ const pinned = manager(read('package.json'));
144
+ const reported = hostPnpmVersion(pinned, env);
145
+ return reported === pinned ? null : `the host's pnpm (${reported ?? 'missing'}) is not the pinned packageManager pnpm@${pinned}`;
146
+ }
147
+ // Repository-relative files that must equal the pinned base for a lock to be prepared from it (pnpm-workspace.yaml is optional).
148
+ export function pnpmInputFiles(lock) {
149
+ const parsed = parseLock(lock.toString('utf8'));
150
+ return ['pnpm-lock.yaml', 'package.json', ...(parsed.importers ?? []).filter(name => name !== '.').map(name => `${name}/package.json`)].sort();
151
+ }
152
+
153
+ function inputs(source, env = process.env, versionTimeoutMs = 5000) {
154
+ const root = path.resolve(source);
155
+ if (fs.realpathSync(root) !== root || !fs.lstatSync(root).isDirectory()) throw failure('dependencies_invalid', 'source directory must be canonical');
156
+ const read = name => readRegular(path.join(root, name), true);
157
+ const lock = read('pnpm-lock.yaml');
158
+ if (!lock) return null;
159
+ const unsupported = pnpmUnsupportedReason(read);
160
+ if (unsupported) throw failure('dependencies_unsupported', unsupported);
161
+ const manifest = readRegular(path.join(root, 'package.json')), workspaceYaml = read('pnpm-workspace.yaml') ?? Buffer.alloc(0);
162
+ const pinned = manager(manifest);
163
+ const reported = hostPnpmVersion(pinned, env, versionTimeoutMs);
164
+ if (reported !== pinned) throw failure('dependencies_unsupported', `the host's pnpm (${reported ?? 'missing'}) is not the pinned packageManager pnpm@${pinned}`);
165
+ const importers = parseLock(lock.toString('utf8')).importers.filter(name => name !== '.').sort();
166
+ const files = new Map();
167
+ for (const name of importers) {
168
+ const dir = path.join(root, name);
169
+ if (fs.realpathSync(dir) !== dir) throw failure('dependencies_invalid', 'importer path must not contain links');
170
+ for (const settings of SETTINGS_FILES) if (fs.existsSync(path.join(dir, settings))) throw failure('dependencies_unsupported', `an importer ${settings} is unsupported`);
171
+ files.set(name, readRegular(path.join(dir, 'package.json')));
172
+ }
173
+ const linkable = [...new Set([...importers, ...workspaceDirectories(root, workspaceGlobs(workspaceYaml.toString('utf8')))])].sort();
174
+ const runtime = { node: process.version, pnpm: pinned, platform: process.platform, arch: process.arch };
175
+ const identity = { kind: 'pnpm', lock_sha256: hash(lock), manifest_sha256: hash(manifest), workspace_yaml_sha256: hash(workspaceYaml), workspaces: Object.fromEntries(importers.map(name => [name, hash(files.get(name))])), runtime };
176
+ const key = hash(JSON.stringify({ kind: 'pnpm', runtime, manifest_sha256: identity.manifest_sha256, workspace_yaml_sha256: identity.workspace_yaml_sha256, workspaces: identity.workspaces }));
177
+ return { root, lock, manifest, workspaceYaml, hasWorkspaceYaml: read('pnpm-workspace.yaml') !== null, files, importers, linkable, identity, key, pinned };
178
+ }
179
+ const entryPath = (base, input) => path.join(base, input.identity.lock_sha256, input.key);
180
+ const placeFor = (input, dir) => ({ dir, workspaces: input.linkable, treeDirs: ['node_modules', ...input.importers.map(name => `${name}/node_modules`)] });
181
+ function lookup(input, base) {
182
+ const entry = entryPath(base, input);
183
+ try {
184
+ checkParents(base); checkDirectory(base, true); checkDirectory(path.dirname(entry), true); checkDirectory(entry, true);
185
+ const metaPath = path.join(entry, 'metadata.json'), st = fs.lstatSync(metaPath);
186
+ if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o222)) throw new Error('bad metadata');
187
+ const metadata = JSON.parse(readRegular(metaPath));
188
+ if (JSON.stringify(metadata.identity) !== JSON.stringify(input.identity)) throw new Error('identity mismatch');
189
+ const places = [{ dir: '', treePath: path.join(entry, 'node_modules') }, ...(metadata.trees ?? []).map(name => ({ dir: name, treePath: path.join(entry, 'workspaces', name, 'node_modules') }))];
190
+ if (places.slice(1).some(place => !input.importers.includes(place.dir))) throw new Error('unexpected workspace tree');
191
+ for (const place of places) validateTree(place.treePath, placeFor(input, place.dir));
192
+ repairScratchMountpoints(places.map(place => place.treePath));
193
+ markUsed(entry);
194
+ return { treePath: places[0].treePath, workspaceTrees: places.slice(1).map(({ dir, treePath }) => ({ path: dir, treePath })), ...input.identity };
195
+ } catch {
196
+ throw failure('dependencies_unprepared', `missing or invalid preparation; owner recovery: ${recovery(input.root)} --replace-invalid`);
197
+ }
198
+ }
199
+ export function resolvePreparedPnpm(sourceDir, options = {}) {
200
+ const input = inputs(sourceDir, options.env ?? process.env);
201
+ return input ? lookup(input, preparedNodeStore(options)) : null;
202
+ }
203
+
204
+ export function preparePnpm(sourceDir, options = {}) {
205
+ const env = options.env ?? process.env;
206
+ const input = inputs(sourceDir, env, options.versionTimeoutMs ?? 120000);
207
+ if (!input) throw failure('dependencies_invalid', 'root pnpm-lock.yaml required');
208
+ const base = preparedNodeStore(options);
209
+ fs.mkdirSync(base, { recursive: true, mode: 0o700 });
210
+ checkParents(base); checkDirectory(base, true);
211
+ fs.mkdirSync(path.join(base, input.identity.lock_sha256), { mode: 0o700, recursive: true }); checkDirectory(path.join(base, input.identity.lock_sha256), true);
212
+ const destination = entryPath(base, input);
213
+ if (fs.existsSync(destination)) {
214
+ try { return lookup(input, base); }
215
+ catch (error) { if (!options.replaceInvalid) throw error; }
216
+ }
217
+ const stage = fs.mkdtempSync(path.join(base, `.stage-${process.pid}-`));
218
+ try {
219
+ const work = path.join(stage, 'work'), store = path.join(stage, 'store'), cache = path.join(stage, 'cache');
220
+ for (const dir of [work, store, cache]) fs.mkdirSync(dir, { mode: 0o700 });
221
+ const write = (name, bytes) => { fs.mkdirSync(path.dirname(path.join(work, name)), { recursive: true, mode: 0o700 }); fs.writeFileSync(path.join(work, name), bytes, { mode: 0o600 }); };
222
+ write('pnpm-lock.yaml', input.lock); write('package.json', input.manifest);
223
+ if (input.hasWorkspaceYaml) write('pnpm-workspace.yaml', input.workspaceYaml);
224
+ for (const [name, bytes] of input.files) write(`${name}/package.json`, bytes);
225
+ // Settings come from the host environment only: an empty user and global rc, no repository rc (refused above).
226
+ const empty = path.join(stage, 'empty-npmrc'); fs.writeFileSync(empty, '', { mode: 0o600 });
227
+ // HOME stays the owner's so pnpm finds the pinned release it switches to; the stage-private store and XDG_CACHE_HOME (pnpm's metadata cache) hold everything this install fetches: the offline install reads the package metadata that fetch cached.
228
+ const childEnv = { ...safeEnv(env), XDG_CACHE_HOME: cache, CI: 'true', COREPACK_ENABLE_AUTO_PIN: '0', npm_config_userconfig: empty, npm_config_globalconfig: empty,
229
+ // `pnpm fetch` has no --ignore-scripts flag; a lifecycle or prepare script must not run on the host during fetch either.
230
+ npm_config_ignore_scripts: 'true', pnpm_config_ignore_scripts: 'true' };
231
+ const run = (args, label) => {
232
+ const result = spawnSync('pnpm', args, { cwd: work, stdio: ['ignore', 'ignore', 'pipe'], encoding: 'utf8', maxBuffer: 1 << 20, timeout: options.timeoutMs ?? 600000, env: childEnv });
233
+ if (result.error || result.status !== 0) {
234
+ const exit = result.error ? `error: ${result.error.message}` : result.signal ? `signal ${result.signal}` : `exit status ${result.status}`;
235
+ const detail = String(result.stderr ?? '').trim().split('\n').slice(-3).join(' ').slice(0, 300);
236
+ throw failure('dependencies_install_failed', `pnpm ${label} failed (${exit}${detail ? `: ${detail}` : ''}); no preparation published`);
237
+ }
238
+ };
239
+ // fetch also fills the virtual store (node_modules/.pnpm), so it needs copy import too: hardlinks there would survive into the published tree.
240
+ run(['fetch', '--ignore-pnpmfile', '--package-import-method=copy', '--store-dir', store], 'fetch');
241
+ run(['install', '--offline', '--frozen-lockfile', '--ignore-scripts', '--ignore-pnpmfile', '--package-import-method=copy', '--store-dir', store], 'install');
242
+ const trees = [];
243
+ fs.mkdirSync(path.join(work, 'node_modules'), { recursive: true, mode: 0o700 });
244
+ fs.renameSync(path.join(work, 'node_modules'), path.join(stage, 'node_modules'));
245
+ for (const name of input.importers) {
246
+ const tree = path.join(work, name, 'node_modules');
247
+ if (!fs.existsSync(tree)) continue;
248
+ fs.mkdirSync(path.join(stage, 'workspaces', name), { recursive: true, mode: 0o700 });
249
+ fs.renameSync(tree, path.join(stage, 'workspaces', name, 'node_modules')); trees.push(name);
250
+ }
251
+ for (const name of ['work', 'store', 'cache']) fs.rmSync(path.join(stage, name), { recursive: true, force: true });
252
+ fs.rmSync(empty, { force: true });
253
+ for (const [dir, tree] of [['', path.join(stage, 'node_modules')], ...trees.map(name => [name, path.join(stage, 'workspaces', name, 'node_modules')])]) { addScratchMountpoints(tree); freezeTree(tree); validateTree(tree, placeFor(input, dir)); }
254
+ fs.writeFileSync(path.join(stage, 'metadata.json'), JSON.stringify({ identity: input.identity, trees }) + '\n', { mode: 0o400 });
255
+ if (fs.existsSync(destination)) {
256
+ try { return lookup(input, base); }
257
+ catch (error) { if (!options.replaceInvalid) throw error; }
258
+ // Keep the old inodes for any running read-only mount; the new bytes go to a new path.
259
+ fs.renameSync(destination, path.join(base, '.replaced-' + randomUUID()));
260
+ }
261
+ try { fs.renameSync(stage, destination); }
262
+ catch (error) { // another publisher won the race: reuse its entry when it is valid, otherwise report the original failure
263
+ try { return lookup(input, base); } catch { throw error; }
264
+ }
265
+ return lookup(input, base);
266
+ } finally {
267
+ if (fs.existsSync(stage)) { thawTree(stage); fs.rmSync(stage, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); }
268
+ }
269
+ }
270
+
271
+ export function preparePnpmInChild(sourceDir, { timeoutMs = 600000, env = process.env } = {}) {
272
+ const root = fs.realpathSync(sourceDir);
273
+ const input = inputs(root, env);
274
+ if (!input) return Promise.resolve(null);
275
+ return prepareInChild({ root, key: `pnpm:${input.identity.lock_sha256}:${input.key}`, base: preparedNodeStore({}), flags: ['--pnpm'], timeoutMs, env });
276
+ }
@@ -0,0 +1,52 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { failure, checkParents, checkDirectory, thawTree, preparedNodeStore } from './prepared-node-modules.mjs';
5
+
6
+ // Keep-newest-N pruning for the prepared node_modules store (npm and pnpm entries share it) and, with `base`, the Go module store (same
7
+ // <lock>/<key>/metadata.json layout). A running check bind-mounts an entry
8
+ // read-only, so an entry is never deleted in place: it is renamed to `.pruned-<uuid>` (open files and mounts keep their inodes), and only a
9
+ // later pass, at least an hour after, deletes it. Entries younger than a day are never touched, which also spares an entry a check
10
+ // resolved moments ago. Entries rank by last use (markUsed touches metadata.json when a check resolves one), not publication time, so a
11
+ // busy repository's entry is not evicted by newer entries of idle ones. Stale `.replaced-*` and abandoned `.stage-*` directories follow the same age rule.
12
+ const HOUR = 3600e3, DAY = 24 * HOUR;
13
+ const list = dir => { try { return fs.readdirSync(dir); } catch { return []; } };
14
+ const remove = target => { try { thawTree(target); fs.rmSync(target, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); return true; } catch { return false; } };
15
+
16
+ export function pruneNodeStore(options = {}) {
17
+ const keep = options.keep ?? 4, now = options.now ?? Date.now();
18
+ if (!Number.isInteger(keep) || keep < 1) throw failure('dependencies_invalid', 'keep must be a positive integer');
19
+ const base = options.base ?? preparedNodeStore(options);
20
+ const result = { kept: [], renamed: [], deleted: [], skipped_young: [] };
21
+ if (!fs.existsSync(base)) return result;
22
+ checkParents(base); checkDirectory(base, true);
23
+ // Published entries: <lock hash>/<key>/metadata.json; its mtime is the last use (publication time until a check resolves the entry).
24
+ const entries = [];
25
+ for (const lockName of list(base).filter(name => !name.startsWith('.'))) {
26
+ for (const key of list(path.join(base, lockName))) {
27
+ const entry = path.join(base, lockName, key);
28
+ try { entries.push({ entry, published: fs.lstatSync(path.join(entry, 'metadata.json')).mtimeMs }); } catch { /* not an entry */ }
29
+ }
30
+ }
31
+ entries.sort((a, b) => b.published - a.published);
32
+ entries.forEach((item, index) => {
33
+ if (index < keep) return result.kept.push(item.entry);
34
+ if (now - item.published < DAY) return result.skipped_young.push(item.entry);
35
+ try { fs.renameSync(item.entry, path.join(base, `.pruned-${randomUUID()}`)); result.renamed.push(item.entry); } catch { result.kept.push(item.entry); }
36
+ });
37
+ // An empty lock directory may belong to a preparation that is still fetching (it creates the directory first and publishes last), so
38
+ // only one that has stayed empty for a day is removed.
39
+ for (const lockName of list(base).filter(name => !name.startsWith('.'))) {
40
+ const dir = path.join(base, lockName);
41
+ try { if (now - fs.lstatSync(dir).mtimeMs >= DAY) fs.rmdirSync(dir); } catch { /* not empty or gone */ }
42
+ }
43
+ // Delete only what an earlier pass renamed (ctime moves on rename) or what has been stale for a day.
44
+ for (const name of list(base)) {
45
+ const target = path.join(base, name);
46
+ let age;
47
+ try { const st = fs.lstatSync(target); age = now - (name.startsWith('.stage-') ? st.mtimeMs : st.ctimeMs); } catch { continue; }
48
+ const limit = name.startsWith('.pruned-') ? HOUR : /^\.(replaced|stage)-/.test(name) ? DAY : Infinity;
49
+ if (age >= limit && remove(target)) result.deleted.push(target);
50
+ }
51
+ return result;
52
+ }
package/src/projects.mjs CHANGED
@@ -96,7 +96,7 @@ export function loadCapacity(file = defaultPath(os.homedir(),'.config/dot-bridge
96
96
  }
97
97
 
98
98
  export function assignmentInput(assignment) {
99
- if (!['read-only', 'implementation'].includes(assignment.execution_scope)) throw new Error('invalid execution scope');
99
+ if (!['read-only', 'implementation'].includes(assignment.execution_scope)) throw new Error('invalid execution_scope: expected one of read-only, implementation');
100
100
  if (assignment.inputs?.length !== 1) throw new Error('one pinned GitHub input required');
101
101
  const input = assignment.inputs[0];
102
102
  if (!validRepo(input.github_repo) || !fullSha.test(input.base_sha || '')) throw new Error('github_repo and full base_sha required');
@@ -254,9 +254,35 @@ export function argvTestFiles(argv) {
254
254
  return [...new Set(found)];
255
255
  }
256
256
 
257
+ export function namedCheckPath(command) {
258
+ if (typeof command !== 'string' || command.length > 512) return null;
259
+ const match = /^node ([A-Za-z0-9_.@/-]+\.(?:mjs|js|cjs))$/.exec(command);
260
+ if (!match || match[0] !== command) return null;
261
+ const target = match[1];
262
+ return !argvOk(['node', target]) || !relPath(target) || target.startsWith('-') ||
263
+ target.split('/').some(segment => !segment || segment === '.') ? null : target;
264
+ }
265
+
266
+ export const isNamedCheck = id => typeof id === 'string' && /^named\/[1-8]$/.test(id) && id.length === 7;
267
+ export function assignmentNamedCheck(assignment, id, defaultSpec) {
268
+ if (!isNamedCheck(id) || !defaultSpec || assignment?.execution_scope !== 'implementation' ||
269
+ !Array.isArray(assignment.checks) || assignment.checks.length > 8) return null;
270
+ const target = namedCheckPath(assignment.checks[Number(id.at(-1)) - 1]);
271
+ if (!target) return null;
272
+ const { install_argv, timeout_ms, output_bytes, prerequisites, host_budget } = defaultSpec;
273
+ return normalizeCheck({
274
+ argv: ['node', target], timeout_ms, output_bytes,
275
+ ...(install_argv ? { install_argv } : {}),
276
+ ...(prerequisites ? { prerequisites } : {}),
277
+ ...(host_budget ? { host_budget } : {}),
278
+ test_paths: [target],
279
+ }, id);
280
+ }
281
+
257
282
  export function normalizeCheck(check, id = 'default', derived = {}) {
258
283
  if (!argvOk(check.argv)) throw new Error(`invalid check ${id}`);
259
284
  if (check.install_argv && !argvOk(check.install_argv)) throw new Error(`invalid install ${id}`);
285
+ if (check.dependencies !== undefined && check.dependencies !== 'prepared-npm') throw new Error(`invalid dependencies ${id}`);
260
286
  const timeout_ms = check.timeout_ms ?? 120000;
261
287
  const output_bytes = check.output_bytes ?? 262144;
262
288
  if (!Number.isInteger(timeout_ms) || timeout_ms < 100 || timeout_ms > 900000) throw new Error(`invalid timeout ${id}`);
@@ -270,6 +296,7 @@ export function normalizeCheck(check, id = 'default', derived = {}) {
270
296
  const test_paths = (check.test_paths ?? derived.test_paths)?.map(p => p === './...' ? p : p.replace(/^\.\//, '').replace(/\/$/, '')) ?? null;
271
297
  return {
272
298
  id, argv: check.argv, install_argv: check.install_argv || null, timeout_ms, output_bytes,
299
+ dependencies: check.dependencies ?? null,
273
300
  ...(check.host_budget === undefined ? {} : { host_budget: parseHostBudget(check.host_budget) }),
274
301
  prerequisites, prerequisites_reason: prerequisites ? null : derived.prerequisites_reason || 'not declared',
275
302
  readiness_argv: check.readiness_argv || null,
@@ -325,9 +352,17 @@ export function ownerChecks() {
325
352
  // describe checks, but it cannot supply this authority or an owner budget.
326
353
  export function ownerCheck(repo, checkId) {
327
354
  const data = ownerChecks();
328
- const check = data?.[repo]?.checks?.[checkId];
329
- if (!check) return null;
330
- try { return normalizeCheck(check, checkId); } catch { return null; }
355
+ const checks = data?.[repo]?.checks;
356
+ if (!checks || !Object.hasOwn(checks, checkId)) return null;
357
+ return normalizeOwnerCheck(checks[checkId], checkId);
358
+ }
359
+
360
+ function normalizeOwnerCheck(check, id) {
361
+ try { return normalizeCheck(check, id); }
362
+ catch {
363
+ // Do not copy an owner command or secrets it may contain into a worker-visible error.
364
+ throw Object.assign(new Error(`owner_check_invalid: check "${id}" is invalid; review its command and limits in owner configuration`), {code:'owner_check_invalid'});
365
+ }
331
366
  }
332
367
 
333
368
  const repoCheckFile=dir=>hasCheckMetadata(dir,'.dalan.json')?'.dalan.json':'.dot-bridge.json';
@@ -347,8 +382,10 @@ function overrideCheck(repo, dir, checkId) {
347
382
  }
348
383
  const data = parseCheckMetadata(text);
349
384
  const source = ownerConfig ? data[repo] : data;
385
+ if (ownerConfig && source?.checks && Object.hasOwn(source.checks, checkId))
386
+ return { spec: normalizeOwnerCheck(source.checks[checkId], checkId), from: 'owner_config' };
350
387
  if (source?.checks?.[checkId]) {
351
- try { return { spec: normalizeCheck(source.checks[checkId], checkId), from: ownerConfig ? 'owner_config' : 'workspace_file' }; }
388
+ try { return { spec: normalizeCheck(source.checks[checkId], checkId), from: 'workspace_file' }; }
352
389
  catch { throw new Error('invalid check metadata'); }
353
390
  }
354
391
  }
@@ -445,6 +482,8 @@ export function withCheckMetadata(mirror, sha, fn) {
445
482
  const caches = path.join(workspaceRoot(), 'caches');
446
483
  fs.mkdirSync(caches, { recursive: true, mode: 0o700 });
447
484
  const dir = fs.mkdtempSync(path.join(caches, 'check-metadata-'));
485
+ let deferredCleanup = false;
486
+ const cleanup = () => fs.rmSync(dir, { recursive: true, force: true });
448
487
  try {
449
488
  const entries = spawnSync('git', ['-C', mirror, 'ls-tree', '-z', '--full-tree', sha, '--', ...checkMetadataFiles], { encoding: 'utf8', timeout: 10000, maxBuffer: 1024 * 1024, env: gitEnv() });
450
489
  if (entries.error || entries.status !== 0) throw new Error('cannot inspect pinned check metadata');
@@ -465,8 +504,21 @@ export function withCheckMetadata(mirror, sha, fn) {
465
504
  if (found.status === 0) fs.writeFileSync(path.join(dir, file), found.stdout);
466
505
  else throw new Error(`cannot read check metadata: ${file}`);
467
506
  }
468
- return fn(dir);
469
- } finally { fs.rmSync(dir, { recursive: true, force: true }); }
507
+ const result = fn(dir);
508
+ if (result && typeof result.then === 'function') {
509
+ const settled = Promise.resolve(result).finally(cleanup);
510
+ deferredCleanup = true;
511
+ return settled;
512
+ }
513
+ return result;
514
+ } finally { if (!deferredCleanup) cleanup(); }
515
+ }
516
+
517
+ // One line saying what run_check will execute for a check, so a worker can judge it before calling.
518
+ export function checkSummary(spec) {
519
+ const text = argv => argv.map(a => a === '/runtime/node' ? 'node' : a).join(' ');
520
+ const command = `${spec.install_argv ? `${text(spec.install_argv)} && ` : ''}${text(spec.argv)}`;
521
+ return `${command.length > 200 ? `${command.slice(0, 197)}...` : command} (limit ${Math.round(spec.timeout_ms / 1000)} s)`;
470
522
  }
471
523
 
472
524
  // Every check spec (id -> normalized spec) at a pinned commit.
@@ -1,6 +1,34 @@
1
1
  import {openSync,closeSync,fstatSync,readSync,constants} from 'node:fs';
2
2
  import {createArtifactJournal,artifactBytesDigest} from './artifact-journal.mjs';
3
+ import {artifactSecretRule,artifactSecretRuleEpoch} from './redaction.mjs';
3
4
  const fail=code=>{throw Object.assign(new Error(code),{code});};
5
+
6
+ // Digest the exact buffer that will be served: a stale or replaced file cannot
7
+ // borrow a clean verdict for previously verified bytes.
8
+ export function createArtifactDownloadGuard({scan=artifactSecretRule,log=()=>{},maxEntries=512}={}) {
9
+ let epoch=artifactSecretRuleEpoch();
10
+ const verdicts=new Map();
11
+ return ({bytes,sha256,id,requestId})=>{
12
+ const digest=artifactBytesDigest(bytes);
13
+ if(typeof sha256!=='string'||digest!==sha256.toLowerCase()) fail('artifact_integrity_mismatch');
14
+ const now=artifactSecretRuleEpoch();
15
+ if(now!==epoch) { verdicts.clear(); epoch=now; }
16
+ let rule=verdicts.get(digest);
17
+ if(!verdicts.has(digest)){
18
+ rule=scan(bytes);
19
+ verdicts.set(digest,rule);
20
+ if(verdicts.size>maxEntries) verdicts.delete(verdicts.keys().next().value);
21
+ }
22
+ if(rule){
23
+ const refusal=typeof rule==='string'?rule:'artifact_unscannable';
24
+ log({kind:'artifact_download_refused',request_id:requestId,artifact_id:id,rule:refusal});
25
+ // The existing protocol/HTTP route recognizes this classification as 422.
26
+ const message=typeof rule==='string'?'artifact_secret_content: '+rule:'artifact_unscannable: '+rule.unscannable;
27
+ throw Object.assign(new Error(message),{code:'artifact_secret_content'});
28
+ }
29
+ };
30
+ }
31
+
4
32
  function inspectNative(store,params,query) {
5
33
  const row=store.db.prepare("SELECT * FROM artifacts WHERE id=? AND request_id=? AND claim_id=? AND kind='upload'").get(query.reference,query.job,params.claimId);
6
34
  if(!row||!Number.isSafeInteger(row.size)||row.size<0||row.size>8*1024*1024)fail('artifact_integrity_mismatch');
@@ -84,13 +84,14 @@ export function finishProtocol(store,id,claimId,outcome,summary,result,subject,e
84
84
  const row=store.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(job);
85
85
  return row?{status:row.status,late:false,compute_stopped:false}:null;
86
86
  }});
87
+ const effective=store.finishPatchOutcome(id,claimId,outcome,summary);
87
88
  const bound=bindings.bind({job:id,subject,worker,claim:claimId,epoch:claim.epoch,
88
- source:parsed.source,policy:parsed.policy,outcome,summary,result,artifacts:refs},()=>{
89
+ source:parsed.source,policy:parsed.policy,...effective,result,artifacts:refs},()=>{
89
90
  // A newly committed report cannot already have an owner decision.
90
91
  store.assertQuestionsResolved(id,claimId,outcome);
91
92
  const captured=captureEvidence?captureEvidence(cleanup=>rollback.push(cleanup)):evidence;
92
93
  const native={...store.finishOnce(id,claimId,outcome,summary,result,subject,captured,worker,null,connectionId),acceptance:'unreviewed'};
93
- store.protocolEventInTransaction(id,'finished',{receipt_id:native.receipt_id,outcome},claim.epoch);
94
+ store.protocolEventInTransaction(id,'finished',{receipt_id:native.receipt_id,outcome:effective.outcome},claim.epoch);
94
95
  return native;
95
96
  });
96
97
  return bound;
@@ -0,0 +1,22 @@
1
+ // D10: who may publish a worker's result. The owner's install file (materialize.json) can narrow publication, but the
2
+ // authority itself is the work's relationship: its current publish grant, read from the bridge at each effect. A missing,
3
+ // ended or non-covering grant means no push and no draft PR. The patch and its evidence are kept either way.
4
+ export const publishEntry = /^(?:org:[A-Za-z0-9][A-Za-z0-9_.-]*|repo:[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9][A-Za-z0-9_.-]*)$/;
5
+
6
+ export function parsePublishGrant(value) {
7
+ if (value === null) return null;
8
+ if (!Array.isArray(value) || value.length > 64 || !value.every(entry => typeof entry === 'string' && publishEntry.test(entry))) {
9
+ throw new Error('invalid grant: expected up to 64 org: or repo: entries, or null to withdraw');
10
+ }
11
+ return value.length ? [...new Set(value)] : null;
12
+ }
13
+
14
+ // authority is the bridge's current answer for the job: {relationship_id, ended, publish_grant} or null.
15
+ export function workGrantProblem(authority, repo) {
16
+ if (!authority?.relationship_id) return 'no_work_grant';
17
+ if (authority.ended) return 'relationship_ended';
18
+ const [org] = String(repo).toLowerCase().split('/');
19
+ const covered = Array.isArray(authority.publish_grant) &&
20
+ authority.publish_grant.some(entry => ['org:' + org, 'repo:' + String(repo).toLowerCase()].includes(entry.toLowerCase()));
21
+ return covered ? null : 'no_work_grant';
22
+ }
@@ -123,7 +123,7 @@ function setOfIds(value, label) {
123
123
 
124
124
  function text(value, label, maximum, multiline) {
125
125
  if (typeof value !== 'string' || value.length > maximum || (!multiline && !value.trim())) fail(`${label}: invalid text`);
126
- const controls = multiline ? /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/ : /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/;
126
+ const controls = multiline ? /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/ : /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/;
127
127
  if (controls.test(value) || !value.isWellFormed()) fail(`${label}: unsafe text controls`);
128
128
  return value;
129
129
  }
@@ -141,7 +141,7 @@ function frozen(value) {
141
141
 
142
142
  // Human-readable literal text, deliberately not Markdown, HTML or shell quoting.
143
143
  function literal(value) {
144
- return JSON.stringify(value).replace(/[<>&`$\[\]()*_#!|~@]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
144
+ return JSON.stringify(value).replace(/[<>&`$\[\]()*_#!|~@\u2028\u2029]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
145
145
  }
146
146
 
147
147
  function evidence(candidate, selection, bound) {