@vecteur/cli 0.10.0 → 0.12.4

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.
@@ -0,0 +1,766 @@
1
+ /** Linux local authority. Pathnames from a Run are untrusted; only this owner reads selections or installs saves.
2
+ * Same-user hostile rename/check/syscall races are outside the qualified boundary (see README).
3
+ */
4
+ import * as fs from 'node:fs';
5
+ import { createHash, randomUUID } from 'node:crypto';
6
+ import { AsyncLocalStorage } from 'node:async_hooks';
7
+ import { createServer } from 'node:net';
8
+ import { spawnSync } from 'node:child_process';
9
+ import { dirname, join, relative, isAbsolute, extname, resolve } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { credentialsPath, readCredentials } from './credentials.js';
12
+ import { readStore, writeStore } from './store.js';
13
+ import { CliError } from './errors.js';
14
+ import { ARTIFACT_MEDIA_TYPES } from './contract.js';
15
+ import { MEDIA, selectSource } from './exchange.js';
16
+
17
+ export const MAX_SELECT_BYTES = 8 * 1024 * 1024;
18
+ const MAX_ARTIFACT = 64 * 1024 * 1024;
19
+ function statInfo(info) {
20
+ return {dev:info.dev,ino:info.ino,size:Number(info.size),mtimeMs:Number(info.mtimeNs)/1e6,ctimeMs:Number(info.ctimeNs)/1e6,mtimeNs:info.mtimeNs,ctimeNs:info.ctimeNs,nlink:Number(info.nlink),
21
+ isFile:()=>info.isFile(),isDirectory:()=>info.isDirectory(),isSymbolicLink:()=>info.isSymbolicLink()};
22
+ }
23
+ const stat=path=>statInfo(fs.statSync(path,{bigint:true}));
24
+ const lstat=path=>statInfo(fs.lstatSync(path,{bigint:true}));
25
+ const fstat=fd=>statInfo(fs.fstatSync(fd,{bigint:true}));
26
+ function readBounded(fd,size) {
27
+ const bytes=Buffer.alloc(size+1);let length=0,n;
28
+ while(length<bytes.length && (n=fs.readSync(fd,bytes,length,bytes.length-length,null))>0)length+=n;
29
+ return bytes.subarray(0,length);
30
+ }
31
+ const C = fs.constants, DIR = C.O_RDONLY | C.O_DIRECTORY | C.O_NOFOLLOW;
32
+ const READ = C.O_RDONLY | C.O_NOFOLLOW | C.O_NONBLOCK | C.O_NOCTTY;
33
+ const context = new AsyncLocalStorage();
34
+ const fail = (code, message = code) => { throw new CliError(code, message); };
35
+ const hash = value => createHash('sha256').update(value).digest('hex');
36
+ const same = (a, b) => String(a.dev ?? a.device) === String(b.dev ?? b.device) && String(a.ino ?? a.inode) === String(b.ino ?? b.inode);
37
+ const inode = info => ({ device: String(info.dev), inode: String(info.ino) });
38
+ const beneath = (root, child) => {
39
+ const path = relative(root, child);
40
+ return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith('../'));
41
+ };
42
+ const proc = (fd, name) => `/proc/self/fd/${fd}${name === undefined ? '' : '/' + name}`;
43
+ const absent = path => { try { return lstat(path); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } };
44
+ export function qualify({ platform = process.platform, version = process.versions.node } = {}) {
45
+ const [major, minor] = version.split('.').map(Number);
46
+ if (platform !== 'linux' || major < 20 || (major === 20 && minor < 8)) fail('platform_unqualified', 'Local file authority requires Linux and Node >=20.8');
47
+ }
48
+ function directory(env) { return dirname(credentialsPath(env)); }
49
+ function store(env, name) { return join(directory(env), name + '.json'); }
50
+ function readGrants(env) {
51
+ const value=readStore(store(env,'local-grants'))??{version:1,grants:{},generations:{},pending:{}};
52
+ if(value.version!==1)fail('store_version_unsupported','Local grant store version is unsupported; bytes preserved');
53
+ if(!value.grants || !value.generations || typeof value.grants!=='object' || typeof value.generations!=='object')fail('store_unreadable','Invalid local grant store; bytes preserved');
54
+ // An interrupted/EIO grant-store commit must not restore authority. The fsynced journal
55
+ // intent supplies the generation floor until the grant-store update is durable.
56
+ for (const [key, generation] of Object.entries(journal(env).grantEnds ?? {})) {
57
+ if ((value.grants[key]?.generation ?? Infinity) < generation) delete value.grants[key];
58
+ if ((value.pending?.[key]?.generation ?? Infinity) < generation) delete value.pending[key];
59
+ value.generations[key] = Math.max(value.generations[key] ?? 0, generation);
60
+ }
61
+ return value;
62
+ }
63
+ function journal(env) {
64
+ const value=readStore(store(env,'local-writes'))??{version:1,writes:[],uploads:[],tombstones:{},admissions:{}};
65
+ if(value.version!==1)fail('store_version_unsupported','Local write store version is unsupported; bytes preserved');
66
+ if(!Array.isArray(value.writes)||!Array.isArray(value.uploads)||!value.tombstones||!value.admissions)fail('store_unreadable','Invalid local write store; bytes preserved');
67
+ return value;
68
+ }
69
+ function saveJournal(env, value) { writeStore(store(env, 'local-writes'), value); }
70
+ function requireLock(env) {
71
+ try { qualify(); } catch(e) { if(e.code==='platform_unqualified') return; throw e; }
72
+ if (!context.getStore()?.active || context.getStore()?.canonical !== fs.realpathSync(directory(env))) fail('local_lock_required');
73
+ }
74
+ export function localLockName(env = process.env) {
75
+ qualify();
76
+ fs.mkdirSync(directory(env), { recursive: true, mode: 0o700 });
77
+ return '\0vecteur-local-' + process.getuid() + '-' + hash(fs.realpathSync(directory(env)));
78
+ }
79
+ export async function withLocalLock(action, env = process.env, { timeout = 30_000 } = {}) {
80
+ const name = localLockName(env), canonical = fs.realpathSync(directory(env));
81
+ if (context.getStore()?.active && context.getStore()?.canonical === canonical) fail('local_lock_reentrant', 'Nested local authority lock is a programming error');
82
+ const deadline = Date.now() + timeout;
83
+ let server;
84
+ while (true) {
85
+ server = createServer();
86
+ try {
87
+ await new Promise((ok, no) => { server.once('error', no); server.listen({ path: name }, ok); });
88
+ break;
89
+ } catch (e) {
90
+ server.close();
91
+ if (e.code !== 'EADDRINUSE') throw e;
92
+ if (Date.now() >= deadline) fail('local_locked', 'Another Vecteur process holds local file authority');
93
+ await new Promise(ok => setTimeout(ok, 25));
94
+ }
95
+ }
96
+ const lease={canonical,active:true};
97
+ try { return await context.run(lease, action); }
98
+ finally { lease.active=false; await new Promise((ok, no) => server.close(e => e ? no(e) : ok())); }
99
+ }
100
+
101
+ export async function withAdmissionLock(action, env = process.env) {
102
+ try { qualify(); } catch(e) { if(e.code==='platform_unqualified') return action(); throw e; }
103
+ return withLocalLock(action,env);
104
+ }
105
+
106
+ /** The existing bin logout and registry APIs are synchronous. Their complete mutation runs in a child holding
107
+ * the same async lock; no lock file, detached work, or early-return promise can leave a grant live after logout.
108
+ * Callers already holding the local lock execute in that context (local -> short synchronous store lock).
109
+ */
110
+ export function localMutation(kind, data, env, action) {
111
+ try { qualify(); } catch(e) { if(e.code==='platform_unqualified') return action(); throw e; }
112
+ fs.mkdirSync(directory(env), { recursive: true, mode: 0o700 });
113
+ if (context.getStore()?.active && context.getStore()?.canonical === fs.realpathSync(directory(env))) return action();
114
+ const script = `import {withLocalLock} from ${JSON.stringify(import.meta.url)};
115
+ let text=''; for await (const c of process.stdin) text+=c; const p=JSON.parse(text);
116
+ try { const value=await withLocalLock(async()=>{
117
+ if(p.kind==='credentials'){ const {clearCredentials}=await import('./credentials.js'); return clearCredentials(p.env,p.data.origin); }
118
+ const {FolderRegistry}=await import('./folders.js'); const r=new FolderRegistry({...p.data,env:p.env});
119
+ return r[p.kind](...p.data.args);
120
+ },p.env); process.stdout.write(JSON.stringify({value})); }
121
+ catch(e){process.stdout.write(JSON.stringify({error:{code:e.code,message:e.message}}));process.exitCode=1;}`;
122
+ // Absolute URL imports in the child: its cwd is this module's directory, never the user's selected folder.
123
+ const child = spawnSync(process.execPath, ['--input-type=module', '-e', script], {
124
+ cwd: dirname(fileURLToPath(import.meta.url)), env: { ...process.env, ...env },
125
+ input: JSON.stringify({ kind, data, env }), encoding: 'utf8', timeout: 35_000, maxBuffer: 1024 * 1024,
126
+ });
127
+ if (child.error) throw child.error;
128
+ let result; try { result = JSON.parse(child.stdout); } catch { fail('local_mutation_failed', 'Local mutation helper failed'); }
129
+ if (result.error) fail(result.error.code ?? 'local_mutation_failed', result.error.message);
130
+ return result.value;
131
+ }
132
+ export function endGrants({ origin, accountId, root } = {}, env = process.env) {
133
+ requireLock(env);
134
+ const file = store(env, 'local-grants');
135
+ const value = readGrants(env);
136
+ const intent = journal(env); intent.grantEnds ??= {};
137
+ const affected = [];
138
+ // An explicit folder revoke advances its generation even before any file grant exists.
139
+ const explicit = origin && accountId && root ? {
140
+ [grantKey({ origin, accountId, root: { path: root } })]: { origin, accountId, root: { path: root }, generation: 0 },
141
+ } : {};
142
+ for (const [key, grant] of Object.entries({ ...explicit, ...value.pending, ...value.grants })) {
143
+ if (origin && origin !== grant.origin || accountId && accountId !== grant.accountId || root && !beneath(root, grant.root.path)) continue;
144
+ delete value.grants[key]; if(value.pending) delete value.pending[key];
145
+ value.generations[key] = (value.generations[key] ?? grant.generation) + 1;
146
+ intent.grantEnds[key] = value.generations[key]; affected.push(key);
147
+ }
148
+ if (affected.length) saveJournal(env, intent);
149
+ writeStore(file, value);
150
+ if (affected.length) {
151
+ for (const key of affected) delete intent.grantEnds[key];
152
+ saveJournal(env, intent);
153
+ }
154
+ }
155
+ export const grantKey = ({ origin, accountId, root }) => hash(JSON.stringify([origin, accountId, root.path]));
156
+ export function currentGrant(pin, env = process.env) { return readGrants(env).grants[grantKey(pin)] ?? null; }
157
+ export function prepareConsent(pin, env = process.env) {
158
+ requireLock(env); const value=readGrants(env), key=grantKey(pin);
159
+ value.pending ??= {}; value.pending[key]={origin:pin.origin,accountId:pin.accountId,root:pin.root,generation:value.generations[key]??0};
160
+ writeStore(store(env,'local-grants'),value); return value.generations[key]??0;
161
+ }
162
+ export function checkConsent(pin, epoch, env = process.env) {
163
+ requireLock(env); const value=readGrants(env);
164
+ const key=grantKey(pin);
165
+ if (!value.pending?.[key] || !same(value.pending[key].root,pin.root) || (value.generations[key]??0)!==epoch) fail('grant_changed','Consent destination changed; review and confirm again');
166
+ }
167
+ export function createGrant(pin, env = process.env, epoch = undefined) {
168
+ requireLock(env);
169
+ if (pin.role === 'VIEWER') fail('role_forbidden', 'Editor access is required for local file authority');
170
+ if(epoch!==undefined)checkConsent(pin,epoch,env);
171
+ const root = rootIdentity(pin.root.path);
172
+ if (!same(root, pin.root)) fail('folder_replaced');
173
+ const value = readGrants(env), key = grantKey(pin);
174
+ const generation = (value.generations[key] ?? 0) + 1;
175
+ const grant = { origin: pin.origin, accountId: pin.accountId, projectId: pin.projectId, root,
176
+ provenance: pin.provenance, generation, capabilities: ['select', 'save-new'], created_at: new Date().toISOString() };
177
+ value.generations[key] = generation; value.grants[key] = grant; if(value.pending)delete value.pending[key];
178
+ writeStore(store(env, 'local-grants'), value); return grant;
179
+ }
180
+ export function rootIdentity(path) {
181
+ const real = fs.realpathSync(path), info = stat(real);
182
+ if (!info.isDirectory()) fail('folder_invalid');
183
+ return { path: real, ...inode(info) };
184
+ }
185
+ export function pinCheck(grant, pin, env = process.env) {
186
+ requireLock(env);
187
+ const live = currentGrant(grant, env);
188
+ if (!live || live.generation !== grant.generation || live.projectId !== pin.projectId
189
+ || pin.accountId !== grant.accountId || pin.origin !== grant.origin) fail('grant_changed', 'Local permission changed; draft kept. Confirm again.');
190
+ if (pin.role === 'VIEWER') fail('role_forbidden');
191
+ if (grant.provenance === 'binding' && pin.binding()?.projectId !== grant.projectId) fail('grant_changed');
192
+ if (pin.credential.kind === 'environment') {
193
+ if (!pin.credential.token || env.VECTEUR_TOKEN !== pin.credential.token) fail('grant_changed');
194
+ } else if (!pin.credential.token || readCredentials(env)?.logins?.[grant.origin]?.token !== pin.credential.token) fail('grant_changed');
195
+ try { if (!same(rootIdentity(grant.root.path), grant.root)) throw new Error('replaced'); }
196
+ catch { endGrants({ origin: grant.origin, accountId: grant.accountId, root: grant.root.path }, env); fail('folder_replaced'); }
197
+ return live;
198
+ }
199
+ export function components(rel) {
200
+ if (typeof rel !== 'string' || !rel || isAbsolute(rel) || rel.includes('\0') || rel.includes('\\')) fail('outside_folder');
201
+ const parts = rel.replace(/^\.\//, '').split('/');
202
+ if (parts.length > 16 || parts.some(c => !c || c === '.' || c === '..' || Buffer.byteLength(c) > 255)) fail('outside_folder');
203
+ return parts;
204
+ }
205
+ function openSafe(path, flags) {
206
+ try { return fs.openSync(path, flags); }
207
+ catch (e) {
208
+ if (e.code === 'ELOOP' || e.code === 'ENOTDIR') fail('symlink_refused');
209
+ throw e;
210
+ }
211
+ }
212
+ export function walk(grant, parts = [], { create, intent = () => {}, done = () => {}, created = () => {} } = {}) {
213
+ qualify();
214
+ if(!Array.isArray(parts)||parts.some(p=>typeof p!=='string'||p.includes('/')))fail('outside_folder');
215
+ if(parts.length)components(parts.join('/'));
216
+ const chain = [];
217
+ try {
218
+ const fd = openSafe(grant.root.path, DIR), info = fstat(fd);
219
+ chain.push({ fd, path: grant.root.path });
220
+ if (!same(info, grant.root)) fail('folder_replaced');
221
+ let made = 0;
222
+ for (const c of parts) {
223
+ const parent = chain.at(-1), path = join(parent.path, c), anchored = proc(parent.fd, c);
224
+ if (!absent(anchored) && create) {
225
+ if (++made > 8) fail('too_many_directories');
226
+ pathCheck(chain); intent(path); fs.mkdirSync(anchored, { mode: 0o755 }); created(path);
227
+ const child = openSafe(anchored, DIR); chain.push({ fd: child, path });
228
+ fs.fsyncSync(parent.fd); done(path, inode(fstat(child))); continue;
229
+ }
230
+ chain.push({ fd: openSafe(anchored, DIR), path });
231
+ }
232
+ pathCheck(chain); return chain;
233
+ } catch (e) { closeChain(chain); throw e; }
234
+ }
235
+ export function closeChain(chain) { for (const { fd } of [...chain].reverse()) fs.closeSync(fd); }
236
+ export function pathCheck(chain) {
237
+ for (const { fd, path } of chain) {
238
+ try {
239
+ if (fs.readlinkSync(proc(fd)) !== path || !same(stat(path), fstat(fd))) fail('folder_moved');
240
+ } catch (e) { if (e.code === 'folder_moved') throw e; fail('folder_moved'); }
241
+ }
242
+ }
243
+ const fixedNames = new Set(['.git', '.ssh', '.aws', '.azure', '.gnupg', '.kube', '.docker', '.netrc', '.npmrc', '.pypirc', '.git-credentials', '.claude', '.codex', '.terraform.d', 'node_modules']);
244
+ function fixedDenied(grant, parts, env) {
245
+ const full = join(grant.root.path, ...parts);
246
+ let own = directory(env); try { own = fs.realpathSync(own); } catch {}
247
+ return beneath(own, full) || parts.some((c, i) => fixedNames.has(c) || c.startsWith('.env') || /\.(?:pem|key)$/.test(c)
248
+ || c.startsWith('id_') || c === '.config' && ['gh', 'gcloud'].includes(parts[i + 1]));
249
+ }
250
+ // Only git wildmatch syntax is accepted. Unknown constructs fail closed; no shell or global git configuration runs.
251
+ function patternRegex(pattern) {
252
+ let out = '';
253
+ for (let i = 0; i < pattern.length; i++) {
254
+ const c = pattern[i];
255
+ if (c === '\\') { if (++i === pattern.length) fail('ignore_policy_unknown'); out += pattern[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
256
+ else if (c === '*') {
257
+ if (pattern[i + 1] === '*') { i++; if (pattern[i + 1] === '/') { i++; out += '(?:.*/)?'; } else out += '.*'; }
258
+ else out += '[^/]*';
259
+ } else if (c === '?') out += '[^/]';
260
+ else if (c === '[') {
261
+ const end = pattern.indexOf(']', i + 1); if (end < 0) fail('ignore_policy_unknown');
262
+ const inner = pattern.slice(i + 1, end); if (!inner || inner.includes('[') || inner.includes('/')) fail('ignore_policy_unknown');
263
+ out += '[' + (inner[0] === '!' ? '^' + inner.slice(1) : inner) + ']'; i = end;
264
+ } else out += c.replace(/[.+^${}()|\]]/g, '\\$&');
265
+ }
266
+ try { return new RegExp('^' + out + '$'); } catch { fail('ignore_policy_unknown'); }
267
+ }
268
+ function policyFile(grant, rel) {
269
+ let chain;
270
+ try {
271
+ if (rel === '.git/info/exclude') {
272
+ chain = walk(grant, []);
273
+ const git = absent(proc(chain[0].fd, '.git'));
274
+ pathCheck(chain);
275
+ if (!git || git.isFile()) return '';
276
+ closeChain(chain); chain = undefined;
277
+ }
278
+ const p = components(rel); chain = walk(grant, p.slice(0, -1));
279
+ const fd = openSafe(proc(chain.at(-1).fd, p.at(-1)), READ);
280
+ chain.push({ fd, path: join(grant.root.path, ...p) });
281
+ const info = fstat(fd);
282
+ if (!info.isFile() || info.nlink !== 1 || info.size > MAX_SELECT_BYTES) fail('ignore_policy_unknown');
283
+ const bytes=readBounded(fd,info.size),after=fstat(fd);
284
+ if(bytes.length!==info.size || after.size!==info.size || after.mtimeNs!==info.mtimeNs || after.ctimeNs!==info.ctimeNs)fail('ignore_policy_unknown');
285
+ const value = new TextDecoder('utf-8',{fatal:true}).decode(bytes); pathCheck(chain); return value;
286
+ } catch (e) { if (e.code === 'ENOENT') return ''; if (['folder_replaced','folder_moved'].includes(e.code)) throw e; fail('ignore_policy_unknown'); }
287
+ finally { if (chain) closeChain(chain); }
288
+ }
289
+ export function excluded(grant, rel, env = process.env, isDirectory = false) {
290
+ const parts = components(rel);
291
+ if (fixedDenied(grant, parts, env)) return true;
292
+ const rules = [];
293
+ function add(base, text) {
294
+ for (let line of text.split(/\r?\n/)) {
295
+ line = line.replace(/(?<!\\) +$/, ''); if (!line || line.startsWith('#')) continue;
296
+ const negate = line.startsWith('!'); if (negate) line = line.slice(1);
297
+ const dir = line.endsWith('/'); if (dir) line = line.slice(0, -1);
298
+ const anchored = line.startsWith('/') || line.includes('/'); if (line.startsWith('/')) line = line.slice(1);
299
+ if (!line) fail('ignore_policy_unknown');
300
+ rules.push({ base, negate, dir, anchored, re: patternRegex(line) });
301
+ }
302
+ }
303
+ add('', policyFile(grant, '.git/info/exclude'));
304
+ for (let depth = 0; depth < parts.length; depth++) {
305
+ const base = parts.slice(0, depth).join('/');
306
+ for (const file of ['.gitignore', '.vecteurignore']) add(base, policyFile(grant, [base, file].filter(Boolean).join('/')));
307
+ }
308
+ // Git cannot re-include a descendant of an excluded directory without re-including the directory itself.
309
+ for (let depth = 1; depth <= parts.length; depth++) {
310
+ const prefix = parts.slice(0, depth).join('/'), directory = depth < parts.length || isDirectory;
311
+ let denied = false;
312
+ for (const rule of rules) {
313
+ if (rule.base && !prefix.startsWith(rule.base + '/')) continue;
314
+ const name = rule.base ? prefix.slice(rule.base.length + 1) : prefix;
315
+ if ((!rule.dir || directory) && rule.re.test(rule.anchored ? name : name.split('/').at(-1))) denied = !rule.negate;
316
+ }
317
+ if (denied) return true;
318
+ }
319
+ return false;
320
+ }
321
+ function allowed(grant, rel, env) { if (excluded(grant, rel, env)) fail('excluded', 'Excluded by local file policy; nothing sent or written'); }
322
+ export function targetStatus(grant, rel, env = process.env, {metadataOnly = false} = {}) {
323
+ const p=components(rel);
324
+ if (metadataOnly) { if(fixedDenied(grant,p,env))fail('excluded'); }
325
+ else allowed(grant,rel,env);
326
+ const chain=walk(grant);
327
+ try {
328
+ for(let i=0;i<p.length-1;i++){
329
+ const parent=chain.at(-1),path=proc(parent.fd,p[i]);
330
+ if(!absent(path))return {exists:false,creates:p.slice(0,-1).map((_,j)=>p.slice(0,j+1).join('/')).slice(i)};
331
+ chain.push({fd:openSafe(path,DIR),path:join(parent.path,p[i])});
332
+ }
333
+ const info=absent(proc(chain.at(-1).fd,p.at(-1)));pathCheck(chain);
334
+ return {exists:!!info,creates:[]};
335
+ } finally {closeChain(chain);}
336
+ }
337
+ export function selectionMetadata(root, rel, env = process.env, { ifPresent = false } = {}) {
338
+ const grant = { root }, p = components(rel);
339
+ if (!ifPresent) allowed(grant, rel, env);
340
+ const chain = walk(grant, p.slice(0, -1));
341
+ try {
342
+ const info = lstat(proc(chain.at(-1).fd, p.at(-1)));
343
+ // Bare words that do not name an entry need no offer or policy notice. This
344
+ // optional probe walks without following symlinks and reads no file content.
345
+ if (ifPresent) allowed(grant, rel, env);
346
+ if (info.isSymbolicLink()) fail('symlink_refused');
347
+ if (!info.isFile()) fail('not_regular_file');
348
+ if (info.nlink !== 1) fail('hardlink_refused');
349
+ if (info.size < 1 || info.size > MAX_SELECT_BYTES) fail('attachment_invalid', 'Select a non-empty file no larger than 8 MiB');
350
+ pathCheck(chain);
351
+ return { rel: p.join('/'), size: info.size, ...inode(info) };
352
+ } finally { closeChain(chain); }
353
+ }
354
+ const SECRET = /vct_[A-Za-z0-9_-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{36,}|sk-[A-Za-z0-9_-]{20,}|xox[abprs]-[A-Za-z0-9-]{10,}|eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\./;
355
+ function scanString(text) { if (SECRET.test(text)) fail('secret_suspected', 'Credential-shaped content refused; nothing uploaded'); }
356
+ function textDecode(bytes) {
357
+ let encoding = 'utf-8', data = bytes;
358
+ // A BOM selects the sole decoder. Unmarked input must be strict UTF-8.
359
+ if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) data = bytes.subarray(3);
360
+ else if (bytes[0] === 0xff && bytes[1] === 0xfe) { encoding = 'utf-16le'; data = bytes.subarray(2); }
361
+ else if (bytes[0] === 0xfe && bytes[1] === 0xff) { encoding = 'utf-16be'; data = bytes.subarray(2); }
362
+ try { return new TextDecoder(encoding, { fatal: true }).decode(data); }
363
+ catch { fail('scan_unsupported'); }
364
+ }
365
+ // Include invisible marks such as variation selectors and the combining grapheme joiner.
366
+ const withoutControls = text => text.replace(/[\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}]/gu, c => /[\t\r\n]/.test(c) ? c : '');
367
+ const scanNormalized = text => { scanString(text); scanString(withoutControls(text)); };
368
+ function scanText(bytes) {
369
+ scanString(bytes.toString('latin1'));
370
+ const text = textDecode(bytes); scanNormalized(text);
371
+ if (/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(text)) fail('scan_unsupported');
372
+ }
373
+ const TEXT_UPLOAD_EXTENSIONS = new Set(['.txt', '.md', '.csv', '.json',
374
+ '.py', '.m', '.jl', '.r', '.c', '.h', '.cpp', '.f90', '.toml', '.yaml', '.yml', '.ini', '.cfg', '.tex', '.rst']);
375
+ export function scanContent(bytes, rel = '') {
376
+ try {
377
+ if (bytes.includes(Buffer.from('%PDF-')) || extname(rel).toLowerCase() === '.pdf')
378
+ fail('scan_unsupported', 'PDF files cannot be checked for credentials before upload yet; upload this PDF in the web app, or attach a text/CSV/Markdown export.');
379
+ const extension = extname(rel).toLowerCase();
380
+ // Refuse containers before decoding, including renamed and prefixed ZIP/OOXML files.
381
+ if (bytes.includes(Buffer.from([0x50, 0x4b, 0x03, 0x04])) ||
382
+ bytes.length >= 4 && [0x06054b50, 0x08074b50].includes(bytes.readUInt32LE(0)) ||
383
+ ['.docx', '.docm', '.dotx', '.dotm', '.xlsx', '.xlsm', '.xltx', '.xltm', '.xlsb', '.xlam', '.pptx', '.pptm', '.potx', '.potm', '.ppsx', '.ppsm', '.ppam', '.sldx', '.sldm', '.zip'].includes(extension))
384
+ fail('scan_unsupported', 'Word files cannot be checked for credentials before upload yet; upload it in the web app, or attach a text/CSV/Markdown export');
385
+ scanString(bytes.toString('latin1'));
386
+ if (!TEXT_UPLOAD_EXTENSIONS.has(extension)) fail('scan_unsupported', 'Local file uploads require a text/CSV/Markdown export or a supported code/configuration text file');
387
+ scanText(bytes);
388
+ } catch (e) { if (e instanceof CliError) throw e; fail('scan_unsupported'); }
389
+ }
390
+ export function readConfined(grant, rel, env = process.env, { selected, hook = () => {}, allowEmpty = false } = {}) {
391
+ const p = components(rel); allowed(grant, rel, env);
392
+ const chain = walk(grant, p.slice(0, -1));
393
+ try {
394
+ hook('before_open', chain);
395
+ const before = lstat(proc(chain.at(-1).fd, p.at(-1)));
396
+ const fd = openSafe(proc(chain.at(-1).fd, p.at(-1)), READ);
397
+ chain.push({ fd, path: join(grant.root.path, ...p) }); hook('opened', chain);
398
+ const info = fstat(fd);
399
+ if (!info.isFile()) fail('not_regular_file');
400
+ if (info.nlink !== 1) fail('hardlink_refused');
401
+ pathCheck(chain);
402
+ if (!same(info, before) || info.size !== before.size || info.mtimeNs !== before.mtimeNs || info.ctimeNs !== before.ctimeNs || selected && (!same(info, selected) || info.size !== selected.size)) fail('attachment_changed');
403
+ if (info.size < (allowEmpty ? 0 : 1) || info.size > MAX_SELECT_BYTES) fail('attachment_invalid');
404
+ const bytes = readBounded(fd,info.size), after = fstat(fd);
405
+ if (bytes.length !== info.size || after.size !== info.size || after.mtimeNs !== info.mtimeNs || after.ctimeNs !== info.ctimeNs) fail('attachment_changed');
406
+ hook('read', chain); pathCheck(chain); allowed(grant, rel, env); scanContent(bytes, rel);
407
+ return { rel, bytes, sha256: hash(bytes), size: bytes.length, mtime_ms: after.mtimeMs, media: MEDIA[extname(rel).toLowerCase()] ?? 'text/plain' };
408
+ } finally { closeChain(chain); }
409
+ }
410
+ /** Explicit --attach consent lasts only for this call, for these paths and this authenticated destination.
411
+ * Reuse the qualified reader, policy and scan. Preflight the entire set before any upload.
412
+ * The caller holds the local admission lock through selection, request freezing and admission.
413
+ */
414
+ export async function selectInvocationFiles(client, projectId, paths, { cwd = process.cwd(), env = process.env, signal } = {}) {
415
+ qualify(); requireLock(env);
416
+ const origin = client.config.origin, token = client.config.token;
417
+ const project = await client.projectGet(projectId, signal);
418
+ if (project.role === 'VIEWER') fail('role_forbidden', 'Editor access is required to attach files');
419
+ // The exact active credential pins the principal for this call. /auth/me is account-PAT-only;
420
+ // Project PATs already authorize projectGet/inputAdd and need no additional permission.
421
+ const grant = { origin, projectId, root: rootIdentity(cwd), capabilities: ['select'] };
422
+ const explicit = [...new Set(paths.map(path => relative(grant.root.path, resolve(cwd, path))))].sort();
423
+ if (!explicit.length || explicit.length > 8) fail('attachment_invalid', 'Select one to eight explicit files');
424
+ const check = () => {
425
+ if (client.config.origin !== origin || client.config.token !== token
426
+ || (env.VECTEUR_TOKEN ? env.VECTEUR_TOKEN : readCredentials(env)?.logins?.[origin]?.token) !== token) fail('grant_changed');
427
+ if (!same(rootIdentity(grant.root.path), grant.root)) fail('folder_replaced');
428
+ };
429
+ check();
430
+ const files = explicit.map(rel => readConfined(grant, rel, env));
431
+ if (files.reduce((n, file) => n + file.size, 0) > 32 * 1024 * 1024) fail('attachment_invalid', 'Selection exceeds 32 MiB');
432
+ const selections = [];
433
+ for (const file of files) {
434
+ check();
435
+ const current = readConfined(grant, file.rel, env);
436
+ if (current.sha256 !== file.sha256) fail('attachment_changed');
437
+ const source = await client.inputAdd(projectId, current.bytes, current.media, signal);
438
+ check();
439
+ selections.push(await selectSource(client, projectId, source, signal));
440
+ }
441
+ check(); return selections;
442
+ }
443
+ export function recordUpload(grant, file, source, env = process.env) {
444
+ requireLock(env); const j = journal(env);
445
+ j.uploads.push({ scope: scope(grant), rel: file.rel, size: file.size, mtime_ms: file.mtime_ms,
446
+ sha256: file.sha256, generation: grant.generation, cas_ref: source.cas_ref, acquisition_ref: source.acquisition_ref });
447
+ establishBase(j, grant, file.rel, file.bytes, file.sha256, 'uploaded', env); saveJournal(env, j);
448
+ }
449
+ export function scope(grant) { return hash(JSON.stringify([grant.origin, grant.accountId, grant.root, grant.projectId])); }
450
+ export function tombstoned(grant, rel, env = process.env) {
451
+ const j = journal(env), key = scope(grant);
452
+ return !!(j.tombstones[key]?.[rel] || j.observed?.[key]?.[rel]);
453
+ }
454
+
455
+ const MAX_BASE_STORE = 256 * 1024 * 1024;
456
+ function baseDirectory(env) {
457
+ const path = join(directory(env), 'local-bases');
458
+ fs.mkdirSync(path, { recursive: true, mode: 0o700 });
459
+ const info = fs.lstatSync(path);
460
+ if (!info.isDirectory() || info.isSymbolicLink() || info.uid !== process.getuid()) fail('store_permissions');
461
+ fs.chmodSync(path, 0o700); return path;
462
+ }
463
+ /** Private content-addressed snapshots only. All writes/eviction share the local authority lock. */
464
+ function retainBase(bytes, sha256, env) {
465
+ requireLock(env);
466
+ if (!bytes || bytes.length > MAX_SELECT_BYTES || hash(bytes) !== sha256) return;
467
+ const dir = baseDirectory(env), path = join(dir, sha256);
468
+ if (readBase(sha256, env)) return;
469
+ const files = fs.readdirSync(dir).filter(n => /^[a-f0-9]{64}$/.test(n)).map(name => ({name, info:fs.lstatSync(join(dir,name))}));
470
+ let total = files.reduce((n,f) => n + f.info.size, 0);
471
+ for (const file of files.sort((a,b) => a.info.mtimeMs-b.info.mtimeMs || a.name.localeCompare(b.name))) {
472
+ if (total + bytes.length <= MAX_BASE_STORE && file.name !== sha256) continue;
473
+ if (!file.info.isFile() || file.info.nlink !== 1) fail('store_permissions');
474
+ fs.unlinkSync(join(dir,file.name)); total -= file.info.size;
475
+ }
476
+ const fd = fs.openSync(path, C.O_WRONLY | C.O_CREAT | C.O_EXCL | C.O_NOFOLLOW, 0o600);
477
+ try { fs.writeFileSync(fd, bytes); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
478
+ const dfd = fs.openSync(dir, DIR); try { fs.fsyncSync(dfd); } finally { fs.closeSync(dfd); }
479
+ }
480
+ export function readBase(sha256, env = process.env) {
481
+ if (!/^[a-f0-9]{64}$/.test(sha256 ?? '')) return null;
482
+ let fd;
483
+ try {
484
+ const dir = join(directory(env),'local-bases'), parent = fs.lstatSync(dir);
485
+ if (!parent.isDirectory() || parent.isSymbolicLink() || parent.uid !== process.getuid() || (parent.mode & 0o077)) return null;
486
+ fd = fs.openSync(join(dir,sha256), READ);
487
+ const info = fs.fstatSync(fd);
488
+ if (!info.isFile() || info.nlink !== 1 || info.uid !== process.getuid() || info.size > MAX_SELECT_BYTES || (info.mode & 0o777) !== 0o600) return null;
489
+ const bytes = readBounded(fd, info.size);
490
+ return bytes.length === info.size && hash(bytes) === sha256 ? bytes : null;
491
+ } catch { return null; } // A missing/unreadable snapshot never erases its journalled hash or provenance.
492
+ finally { if (fd !== undefined) fs.closeSync(fd); }
493
+ }
494
+ function establishBase(j, grant, rel, bytes, sha256, provenance, env) {
495
+ retainBase(bytes, sha256, env);
496
+ const key = scope(grant);
497
+ ((j.baselines ??= {})[key] ??= {})[rel] = {last_synced_sha256:sha256, provenance};
498
+ ((j.observed ??= {})[key] ??= {})[rel] = true;
499
+ }
500
+ export function proposals(grant, env = process.env) {
501
+ return journal(env).writes.filter(e => e.proposal && e.phase === 'done' && scope(e.grant) === scope(grant))
502
+ .map(e => ({path:e.rel, originalPath:e.proposal.originalPath, cas_ref:e.proposal.cas_ref, kind:e.expected.kind, runId:e.expected.runId, revision:e.expected.revision}));
503
+ }
504
+ /** Record existence before any policy/content read can refuse; pre-consent discovery is metadata only. */
505
+ export function observeTargetMetadata(pin, rel, env = process.env) {
506
+ requireLock(env);
507
+ const status = targetStatus(pin, rel, env, {metadataOnly:true});
508
+ if (status.exists) {
509
+ const j = journal(env), key = scope(pin);
510
+ ((j.observed ??= {})[key] ??= {})[rel] = true;
511
+ saveJournal(env,j);
512
+ }
513
+ return {...status, sha256:null};
514
+ }
515
+ /** Observe adoption from original-path bytes and durable CAS identity, never from an editable proposal. */
516
+ export function inspectTarget(grant, rel, proposedSha256, env = process.env, pin) {
517
+ requireLock(env);
518
+ if (!pin) fail('grant_changed','Local read permission requires a current pin');
519
+ pinCheck(grant,pin,env);
520
+ const status = observeTargetMetadata(grant, rel, env);
521
+ const local = status.exists ? readConfined(grant, rel, env, {allowEmpty:true}) : null;
522
+ const j = journal(env), key = scope(grant);
523
+ if (local) {
524
+ const adopted = j.writes.some(e => e.phase === 'done' && scope(e.grant) === key
525
+ && e.proposal?.originalPath === rel && e.proposal.cas_ref === 'sha256:' + local.sha256);
526
+ const prior = j.baselines?.[key]?.[rel];
527
+ if (adopted && prior?.last_synced_sha256 !== local.sha256) establishBase(j,grant,rel,local.bytes,local.sha256,'adopted-observed',env);
528
+ saveJournal(env,j);
529
+ }
530
+ const base = j.baselines?.[key]?.[rel];
531
+ const classification = !local ? 'absent' : local.sha256 === proposedSha256 ? 'already identical'
532
+ : !base ? 'first sync' : local.sha256 === base.last_synced_sha256 ? 'clean' : 'local changed';
533
+ return {...status, sha256:local?.sha256 ?? null, bytes:local?.bytes, classification, baseline:base,
534
+ baseBytes:base ? readBase(base.last_synced_sha256,env) : null};
535
+ }
536
+ export function observeTargets(grant, env = process.env, pin) {
537
+ requireLock(env); const j = journal(env), key = scope(grant), reports = [];
538
+ const paths = new Set([...Object.keys(j.observed?.[key] ?? {}), ...Object.keys(j.baselines?.[key] ?? {}), ...proposals(grant,env).map(p=>p.originalPath)]);
539
+ for (const rel of paths) try { inspectTarget(grant,rel,null,env,pin); } catch(e) { reports.push({path:rel,code:e.code}); }
540
+ return reports;
541
+ }
542
+
543
+ export function proposalName(rel, runId, revision) {
544
+ const run8 = String(runId).replace(/-/g,'').slice(0,8);
545
+ if (!/^[a-f0-9]{8}$/i.test(run8) || !Number.isSafeInteger(revision) || revision < 1) fail('artifact_invalid','Proposal requires a Run id and revision');
546
+ const name = `${rel}.vecteur-${run8.toLowerCase()}-${revision}`; components(name); return name;
547
+ }
548
+ export async function writeProposalConfined(grant, rel, fetchBytes, expected, options) {
549
+ const name = proposalName(rel,expected.runId,expected.revision);
550
+ const bytes = await downloadLocalArtifact(fetchBytes,expected);
551
+ for (let n=0;n<=99;n++) {
552
+ try {
553
+ return await writeNewConfined(grant,name+(n?`-${n}`:''),async sink=>{sink(bytes);return {bytes:bytes.length,content_type:ARTIFACT_MEDIA_TYPES[expected.kind]};},expected,
554
+ {...options,proposalFor:rel});
555
+ } catch(e) { if(e.code !== 'output_exists') throw e; }
556
+ }
557
+ fail('proposal_name_unavailable','All 100 proposal names already exist; nothing written');
558
+ }
559
+ export function admissionIntent(origin, projectId, key, body, env = process.env) {
560
+ requireLock(env); const j = journal(env);
561
+ j.admissions ??= {};
562
+ const id = hash(JSON.stringify([origin, projectId, key]));
563
+ const prior = j.admissions[id];
564
+ if (prior && JSON.stringify(prior.body) !== JSON.stringify(body)) fail('submission_mismatch');
565
+ j.admissions[id] = { origin, projectId, key, body }; saveJournal(env, j); return id;
566
+ }
567
+ export function admissionResolved(id, env = process.env) { requireLock(env); const j = journal(env); delete j.admissions[id]; saveJournal(env, j); }
568
+ export function unresolvedAdmissions(origin, projectId, env = process.env) {
569
+ const folders = readStore(store(env, 'folders'))?.folders ?? {};
570
+ return [...Object.values(folders).filter(r => r.origin === origin && r.pendingRun?.projectId === projectId).map(r => r.pendingRun),
571
+ ...Object.values(journal(env).admissions ?? {}).filter(r => r.origin === origin && r.projectId === projectId)];
572
+ }
573
+ export async function reconcileAdmissions(client, origin, env = process.env) {
574
+ requireLock(env);
575
+ for (const [id, row] of Object.entries(journal(env).admissions ?? {})) {
576
+ if (row.origin !== origin) continue;
577
+ try { await client.runAdmit(row.projectId, row.body, row.key); admissionResolved(id, env); }
578
+ catch (e) { if (e.admission === 'refused' || ['state_fork', 'state_busy', 'not_supported', 'project_read_only'].includes(e.code)) admissionResolved(id, env); else throw e; }
579
+ }
580
+ }
581
+
582
+ function entryUpdate(entry, phase, detail, env) {
583
+ requireLock(env); entry.events.push({ phase, ...detail }); entry.phase = phase;
584
+ const j = journal(env), at = j.writes.findIndex(r => r.id === entry.id);
585
+ if (at < 0) j.writes.push(entry); else j.writes[at] = entry;
586
+ saveJournal(env, j);
587
+ }
588
+ function markDone(entry, info, env) {
589
+ requireLock(env); const j = journal(env);
590
+ entry.events.push({phase:'done',local_sha256:entry.sha256,...inode(info)}); entry.phase='done';
591
+ const at=j.writes.findIndex(r=>r.id===entry.id); if(at<0)j.writes.push(entry);else j.writes[at]=entry;
592
+ (j.tombstones[scope(entry.grant)] ??= {})[entry.rel] = true;
593
+ if (!entry.proposal) establishBase(j,entry.grant,entry.rel,readBase(entry.sha256,env),entry.sha256,'saved',env);
594
+ saveJournal(env, j);
595
+ }
596
+ function cleanupName(parentfd, name, owned, report, entry, env) {
597
+ if (!name) return;
598
+ const path = proc(parentfd, name), info = absent(path); if (!info) return;
599
+ if (owned && same(info, owned)) { entryUpdate(entry,'cleanup_unlink_intent',{name,...owned},env); fs.unlinkSync(path); report.cleaned.push(name); }
600
+ else report.remains.push({ path: name, ...inode(info), reason: 'identity not owned' });
601
+ }
602
+ function cleanupDirs(entry, report, env) {
603
+ for (const event of [...entry.events].reverse()) {
604
+ if (event.phase !== 'mkdir_done') continue;
605
+ try {
606
+ const p = relative(entry.grant.root.path, event.path).split('/'), chain = walk(entry.grant, p.slice(0, -1));
607
+ try {
608
+ const path = proc(chain.at(-1).fd, p.at(-1)), info = absent(path);
609
+ if (info && same(info, event)) { pathCheck(chain); entryUpdate(entry,'cleanup_rmdir_intent',{path:event.path,...inode(info)},env); fs.rmdirSync(path); fs.fsyncSync(chain.at(-1).fd); report.cleaned.push(event.path); }
610
+ else if (info) report.remains.push({ path: event.path, reason: 'directory identity changed' });
611
+ } finally { closeChain(chain); }
612
+ } catch (e) { if (e.code !== 'ENOENT') report.remains.push({ path: event.path, reason: e.code }); }
613
+ }
614
+ for (const e of entry.events.filter(e => e.phase === 'mkdir_intent')) if (!entry.events.some(d => d.phase === 'mkdir_done' && d.path === e.path)) {
615
+ if (absent(e.path)) report.remains.push({ path: e.path, reason: 'may have been created by an interrupted save' });
616
+ }
617
+ }
618
+ /** Single writer: fetch/verify in memory first, then one locked fence and a synchronous, journalled install. */
619
+ export async function downloadLocalArtifact(fetchBytes, expected) {
620
+ const chunks = []; let length = 0;
621
+ const result = await fetchBytes(chunk => {
622
+ length += chunk.byteLength; if (length > MAX_ARTIFACT) fail('artifact_invalid', 'Artifact exceeds 64 MiB'); chunks.push(Buffer.from(chunk));
623
+ });
624
+ const bytes = Buffer.concat(chunks);
625
+ if (result.bytes !== length || result.content_type !== ARTIFACT_MEDIA_TYPES[expected.kind] || 'sha256:' + hash(bytes) !== expected.cas_ref) fail('artifact_invalid');
626
+ return bytes;
627
+ }
628
+ export async function writeNewConfined(grant, rel, fetchBytes, expected, { env = process.env, pin, head, hook = () => {}, approval, proposalFor } = {}) {
629
+ qualify(); const p = components(rel), bytes = await downloadLocalArtifact(fetchBytes,expected), length = bytes.length;
630
+ return withLocalLock(async () => {
631
+ pinCheck(grant, pin(), env);
632
+ if (unresolvedAdmissions(grant.origin, grant.projectId, env).length) fail('admission_unresolved', 'admission_unresolved, resolve it with /resume');
633
+ if ((await head(grant.projectId))?.run_id !== expected.runId) fail('newer_turn', 'a newer turn exists, review it');
634
+ // Effective selection and credentials can change in this process while the head read awaits.
635
+ pinCheck(grant, pin(), env); allowed(grant, rel, env);
636
+ if (approval) {
637
+ const now = inspectTarget(grant,approval.rel,expected.cas_ref.slice(7),env,pin());
638
+ if (now.sha256 !== approval.sha256 || now.exists !== approval.exists) fail('target_changed','Target changed; approval withdrawn. Review the refreshed diff and confirm again.');
639
+ }
640
+ retainBase(bytes,hash(bytes),env);
641
+ const entry = { id: randomUUID(), grant, rel, expected, sha256: hash(bytes), events: [], phase: 'created',
642
+ ...(proposalFor ? {proposal:{originalPath:proposalFor,cas_ref:expected.cas_ref}} : {}) };
643
+ let chain, tempfd, tempIdentity, parentfd, leafPublished = false;
644
+ const event = (phase, detail = {}) => { entryUpdate(entry, phase, detail, env); hook(phase, entry, chain); };
645
+ try {
646
+ hook('before_intent', entry); event('created');
647
+ chain = walk(grant, p.slice(0, -1), { create: true, created: path => hook('mkdir_created',entry,chain), intent: path => event('mkdir_intent', { path }), done: (path, id) => event('mkdir_done', { path, ...id }) });
648
+ parentfd = chain.at(-1).fd; entry.parentChain = chain.map(({fd,path}) => ({ path, ...inode(fstat(fd)) }));
649
+ const leaf = p.at(-1); entry.temp = `.vecteur-${leaf}-${entry.id}.part`;
650
+ event('temp_intent', { name: entry.temp });
651
+ tempfd = fs.openSync(proc(parentfd, entry.temp), C.O_WRONLY | C.O_CREAT | C.O_EXCL | C.O_NOFOLLOW | C.O_NOCTTY, 0o600);
652
+ tempIdentity = inode(fstat(tempfd)); hook('temp_created', entry, chain);
653
+ event('temp_done', tempIdentity); event('write_intent'); fs.writeFileSync(tempfd, bytes); fs.fsyncSync(tempfd); event('chmod_intent'); fs.fchmodSync(tempfd, 0o644 & ~process.umask()); fs.fsyncSync(tempfd);
654
+ event('pending'); pathCheck(chain);
655
+ if (!same(lstat(proc(parentfd, entry.temp)), tempIdentity)) fail('install_unverified');
656
+ hook('before_link', entry, chain);
657
+ fs.linkSync(proc(parentfd, entry.temp), proc(parentfd, leaf)); leafPublished = true; hook('linked', entry, chain);
658
+ const fd = openSafe(proc(parentfd, leaf), READ);
659
+ try {
660
+ const info = fstat(fd);
661
+ if (!info.isFile() || !same(info, tempIdentity) || info.nlink !== 2) fail('install_unverified');
662
+ pathCheck([...chain, { fd, path: join(grant.root.path, ...p) }]);
663
+ } finally { fs.closeSync(fd); }
664
+ event('unlink_intent');
665
+ if (!same(lstat(proc(parentfd, entry.temp)), tempIdentity)) fail('install_unverified');
666
+ fs.unlinkSync(proc(parentfd, entry.temp)); fs.fsyncSync(parentfd); hook('unlinked', entry, chain);
667
+ markDone(entry, fstat(tempfd), env); return { path: join(grant.root.path, ...p), bytes: length, sha256: entry.sha256 };
668
+ } catch (e) {
669
+ const report = { cleaned: [], remains: [] };
670
+ // Durably announce cleanup too. A failed journal aborts cleanup rather than making an unrecorded mutation.
671
+ event('cleanup_intent', { cause: e.code });
672
+ if (parentfd !== undefined) {
673
+ if (leafPublished) cleanupName(parentfd, p.at(-1), tempIdentity, report, entry, env);
674
+ cleanupName(parentfd, entry.temp, tempIdentity, report, entry, env); fs.fsyncSync(parentfd);
675
+ }
676
+ cleanupDirs(entry, report, env);
677
+ const unverified = e.code === 'install_unverified' || leafPublished || report.remains.length;
678
+ event(unverified ? 'install_unverified' : 'failed', report);
679
+ if (unverified) fail('install_unverified', JSON.stringify({ cause: e.code, ...report }));
680
+ if (e.code === 'EEXIST') fail('output_exists', 'exists locally, not written');
681
+ throw e;
682
+ } finally { if (tempfd !== undefined) fs.closeSync(tempfd); if (chain) closeChain(chain); }
683
+ }, env);
684
+ }
685
+
686
+ export function reconcileWrites(env = process.env) {
687
+ requireLock(env); const reports = [];
688
+ for (const entry of journal(env).writes) {
689
+ if (['done', 'failed'].includes(entry.phase)) continue;
690
+ let chain;
691
+ const report = { id: entry.id, cleaned: [], remains: [] }, p = components(entry.rel);
692
+ try {
693
+ chain = walk(entry.grant, p.slice(0, -1));
694
+ const parentfd = chain.at(-1).fd, path = proc(parentfd, p.at(-1));
695
+ let target, verified = false;
696
+ target=absent(path);
697
+ if (target?.isFile() && entry.events.some(e=>e.phase==='pending')) {
698
+ const fd = openSafe(path, READ);
699
+ try { target = fstat(fd);
700
+ if (target.isFile() && target.size <= MAX_ARTIFACT) {
701
+ const bytes = readBounded(fd,target.size); pathCheck([...chain, {fd,path:join(entry.grant.root.path,...p)}]);
702
+ verified = bytes.length === target.size && hash(bytes) === entry.sha256;
703
+ }
704
+ } finally { fs.closeSync(fd); }
705
+ }
706
+ const tempEvent = entry.events.find(e => e.phase === 'temp_done');
707
+ const tmpPath = entry.temp && proc(parentfd, entry.temp), tmp = tmpPath && absent(tmpPath);
708
+ if (tmp) {
709
+ const owned = tempEvent ? same(tmp, tempEvent) : entry.temp.endsWith(`-${entry.id}.part`);
710
+ const linksExplained = tmp.nlink === 1 || tmp.nlink === 2 && verified && same(tmp, target) && (!tempEvent || same(target, tempEvent));
711
+ if (owned && tmp.isFile() && tmp.size <= MAX_ARTIFACT && linksExplained) {
712
+ entryUpdate(entry, 'recovery_unlink_intent', {}, env); fs.unlinkSync(tmpPath); fs.fsyncSync(parentfd); report.cleaned.push(entry.temp);
713
+ } else report.remains.push({ path: entry.temp, reason: 'foreign staging identity or unexplained links' });
714
+ }
715
+ if (verified && !report.remains.length) {
716
+ if (target.nlink !== (tmp && same(tmp,target) ? 2 : 1)) report.remains.push({ path: entry.rel, reason: 'unexplained target links' });
717
+ else markDone(entry, target, env);
718
+ } else {
719
+ if (target) report.remains.push({ path: entry.rel, reason: 'not written; target differs or is not inspectable' });
720
+ entryUpdate(entry, 'recovery_cleanup_intent', {}, env); cleanupDirs(entry, report, env);
721
+ entryUpdate(entry, report.remains.length ? 'install_unverified' : 'failed', report, env);
722
+ }
723
+ } catch (e) {
724
+ if (e.code === 'ENOENT') {
725
+ entryUpdate(entry, 'recovery_cleanup_intent', {}, env); cleanupDirs(entry, report, env);
726
+ entryUpdate(entry, report.remains.length ? 'install_unverified' : 'failed', report, env);
727
+ } else report.remains.push({ path: entry.grant.root.path, reason: e.code === 'folder_replaced' ? 'root changed, not reconciled' : e.code });
728
+ } finally { if (chain) closeChain(chain); }
729
+ reports.push(report);
730
+ }
731
+ return reports;
732
+ }
733
+
734
+ export function discover(root, env = process.env, prefix = '', { max = 1000 } = {}) {
735
+ qualify(); const files = [], grant = {root};
736
+ function visit(parts) {
737
+ const chain = walk(grant, parts);
738
+ try {
739
+ for (const item of fs.readdirSync(proc(chain.at(-1).fd), { withFileTypes: true })) {
740
+ const rel = [...parts, item.name].join('/');
741
+ try { if (excluded(grant, rel, env, item.isDirectory())) continue; }
742
+ catch (e) { if (e.code === 'ignore_policy_unknown') continue; throw e; }
743
+ if (item.isDirectory() && parts.length < 15) visit([...parts, item.name]);
744
+ else if (item.isFile() && rel.startsWith(prefix)) {
745
+ try { files.push(selectionMetadata(root, rel, env)); } catch(e) { if (!['attachment_invalid','hardlink_refused','ignore_policy_unknown'].includes(e.code)) throw e; }
746
+ }
747
+ if (files.length >= max) return;
748
+ }
749
+ pathCheck(chain);
750
+ } finally { closeChain(chain); }
751
+ }
752
+ // Establish the root policy before per-entry/subtree failure isolation.
753
+ excluded(grant, '.gitignore', env);
754
+ visit([]); return files;
755
+ }
756
+ export function nameOffers(text, files, selected = []) {
757
+ const tokens = new Set(text.split(/\s+/).filter(Boolean)), groups = [];
758
+ for (const token of tokens) {
759
+ if (token.startsWith('@') || token.startsWith('/') || token.split('/').includes('..')) continue;
760
+ const name = token.replace(/^\.\//, '');
761
+ const matches = files.filter(f => !selected.includes(f.rel) && (f.rel === name || !name.includes('/') && f.rel.split('/').at(-1) === name));
762
+ if (matches.length) groups.push(matches);
763
+ if (groups.length === 3) break;
764
+ }
765
+ return groups;
766
+ }