introsio 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +61 -0
- package/README.md +132 -30
- package/cli.mjs +161 -9
- package/docs/managed-workspaces.md +65 -0
- package/docs/releasing.md +118 -0
- package/hook/engine.mjs +28 -4
- package/hook/features/claims.mjs +6 -0
- package/hook/features/notes.mjs +1 -0
- package/hook/features/parallel.mjs +184 -0
- package/hook/normalize.mjs +1 -0
- package/hook/state.mjs +1 -1
- package/lib/config.mjs +12 -3
- package/lib/git.mjs +31 -0
- package/lib/jsonFile.mjs +13 -5
- package/package.json +4 -2
- package/runner/activityCollector.mjs +169 -0
- package/runner/agentRegistry.mjs +68 -0
- package/runner/managedActivity.mjs +58 -0
- package/runner/processJournal.mjs +42 -0
- package/runner/projectLinks.mjs +118 -0
- package/runner/providers/index.mjs +41 -0
- package/runner/runnerController.mjs +61 -0
- package/runner/runnerLoop.mjs +62 -0
- package/runner/runnerTransport.mjs +150 -0
- package/runner/supervisedProcess.mjs +113 -0
- package/runner/workspaceArtifacts.mjs +93 -0
- package/runner/workspaceJournal.mjs +91 -0
- package/runner/workspaceManager.mjs +166 -0
- package/runner/workspaceRecovery.mjs +54 -0
- package/runner/workspaceResources.mjs +53 -0
- package/templates/execute.md +12 -4
- package/templates/pause.md +1 -1
- package/templates/resume.md +2 -2
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// Stateless MCP transport. The bearer is supplied in memory by the authorized
|
|
2
|
+
// host; it is never written to disk, passed to an agent, or sent to a redirect.
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { attemptIdentity } from './workspaceJournal.mjs';
|
|
5
|
+
const DEFAULT='https://api.introsio.app/mcp?toolset=execute';
|
|
6
|
+
const ALLOWED=new Set(['registerWorkerSession','renewWorkerSession','revokeWorkerSession','claimTask','waitForWork','pinWorkspaceAttempt','getWorkspaceAuthority','recordWorkspaceArtifact','pauseTask','completeTask','updateSubtask']);
|
|
7
|
+
const ID=/^[a-f0-9]{24}$/;
|
|
8
|
+
const TOKEN=/^[a-f0-9]{64}$/;
|
|
9
|
+
const MAX_BYTES=2*1024*1024;
|
|
10
|
+
function error(message,code='RUNNER_TRANSPORT_ERROR'){return Object.assign(new Error(message),{code});}
|
|
11
|
+
function endpoint(value,allowLoopback){
|
|
12
|
+
const url=new URL(value);
|
|
13
|
+
if(url.username||url.password||url.hash||url.pathname!=='/mcp'||
|
|
14
|
+
!(url.protocol==='https:'&&url.hostname==='api.introsio.app'&&!url.port||
|
|
15
|
+
allowLoopback&&url.protocol==='http:'&&url.hostname==='127.0.0.1'))
|
|
16
|
+
throw error('Unapproved MCP endpoint.');
|
|
17
|
+
url.search='?toolset=execute';
|
|
18
|
+
return url.href;
|
|
19
|
+
}
|
|
20
|
+
async function readBounded(response){
|
|
21
|
+
if(!response.body)throw error('Empty server response.');
|
|
22
|
+
const reader=response.body.getReader();let size=0;const chunks=[];
|
|
23
|
+
try {
|
|
24
|
+
for(;;){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>MAX_BYTES)throw error('Server response exceeds limit.');chunks.push(Buffer.from(value));}
|
|
25
|
+
}finally{await reader.cancel().catch(()=>{});}
|
|
26
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
27
|
+
}
|
|
28
|
+
function decode(text,contentType,id){
|
|
29
|
+
const parse=value=>{try{return JSON.parse(value);}catch{throw error('Malformed MCP response.');}};
|
|
30
|
+
let frames;
|
|
31
|
+
if(contentType.startsWith('text/event-stream')){
|
|
32
|
+
frames=text.replace(/\r\n/g,'\n').split('\n\n').map(frame=>frame.split('\n').filter(l=>l.startsWith('data:')).map(l=>l.slice(5).trimStart()).join('\n')).filter(Boolean).map(parse);
|
|
33
|
+
}else if(contentType.startsWith('application/json'))frames=[parse(text)];
|
|
34
|
+
else throw error('Unexpected MCP response type.');
|
|
35
|
+
const matches=frames.filter(f=>f?.jsonrpc==='2.0'&&f.id===id);
|
|
36
|
+
if(matches.length!==1||matches[0].error)throw error('MCP request refused or response did not match.');
|
|
37
|
+
const result=matches[0].result;
|
|
38
|
+
if(!result||!Array.isArray(result.content)||result.content.length!==1||result.content[0].type!=='text')throw error('Invalid tool response.');
|
|
39
|
+
const body=parse(result.content[0].text);
|
|
40
|
+
if(result.isError||body?.success===false)throw error('Introsio refused runner operation.',typeof body?.code==='string'&&/^[A-Z0-9_]{1,64}$/.test(body.code)?body.code:'RUNNER_REFUSED');
|
|
41
|
+
return body;
|
|
42
|
+
}
|
|
43
|
+
export function createRunnerTransport({getAccessToken,url=DEFAULT,allowLoopback=false,timeoutMs=15000,fetchImpl=fetch}={}){
|
|
44
|
+
if(typeof getAccessToken!=='function'||!Number.isSafeInteger(timeoutMs)||timeoutMs<100||timeoutMs>60000)throw error('Invalid runner transport configuration.');
|
|
45
|
+
const target=endpoint(url,allowLoopback);
|
|
46
|
+
return Object.freeze({async call(name,args,{signal}={}){
|
|
47
|
+
if(!ALLOWED.has(name))throw error('Unsupported runner operation.');
|
|
48
|
+
const bearer=await getAccessToken();
|
|
49
|
+
if(typeof bearer!=='string'||!bearer||bearer.length>16384||/[\s]/.test(bearer))throw error('Valid OAuth access token required.');
|
|
50
|
+
const id=randomUUID(),controller=new AbortController();
|
|
51
|
+
const abort=()=>controller.abort();
|
|
52
|
+
signal?.addEventListener('abort',abort,{once:true});
|
|
53
|
+
if(signal?.aborted)controller.abort();
|
|
54
|
+
const deadline=name==='waitForWork'?Math.max(timeoutMs,Math.min(30000,((args.timeoutSeconds??20)+5)*1000)):timeoutMs;
|
|
55
|
+
const timer=setTimeout(()=>controller.abort(),deadline);
|
|
56
|
+
try{
|
|
57
|
+
const response=await fetchImpl(target,{method:'POST',redirect:'error',signal:controller.signal,
|
|
58
|
+
headers:{authorization:'Bearer '+bearer,'content-type':'application/json',accept:'application/json, text/event-stream'},
|
|
59
|
+
body:JSON.stringify({jsonrpc:'2.0',id,method:'tools/call',params:{name,arguments:args}})});
|
|
60
|
+
if(response.status!==200){await response.body?.cancel().catch(()=>{});throw error('MCP HTTP request refused.',response.status===401?'RUNNER_UNAUTHENTICATED':'RUNNER_HTTP_ERROR');}
|
|
61
|
+
return decode(await readBounded(response),response.headers.get('content-type')??'',id);
|
|
62
|
+
}catch(e){if(e?.code?.startsWith('RUNNER_')||/^[A-Z0-9_]{1,64}$/.test(e?.code??''))throw error('Runner request failed.',e.code);throw error('Runner request failed.');}
|
|
63
|
+
finally{clearTimeout(timer);signal?.removeEventListener('abort',abort);}
|
|
64
|
+
}});
|
|
65
|
+
}
|
|
66
|
+
export async function openRunnerSession({transport,projectId,profile}){
|
|
67
|
+
if(typeof projectId!=='string'||!ID.test(projectId)||typeof transport?.call!=='function')throw error('Invalid runner project.');
|
|
68
|
+
const registered=await transport.call('registerWorkerSession',{projectId,protocolVersion:2,...(profile?{profile}:{})});
|
|
69
|
+
if(registered?.protocolVersion!==2||registered.projectId!==projectId||!TOKEN.test(registered.workerSession??'')||
|
|
70
|
+
typeof registered.workerId!=='string'||!/^[A-Za-z0-9._:-]{1,64}$/.test(registered.workerId)||
|
|
71
|
+
!(Date.parse(registered.expiresAt)>Date.now()))throw error('Protocol v2 worker registration required.');
|
|
72
|
+
// The credential is private to this closure. Never return it from session APIs.
|
|
73
|
+
const auth={workerSession:registered.workerSession,workerId:registered.workerId};
|
|
74
|
+
let closed=false,held=null,claimKey=null,busy=false,waiting=false;
|
|
75
|
+
function live(){if(closed)throw error('Runner session closed.');}
|
|
76
|
+
const call=(name,args,options)=>{live();return transport.call(name,{...args,...auth},options);};
|
|
77
|
+
function ref(identity){return {projectId,taskId:identity.taskId,attempt:{attemptId:identity.attemptId,fence:identity.fence,generation:identity.generation}};}
|
|
78
|
+
function verify(packet,expected){
|
|
79
|
+
const id=attemptIdentity(packet);
|
|
80
|
+
if(id.projectId!==projectId||id.taskId!==expected.taskId||id.attemptId!==expected.attemptId||
|
|
81
|
+
id.fence!==expected.fence||id.generation!==expected.generation||packet.active!==true||
|
|
82
|
+
!(Date.parse(packet.expiresAt)>Date.now()))throw error('Server returned invalid workspace authority.');
|
|
83
|
+
return id;
|
|
84
|
+
}
|
|
85
|
+
const session={
|
|
86
|
+
workerId:registered.workerId,projectId,
|
|
87
|
+
async claim(options={}){
|
|
88
|
+
live();if(busy||held||waiting)throw error('Worker already has an unresolved claim or wait.');
|
|
89
|
+
busy=true;claimKey??=randomUUID();
|
|
90
|
+
try{
|
|
91
|
+
const response=await call('claimTask',{projectId,claimKey,...(options.taskId?{taskId:options.taskId,resume:options.resume===true}:{})});
|
|
92
|
+
if(response?.claimed===false){claimKey=null;return {claimed:false,reason:String(response.reason??'unavailable')};}
|
|
93
|
+
if(response?.claimed!==true||response.workerId!==auth.workerId||!ID.test(response.task?.id??''))throw error('Invalid claim response.');
|
|
94
|
+
const a=response.attempt;
|
|
95
|
+
const expected={taskId:response.task.id,attemptId:a?.attemptId,fence:a?.fence,generation:a?.generation};
|
|
96
|
+
// Retain the exact attempt even if pinning fails. No other
|
|
97
|
+
// claim is permitted until recovery resolves it.
|
|
98
|
+
held=expected;
|
|
99
|
+
const pin=await call('pinWorkspaceAttempt',ref(expected));
|
|
100
|
+
const id=verify(pin,expected);
|
|
101
|
+
held=id;claimKey=null;
|
|
102
|
+
return {claimed:true,identity:id,repository:pin.repository,task:response.task,inputs:response.inputs??[],
|
|
103
|
+
dependencySnapshot:pin.dependencySnapshot??response.dependencySnapshot};
|
|
104
|
+
}finally{busy=false;}
|
|
105
|
+
},
|
|
106
|
+
async wait(cursor=0,{signal,timeoutSeconds=20}={}){
|
|
107
|
+
live();if(held||busy||claimKey||waiting)throw error('Resolve active work before waiting.');
|
|
108
|
+
waiting=true;
|
|
109
|
+
try{
|
|
110
|
+
const response=await call('waitForWork',{projectId,cursor,timeoutSeconds},{signal});
|
|
111
|
+
if(!Number.isSafeInteger(response?.cursor)||response.cursor<cursor||typeof response.reason!=='string')throw error('Invalid wake cursor.');
|
|
112
|
+
return response;
|
|
113
|
+
}finally{waiting=false;}
|
|
114
|
+
},
|
|
115
|
+
async authorizeAttempt(identity, { publication = false } = {}){
|
|
116
|
+
const id=attemptIdentity(identity);
|
|
117
|
+
if(!held||!Object.keys(id).every(k=>held[k]===id[k]))throw error('Attempt is not held by this runner.');
|
|
118
|
+
const packet=await call('getWorkspaceAuthority', { ...ref(id), ...(publication && { publication: true }) });
|
|
119
|
+
if(verify(packet,id).baseSha!==id.baseSha)throw error('Pinned SHA changed.');
|
|
120
|
+
if (publication && packet.publicationAllowed !== true) throw error('Checkpoint publication is unavailable for this attempt.');
|
|
121
|
+
return packet;
|
|
122
|
+
},
|
|
123
|
+
async recordArtifact(artifact) {
|
|
124
|
+
if (!held || busy) throw error('No stable held attempt.');
|
|
125
|
+
return call('recordWorkspaceArtifact', { ...ref(held), artifact });
|
|
126
|
+
},
|
|
127
|
+
async verifyArtifact(artifactId) {
|
|
128
|
+
if (!held || busy || typeof artifactId !== 'string' || !ID.test(artifactId)) throw error('A held attempt and artifact ID are required.');
|
|
129
|
+
return call('recordWorkspaceArtifact', { ...ref(held), verifyArtifactId: artifactId });
|
|
130
|
+
},
|
|
131
|
+
async renew(profile){return call('renewWorkerSession',profile?{profile}:{});},
|
|
132
|
+
async complete({outcome,completedSubtasks=[]}){
|
|
133
|
+
if(!held||busy||waiting)throw error('No stable held attempt.');
|
|
134
|
+
const result=await call('completeTask',{...ref(held),outcome,completedSubtasks});
|
|
135
|
+
if(result?.task?.id!==held.taskId||result.task.completed!==true)throw error('Completion was not confirmed by the server.');
|
|
136
|
+
held=null;claimKey=null;return result;
|
|
137
|
+
},
|
|
138
|
+
async pause(handoff){
|
|
139
|
+
if(!held||busy)throw error('No stable held attempt.');
|
|
140
|
+
const {taskId,attempt}=ref(held);
|
|
141
|
+
const result=await call('pauseTask',{taskId,attempt,handoff,release:false});
|
|
142
|
+
held=null;claimKey=null;return result;
|
|
143
|
+
},
|
|
144
|
+
async close(){
|
|
145
|
+
if(held||busy||claimKey||waiting)throw error('Unresolved claim or wait; preserve it before closing.');
|
|
146
|
+
const result=await call('revokeWorkerSession',{});closed=true;return result;
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
return Object.freeze(session);
|
|
150
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Supervised child process primitive for locally trusted adapters only.
|
|
2
|
+
// No shell, no inherited secrets, no launch command taken from a server packet.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
6
|
+
import { acquireLock } from '../lib/lock.mjs';
|
|
7
|
+
import { attemptIdentity, workspacePaths } from './workspaceJournal.mjs';
|
|
8
|
+
import { provisionWorkspace } from './workspaceManager.mjs';
|
|
9
|
+
import { prepareResources, isolatedEnvironment } from './workspaceResources.mjs';
|
|
10
|
+
import { classifyAuthority } from './workspaceRecovery.mjs';
|
|
11
|
+
import { beginProcessRecord,finishProcessRecord } from './processJournal.mjs';
|
|
12
|
+
|
|
13
|
+
const MAX_TIMEOUT = 60 * 60 * 1000;
|
|
14
|
+
function validateCommand(executable, args) {
|
|
15
|
+
if (typeof executable !== 'string' || !path.isAbsolute(executable) ||
|
|
16
|
+
!Array.isArray(args) || args.length > 128 ||
|
|
17
|
+
args.some(a => typeof a !== 'string' || a.length > 32768 || a.includes('\0'))) throw new Error('Trusted absolute executable and bounded argument vector required.');
|
|
18
|
+
const actual = fs.realpathSync.native(executable);
|
|
19
|
+
if (!fs.statSync(actual).isFile() ||
|
|
20
|
+
(process.platform === 'win32' && path.extname(actual).toLowerCase() !== '.exe')) throw new Error('Executable must be a regular native binary.');
|
|
21
|
+
fs.accessSync(actual, process.platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK);
|
|
22
|
+
return actual;
|
|
23
|
+
}
|
|
24
|
+
function stopTree(child) {
|
|
25
|
+
if (!child.pid || child.exitCode !== null || child.signalCode !== null) return;
|
|
26
|
+
if (process.platform === 'win32') {
|
|
27
|
+
// Do not kill a PID recovered from disk. Only the child owned by this
|
|
28
|
+
// supervisor. taskkill is best effort; Windows Job Objects remain a gate.
|
|
29
|
+
const systemRoot = process.env.SystemRoot ?? process.env.SYSTEMROOT;
|
|
30
|
+
if (systemRoot && path.isAbsolute(systemRoot)) {
|
|
31
|
+
spawnSync(path.join(systemRoot,'System32','taskkill.exe'), ['/pid',String(child.pid),'/T','/F'], {
|
|
32
|
+
windowsHide:true, stdio:'ignore', timeout:5000, shell:false,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
try { child.kill('SIGKILL'); } catch { /* already exited */ }
|
|
36
|
+
} else {
|
|
37
|
+
try { process.kill(-child.pid,'SIGKILL'); } catch { try { child.kill('SIGKILL'); } catch { /* exited */ } }
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function bounded(promise, ms) {
|
|
41
|
+
let timer;
|
|
42
|
+
return Promise.race([promise,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error('Authority check timed out.')),ms);})]).finally(()=>clearTimeout(timer));
|
|
43
|
+
}
|
|
44
|
+
/** Only invoked with a verified transport and trusted local executable policy.
|
|
45
|
+
* The authorization callback must check the live server attempt; it is not a
|
|
46
|
+
* substitute for server-side lease enforcement. No credentials persisted. */
|
|
47
|
+
export async function runWorkspaceProcess(input, {
|
|
48
|
+
env=process.env, authorizeAttempt, fetchCommit, executable, args=[],
|
|
49
|
+
signal, timeoutMs=300000, heartbeatMs=5000, authorityTimeoutMs=5000,
|
|
50
|
+
}={}) {
|
|
51
|
+
const identity=attemptIdentity(input);
|
|
52
|
+
const command=validateCommand(executable,args);
|
|
53
|
+
if (![timeoutMs,heartbeatMs,authorityTimeoutMs].every(Number.isSafeInteger) ||
|
|
54
|
+
timeoutMs<100 || timeoutMs>MAX_TIMEOUT || heartbeatMs<100 || heartbeatMs>60000 ||
|
|
55
|
+
authorityTimeoutMs<100 || authorityTimeoutMs>30000) throw new Error('Invalid supervision limits.');
|
|
56
|
+
if (typeof authorizeAttempt!=='function') throw new Error('Verified server attempt authorization required.');
|
|
57
|
+
if (signal?.aborted) return {status:'cancelled',code:null};
|
|
58
|
+
const check=()=>bounded(Promise.resolve().then(()=>authorizeAttempt(identity)),authorityTimeoutMs);
|
|
59
|
+
const workspace=await provisionWorkspace(identity,{env,authorizeAttempt:check,fetchCommit});
|
|
60
|
+
const paths=workspacePaths(identity,env);
|
|
61
|
+
const release=await acquireLock(path.join(paths.dir,'process'),{staleMs:Infinity,waitMs:1000});
|
|
62
|
+
if(!release.acquired) throw new Error('Workspace process already supervised; retry only after it stops.');
|
|
63
|
+
try {
|
|
64
|
+
const resources=prepareResources(identity,env);
|
|
65
|
+
const current=await check();
|
|
66
|
+
// Provisioning validated repository identity. Re-read it rather than
|
|
67
|
+
// trusting a repository value returned by a subsequent authority check.
|
|
68
|
+
const { readJournal }=await import('./workspaceJournal.mjs');
|
|
69
|
+
const journal=readJournal(paths.file);
|
|
70
|
+
if(!journal||classifyAuthority(journal,current)!=='active') throw new Error('Attempt authorization lost before launch.');
|
|
71
|
+
if(signal?.aborted) return {status:'cancelled',code:null};
|
|
72
|
+
const processRecord=beginProcessRecord(identity,env);
|
|
73
|
+
const result=await new Promise((resolve,reject)=>{
|
|
74
|
+
let child;
|
|
75
|
+
try {
|
|
76
|
+
child=spawn(command,args,{
|
|
77
|
+
cwd:workspace.cwd, env:isolatedEnvironment(env,resources), shell:false,
|
|
78
|
+
detached:process.platform!=='win32',windowsHide:true,stdio:'ignore',
|
|
79
|
+
});
|
|
80
|
+
} catch { reject(new Error('Provider process could not start.'));return; }
|
|
81
|
+
let settled=false,reason=null,heartbeat,deadline,killDeadline,checking=false;
|
|
82
|
+
const finish=(code,status)=>{
|
|
83
|
+
if(settled)return;
|
|
84
|
+
settled=true;clearInterval(heartbeat);clearTimeout(deadline);clearTimeout(killDeadline);
|
|
85
|
+
signal?.removeEventListener('abort',cancel);
|
|
86
|
+
resolve({status,code});
|
|
87
|
+
};
|
|
88
|
+
const stop=status=>{
|
|
89
|
+
if(settled||reason)return;
|
|
90
|
+
reason=status;stopTree(child);
|
|
91
|
+
// A failed termination must not masquerade as a successful stop.
|
|
92
|
+
killDeadline=setTimeout(()=>finish(null,'termination-unconfirmed'),10000);
|
|
93
|
+
};
|
|
94
|
+
const cancel=()=>stop('cancelled');
|
|
95
|
+
child.once('error',()=>finish(null,'launch-failed'));
|
|
96
|
+
child.once('exit',(code)=>finish(code,reason??(code===0?'exited':'failed')));
|
|
97
|
+
signal?.addEventListener('abort',cancel,{once:true});
|
|
98
|
+
deadline=setTimeout(()=>stop('timed-out'),timeoutMs);
|
|
99
|
+
heartbeat=setInterval(async()=>{
|
|
100
|
+
if(settled||reason||checking)return;
|
|
101
|
+
checking=true;
|
|
102
|
+
try {
|
|
103
|
+
const response=await check();
|
|
104
|
+
if(classifyAuthority(journal,response)!=='active')stop('authority-lost');
|
|
105
|
+
} catch { stop('authority-lost'); }
|
|
106
|
+
finally { checking=false; }
|
|
107
|
+
},heartbeatMs);
|
|
108
|
+
if(signal?.aborted)cancel();
|
|
109
|
+
});
|
|
110
|
+
finishProcessRecord(identity,processRecord,result,env);
|
|
111
|
+
return result;
|
|
112
|
+
} finally {release();}
|
|
113
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { verifyProjectLink } from './projectLinks.mjs';
|
|
3
|
+
import { inspectWorkspace } from './workspaceManager.mjs';
|
|
4
|
+
import { workspacePaths } from './workspaceJournal.mjs';
|
|
5
|
+
|
|
6
|
+
const SHA = /^[a-f0-9]{40}$/;
|
|
7
|
+
const ID = /^[a-f0-9]{24}$/;
|
|
8
|
+
const BRANCH = /^introsio\/checkpoints\/[a-f0-9-]{36}\/[a-f0-9]{24}$/;
|
|
9
|
+
|
|
10
|
+
function git(directory, args, timeout) {
|
|
11
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^GIT_/i.test(key)));
|
|
12
|
+
return spawnSync('git', [
|
|
13
|
+
'--no-replace-objects',
|
|
14
|
+
'-c', 'core.hooksPath=' + (process.platform === 'win32' ? 'NUL' : '/dev/null'),
|
|
15
|
+
'-c', 'protocol.allow=never', '-c', 'protocol.https.allow=always', '-c', 'protocol.ssh.allow=always',
|
|
16
|
+
...args,
|
|
17
|
+
], {
|
|
18
|
+
cwd: directory, env: { ...env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never' }, shell: false,
|
|
19
|
+
windowsHide: true, encoding: 'utf8', timeout, maxBuffer: 1024 * 1024,
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function pushCheckpoint(directory, headSha, branch) {
|
|
24
|
+
if (!SHA.test(headSha) || !BRANCH.test(branch)) throw new Error('Invalid checkpoint ref.');
|
|
25
|
+
const ref = 'refs/heads/' + branch;
|
|
26
|
+
// Empty expected value is a Git compare-and-swap against a nonexistent ref.
|
|
27
|
+
// The configured credential helper handles authentication outside the model.
|
|
28
|
+
return git(directory, [
|
|
29
|
+
'-c', 'push.followTags=false', 'push', '--porcelain', '--recurse-submodules=no',
|
|
30
|
+
'--force-with-lease=' + ref + ':', 'origin', headSha + ':' + ref,
|
|
31
|
+
], 90000).status === 0;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function verifyOwnedCommits(directory, baseSha, headSha) {
|
|
35
|
+
if (!SHA.test(baseSha) || !SHA.test(headSha)) throw new Error('A full GitHub commit SHA is required.');
|
|
36
|
+
// Explicitly separate revisions from paths. Git for Windows can otherwise
|
|
37
|
+
// stat the range as a filename inside a deeply nested managed worktree.
|
|
38
|
+
const result = git(directory, ['rev-list', '--parents', '--topo-order', '--reverse',
|
|
39
|
+
'--max-count=101', headSha, '^' + baseSha, '--'], 15000);
|
|
40
|
+
const lines = result.stdout?.trim().split(/\r?\n/) ?? [];
|
|
41
|
+
if (result.status !== 0) throw new Error('Checkpoint history could not be read.');
|
|
42
|
+
if (lines.length > 100) throw new Error('The checkpoint must contain at most 100 owned commits.');
|
|
43
|
+
const known = new Set([baseSha]);
|
|
44
|
+
for (const line of lines) {
|
|
45
|
+
const [commit, ...parents] = line.split(' ');
|
|
46
|
+
if (!SHA.test(commit) || known.has(commit) || !parents.length || parents.length > 16 ||
|
|
47
|
+
!parents.every(parent => known.has(parent))) throw new Error('The checkpoint contains commits outside the pinned attempt history.');
|
|
48
|
+
known.add(commit);
|
|
49
|
+
}
|
|
50
|
+
if (!known.has(headSha) || baseSha === headSha) throw new Error('The checkpoint has no new commits.');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function captureWorkspaceArtifact({
|
|
54
|
+
identity, session, handover, inputArtifactIds = [], supersedes, publish = false, env = process.env,
|
|
55
|
+
}) {
|
|
56
|
+
const authority = await session.authorizeAttempt(identity);
|
|
57
|
+
const state = inspectWorkspace(identity, env);
|
|
58
|
+
if (state.state !== 'ready' || !state.exists || !SHA.test(state.head) || state.head === identity.baseSha) {
|
|
59
|
+
throw new Error('Commit the owned changes in the ready attempt workspace first.');
|
|
60
|
+
}
|
|
61
|
+
const { head: headSha } = state;
|
|
62
|
+
const directory = workspacePaths(identity, env).checkout;
|
|
63
|
+
verifyOwnedCommits(directory, authority.baseSha, headSha);
|
|
64
|
+
const link = verifyProjectLink(identity.projectId, env);
|
|
65
|
+
if (link.repository !== authority.repository) throw new Error('The local repository link changed.');
|
|
66
|
+
const artifact = await session.recordArtifact({ headSha, handover, inputArtifactIds, ...(supersedes && { supersedes }) });
|
|
67
|
+
const branch = 'introsio/checkpoints/' + identity.attemptId + '/' + artifact?.artifactId;
|
|
68
|
+
if (!ID.test(artifact?.artifactId ?? '') || artifact.branch !== branch || artifact.headSha !== headSha ||
|
|
69
|
+
artifact.baseSha !== authority.baseSha || artifact.attemptId !== identity.attemptId ||
|
|
70
|
+
artifact.repositoryId !== authority.repositoryId) throw new Error('The server returned a different checkpoint identity.');
|
|
71
|
+
if (!publish) return artifact;
|
|
72
|
+
|
|
73
|
+
// Retrying after a lost response first checks whether the exact ref is
|
|
74
|
+
// already present. A moved, unprotected or invalid range is left alone.
|
|
75
|
+
const before = await session.verifyArtifact(artifact.artifactId);
|
|
76
|
+
if (before.state !== 'missing') return before;
|
|
77
|
+
if (before.publicationGuard) {
|
|
78
|
+
const guard = before.publicationGuard;
|
|
79
|
+
if (guard.allowed !== true || !Array.isArray(guard.protectedPaths)) throw new Error('The repository verification policy blocks checkpoint publication.');
|
|
80
|
+
const delta = git(directory, ['diff', '--name-only', '--no-renames', '-z', authority.baseSha, headSha, '--'], 15000);
|
|
81
|
+
if (delta.status !== 0 || delta.stdout.split('\0').filter(Boolean).some(file => guard.protectedPaths.some(prefix =>
|
|
82
|
+
file === prefix || file.startsWith(prefix.endsWith('/') ? prefix : prefix + '/')))) {
|
|
83
|
+
throw new Error('Checkpoint changes trusted verification sources; publish only through supervised review.');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
await session.authorizeAttempt(identity, { publication: true });
|
|
87
|
+
const checked = verifyProjectLink(identity.projectId, env);
|
|
88
|
+
if (checked.repository !== link.repository || checked.commonDir !== link.commonDir ||
|
|
89
|
+
inspectWorkspace(identity, env).head !== headSha) throw new Error('Workspace or repository changed before the checkpoint push.');
|
|
90
|
+
const pushed = pushCheckpoint(directory, headSha, branch);
|
|
91
|
+
const after = await session.verifyArtifact(artifact.artifactId);
|
|
92
|
+
return { ...after, pushAcknowledged: pushed };
|
|
93
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Durable local attempt journal. Never stores session credentials or claim packets.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { introsioDir } from '../lib/paths.mjs';
|
|
5
|
+
import { writeJson } from '../lib/jsonFile.mjs';
|
|
6
|
+
|
|
7
|
+
const ID = /^[a-f0-9]{24}$/;
|
|
8
|
+
const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
|
|
9
|
+
const SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
|
|
10
|
+
const STATES = new Set(['provisioning', 'ready', 'quarantined']);
|
|
11
|
+
export function attemptIdentity(value) {
|
|
12
|
+
const { projectId, taskId, attemptId, baseSha, fence, generation } = value ?? {};
|
|
13
|
+
if (![projectId,taskId,attemptId,baseSha].every(v=>typeof v==='string') ||
|
|
14
|
+
!ID.test(projectId) || !ID.test(taskId) || !UUID.test(attemptId) ||
|
|
15
|
+
!SHA.test(baseSha) || !Number.isSafeInteger(fence) || fence < 1 ||
|
|
16
|
+
!Number.isSafeInteger(generation) || generation < 0) throw new Error('Invalid attempt identity or pinned commit.');
|
|
17
|
+
return { projectId, taskId, attemptId, baseSha, fence, generation };
|
|
18
|
+
}
|
|
19
|
+
export function privateDir(dir, create = false) {
|
|
20
|
+
let stat = fs.lstatSync(dir, { throwIfNoEntry: false });
|
|
21
|
+
if (!stat && create) {
|
|
22
|
+
try { fs.mkdirSync(dir, { mode: 0o700 }); } catch (e) { if (e.code !== 'EEXIST') throw e; }
|
|
23
|
+
stat = fs.lstatSync(dir);
|
|
24
|
+
}
|
|
25
|
+
if (!stat) return false;
|
|
26
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() ||
|
|
27
|
+
(process.platform !== 'win32' && (stat.mode & 0o077))) throw new Error('Unsafe runner directory; no changes made.');
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
function stateRoot(env, create) {
|
|
31
|
+
const home = path.resolve(introsioDir(env));
|
|
32
|
+
if (create) fs.mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
33
|
+
const stat = fs.lstatSync(home, { throwIfNoEntry: false });
|
|
34
|
+
if (!stat) return null;
|
|
35
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Runner home is redirected.');
|
|
36
|
+
const runner = path.join(home, 'runner');
|
|
37
|
+
if (!privateDir(runner, create)) return null;
|
|
38
|
+
const ws = path.join(runner, 'workspaces');
|
|
39
|
+
return privateDir(ws, create) ? ws : null;
|
|
40
|
+
}
|
|
41
|
+
export function workspacePaths(identity, env = process.env, create = false) {
|
|
42
|
+
const { projectId, taskId, attemptId } = attemptIdentity(identity);
|
|
43
|
+
const root = stateRoot(env, create);
|
|
44
|
+
if (!root) return null;
|
|
45
|
+
const project = path.join(root, projectId);
|
|
46
|
+
if (!privateDir(project, create)) return null;
|
|
47
|
+
const task = path.join(project, taskId);
|
|
48
|
+
if (!privateDir(task, create)) return null;
|
|
49
|
+
const attempt = path.join(task, attemptId);
|
|
50
|
+
if (!privateDir(attempt, create)) return null;
|
|
51
|
+
return { dir: attempt, file: path.join(attempt, 'journal.json'), checkout: path.join(attempt, 'checkout') };
|
|
52
|
+
}
|
|
53
|
+
export function readJournal(file) {
|
|
54
|
+
const st = fs.lstatSync(file, { throwIfNoEntry: false });
|
|
55
|
+
if (!st) return null;
|
|
56
|
+
if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1 ||
|
|
57
|
+
(process.platform !== 'win32' && (st.mode & 0o077))) throw new Error('Unsafe workspace journal.');
|
|
58
|
+
let row;
|
|
59
|
+
try { row = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { throw new Error('Corrupt workspace journal; preserve for recovery.'); }
|
|
60
|
+
attemptIdentity(row);
|
|
61
|
+
if (row.version !== 1 || !STATES.has(row.state) || typeof row.repository !== 'string' ||
|
|
62
|
+
!path.isAbsolute(row.commonDir ?? '') || !Number.isFinite(Date.parse(row.createdAt))) throw new Error('Unsupported workspace journal.');
|
|
63
|
+
return row;
|
|
64
|
+
}
|
|
65
|
+
export function saveJournal(file, record) {
|
|
66
|
+
attemptIdentity(record);
|
|
67
|
+
if (!STATES.has(record.state)) throw new Error('Invalid journal state.');
|
|
68
|
+
// Read existing file first to reject redirects/corrupt state.
|
|
69
|
+
readJournal(file);
|
|
70
|
+
writeJson(file, record, { mode: 0o600, durable: true });
|
|
71
|
+
}
|
|
72
|
+
export function listJournals(env = process.env) {
|
|
73
|
+
const root = stateRoot(env, false);
|
|
74
|
+
if (!root) return [];
|
|
75
|
+
const records = [];
|
|
76
|
+
for (const projectId of fs.readdirSync(root).filter(v => ID.test(v))) {
|
|
77
|
+
const p = path.join(root, projectId); privateDir(p);
|
|
78
|
+
for (const taskId of fs.readdirSync(p).filter(v => ID.test(v))) {
|
|
79
|
+
const t = path.join(p, taskId); privateDir(t);
|
|
80
|
+
for (const attemptId of fs.readdirSync(t).filter(v => UUID.test(v))) {
|
|
81
|
+
const a = path.join(t, attemptId); privateDir(a);
|
|
82
|
+
const file = path.join(a, 'journal.json');
|
|
83
|
+
const record = readJournal(file);
|
|
84
|
+
if (!record) { records.push({ projectId, taskId, attemptId, state: 'orphaned' }); continue; }
|
|
85
|
+
if (record.projectId !== projectId || record.taskId !== taskId || record.attemptId !== attemptId) throw new Error('Journal path identity mismatch.');
|
|
86
|
+
records.push(record);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return records;
|
|
91
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// Attempt-scoped workspace provisioning, no reset, no deletion, no push.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { acquireLock } from '../lib/lock.mjs';
|
|
6
|
+
import { verifyProjectLink } from './projectLinks.mjs';
|
|
7
|
+
import { canonicalPath, introsioDir } from '../lib/paths.mjs';
|
|
8
|
+
import { attemptIdentity, workspacePaths, readJournal, saveJournal, listJournals } from './workspaceJournal.mjs';
|
|
9
|
+
|
|
10
|
+
const real = p => fs.realpathSync.native(p);
|
|
11
|
+
const same = (a,b) => process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
12
|
+
function git(cwd, args, timeout = 30000, allowFailure = false) {
|
|
13
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^GIT_/i.test(k)));
|
|
14
|
+
// Disable hooks and submodule execution. Only trusted local repositories
|
|
15
|
+
// may be linked: worktrees are not a sandbox for untrusted Git config.
|
|
16
|
+
const r = spawnSync('git', ['--no-optional-locks', '--no-replace-objects', '-c', 'core.hooksPath=' + (process.platform === 'win32' ? 'NUL' : '/dev/null'),
|
|
17
|
+
'-c', 'submodule.recurse=false', '-c', 'protocol.ext.allow=never', '-c', 'protocol.file.allow=never', ...args], {
|
|
18
|
+
cwd, shell: false, windowsHide: true, encoding: 'utf8', timeout,
|
|
19
|
+
maxBuffer: 8 * 1024 * 1024, env: { ...env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never' },
|
|
20
|
+
});
|
|
21
|
+
if (r.error || (r.status !== 0 && !allowFailure)) throw new Error('Git workspace operation failed; existing work was retained.');
|
|
22
|
+
return { ok: r.status === 0, out: (r.stdout ?? '').trimEnd() };
|
|
23
|
+
}
|
|
24
|
+
const value = (cwd,args) => git(cwd,args).out;
|
|
25
|
+
function branchFor(id) { return 'introsio/task/' + id.taskId + '/attempt-' + id.attemptId; }
|
|
26
|
+
function safeCheckout(checkout) {
|
|
27
|
+
const st = fs.lstatSync(checkout, { throwIfNoEntry: false });
|
|
28
|
+
if (!st) return false;
|
|
29
|
+
if (!st.isDirectory() || st.isSymbolicLink() || !same(real(checkout), path.join(real(path.dirname(checkout)), path.basename(checkout)))) throw new Error('Managed checkout is redirected.');
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
function inspectCheckout(record, paths) {
|
|
33
|
+
if (!safeCheckout(paths.checkout)) return { exists: false };
|
|
34
|
+
const cwd = paths.checkout;
|
|
35
|
+
if (!same(real(value(cwd,['rev-parse','--show-toplevel'])),real(cwd)) ||
|
|
36
|
+
!same(real(value(cwd,['rev-parse','--path-format=absolute','--git-common-dir'])),record.commonDir) ||
|
|
37
|
+
value(cwd,['symbolic-ref','HEAD']) !== 'refs/heads/' + branchFor(record)) throw new Error('Workspace Git identity differs from its journal.');
|
|
38
|
+
const head = value(cwd,['rev-parse','--verify','HEAD']);
|
|
39
|
+
if (!git(cwd,['merge-base','--is-ancestor',record.baseSha,head],30000,true).ok) throw new Error('Workspace history no longer descends from its pinned base.');
|
|
40
|
+
const status = value(cwd,['status','--porcelain=v1','--untracked-files=all']);
|
|
41
|
+
const upstream = git(cwd,['rev-parse','--verify','@{u}'],30000,true);
|
|
42
|
+
const ahead = upstream.ok ? Number(value(cwd,['rev-list','--count','@{u}..HEAD'])) : null;
|
|
43
|
+
return { exists:true, head, dirty:status.length>0, ahead, unpushed:!upstream.ok || ahead>0 };
|
|
44
|
+
}
|
|
45
|
+
function match(record, id, link) {
|
|
46
|
+
return Object.keys(id).every(k=>record[k]===id[k]) && record.repository===link.repository && same(record.commonDir,link.commonDir);
|
|
47
|
+
}
|
|
48
|
+
// Fetch the exact full SHA, without updating FETCH_HEAD, tags, human branches or
|
|
49
|
+
// tracking refs. The verified server packet must pin both repository and commit.
|
|
50
|
+
function fetchPinned(link, id) {
|
|
51
|
+
git(link.localRoot,['-c','protocol.allow=never','-c','protocol.https.allow=always','-c','protocol.ssh.allow=always',
|
|
52
|
+
'fetch','--no-tags','--no-write-fetch-head','--no-auto-maintenance','--refmap=','origin',id.baseSha],120000);
|
|
53
|
+
}
|
|
54
|
+
function ensureCommit(link,id) {
|
|
55
|
+
if (value(link.localRoot,['cat-file','-t',id.baseSha])!=='commit' ||
|
|
56
|
+
value(link.localRoot,['rev-parse','--verify',id.baseSha+'^{commit}'])!==id.baseSha) throw new Error('Pinned object is not the exact commit.');
|
|
57
|
+
}
|
|
58
|
+
async function verifyDependencyCommits(link, identity, snapshot, fetchCommit) {
|
|
59
|
+
if (!snapshot) return;
|
|
60
|
+
if (snapshot.baseSha !== identity.baseSha || !/^[a-f0-9]{64}$/.test(snapshot.signature ?? '') ||
|
|
61
|
+
!Array.isArray(snapshot.inputs) || snapshot.inputs.length > 20) throw new Error('Invalid dependency reservation.');
|
|
62
|
+
const heads = [...new Set(snapshot.inputs.flatMap(input => [input.integrationSha, input.artifactHeadSha]))];
|
|
63
|
+
if (!heads.every(sha => /^[a-f0-9]{40}$/.test(sha ?? ''))) throw new Error('Full dependency commit IDs are required.');
|
|
64
|
+
for (const sha of heads) {
|
|
65
|
+
await fetchCommit(link, { ...identity, baseSha: sha });
|
|
66
|
+
ensureCommit(link, { baseSha: sha });
|
|
67
|
+
}
|
|
68
|
+
for (const input of snapshot.inputs) {
|
|
69
|
+
if (!git(link.localRoot, ['merge-base', '--is-ancestor', input.integrationSha, identity.baseSha], 30000, true).ok) {
|
|
70
|
+
throw new Error('The pinned workspace does not contain the verified dependency commit.');
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** Internal runner API: only a trusted transport may supply authorizeAttempt.
|
|
75
|
+
* No provisioning CLI is exposed until the authenticated claim adapter exists.
|
|
76
|
+
* The fetch dependency is injectable for isolated real-Git fixture tests. */
|
|
77
|
+
export async function provisionWorkspace(input, { env=process.env, authorizeAttempt, fetchCommit=fetchPinned }={}) {
|
|
78
|
+
const id = attemptIdentity(input);
|
|
79
|
+
if (typeof authorizeAttempt!=='function') throw new Error('Verified server attempt authorization required.');
|
|
80
|
+
const authorize = async () => {
|
|
81
|
+
const packet = await authorizeAttempt(id);
|
|
82
|
+
const authorized = attemptIdentity(packet);
|
|
83
|
+
if (!Object.keys(id).every(k=>id[k]===authorized[k]) || packet.active!==true ||
|
|
84
|
+
typeof packet.repository!=='string' || !Number.isFinite(Date.parse(packet.expiresAt)) ||
|
|
85
|
+
Date.parse(packet.expiresAt)<=Date.now()) throw new Error('Server attempt is stale or does not authorize this workspace.');
|
|
86
|
+
return packet;
|
|
87
|
+
};
|
|
88
|
+
const packet = await authorize();
|
|
89
|
+
const link = verifyProjectLink(id.projectId,env);
|
|
90
|
+
if (packet.repository.toLowerCase()!==link.repository) throw new Error('Server repository does not match the local link.');
|
|
91
|
+
const stateRoot = canonicalPath(path.join(introsioDir(env),'runner','workspaces'));
|
|
92
|
+
const within = (parent,child) => { const rel=path.relative(parent,child); return rel==='' || (!path.isAbsolute(rel)&&rel!=='..'&&!rel.startsWith('..'+path.sep)); };
|
|
93
|
+
const roots = value(link.localRoot,['worktree','list','--porcelain','-z']).split('\0').filter(s=>s.startsWith('worktree ')).map(s=>canonicalPath(s.slice(9)));
|
|
94
|
+
if (within(link.commonDir,stateRoot) || roots.some(r=>within(r,stateRoot))) throw new Error('Runner workspace state must be outside every existing checkout and Git metadata.');
|
|
95
|
+
const paths = workspacePaths(id,env,true);
|
|
96
|
+
// Lock in common Git metadata so distinct project links to the same repo
|
|
97
|
+
// serialize their mutations even when using different Introsio homes.
|
|
98
|
+
const release = await acquireLock(path.join(link.commonDir,'introsio-workspace'),{staleMs:Infinity,waitMs:10000});
|
|
99
|
+
if (!release.acquired) throw new Error('Repository workspace lock busy; retry.');
|
|
100
|
+
try {
|
|
101
|
+
const current = await authorize();
|
|
102
|
+
const checked = verifyProjectLink(id.projectId,env);
|
|
103
|
+
if (!same(checked.commonDir,link.commonDir) || !same(checked.localRoot,link.localRoot) || checked.repository!==link.repository ||
|
|
104
|
+
current.repository.toLowerCase()!==link.repository) throw new Error('Repository identity changed.');
|
|
105
|
+
let record = readJournal(paths.file);
|
|
106
|
+
const quarantine = (reason) => {
|
|
107
|
+
if (record && match(record,id,link)) saveJournal(paths.file,{...record,state:'quarantined',reason});
|
|
108
|
+
throw new Error(reason+' Existing files were retained.');
|
|
109
|
+
};
|
|
110
|
+
if (record && !match(record,id,link)) throw new Error('Workspace journal identity mismatch; preserve for recovery.');
|
|
111
|
+
if (record?.state==='quarantined') throw new Error('Workspace quarantined; explicit recovery required.');
|
|
112
|
+
if (record?.dependencySignature && record.dependencySignature !== current.dependencySnapshot?.signature) {
|
|
113
|
+
return quarantine('Dependency reservation changed during the attempt.');
|
|
114
|
+
}
|
|
115
|
+
if (!record) {
|
|
116
|
+
if (fs.lstatSync(paths.checkout,{throwIfNoEntry:false})) throw new Error('Unregistered checkout exists; preserve for recovery.');
|
|
117
|
+
record = {version:1,...id,repository:link.repository,commonDir:link.commonDir,state:'provisioning',createdAt:new Date().toISOString(),
|
|
118
|
+
...(current.dependencySnapshot ? { dependencySignature: current.dependencySnapshot.signature } : {})};
|
|
119
|
+
saveJournal(paths.file,record);
|
|
120
|
+
}
|
|
121
|
+
let existing;
|
|
122
|
+
try { existing=inspectCheckout(record,paths); } catch { return quarantine('Workspace Git identity could not be verified.'); }
|
|
123
|
+
if (existing.exists) {
|
|
124
|
+
await verifyDependencyCommits(link, id, current.dependencySnapshot, fetchCommit);
|
|
125
|
+
if (record.state==='provisioning' && (existing.head!==id.baseSha || existing.dirty)) return quarantine('Interrupted provisioning contains unexpected work.');
|
|
126
|
+
if (record.state!=='ready') saveJournal(paths.file,{...record,state:'ready'});
|
|
127
|
+
return { ...id, cwd:paths.checkout, branch:branchFor(id), reused:true };
|
|
128
|
+
}
|
|
129
|
+
if (record.state==='ready') return quarantine('Previously registered checkout is missing.');
|
|
130
|
+
// Never adopt an unrelated existing branch, including crash remnants.
|
|
131
|
+
if (git(link.localRoot,['show-ref','--verify','--quiet','refs/heads/'+branchFor(id)],30000,true).ok)
|
|
132
|
+
return quarantine('Attempt branch already exists without its checkout.');
|
|
133
|
+
await fetchCommit(link,id);
|
|
134
|
+
ensureCommit(link,id);
|
|
135
|
+
await verifyDependencyCommits(link, id, current.dependencySnapshot, fetchCommit);
|
|
136
|
+
const final=await authorize();
|
|
137
|
+
if(final.repository.toLowerCase()!==link.repository) throw new Error('Server repository changed before provisioning.');
|
|
138
|
+
const last=verifyProjectLink(id.projectId,env);
|
|
139
|
+
if(!same(last.commonDir,link.commonDir)||!same(last.localRoot,link.localRoot)) throw new Error('Repository changed before provisioning.');
|
|
140
|
+
if(safeCheckout(paths.checkout)) return quarantine('Checkout unexpectedly appeared.');
|
|
141
|
+
git(link.localRoot,['worktree','add','-b',branchFor(id),'--',paths.checkout,id.baseSha],120000);
|
|
142
|
+
let saved;
|
|
143
|
+
try { saved=inspectCheckout(record,paths); } catch { return quarantine('Created checkout failed verification.'); }
|
|
144
|
+
if(!saved.exists||saved.head!==id.baseSha||saved.dirty) return quarantine('Created checkout differs from pinned base.');
|
|
145
|
+
try { const verified=await authorize(); if(verified.repository.toLowerCase()!==link.repository) throw new Error('Repository changed'); } catch { return quarantine('Attempt authorization changed during provisioning.'); }
|
|
146
|
+
saveJournal(paths.file,{...record,state:'ready'});
|
|
147
|
+
return { ...id,cwd:paths.checkout,branch:branchFor(id),reused:false };
|
|
148
|
+
} finally { release(); }
|
|
149
|
+
}
|
|
150
|
+
export function inspectWorkspace(record,env=process.env) {
|
|
151
|
+
const paths=workspacePaths(record,env);
|
|
152
|
+
if(!paths) return {state:'missing'};
|
|
153
|
+
const persisted=readJournal(paths.file);
|
|
154
|
+
if(!persisted) return {state:'orphaned'};
|
|
155
|
+
try {
|
|
156
|
+
const link=verifyProjectLink(persisted.projectId,env);
|
|
157
|
+
if(!match(persisted,attemptIdentity(record),link)) return {state:'quarantined'};
|
|
158
|
+
return {...persisted,...inspectCheckout(persisted,paths),cwd:paths.checkout};
|
|
159
|
+
} catch { return {...persisted,state:'quarantined'}; }
|
|
160
|
+
}
|
|
161
|
+
export function listWorkspaces(env=process.env) {
|
|
162
|
+
return listJournals(env).map(row => {
|
|
163
|
+
const { telemetry, telemetryHistory, ...workspace } = row.state === 'orphaned' ? row : inspectWorkspace(row, env);
|
|
164
|
+
return { ...workspace, ...(telemetry ? { telemetry: { sessionId: telemetry.sessionId, sequence: telemetry.sequence, pending: Boolean(telemetry.pending) } } : {}) };
|
|
165
|
+
});
|
|
166
|
+
}
|