mlai-code 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/README.md +12 -2
  2. package/bin/mlai.mjs +3 -0
  3. package/package.json +18 -3
  4. package/src/browser-setup.mjs +77 -0
  5. package/src/cli-ext.mjs +146 -0
  6. package/src/cli.mjs +534 -0
  7. package/src/cloud.mjs +29 -0
  8. package/src/completion.mjs +159 -0
  9. package/src/credentials.mjs +54 -0
  10. package/src/deploy.mjs +134 -0
  11. package/src/distribution.mjs +373 -0
  12. package/src/engine-key.mjs +4 -0
  13. package/src/engine.mjs +167 -0
  14. package/src/headless.mjs +196 -0
  15. package/src/home.mjs +22 -0
  16. package/src/host.mjs +123 -0
  17. package/src/local-models.mjs +64 -0
  18. package/src/modes.mjs +38 -0
  19. package/src/netbox.mjs +97 -0
  20. package/src/netjail.py +59 -0
  21. package/src/offline.mjs +98 -0
  22. package/src/parity.mjs +86 -0
  23. package/src/project.mjs +68 -0
  24. package/src/relay.mjs +140 -0
  25. package/src/render.mjs +73 -0
  26. package/src/restricted.mjs +47 -0
  27. package/src/review.mjs +70 -0
  28. package/src/runner.mjs +127 -0
  29. package/src/runtime.mjs +75 -0
  30. package/src/sandbox.mjs +135 -0
  31. package/src/sdk.mjs +11 -0
  32. package/src/server.mjs +110 -0
  33. package/src/session.mjs +290 -0
  34. package/src/settings.mjs +135 -0
  35. package/src/shared-data.mjs +3 -0
  36. package/src/tui/acp.mjs +145 -0
  37. package/src/tui/agents-cli.mjs +114 -0
  38. package/src/tui/agents-local.mjs +65 -0
  39. package/src/tui/ansi.mjs +123 -0
  40. package/src/tui/app.mjs +710 -0
  41. package/src/tui/approval.mjs +88 -0
  42. package/src/tui/bg.mjs +172 -0
  43. package/src/tui/bgterm.mjs +79 -0
  44. package/src/tui/chat.mjs +230 -0
  45. package/src/tui/clipboard.mjs +74 -0
  46. package/src/tui/cloud-cli.mjs +57 -0
  47. package/src/tui/cloud-run.mjs +123 -0
  48. package/src/tui/cmd-agents.mjs +130 -0
  49. package/src/tui/cmd-auto-review.mjs +94 -0
  50. package/src/tui/cmd-cloud.mjs +17 -0
  51. package/src/tui/cmd-config.mjs +104 -0
  52. package/src/tui/cmd-core.mjs +160 -0
  53. package/src/tui/cmd-distribution.mjs +15 -0
  54. package/src/tui/cmd-ecosystem.mjs +169 -0
  55. package/src/tui/cmd-extensibility.mjs +333 -0
  56. package/src/tui/cmd-remote.mjs +18 -0
  57. package/src/tui/cmd-review.mjs +58 -0
  58. package/src/tui/cmd-session-extra.mjs +152 -0
  59. package/src/tui/cmd-tui.mjs +200 -0
  60. package/src/tui/commands.mjs +160 -0
  61. package/src/tui/custom-commands.mjs +98 -0
  62. package/src/tui/diff.mjs +60 -0
  63. package/src/tui/editor.mjs +190 -0
  64. package/src/tui/ext-state.mjs +16 -0
  65. package/src/tui/extensions-local.mjs +140 -0
  66. package/src/tui/files.mjs +72 -0
  67. package/src/tui/handoff.mjs +110 -0
  68. package/src/tui/import-setups.mjs +151 -0
  69. package/src/tui/init.mjs +104 -0
  70. package/src/tui/keymap.mjs +70 -0
  71. package/src/tui/keys.mjs +101 -0
  72. package/src/tui/loop.mjs +75 -0
  73. package/src/tui/markdown.mjs +118 -0
  74. package/src/tui/mcp-config.mjs +225 -0
  75. package/src/tui/mcp-oauth.mjs +162 -0
  76. package/src/tui/permissions.mjs +189 -0
  77. package/src/tui/plain.mjs +32 -0
  78. package/src/tui/plugins-local.mjs +103 -0
  79. package/src/tui/remote.mjs +125 -0
  80. package/src/tui/review-cli.mjs +332 -0
  81. package/src/tui/review-github.mjs +59 -0
  82. package/src/tui/screen.mjs +60 -0
  83. package/src/tui/session-ops.mjs +104 -0
  84. package/src/tui/skills-local.mjs +92 -0
  85. package/src/tui/snapshots.mjs +87 -0
  86. package/src/tui/statusline.mjs +98 -0
  87. package/src/tui/transcript.mjs +116 -0
  88. package/src/two-words.mjs +36 -0
  89. package/src/wakeups.mjs +53 -0
  90. package/src/winenv.mjs +94 -0
  91. package/src/winsandbox.py +351 -0
  92. package/src/workspace-api.mjs +621 -0
  93. package/src/worktree.mjs +128 -0
  94. package/vendor/client-sdk/controller.cjs +115 -0
  95. package/vendor/client-sdk/files.cjs +38 -0
  96. package/vendor/client-sdk/index.cjs +133 -0
  97. package/vendor/client-sdk/login.cjs +52 -0
  98. package/vendor/client-sdk/updates.cjs +41 -0
  99. package/vendor/cloud-cli/mlai.mjs +394 -0
  100. package/worker/architecture_parse.cjs +23 -0
  101. package/worker/architecture_worker.py +394 -0
  102. package/worker/ask_first.py +96 -0
  103. package/worker/attachment_reader.py +66 -0
  104. package/worker/background_jobs.py +111 -0
  105. package/worker/brief_questions.py +56 -0
  106. package/worker/browser_local.py +49 -0
  107. package/worker/browser_pane.py +89 -0
  108. package/worker/browser_tool.py +101 -0
  109. package/worker/build_planner.py +187 -0
  110. package/worker/chat_fork.py +277 -0
  111. package/worker/checkpoints.py +133 -0
  112. package/worker/cloud_pty.py +351 -0
  113. package/worker/command_policy.py +39 -0
  114. package/worker/command_safety.py +717 -0
  115. package/worker/computer_card.sh +23 -0
  116. package/worker/computer_setup.sh +86 -0
  117. package/worker/computer_use.py +221 -0
  118. package/worker/connector_search.py +43 -0
  119. package/worker/context_manager.py +60 -0
  120. package/worker/conversation.py +144 -0
  121. package/worker/deploy_pack.py +116 -0
  122. package/worker/design_director.py +240 -0
  123. package/worker/dev_jobs.py +166 -0
  124. package/worker/edit_guard.py +99 -0
  125. package/worker/env_setup.py +129 -0
  126. package/worker/evidence.py +109 -0
  127. package/worker/fast_search.py +24 -0
  128. package/worker/git_sync.py +333 -0
  129. package/worker/goals.py +156 -0
  130. package/worker/handover.py +98 -0
  131. package/worker/harness_memory.py +194 -0
  132. package/worker/image_generation.py +173 -0
  133. package/worker/intelligence.py +149 -0
  134. package/worker/intent_model.py +78 -0
  135. package/worker/intent_weights.json +1 -0
  136. package/worker/ios_simulator.py +87 -0
  137. package/worker/kimi_bridge.py +997 -0
  138. package/worker/kimi_compact.py +93 -0
  139. package/worker/kimi_gates.py +304 -0
  140. package/worker/kimi_hook.py +617 -0
  141. package/worker/lifecycle.py +95 -0
  142. package/worker/lsp.py +77 -0
  143. package/worker/mcp_local.py +293 -0
  144. package/worker/memory.py +99 -0
  145. package/worker/mlai_auto_review.py +177 -0
  146. package/worker/mlai_hooks.py +966 -0
  147. package/worker/mlai_mcp.py +441 -0
  148. package/worker/mlai_permissions.py +283 -0
  149. package/worker/model_stream.py +75 -0
  150. package/worker/nested_repos.py +76 -0
  151. package/worker/offline_guard.py +17 -0
  152. package/worker/preview.py +806 -0
  153. package/worker/proc_watch.py +124 -0
  154. package/worker/project_context.py +72 -0
  155. package/worker/project_rules.py +99 -0
  156. package/worker/quality.py +180 -0
  157. package/worker/reply_language.py +56 -0
  158. package/worker/repo_hygiene.py +132 -0
  159. package/worker/repo_memory.py +101 -0
  160. package/worker/repo_policy.py +269 -0
  161. package/worker/roles.json +3173 -0
  162. package/worker/roles.py +303 -0
  163. package/worker/runner.py +1795 -0
  164. package/worker/runtime_control.py +205 -0
  165. package/worker/secret_scan.py +168 -0
  166. package/worker/session_hub.py +80 -0
  167. package/worker/skill_library.py +129 -0
  168. package/worker/skill_pack.py +533 -0
  169. package/worker/subagents.py +91 -0
  170. package/worker/task_controller.py +139 -0
  171. package/worker/task_skills.py +159 -0
  172. package/worker/team_checkpoint.py +33 -0
  173. package/worker/token_count.py +32 -0
  174. package/worker/tool_catalog.py +38 -0
  175. package/worker/upload_storage.py +531 -0
  176. package/worker/verification.py +725 -0
  177. package/worker/vision.py +84 -0
  178. package/worker/wakeups.py +63 -0
  179. package/worker/web_tools.py +203 -0
  180. package/worker/winproc.py +135 -0
  181. package/worker/work_ledger.py +117 -0
  182. package/worker/worktrees.py +79 -0
@@ -0,0 +1,332 @@
1
+ // ML AI Review in the terminal: `/review` in a session and `mlai review` for scripts and CI. The reviewer
2
+ // (worker/mlai_review) runs with the engine's Python on this computer against uncommitted changes, the branch
3
+ // against its base, a pull request fetched from origin, or the whole repository. Findings print with file:line;
4
+ // the exit code is nonzero when a blocking finding is left, so CI can gate on it.
5
+ import {spawn,execFile} from 'node:child_process';
6
+ import {readFile,writeFile,mkdir,rename} from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import {reviewRequest,addDismissal} from '../review.mjs';
9
+
10
+ export const SEVERITIES=['critical','high','medium','low','info'];
11
+ const RANK={critical:0,high:1,medium:2,low:3,info:4};
12
+ export const REVIEW_EXIT={clean:0,blocking:1,usage:2,unfinished:3,auth:4,stopped:130};
13
+ const plain={dim:s=>String(s),bold:s=>String(s),red:s=>String(s),yellow:s=>String(s),cyan:s=>String(s),gray:s=>String(s),green:s=>String(s)};
14
+
15
+ /* ---------- arguments ---------- */
16
+
17
+ export class ReviewUsage extends Error{constructor(m){super(m);this.name='ReviewUsage'}}
18
+ /**
19
+ * Words and flags shared by `/review ...` and `mlai review ...`:
20
+ * deep | security (scan) | repo | uncommitted (changes) | branch | #123 (pr 123, --pr 123) | --base <ref> (base <ref>)
21
+ * --fail-on <severity|none> --json --model <id> --no-lint, and any other words are the focus ("the auth flow").
22
+ */
23
+ export function parseReviewArgs(input){
24
+ const words=Array.isArray(input)?input.slice():String(input||'').trim().split(/\s+/).filter(Boolean);
25
+ const o={mode:'standard',target:'auto',base:'',pr:null,focus:'',failOn:'high',json:false,format:'text',post:false,model:null,analysis:'auto',server:null,help:false};
26
+ const focus=[];
27
+ const val=(i,flag)=>{const v=words[i+1];if(v===undefined||v.startsWith('--'))throw new ReviewUsage('Missing value for '+flag);return v};
28
+ const pr=v=>{const n=Number(String(v).replace(/^#/,''));if(!Number.isInteger(n)||n<1)throw new ReviewUsage('Pull request numbers look like #123');o.target='pr';o.pr=n};
29
+ for(let i=0;i<words.length;i++){
30
+ const w=words[i],l=w.toLowerCase(),eq=/^(--[a-z-]+)=(.*)$/.exec(w);
31
+ if(eq){words.splice(i,1,eq[1],eq[2]);i--;continue}
32
+ if(l==='deep')o.mode='deep';
33
+ else if(l==='security'||l==='scan'||l==='--security')o.mode='security';
34
+ else if(l==='--deep')o.mode='deep';
35
+ else if(l==='--mode'){const m=val(i,w);i++;if(!['standard','deep','security'].includes(m))throw new ReviewUsage('--mode must be standard, deep or security');o.mode=m}
36
+ else if(l==='repo'||l==='repository'||l==='--repo')o.target='repo';
37
+ else if(l==='uncommitted'||l==='changes'||l==='--uncommitted')o.target='changes';
38
+ else if(l==='branch'||l==='--branch')o.target='branch';
39
+ else if(/^#\d+$/.test(w))pr(w);
40
+ else if((l==='pr'||l==='--pr')&&/^#?\d+$/.test(words[i+1]||'')){pr(words[++i])}
41
+ else if(l==='--pr')throw new ReviewUsage('--pr needs a pull request number');
42
+ else if(l==='--base'||(l==='base'&&words[i+1]&&!words[i+1].startsWith('-'))){o.base=val(i,w);i++;if(o.target==='auto')o.target='branch'}
43
+ else if(l==='--fail-on'){const s=val(i,w).toLowerCase();i++;if(s!=='none'&&!RANK.hasOwnProperty(s))throw new ReviewUsage('--fail-on must be one of '+SEVERITIES.join(', ')+' or none');o.failOn=s}
44
+ else if(l==='--json'){o.json=true;o.format='json'}
45
+ else if(l==='--format'){const f=val(i,w).toLowerCase();i++;if(!['text','json','github'].includes(f))throw new ReviewUsage('--format must be text, json or github');o.format=f;o.json=f!=='text'}
46
+ else if(l==='--post')o.post=true;
47
+ else if(l==='--model'||l==='-m'){o.model=val(i,w);i++}
48
+ else if(l==='--server'){o.server=val(i,w);i++}
49
+ else if(l==='--no-lint'||l==='--no-analysis')o.analysis='off';
50
+ else if(l==='-h'||l==='--help'||l==='help')o.help=true;
51
+ else if(w.startsWith('--'))throw new ReviewUsage('Unknown option '+w+'. Run mlai review --help.');
52
+ else focus.push(w);
53
+ }
54
+ o.focus=focus.join(' ').slice(0,500);
55
+ if(o.post&&o.format!=='github')throw new ReviewUsage('--post needs --format github');
56
+ return o;
57
+ }
58
+
59
+ /* ---------- what to review ---------- */
60
+
61
+ const REF=/^(?!-)[A-Za-z0-9._\/~^@{}-]{1,200}$/;
62
+ export function gitRunner(root,execImpl=execFile){
63
+ return (args,{allowFail=false}={})=>new Promise((resolve,reject)=>execImpl('git',args,{cwd:root,maxBuffer:8<<20,windowsHide:true},(e,stdout,stderr)=>{
64
+ if(e&&!allowFail)reject(Object.assign(new Error(String(stderr||e.message).trim().split('\n').slice(-1)[0]||'git failed'),{code:e.code}));
65
+ else resolve(e?null:String(stdout).trim())}));
66
+ }
67
+ /** origin's default branch, else main or master (remote first). */
68
+ export async function defaultBase(git){
69
+ const head=await git(['symbolic-ref','--quiet','--short','refs/remotes/origin/HEAD'],{allowFail:true});
70
+ if(head)return head;
71
+ for(const r of ['origin/main','main','origin/master','master'])if(await git(['rev-parse','--verify','--quiet',r+'^{commit}'],{allowFail:true}))return r;
72
+ return '';
73
+ }
74
+ /**
75
+ * The reviewer's scope for a parsed target: {scope, base, head, title, body, label} or {empty:true, label}.
76
+ * gh (optional): (args) => stdout|null, for a pull request's base branch and title.
77
+ */
78
+ export async function resolveTarget(o,{git,gh=async()=>null}){
79
+ if(o.target==='repo')return {scope:'repo',label:'the whole repository'};
80
+ if(await git(['rev-parse','--is-inside-work-tree'],{allowFail:true})!=='true')throw new ReviewUsage('This folder is not a git repository. Use /review repo to scan every file.');
81
+ if(o.base&&(!REF.test(o.base)||o.base.includes('..')))throw new ReviewUsage('Invalid base '+o.base);
82
+ if(o.target==='pr'){
83
+ const n=o.pr;let info=null;
84
+ try{info=JSON.parse(await gh(['pr','view',String(n),'--json','baseRefName,title,body'])||'null')}catch{info=null}
85
+ const head='refs/mlai/pr/'+n;
86
+ try{await git(['fetch','-q','--no-tags','origin','+refs/pull/'+n+'/head:'+head])}
87
+ catch(e){throw new ReviewUsage('Could not fetch pull request #'+n+' from origin: '+e.message)}
88
+ let base=o.base;
89
+ if(!base&&info?.baseRefName&&REF.test(info.baseRefName)){
90
+ const ref='refs/mlai/pr/'+n+'-base';
91
+ if(await git(['fetch','-q','--no-tags','origin','+refs/heads/'+info.baseRefName+':'+ref],{allowFail:true})!==null)base=ref;
92
+ }
93
+ base=base||await defaultBase(git);
94
+ if(!base)throw new ReviewUsage('Could not tell what #'+n+' merges into. Add --base <branch>.');
95
+ return {scope:'range',base,head,title:String(info?.title||'Pull request #'+n),body:String(info?.body||''),label:'pull request #'+n};
96
+ }
97
+ const dirty=!!(await git(['status','--porcelain','--untracked-files=normal'],{allowFail:true}));
98
+ if(o.target==='changes'||(o.target==='auto'&&dirty))return dirty?{scope:'changes',label:'uncommitted changes'}:{empty:true,label:'uncommitted changes'};
99
+ // The branch against its base: from where they split, to the working tree (so uncommitted work is included).
100
+ const base=o.base||await defaultBase(git);
101
+ if(!base)throw new ReviewUsage('No base branch found. Add --base <branch>.');
102
+ if(!await git(['rev-parse','--verify','--quiet',base+'^{commit}'],{allowFail:true}))throw new ReviewUsage('Unknown base '+base+'.');
103
+ const split=await git(['merge-base',base,'HEAD'],{allowFail:true});
104
+ if(!split)throw new ReviewUsage('This branch shares no history with '+base+'.');
105
+ const ahead=Number(await git(['rev-list','--count',split+'..HEAD'],{allowFail:true})||0);
106
+ if(!ahead&&!dirty)return {empty:true,label:'changes since '+base};
107
+ return {scope:'range',base:split,head:'',label:'changes since '+base};
108
+ }
109
+
110
+ /* ---------- events ---------- */
111
+
112
+ const str=(v,n=4000)=>typeof v==='string'?v.slice(0,n):'';
113
+ function findingOf(f){
114
+ if(!f||typeof f!=='object'||!str(f.path))return null;
115
+ return {fingerprint:str(f.fingerprint,80),title:str(f.title,300),severity:SEVERITIES.includes(f.severity)?f.severity:'info',category:str(f.category,40),path:str(f.path,500),
116
+ line:Number.isInteger(f.line)&&f.line>0?f.line:null,explanation:str(f.explanation),suggestion:str(f.suggestion),confidence:typeof f.confidence==='number'?f.confidence:0,
117
+ inDiff:f.inDiff!==false,tentative:f.tentative===true};
118
+ }
119
+ const bySeverity=(a,b)=>RANK[a.severity]-RANK[b.severity]||a.path.localeCompare(b.path)||(a.line||0)-(b.line||0);
120
+ /** The event log folded into one state; the same rules as lib/review-events.ts reviewState (parity test). */
121
+ export function foldReview(input,id=''){
122
+ const events=typeof input==='string'?input.split('\n').map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(Boolean):input;
123
+ const s={id,mode:'standard',scope:'changes',state:'running',progress:'Starting the review',findings:[],resolved:[],verdict:'',title:'',summary:'',counts:{critical:0,high:0,medium:0,low:0,info:0},error:'',usage:null,limited:''};
124
+ const seen=new Map();const key=f=>f.fingerprint||f.path+':'+f.line+':'+f.title;
125
+ for(const e of events){
126
+ if(!e||typeof e!=='object')continue;
127
+ if(e.type==='started'){s.id=str(e.id,40)||s.id;if(['standard','deep','security'].includes(e.mode))s.mode=e.mode;if(['changes','range','repo'].includes(e.scope))s.scope=e.scope}
128
+ else if(e.type==='progress')s.progress=str(e.message,200)||s.progress;
129
+ else if(e.type==='finding'){const f=findingOf(e.finding);if(f)seen.set(key(f),f)}
130
+ else if(e.type==='resolved'&&e.prior)s.resolved.push({fingerprint:str(e.prior.fingerprint,80),path:str(e.prior.path,500),title:str(e.prior.title,300),message:str(e.message,300)});
131
+ else if(e.type==='done'&&e.report){const r=e.report;s.state='done';s.verdict=str(r.verdict,40);s.title=str(r.title,300);s.summary=str(r.summary,20000);
132
+ for(const f of Array.isArray(r.findings)?r.findings:[]){const x=findingOf(f);if(x&&!seen.has(x.fingerprint))seen.set(key(x),x)}
133
+ if(e.usage)s.usage=e.usage}
134
+ else if(e.type==='usage'&&e.usage)s.usage=e.usage;
135
+ else if(e.type==='limited')s.limited=str(e.message,300)||'Credits ran out before the review finished.';
136
+ else if(e.type==='error'){s.state='error';s.error=str(e.message,300)||'The review could not finish.';if(e.limited===true)s.limited=s.error;if(e.usage)s.usage=e.usage}
137
+ }
138
+ s.findings=[...seen.values()].sort(bySeverity);
139
+ for(const f of s.findings)s.counts[f.severity]++;
140
+ if(s.state==='done')s.progress=s.findings.length?s.findings.length+' finding'+(s.findings.length===1?'':'s'):'No issues found';
141
+ return s;
142
+ }
143
+ /** Findings at or above failOn ('none' never blocks); tentative ones never block. */
144
+ export function blockingFindings(s,failOn='high'){
145
+ if(failOn==='none')return [];
146
+ const limit=RANK[failOn]??RANK.high;
147
+ return s.findings.filter(f=>!f.tentative&&RANK[f.severity]<=limit);
148
+ }
149
+ export function reviewExit(s,failOn='high'){
150
+ if(s.state==='stopped')return REVIEW_EXIT.stopped;
151
+ if(blockingFindings(s,failOn).length)return REVIEW_EXIT.blocking;
152
+ if(s.state!=='done'||s.limited)return REVIEW_EXIT.unfinished;
153
+ return REVIEW_EXIT.clean;
154
+ }
155
+
156
+ /* ---------- output ---------- */
157
+
158
+ const SEV_COLOR={critical:'red',high:'red',medium:'yellow',low:'cyan',info:'gray'};
159
+ const where=f=>f.path+(f.line?':'+f.line:'');
160
+ const oneLine=t=>String(t||'').replace(/\s+/g,' ').trim();
161
+ /** One finding: " 1. high app/users.py:3 Title", then the explanation and suggested fix, indented. */
162
+ export function renderFinding(f,n,c=plain){
163
+ const sev=(c[SEV_COLOR[f.severity]]||c.dim)(f.severity.padEnd(8));
164
+ const out=[' '+String(n).padStart(2)+'. '+sev+' '+c.bold(where(f))+' '+oneLine(f.title)+(f.tentative?c.dim(' (tentative)'):'')];
165
+ if(f.explanation)out.push(' '+oneLine(f.explanation));
166
+ if(f.suggestion)out.push(' '+c.dim('Fix: ')+oneLine(f.suggestion));
167
+ return out.join('\n');
168
+ }
169
+ export function countsLine(s){
170
+ const parts=SEVERITIES.filter(k=>s.counts[k]).map(k=>s.counts[k]+' '+k);
171
+ return s.findings.length?s.findings.length+' finding'+(s.findings.length===1?'':'s')+' ('+parts.join(', ')+')':'No issues found';
172
+ }
173
+ /** The whole report for the terminal. */
174
+ export function renderReview(s,{label='',failOn='high',c=plain}={}){
175
+ const lines=[];
176
+ const kind=s.mode==='security'?'Security scan':s.mode==='deep'?'Deep review':'Review';
177
+ lines.push(c.bold(kind+(label?' of '+label:''))+': '+countsLine(s));
178
+ if(s.findings.length)lines.push('',...s.findings.map((f,i)=>renderFinding(f,i+1,c)));
179
+ if(s.resolved.length)lines.push('',c.dim(s.resolved.length+' earlier finding'+(s.resolved.length===1?' is':'s are')+' resolved.'));
180
+ if(s.summary)lines.push('',oneLine(s.summary).slice(0,1200));
181
+ if(s.limited)lines.push('',c.yellow(s.limited));
182
+ if(s.state==='error'&&s.error&&s.error!==s.limited)lines.push('',c.red(s.error));
183
+ if(s.state==='stopped')lines.push('',c.yellow('The review was stopped.'));
184
+ const block=blockingFindings(s,failOn).length;
185
+ if(block)lines.push('',c.red(block+' blocking finding'+(block===1?'':'s')+' ('+failOn+' or worse).'));
186
+ return lines.join('\n');
187
+ }
188
+ /** For --json: a stable, complete result. */
189
+ export function reviewJson(s,{target={},failOn='high'}={}){
190
+ return {id:s.id,state:s.state,mode:s.mode,scope:target.scope||s.scope,label:target.label||'',base:target.base||null,head:target.head||null,
191
+ verdict:s.verdict,title:s.title,summary:s.summary,counts:s.counts,findings:s.findings,resolved:s.resolved,
192
+ blocking:blockingFindings(s,failOn).length,failOn,usage:s.usage,error:s.error||null,limited:s.limited||null,exit:reviewExit(s,failOn)};
193
+ }
194
+ /** A task for the agent that fixes one finding (the app's Fix this button). */
195
+ export function fixPrompt(f){
196
+ return ['Fix this review finding in '+where(f)+': '+f.title,'',f.explanation,f.suggestion?'\nSuggested change: '+f.suggestion:'','\nKeep the change small and run the relevant tests.'].filter(Boolean).join('\n');
197
+ }
198
+
199
+ /* ---------- running ---------- */
200
+
201
+ const reviewId=()=>Math.random().toString(36).slice(2,14).padEnd(12,'0');
202
+ /**
203
+ * Runs one review to the end. cloud: the signed-in Cloud (run token for our model route, closed when the reviewer
204
+ * exits). onEvent sees each event as it is written. signal stops the reviewer. Returns {state, target, id}.
205
+ */
206
+ export async function runReview({root,dir,target,mode='standard',focus='',model=null,analysis='auto',cloud,project,folder,python,workerDir,
207
+ spawnImpl=spawn,onEvent=()=>{},signal,every=300,env={}}){
208
+ if(!cloud)throw Object.assign(new ReviewUsage('Sign in with mlai login to review code.'),{exit:REVIEW_EXIT.auth});
209
+ await mkdir(dir,{recursive:true});
210
+ const started=await cloud.device.request('/api/laptop',{action:'start',project,folder,title:'Code review',...(model?{model}:{})});
211
+ const id=reviewId();
212
+ const body=[focus?'Focus on: '+focus:'',target.body||''].filter(Boolean).join('\n\n');
213
+ const request=reviewRequest({mode,scope:target.scope,base:target.base,head:target.head,title:target.title||'',body,analysis},
214
+ {id,repo:root,reviews:dir,model:{endpoint:started.gateway,model:started.model?.id||'mlai-code',provider:started.model?.effort?'isoquant':'gateway'}});
215
+ const file=path.join(dir,id+'.json');await writeFile(file,JSON.stringify(request));
216
+ const py=await python(),worker=workerDir();
217
+ let closed=false;const close=st=>{if(closed)return;closed=true;Promise.resolve(cloud.finish(started.token,st)).catch(()=>{})};
218
+ const child=spawnImpl(py,['-m','mlai_review','run',file],{cwd:worker,stdio:['ignore','ignore','pipe'],windowsHide:true,
219
+ env:{...process.env,...env,PYTHONPATH:worker,PYTHONDONTWRITEBYTECODE:'1',PYTHONUTF8:'1',MODEL_API_KEY:started.token}});
220
+ let err='';child.stderr?.on?.('data',d=>{err=(err+d).slice(-2000)});
221
+ let seen=0,stopped=false;
222
+ const drain=async()=>{const text=await readFile(request.out,'utf8').catch(()=>'');const lines=text.split('\n');
223
+ for(;seen<lines.length-1;seen++){try{onEvent(JSON.parse(lines[seen]))}catch{}}return text};
224
+ const timer=setInterval(()=>{drain().catch(()=>{})},every);
225
+ const onAbort=()=>{stopped=true;try{child.kill()}catch{}};
226
+ signal?.addEventListener?.('abort',onAbort,{once:true});
227
+ const code=await new Promise(resolve=>{child.on('error',()=>resolve(-1));child.on('exit',c=>resolve(c))});
228
+ clearInterval(timer);signal?.removeEventListener?.('abort',onAbort);
229
+ const text=await drain();
230
+ const state=foldReview(text,id);
231
+ if(stopped){state.state='stopped'}
232
+ else if(code===-1){state.state='error';state.error='The review could not start on this computer. Run mlai doctor --fix.'}
233
+ else if(state.state==='running'){state.state='error';state.error='The reviewer stopped without a result.'+(err.trim()?' '+err.trim().split('\n').slice(-1)[0].slice(0,200):'')}
234
+ close(stopped?'stopped':state.state==='done'?'done':'error');
235
+ return {state,target,id};
236
+ }
237
+
238
+ /** Saves a dismissal so the next review stays quiet about that finding. */
239
+ export async function dismissFinding(dir,f,reason){
240
+ const file=path.join(dir,'dismissed.json');await mkdir(dir,{recursive:true});
241
+ const next=addDismissal(await readFile(file,'utf8').catch(()=>''),f,reason);
242
+ const tmp=file+'.'+process.pid+'.tmp';await writeFile(tmp,next);await rename(tmp,file);
243
+ }
244
+
245
+ /** Default engine pieces, loaded lazily so tests and the registry do not touch the runtime. */
246
+ export async function engineDeps(){
247
+ const [{ensureRuntime},{workerDir}]=await Promise.all([import('../runtime.mjs'),import('../home.mjs')]);
248
+ return {python:()=>ensureRuntime(),workerDir};
249
+ }
250
+ /** gh, when installed and signed in; null otherwise (a pull request then reviews against the default base). */
251
+ export function ghRunner(root,execImpl=execFile){
252
+ return args=>new Promise(resolve=>execImpl('gh',args,{cwd:root,timeout:15000,windowsHide:true},(e,stdout)=>resolve(e?null:String(stdout))));
253
+ }
254
+
255
+ /* ---------- mlai review ---------- */
256
+
257
+ export const REVIEW_HELP=`mlai review: ML AI Review on this computer.
258
+
259
+ Usage
260
+ mlai review Uncommitted changes, or the branch against its base when the tree is clean
261
+ mlai review --base main This branch against main (from where they split, uncommitted work included)
262
+ mlai review --pr 123 A pull request, fetched from origin (base from gh when it is installed)
263
+ mlai review --uncommitted Only uncommitted changes
264
+ mlai review --repo Every source file
265
+ mlai review [words] Anything else is the focus, for example: mlai review the auth flow
266
+
267
+ Options
268
+ --deep More readings and a challenge pass
269
+ --security A security scan
270
+ --fail-on <severity|none> Exit 1 when a finding is this severe or worse (default high)
271
+ --json Print one JSON result instead of the report (same as --format json)
272
+ --format text|json|github github prints a pull request review: inline comments at file:line
273
+ --post With --format github, post it to this job's pull request (GITHUB_TOKEN)
274
+ --model <id> The model to review with (default: the reviewModel setting, then model)
275
+ --no-lint Skip the linters
276
+ --server URL ML AI Code server
277
+
278
+ Exit codes: 0 no blocking findings, 1 blocking findings, 2 usage, 3 the review did not finish, 4 sign-in needed, 130 stopped.`;
279
+
280
+ /**
281
+ * `mlai review ...`. deps: {cloud(o) => Cloud (throws when signed out), stdout, stderr, cwd, engine?, git?, gh?, spawnImpl?, color?}.
282
+ * Returns the exit code.
283
+ */
284
+ /** --format github: prints the review body; with --post sends it to the pull request. Returns an exit code only on failure. */
285
+ async function githubOut(s,target,o,deps,stdout,stderr){
286
+ const {githubReview,postReview}=await import('./review-github.mjs');
287
+ const review=githubReview(s,{target,failOn:o.failOn});
288
+ stdout(JSON.stringify(review)+'\n');
289
+ if(!o.post)return 0;
290
+ try{const p=await postReview(review,{env:deps.env||process.env,fetchImpl:deps.fetch||fetch});stderr('Posted the review'+(p.url?' '+p.url:'')+' ('+p.inline+' inline comment'+(p.inline===1?'':'s')+(p.fallback?'; GitHub refused inline comments, so they are in the body':'')+').\n');return 0}
291
+ catch(e){stderr((e?.message||String(e))+'\n');return REVIEW_EXIT.unfinished}
292
+ }
293
+ export async function reviewMain(argv,deps){
294
+ const stdout=deps.stdout||(t=>process.stdout.write(t)),stderr=deps.stderr||(t=>process.stderr.write(t));
295
+ let o;
296
+ try{o=parseReviewArgs(argv)}catch(e){stderr(e.message+'\n');return REVIEW_EXIT.usage}
297
+ if(o.help){stdout(REVIEW_HELP+'\n');return 0}
298
+ const c=deps.color||plain;
299
+ try{
300
+ const {projectRoot,projectId}=await import('../project.mjs');
301
+ const {root}=await projectRoot(deps.cwd||process.cwd());
302
+ const git=deps.git||gitRunner(root),gh=deps.gh||ghRunner(root);
303
+ const target=await resolveTarget(o,{git,gh});
304
+ if(target.empty){
305
+ const s=foldReview([{type:'done',report:{verdict:'approve',findings:[]}}]);
306
+ if(o.format==='github')return await githubOut(s,target,o,deps,stdout,stderr);
307
+ if(o.json)stdout(JSON.stringify({...reviewJson(s,{target,failOn:o.failOn}),empty:true})+'\n');else stdout('Nothing to review: no '+target.label+'.\n');
308
+ return REVIEW_EXIT.clean;
309
+ }
310
+ let cloud;
311
+ try{cloud=await deps.cloud(o)}catch(e){stderr((e?.message||'Not signed in. Run `mlai login`.')+'\n');return REVIEW_EXIT.auth}
312
+ const {sub}=await import('../home.mjs');
313
+ const project=await projectId(root);
314
+ const dir=deps.dir||sub('reviews',String(project).replace(/[^a-z0-9-]/gi,'').slice(0,64)||'default');
315
+ const engine=deps.engine||await engineDeps();
316
+ const ac=new AbortController();const onInt=()=>ac.abort();process.once('SIGINT',onInt);
317
+ if(!o.json)stderr(c.dim('Reviewing '+target.label+'...')+'\n');
318
+ let last='';
319
+ let set={};try{set=(await import('../settings.mjs')).loadSettings({root})}catch{}
320
+ const r=await runReview({root,dir,target,mode:o.mode,focus:o.focus,model:o.model||set.reviewModel||set.model||null,analysis:o.analysis,cloud,project,folder:path.basename(root),
321
+ ...engine,spawnImpl:deps.spawnImpl,signal:ac.signal,every:deps.every,
322
+ onEvent:e=>{if(!o.json&&e?.type==='progress'&&e.message&&e.message!==last){last=e.message;stderr(c.dim(' '+oneLine(e.message).slice(0,160))+'\n')}}}).finally(()=>process.removeListener('SIGINT',onInt));
323
+ if(o.format==='github'){const code=await githubOut(r.state,target,o,deps,stdout,stderr);return code||reviewExit(r.state,o.failOn)}
324
+ if(o.json)stdout(JSON.stringify(reviewJson(r.state,{target,failOn:o.failOn}))+'\n');
325
+ else stdout(renderReview(r.state,{label:target.label,failOn:o.failOn,c})+'\n');
326
+ return reviewExit(r.state,o.failOn);
327
+ }catch(e){
328
+ if(e instanceof ReviewUsage){stderr(e.message+'\n');return e.exit||REVIEW_EXIT.usage}
329
+ const {friendly}=await import('../cloud.mjs');
330
+ stderr(friendly(e)+'\n');return e?.status===401?REVIEW_EXIT.auth:REVIEW_EXIT.unfinished;
331
+ }
332
+ }
@@ -0,0 +1,59 @@
1
+ // mlai review --format github (code_review_engineer): findings as a GitHub pull request review, inline at file:line.
2
+ // githubReview() builds the "create a review" body; postReview() sends it from a GitHub Actions job (--post).
3
+ import {readFileSync} from 'node:fs';
4
+
5
+ const SEV_LABEL={critical:'Critical',high:'High',medium:'Medium',low:'Low',info:'Info'};
6
+ const MAX_INLINE=50;
7
+ const one=s=>String(s||'').replace(/\s+/g,' ').trim();
8
+ const clean=p=>String(p||'').replace(/\\/g,'/').replace(/^\.\//,'');
9
+
10
+ export function commentBody(f){
11
+ return ['**'+(SEV_LABEL[f.severity]||'Info')+': '+one(f.title)+'**'+(f.tentative?' (tentative)':''),f.explanation?'\n'+String(f.explanation).trim():'',
12
+ f.suggestion?'\n**Suggested fix:** '+String(f.suggestion).trim():''].filter(Boolean).join('\n');
13
+ }
14
+
15
+ /**
16
+ * The review for POST /repos/{repo}/pulls/{n}/reviews: {event:'COMMENT', body, comments:[{path,line,side,body}]}.
17
+ * Findings with a line in the diff become inline comments; the rest are listed in the body. Never REQUEST_CHANGES:
18
+ * the job's exit code (--fail-on) is what blocks a merge.
19
+ */
20
+ export function githubReview(s,{target={},failOn='high',commitId=null}={}){
21
+ const inline=[],other=[];
22
+ for(const f of s.findings||[])(f.line&&f.inDiff!==false&&inline.length<MAX_INLINE?inline:other).push(f);
23
+ const parts=Object.keys(SEV_LABEL).filter(k=>s.counts?.[k]).map(k=>s.counts[k]+' '+k);
24
+ const head=(s.findings||[]).length?(s.findings.length+' finding'+(s.findings.length===1?'':'s')+' ('+parts.join(', ')+')'):'No issues found';
25
+ const body=['### ML AI Review'+(target.label?' of '+target.label:''),'',s.summary?String(s.summary).trim()+'\n':'',head+'.',
26
+ ...(other.length?['','Not on a changed line:','',...other.map(f=>'- **'+(SEV_LABEL[f.severity]||'Info')+'** `'+clean(f.path)+(f.line?':'+f.line:'')+'` '+one(f.title)+(f.explanation?': '+one(f.explanation).slice(0,400):''))]:[]),
27
+ ...(s.state&&s.state!=='done'?['','The review did not finish ('+(s.error||s.state)+').']:[]),
28
+ '','Blocking at '+failOn+' and above.'].join('\n').replace(/\n{3,}/g,'\n\n');
29
+ return {...(commitId?{commit_id:commitId}:{}),event:'COMMENT',body,comments:inline.map(f=>({path:clean(f.path),line:f.line,side:'RIGHT',body:commentBody(f)}))};
30
+ }
31
+
32
+ /** The pull request number and head commit of this Actions job, from GITHUB_EVENT_PATH or GITHUB_REF (refs/pull/N/merge). */
33
+ export function prContext(env=process.env,read=p=>readFileSync(p,'utf8')){
34
+ let ev={};try{if(env.GITHUB_EVENT_PATH)ev=JSON.parse(read(env.GITHUB_EVENT_PATH))}catch{}
35
+ const pr=ev.pull_request||ev.issue?.pull_request&&ev.issue||null;
36
+ const number=Number(pr?.number||/^refs\/pull\/(\d+)\//.exec(env.GITHUB_REF||'')?.[1])||null;
37
+ return {repo:env.GITHUB_REPOSITORY||null,number,commitId:ev.pull_request?.head?.sha||null,api:(env.GITHUB_API_URL||'https://api.github.com').replace(/\/$/,'')};
38
+ }
39
+
40
+ /**
41
+ * Posts the review. GitHub rejects the whole review (422) when one comment is not on a diff line; then the inline
42
+ * comments move into the body and it posts once more. Returns {url, inline, fallback}.
43
+ */
44
+ export async function postReview(review,{env=process.env,fetchImpl=fetch,read}={}){
45
+ const ctx=prContext(env,read);const token=env.GITHUB_TOKEN||env.GH_TOKEN;
46
+ if(!token)throw new Error('--post needs GITHUB_TOKEN (in a workflow: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}).');
47
+ if(!ctx.repo||!ctx.number)throw new Error('--post runs in a pull_request workflow (GITHUB_REPOSITORY and the pull request number were not found).');
48
+ const url=ctx.api+'/repos/'+ctx.repo+'/pulls/'+ctx.number+'/reviews';
49
+ const send=body=>fetchImpl(url,{method:'POST',headers:{authorization:'Bearer '+token,accept:'application/vnd.github+json','content-type':'application/json','x-github-api-version':'2022-11-28'},body:JSON.stringify(body)});
50
+ const withCommit={...review,...(ctx.commitId&&!review.commit_id?{commit_id:ctx.commitId}:{})};
51
+ let r=await send(withCommit),fallback=false;
52
+ if(r.status===422&&withCommit.comments?.length){
53
+ fallback=true;
54
+ r=await send({...withCommit,comments:[],body:withCommit.body+'\n\nInline comments:\n\n'+withCommit.comments.map(c=>'- `'+c.path+':'+c.line+'` '+one(c.body)).join('\n')});
55
+ }
56
+ if(!r.ok)throw new Error('GitHub did not accept the review ('+r.status+'): '+one(await r.text().catch(()=>'')).slice(0,300));
57
+ const j=await r.json().catch(()=>({}));
58
+ return {url:j.html_url||null,inline:fallback?0:(withCommit.comments||[]).length,fallback};
59
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Inline screen: the transcript goes to the terminal's normal scrollback (so it can be scrolled, searched and copied
3
+ * like any output) and a live footer (streaming preview, spinner, popups, input box, status line) is redrawn below it.
4
+ *
5
+ * print(lines) clears the footer, writes lines for good, redraws the footer
6
+ * draw(footer) footer = {lines:string[], cursor:{row,col}|null}; rows are cut to the width so nothing wraps
7
+ *
8
+ * Redraws are wrapped in synchronized-output markers (DEC 2026), which modern terminals use to avoid flicker
9
+ * and others ignore. After a resize the previous footer may have re-wrapped; its height is recomputed from the
10
+ * widths it was drawn with.
11
+ */
12
+ import {width,truncate} from './ansi.mjs';
13
+
14
+ const ESC='\x1b[';
15
+ export class Screen{
16
+ constructor(out,{sync=true}={}){
17
+ this.out=out;this.sync=sync;this.prev=[];this.prevCols=this.cols;this.cursorRow=0;this.footer={lines:[],cursor:null};this.hidden=false;
18
+ }
19
+ get cols(){return Math.max(20,this.out.columns||80)}
20
+ get rows(){return Math.max(6,this.out.rows||24)}
21
+ /** Rows the previous footer takes now, given the current width (lines wider than the screen wrapped). */
22
+ #height(widths,cols){return widths.reduce((a,w)=>a+Math.max(1,Math.ceil(w/cols)),0)}
23
+ #erase(){
24
+ if(!this.prev.length)return '';
25
+ const cols=this.cols;let up=this.cursorRow;
26
+ if(cols!==this.prevCols){
27
+ // The terminal re-wrapped what we drew; count the rows above the cursor at the new width.
28
+ up=this.#height(this.prev.slice(0,this.cursorRow).map(x=>Math.min(x,this.prevCols)),cols);
29
+ }
30
+ this.prev=[];
31
+ return (up?ESC+up+'A':'')+'\r'+ESC+'J';
32
+ }
33
+ #render(){
34
+ const cols=this.cols,max=this.rows-1;
35
+ let lines=this.footer.lines.map(l=>width(l)>cols-1?truncate(l,cols-1):l);
36
+ let cur=this.footer.cursor;
37
+ if(lines.length>max){const cut=lines.length-max;lines=lines.slice(cut);if(cur)cur={...cur,row:Math.max(0,cur.row-cut)}}
38
+ this.prev=lines.map(l=>width(l));this.prevCols=cols;
39
+ let s=lines.join('\r\n');
40
+ const last=lines.length-1;
41
+ if(cur&&!this.hidden){
42
+ const up=last-cur.row;s+=(up>0?ESC+up+'A':'')+'\r'+(cur.col>0?ESC+cur.col+'C':'')+ESC+'?25h';this.cursorRow=cur.row;
43
+ }else{this.cursorRow=Math.max(0,last);s+=ESC+'?25l'}
44
+ return s;
45
+ }
46
+ #write(s){this.out.write(this.sync?ESC+'?2026h'+s+ESC+'?2026l':s)}
47
+ /** Redraws the footer. */
48
+ draw(footer=this.footer){this.footer=footer;this.#write(this.#erase()+this.#render())}
49
+ /** Writes transcript lines above the footer. */
50
+ print(lines){
51
+ const list=Array.isArray(lines)?lines:String(lines).split('\n');
52
+ if(!list.length)return;
53
+ // A bare CR (Windows CRLF output, progress bars) would return to column 0 and the erase would wipe the row.
54
+ this.#write(this.#erase()+list.map(l=>String(l).replace(/\r/g,'')+ESC+'K').join('\r\n')+'\r\n'+this.#render());
55
+ }
56
+ /** Removes the footer (before exit or handing the terminal to a child process). */
57
+ clear(){this.#write(this.#erase()+ESC+'?25h');this.prev=[];this.cursorRow=0}
58
+ /** Clears the whole screen and scrollback view (Ctrl-L), then redraws the footer at the top. */
59
+ reset(){this.prev=[];this.cursorRow=0;this.#write(ESC+'2J'+ESC+'H'+this.#render())}
60
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Session housekeeping shared by the slash commands and `mlai unarchive` (CLI wave 2, section 3):
3
+ * archive moves ~/.mlai/sessions/<id> to ~/.mlai/sessions-archive/<id>; lists and resume skip it
4
+ * unarchive moves it back
5
+ * remove deletes a session folder (its worktree, if any, is left alone and reported)
6
+ * and worktrees from a name, a pull request number (#123) or a pull request URL.
7
+ */
8
+ import {existsSync} from 'node:fs';
9
+ import {readdir,readFile,rename,rm,mkdir,writeFile} from 'node:fs/promises';
10
+ import {execFile} from 'node:child_process';
11
+ import {promisify} from 'node:util';
12
+ import path from 'node:path';
13
+ import {sub} from '../home.mjs';
14
+ import {createWorktree} from '../worktree.mjs';
15
+
16
+ const run=promisify(execFile);
17
+ const ID=/^[0-9a-f-]{8,36}$/i;
18
+ export const archiveDir=()=>sub('sessions-archive');
19
+ const live=id=>path.join(sub('sessions'),id),stored=id=>path.join(archiveDir(),id);
20
+ const readMeta=async dir=>{try{return JSON.parse(await readFile(path.join(dir,'session.json'),'utf8'))}catch{return null}};
21
+
22
+ /** Archived sessions, newest first: [{id, title, folder, root, turns, archived}]. */
23
+ export async function listArchived(){
24
+ const out=[];
25
+ for(const id of await readdir(archiveDir()).catch(()=>[])){const m=await readMeta(stored(id));if(m)out.push(m)}
26
+ return out.sort((a,b)=>String(b.archived||b.updated||'').localeCompare(String(a.archived||a.updated||'')));
27
+ }
28
+ /** Full ids matching a prefix (or a title) in a folder of sessions. */
29
+ async function match(dir,q){
30
+ const ids=await readdir(dir).catch(()=>[]),s=String(q||'').trim().toLowerCase();
31
+ if(!s)return [];
32
+ const byId=ids.filter(id=>id.toLowerCase().startsWith(s));if(byId.length)return byId;
33
+ const out=[];for(const id of ids){const m=await readMeta(path.join(dir,id));if(m&&String(m.title||'').toLowerCase()===s)out.push(id)}
34
+ return out;
35
+ }
36
+ const one=(ids,q,where)=>{
37
+ if(!ids.length)throw new Error('No '+where+'session matches '+q+'.');
38
+ if(ids.length>1)throw new Error(q+' matches '+ids.length+' '+where+'sessions; give more of the id.');
39
+ return ids[0];
40
+ };
41
+ export async function archiveSession(id){
42
+ if(!ID.test(id)||!existsSync(live(id)))throw new Error('No session '+id+'.');
43
+ if(existsSync(path.join(live(id),'running.lock')))throw new Error('That session is running; stop it first.');
44
+ await mkdir(archiveDir(),{recursive:true,mode:0o700});
45
+ const meta=await readMeta(live(id));
46
+ await rename(live(id),stored(id));
47
+ if(meta){meta.archived=new Date().toISOString();await writeFile(path.join(stored(id),'session.json'),JSON.stringify(meta))}
48
+ return meta;
49
+ }
50
+ export async function unarchiveSession(q){
51
+ const id=one(await match(archiveDir(),q),q,'archived ');
52
+ if(existsSync(live(id)))throw new Error('A session '+id.slice(0,8)+' already exists.');
53
+ await mkdir(sub('sessions'),{recursive:true,mode:0o700});
54
+ await rename(stored(id),live(id));
55
+ const meta=await readMeta(live(id));
56
+ if(meta?.archived){delete meta.archived;await writeFile(path.join(live(id),'session.json'),JSON.stringify(meta))}
57
+ return meta;
58
+ }
59
+ /** Deletes a live or archived session. Returns its metadata. */
60
+ export async function removeSession(id,{archived=false}={}){
61
+ const dir=archived?stored(id):live(id);
62
+ if(!ID.test(id)||!existsSync(dir))throw new Error('No session '+id+'.');
63
+ if(existsSync(path.join(dir,'running.lock')))throw new Error('That session is running; stop it first.');
64
+ const meta=await readMeta(dir);await rm(dir,{recursive:true,force:true});return meta;
65
+ }
66
+ export const findArchived=async q=>one(await match(archiveDir(),q),q,'archived ');
67
+
68
+ /** '#123' | '123' | 'https://github.com/owner/repo/pull/123' -> {number, repo?, host?}; null for anything else. */
69
+ export function parsePr(v){
70
+ const s=String(v||'').trim();
71
+ let m=/^#?(\d{1,7})$/.exec(s);if(m)return {number:Number(m[1])};
72
+ m=/^https?:\/\/([\w.-]+)\/([\w.-]+\/[\w.-]+?)(?:\.git)?\/(?:pull|pulls|merge_requests|-\/merge_requests)\/(\d{1,7})(?:[/?#].*)?$/.exec(s);
73
+ if(m)return {number:Number(m[3]),host:m[1],repo:m[2]};
74
+ return null;
75
+ }
76
+ const git=async(cwd,args)=>(await run('git',args,{cwd,timeout:180000,maxBuffer:8e6,env:{...process.env,GIT_TERMINAL_PROMPT:'0'}})).stdout.trim();
77
+ /** The remote whose URL points at host/repo, else origin, else the first remote. */
78
+ async function remoteFor(root,pr){
79
+ const names=(await git(root,['remote']).catch(()=>'')).split('\n').filter(Boolean);
80
+ if(pr.repo){
81
+ for(const n of names){const u=await git(root,['remote','get-url',n]).catch(()=>'');if(u.replace(/\.git$/,'').toLowerCase().endsWith(pr.repo.toLowerCase())&&u.toLowerCase().includes(pr.host.toLowerCase()))return n}
82
+ return 'https://'+pr.host+'/'+pr.repo+'.git';
83
+ }
84
+ if(names.includes('origin'))return 'origin';
85
+ if(names[0])return names[0];
86
+ throw new Error('This repository has no remote to fetch the pull request from.');
87
+ }
88
+ /**
89
+ * A worktree from what the user typed: a pull request (#123 or its URL) is fetched (refs/pull/<n>/head, or GitLab's
90
+ * refs/merge-requests/<n>/head) and checked out on mlai/pr-<n>; anything else is a name for a new branch from HEAD.
91
+ */
92
+ export async function worktreeFromArg(root,value,{task}={}){
93
+ const pr=parsePr(value);
94
+ if(!pr)return createWorktree(root,{name:typeof value==='string'&&value.trim()?value.trim():task||undefined});
95
+ const remote=await remoteFor(root,pr);
96
+ const refs=pr.host&&/gitlab/i.test(pr.host)?['merge-requests/'+pr.number+'/head']:['pull/'+pr.number+'/head','merge-requests/'+pr.number+'/head'];
97
+ let sha=null,lastErr=null;
98
+ for(const ref of refs){
99
+ try{await git(root,['fetch','--quiet',remote,ref]);sha=await git(root,['rev-parse','FETCH_HEAD']);break}catch(e){lastErr=e}
100
+ }
101
+ if(!sha)throw new Error('Could not fetch pull request #'+pr.number+' from '+remote+': '+String(lastErr?.stderr||lastErr?.message||'').trim().split('\n').pop());
102
+ const tree=await createWorktree(root,{name:'pr-'+pr.number,from:sha});
103
+ return {...tree,named:true,pr:{number:pr.number,...(pr.repo?{repo:pr.repo}:{}),remote}};
104
+ }