mlai-code 0.3.2 → 0.3.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.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/checkpoints.mjs +217 -0
- package/src/cli.mjs +178 -31
- package/src/cloud.mjs +2 -0
- package/src/engine.mjs +1 -1
- package/src/headless.mjs +25 -9
- package/src/home.mjs +3 -2
- package/src/host.mjs +141 -13
- package/src/ide-quick.mjs +147 -0
- package/src/ide.mjs +182 -0
- package/src/netbox.mjs +1 -1
- package/src/parity.mjs +20 -1
- package/src/relay.mjs +1 -1
- package/src/render.mjs +12 -3
- package/src/runtime.mjs +23 -1
- package/src/sandbox.mjs +19 -3
- package/src/server.mjs +46 -7
- package/src/session.mjs +53 -10
- package/src/shared-data.mjs +1 -1
- package/src/tui/acp.mjs +121 -19
- package/src/tui/app.mjs +24 -5
- package/src/tui/chat.mjs +43 -16
- package/src/tui/cmd-config.mjs +3 -1
- package/src/tui/cmd-core.mjs +11 -7
- package/src/tui/cmd-extensibility.mjs +13 -2
- package/src/tui/commands.mjs +2 -1
- package/src/tui/extensions-local.mjs +2 -0
- package/src/tui/mcp-config.mjs +22 -4
- package/src/tui/review-cli.mjs +15 -4
- package/src/tui/snapshots.mjs +57 -16
- package/src/tui/statusline.mjs +2 -1
- package/src/two-words.mjs +14 -8
- package/src/view-sync.mjs +48 -0
- package/src/wakeups.mjs +2 -2
- package/src/winenv.mjs +1 -1
- package/src/workspace-api.mjs +21 -4
- package/vendor/client-sdk/index.cjs +5 -4
- package/vendor/cloud-cli/mlai.mjs +184 -28
- package/worker/architecture_worker.py +33 -4
- package/worker/browser_tool.py +19 -1
- package/worker/build_planner.py +75 -7
- package/worker/chat_fork.py +4 -1
- package/worker/checkpoints.py +71 -8
- package/worker/cloud_pty.py +91 -2
- package/worker/command_safety.py +80 -3
- package/worker/compaction_brief.py +186 -0
- package/worker/connected_turn.py +30 -0
- package/worker/context_manager.py +6 -0
- package/worker/conversation.py +139 -12
- package/worker/deck_render.js +11 -0
- package/worker/deck_tools.py +825 -0
- package/worker/git_sync.py +42 -17
- package/worker/goals.py +4 -0
- package/worker/image_generation.py +102 -23
- package/worker/kimi_bridge.py +580 -52
- package/worker/kimi_gates.py +74 -6
- package/worker/kimi_hook.py +213 -19
- package/worker/media_tools.py +182 -0
- package/worker/memory.py +2 -2
- package/worker/mlai_hooks.py +314 -5
- package/worker/mlai_mcp.py +49 -11
- package/worker/mlai_review/README.md +35 -0
- package/worker/mlai_review/__init__.py +1 -0
- package/worker/mlai_review/__main__.py +261 -0
- package/worker/mlai_review/_compat.py +29 -0
- package/worker/mlai_review/analysis/__init__.py +3 -0
- package/worker/mlai_review/analysis/detect.py +50 -0
- package/worker/mlai_review/analysis/main.py +128 -0
- package/worker/mlai_review/analysis/messages.py +8 -0
- package/worker/mlai_review/analysis/tools.py +194 -0
- package/worker/mlai_review/application/__init__.py +1 -0
- package/worker/mlai_review/application/asking.py +53 -0
- package/worker/mlai_review/application/challengers.py +142 -0
- package/worker/mlai_review/application/context_builder.py +194 -0
- package/worker/mlai_review/application/errors.py +17 -0
- package/worker/mlai_review/application/feedback.py +52 -0
- package/worker/mlai_review/application/matching.py +46 -0
- package/worker/mlai_review/application/messages.py +41 -0
- package/worker/mlai_review/application/ports.py +222 -0
- package/worker/mlai_review/application/prompts.py +342 -0
- package/worker/mlai_review/application/review_service.py +200 -0
- package/worker/mlai_review/application/reviewers.py +438 -0
- package/worker/mlai_review/application/streaming.py +91 -0
- package/worker/mlai_review/application/tools.py +138 -0
- package/worker/mlai_review/application/usage.py +145 -0
- package/worker/mlai_review/application/write_check.py +46 -0
- package/worker/mlai_review/contracts/__init__.py +5 -0
- package/worker/mlai_review/contracts/analysis.py +57 -0
- package/worker/mlai_review/contracts/review.py +42 -0
- package/worker/mlai_review/domain/__init__.py +4 -0
- package/worker/mlai_review/domain/changes.py +77 -0
- package/worker/mlai_review/domain/context.py +147 -0
- package/worker/mlai_review/domain/diagnostics.py +239 -0
- package/worker/mlai_review/domain/feedback.py +216 -0
- package/worker/mlai_review/domain/findings.py +505 -0
- package/worker/mlai_review/domain/lifecycle.py +85 -0
- package/worker/mlai_review/domain/partition.py +42 -0
- package/worker/mlai_review/domain/relations.py +166 -0
- package/worker/mlai_review/domain/relevance.py +202 -0
- package/worker/mlai_review/domain/report.py +99 -0
- package/worker/mlai_review/domain/structure.py +56 -0
- package/worker/mlai_review/domain/writes.py +86 -0
- package/worker/mlai_review/eval.py +221 -0
- package/worker/mlai_review/eval_cases/clean-rename.json +11 -0
- package/worker/mlai_review/eval_cases/missing-ownership-check.json +22 -0
- package/worker/mlai_review/eval_cases/off-by-one.json +22 -0
- package/worker/mlai_review/eval_cases/sql-injection.json +20 -0
- package/worker/mlai_review/feedback_report.py +60 -0
- package/worker/mlai_review/infrastructure/__init__.py +1 -0
- package/worker/mlai_review/infrastructure/analysis/__init__.py +1 -0
- package/worker/mlai_review/infrastructure/analysis/none.py +12 -0
- package/worker/mlai_review/infrastructure/analysis/translate.py +17 -0
- package/worker/mlai_review/infrastructure/github/__init__.py +0 -0
- package/worker/mlai_review/infrastructure/github/client.py +445 -0
- package/worker/mlai_review/infrastructure/github/feedback.py +212 -0
- package/worker/mlai_review/infrastructure/github/http.py +31 -0
- package/worker/mlai_review/infrastructure/github/rendering.py +398 -0
- package/worker/mlai_review/infrastructure/github/token.py +20 -0
- package/worker/mlai_review/infrastructure/local/__init__.py +1 -0
- package/worker/mlai_review/infrastructure/local/analyzer.py +48 -0
- package/worker/mlai_review/infrastructure/local/events.py +100 -0
- package/worker/mlai_review/infrastructure/local/git_reader.py +233 -0
- package/worker/mlai_review/infrastructure/local/publisher.py +138 -0
- package/worker/mlai_review/infrastructure/messages.py +54 -0
- package/worker/mlai_review/infrastructure/models/__init__.py +0 -0
- package/worker/mlai_review/infrastructure/models/openai_compatible.py +269 -0
- package/worker/mlai_review/infrastructure/structure/__init__.py +1 -0
- package/worker/mlai_review/infrastructure/structure/heuristic.py +186 -0
- package/worker/mlai_review/infrastructure/structure/tree_sitter.py +186 -0
- package/worker/mlai_review/infrastructure/workspace/__init__.py +1 -0
- package/worker/mlai_review/infrastructure/workspace/local.py +105 -0
- package/worker/mlai_review/infrastructure/workspace/memory.py +77 -0
- package/worker/mlai_review/infrastructure/workspace/paths.py +17 -0
- package/worker/mlai_review/pipeline.py +89 -0
- package/worker/mlai_review/runtime.py +194 -0
- package/worker/mlai_review/settings.py +139 -0
- package/worker/model_stream.py +21 -7
- package/worker/offline_guard.py +1 -1
- package/worker/preview.py +62 -4
- package/worker/product_facts.py +20 -0
- package/worker/project_context.py +33 -7
- package/worker/reply_language.py +92 -10
- package/worker/repo_policy.py +5 -0
- package/worker/roles.json +199 -37
- package/worker/roles.py +271 -9
- package/worker/runner.py +366 -53
- package/worker/runtime_control.py +64 -3
- package/worker/secret_scan.py +3 -2
- package/worker/server_memory.py +122 -0
- package/worker/site_check.py +279 -0
- package/worker/skill_library.py +15 -3
- package/worker/skill_pack.py +170 -16
- package/worker/subagents.py +6 -2
- package/worker/tool_catalog.py +4 -3
- package/worker/verification.py +156 -19
- package/worker/wakeups.py +56 -4
package/README.md
CHANGED
package/package.json
CHANGED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Step checkpoints for editor sessions (VS Code, JetBrains, ACP). The working tree is recorded in a private git store
|
|
3
|
+
* in the session folder (~/.mlai/sessions/<id>/checkpoints.git), never in the project's own repository: no commits,
|
|
4
|
+
* refs, index changes or stash entries appear there. Untracked files are included; .gitignore rules are honored.
|
|
5
|
+
*
|
|
6
|
+
* A checkpoint is taken at the start of every turn and after every agent step that changed files, so restoring one
|
|
7
|
+
* returns the folder to the moment before the next step wrote anything.
|
|
8
|
+
*/
|
|
9
|
+
import {execFile} from 'node:child_process';
|
|
10
|
+
import {existsSync} from 'node:fs';
|
|
11
|
+
import {mkdir,readFile,writeFile,rm,rename,lstat} from 'node:fs/promises';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
|
|
14
|
+
const LIMIT_MS=30000,MAX_BUFFER=64*1024*1024,KEEP=400;
|
|
15
|
+
export const TEXT_CAP=200_000;
|
|
16
|
+
const ID=/^[0-9a-f]{40}$/;
|
|
17
|
+
|
|
18
|
+
export class CheckpointError extends Error{constructor(message,status=400,code){super(message);this.status=status;this.code=code}}
|
|
19
|
+
|
|
20
|
+
export class Checkpoints{
|
|
21
|
+
/** session: a Session (meta.root is the folder, dir is the session folder). */
|
|
22
|
+
constructor(session){this.session=session;this.queue=Promise.resolve();this.cache=null}
|
|
23
|
+
get root(){return this.session.meta.root}
|
|
24
|
+
get store(){return path.join(this.session.dir,'checkpoints.git')}
|
|
25
|
+
get file(){return path.join(this.session.dir,'checkpoints.json')}
|
|
26
|
+
git(args,{input,encoding='utf8'}={}){
|
|
27
|
+
const dir=this.store;
|
|
28
|
+
const env={...process.env,GIT_DIR:dir,GIT_WORK_TREE:this.root,GIT_INDEX_FILE:path.join(dir,'mlai-index'),
|
|
29
|
+
GIT_AUTHOR_NAME:'ML AI Code',GIT_AUTHOR_EMAIL:'checkpoints@mlai.local',GIT_COMMITTER_NAME:'ML AI Code',GIT_COMMITTER_EMAIL:'checkpoints@mlai.local',GIT_TERMINAL_PROMPT:'0'};
|
|
30
|
+
for(const k of ['GIT_OBJECT_DIRECTORY','GIT_ALTERNATE_OBJECT_DIRECTORIES','GIT_CEILING_DIRECTORIES','GIT_NAMESPACE'])delete env[k];
|
|
31
|
+
return new Promise((resolve,reject)=>{
|
|
32
|
+
const p=execFile('git',['-c','core.autocrlf=false','-c','core.safecrlf=false','-c','gc.auto=0','-c','core.quotepath=false',...args],{cwd:this.root,env,timeout:LIMIT_MS,maxBuffer:MAX_BUFFER,encoding,windowsHide:true},
|
|
33
|
+
(e,stdout,stderr)=>e?reject(Object.assign(new Error(String(stderr||e.message).trim().split('\n').pop()),{code:e.code,killed:e.killed})):resolve(encoding==='utf8'?stdout.replace(/\n$/,''):stdout));
|
|
34
|
+
if(input!=null)p.stdin.end(input);
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
/** Serializes work on the store: the harness may finish steps faster than git records them. */
|
|
38
|
+
run(fn){const next=this.queue.then(fn,fn);this.queue=next.catch(()=>{});return next}
|
|
39
|
+
async ensure(){
|
|
40
|
+
if(existsSync(path.join(this.store,'HEAD')))return;
|
|
41
|
+
await mkdir(this.store,{recursive:true,mode:0o700});
|
|
42
|
+
await new Promise((res,rej)=>execFile('git',['init','-q','--bare',this.store],{timeout:LIMIT_MS,windowsHide:true},e=>e?rej(e):res()));
|
|
43
|
+
// The project's own excludes, plus the session store itself when the session lives inside the project.
|
|
44
|
+
const own=await readFile(path.join(this.root,'.git','info','exclude'),'utf8').catch(()=>'');
|
|
45
|
+
await mkdir(path.join(this.store,'info'),{recursive:true});
|
|
46
|
+
await writeFile(path.join(this.store,'info','exclude'),own+'\n.git\n.mlai/sessions/\n');
|
|
47
|
+
}
|
|
48
|
+
async list(){
|
|
49
|
+
if(this.cache)return this.cache;
|
|
50
|
+
try{const v=JSON.parse(await readFile(this.file,'utf8'));this.cache=Array.isArray(v)?v:[]}catch{this.cache=[]}
|
|
51
|
+
return this.cache;
|
|
52
|
+
}
|
|
53
|
+
async #save(list){this.cache=list;const tmp=this.file+'.tmp';await writeFile(tmp,JSON.stringify(list));await rename(tmp,this.file)}
|
|
54
|
+
/** The public shape: [{id, turn, step, at, label, files}]. */
|
|
55
|
+
async public(){return (await this.list()).filter(c=>!c.undo).map(({tree,parent,...c})=>c)}
|
|
56
|
+
async #tree(){await this.git(['add','-A','--','.']);return this.git(['write-tree'])}
|
|
57
|
+
/**
|
|
58
|
+
* Records the folder. Returns the new checkpoint, or null when nothing changed since the last one (unless `force`)
|
|
59
|
+
* or when checkpoints are off for this session (a folder too large to record in time).
|
|
60
|
+
*/
|
|
61
|
+
capture({turn,step=0,label,force=false,undo=false}={}){
|
|
62
|
+
return this.run(async()=>{
|
|
63
|
+
if(this.session.meta.checkpoints===false)return null;
|
|
64
|
+
try{
|
|
65
|
+
await this.ensure();
|
|
66
|
+
const list=await this.list(),last=[...list].reverse().find(c=>!c.undo)||null;
|
|
67
|
+
const tree=await this.#tree();
|
|
68
|
+
if(!force&&last&&last.tree===tree)return null;
|
|
69
|
+
const files=last?await this.#names(last.tree,tree):[];
|
|
70
|
+
if(!force&&last&&!files.length)return null;
|
|
71
|
+
const id=await this.git(['commit-tree',tree,...(last?['-p',last.id]:[]),'-m',String(label||'Checkpoint').slice(0,200)]);
|
|
72
|
+
await this.git(['update-ref','refs/checkpoints/'+id,id]);
|
|
73
|
+
const cp={id,turn:Number.isInteger(turn)?turn:Math.max(0,this.session.meta.turns.length-1),step,at:new Date().toISOString(),label:String(label||'Checkpoint').slice(0,200),files:files.map(f=>f.path),changes:files,tree,...(undo?{undo:true}:{})};
|
|
74
|
+
const next=[...list,cp];
|
|
75
|
+
// Old checkpoints drop off the list (and their refs), oldest first; turn starts are kept longest.
|
|
76
|
+
while(next.length>KEEP){const i=next.findIndex(c=>c.step!==0||c.undo);const [gone]=next.splice(i>=0?i:0,1);await this.git(['update-ref','-d','refs/checkpoints/'+gone.id]).catch(()=>{})}
|
|
77
|
+
await this.#save(next);
|
|
78
|
+
return cp;
|
|
79
|
+
}catch(e){
|
|
80
|
+
if(e.killed||e.code==='ETIMEDOUT'||/timed out|ENOBUFS|maxBuffer/i.test(e.message)){this.session.meta.checkpoints=false;await this.session.save().catch(()=>{})}
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
/** The checkpoint for an id, or for 'turn-start' (the start of the latest turn). */
|
|
86
|
+
async find(ref){
|
|
87
|
+
const list=(await this.list()).filter(c=>!c.undo);
|
|
88
|
+
if(ref==null||ref===''||ref==='turn-start'){const t=[...list].reverse().find(c=>c.step===0);if(!t)throw new CheckpointError('No checkpoint yet. Checkpoints start with the first task.',404,'no_checkpoint');return t}
|
|
89
|
+
if(/^turn-\d+$/.test(String(ref))){const n=Number(String(ref).slice(5));const t=list.find(c=>c.step===0&&c.turn===n);if(!t)throw new CheckpointError('No checkpoint for that turn',404,'no_checkpoint');return t}
|
|
90
|
+
const s=String(ref);if(!/^[0-9a-f]{7,40}$/.test(s))throw new CheckpointError('Unknown checkpoint',404,'no_checkpoint');
|
|
91
|
+
const hit=list.filter(c=>c.id.startsWith(s));if(hit.length!==1)throw new CheckpointError('Unknown checkpoint',404,'no_checkpoint');
|
|
92
|
+
return hit[0];
|
|
93
|
+
}
|
|
94
|
+
async #names(a,b){
|
|
95
|
+
const out=await this.git(['diff','--name-status','--no-renames','-z',a,b]);
|
|
96
|
+
const parts=out.split('\0').filter(Boolean),files=[];
|
|
97
|
+
for(let i=0;i+1<parts.length;i+=2)files.push({path:parts[i+1],status:parts[i][0]==='A'?'added':parts[i][0]==='D'?'deleted':'modified'});
|
|
98
|
+
return files;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Files that differ between a checkpoint and the folder now:
|
|
102
|
+
* [{path, status, before, after, additions, deletions, hunks}] (text up to TEXT_CAP; {binary:true} or {tooLarge:true} otherwise).
|
|
103
|
+
*/
|
|
104
|
+
changes(since){
|
|
105
|
+
return this.run(async()=>{
|
|
106
|
+
await this.ensure();
|
|
107
|
+
const cp=await this.find(since),now=await this.#tree();
|
|
108
|
+
const files=await this.#names(cp.tree,now);
|
|
109
|
+
const stat=await this.git(['diff','--numstat','--no-renames','-z',cp.tree,now]);
|
|
110
|
+
const counts=new Map();for(const rec of stat.split('\0').filter(Boolean)){const m=/^(-|\d+)\t(-|\d+)\t(.*)$/s.exec(rec);if(m)counts.set(m[3],{additions:m[1]==='-'?null:Number(m[1]),deletions:m[2]==='-'?null:Number(m[2]),binary:m[1]==='-'})}
|
|
111
|
+
const out=[];
|
|
112
|
+
for(const f of files){
|
|
113
|
+
const c=counts.get(f.path)||{additions:0,deletions:0,binary:false};
|
|
114
|
+
const item={path:f.path,status:f.status,additions:c.additions||0,deletions:c.deletions||0,checkpoint:cp.id};
|
|
115
|
+
if(c.binary){out.push({...item,binary:true});continue}
|
|
116
|
+
const before=f.status==='added'?'':await this.#blob(cp.tree,f.path);
|
|
117
|
+
const after=f.status==='deleted'?'':await this.#blob(now,f.path);
|
|
118
|
+
if(before==null||after==null||before.length>TEXT_CAP||after.length>TEXT_CAP){out.push({...item,tooLarge:true});continue}
|
|
119
|
+
out.push({...item,before,after,hunks:await this.#hunks(cp.tree,now,f.path)});
|
|
120
|
+
}
|
|
121
|
+
return {since:cp.id,files:out};
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
async #blob(tree,file){try{return (await this.git(['cat-file','blob',tree+':'+file],{encoding:'buffer'})).toString('utf8')}catch{return null}}
|
|
125
|
+
async #hunks(a,b,file){
|
|
126
|
+
const d=await this.git(['diff','-U0','--no-color','--no-ext-diff',a,b,'--',file]).catch(()=>'');
|
|
127
|
+
return parseHunks(d);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Restores the folder to a checkpoint. The current state is recorded first (an undo checkpoint), so a restore can
|
|
131
|
+
* itself be undone. Returns {restored, removed}.
|
|
132
|
+
*/
|
|
133
|
+
restoreFiles(ref){
|
|
134
|
+
return this.run(async()=>{
|
|
135
|
+
await this.ensure();
|
|
136
|
+
const cp=await this.find(ref),now=await this.#tree();
|
|
137
|
+
const undo=await this.git(['commit-tree',now,'-m','Before restore']);await this.git(['update-ref','refs/checkpoints/undo-'+Date.now(),undo]);
|
|
138
|
+
const changes=await this.#names(cp.tree,now);
|
|
139
|
+
const created=changes.filter(c=>c.status==='added').map(c=>c.path);
|
|
140
|
+
for(const f of created){const abs=path.resolve(this.root,f);if(abs.startsWith(path.resolve(this.root)+path.sep))await rm(abs,{force:true})}
|
|
141
|
+
await this.git(['read-tree',cp.tree]);
|
|
142
|
+
await this.git(['checkout-index','-a','-f']);
|
|
143
|
+
return {checkpoint:cp.id,undo,restored:changes.length-created.length,removed:created.length,files:changes.map(c=>c.path)};
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Reverts one file to a checkpoint (default: the start of the latest turn). With `hunks`, only those hunks
|
|
148
|
+
* ({oldStart, oldLines, newStart, newLines} from changes()) are reverted; the rest of the file stays as it is.
|
|
149
|
+
*/
|
|
150
|
+
revert(file,{hunks=null,since='turn-start'}={}){
|
|
151
|
+
return this.run(async()=>{
|
|
152
|
+
await this.ensure();
|
|
153
|
+
const rel=safeRel(this.root,file),abs=path.join(this.root,rel);
|
|
154
|
+
const cp=await this.find(since);
|
|
155
|
+
const before=await this.git(['cat-file','blob',cp.tree+':'+rel],{encoding:'buffer'}).catch(()=>null);
|
|
156
|
+
if(!Array.isArray(hunks)||!hunks.length){
|
|
157
|
+
if(before==null){await rm(abs,{force:true});return {path:rel,status:'removed',checkpoint:cp.id}}
|
|
158
|
+
await mkdir(path.dirname(abs),{recursive:true});await writeFile(abs,before);return {path:rel,status:'restored',checkpoint:cp.id};
|
|
159
|
+
}
|
|
160
|
+
let current;try{if((await lstat(abs)).isSymbolicLink())throw new CheckpointError('This file is a link; revert the whole file');current=await readFile(abs)}catch(e){if(e instanceof CheckpointError)throw e;throw new CheckpointError('The file no longer exists. Revert the whole file instead.',409,'file_missing')}
|
|
161
|
+
if(before==null)throw new CheckpointError('This file is new since the checkpoint. Revert the whole file instead.',409,'file_added');
|
|
162
|
+
const blob=await this.git(['hash-object','-w','--stdin'],{input:current});
|
|
163
|
+
const oldBlob=await this.git(['rev-parse',cp.tree+':'+rel]);
|
|
164
|
+
const diff=await this.git(['diff','-U0','--no-color','--no-ext-diff',oldBlob,blob]);
|
|
165
|
+
const all=parseHunks(diff,{lines:true});
|
|
166
|
+
const key=h=>[h.oldStart,h.oldLines,h.newStart,h.newLines].join(',');
|
|
167
|
+
const want=new Set(hunks.map(h=>key({oldStart:Number(h?.oldStart),oldLines:Number(h?.oldLines),newStart:Number(h?.newStart),newLines:Number(h?.newLines)})));
|
|
168
|
+
const pick=all.filter(h=>want.has(key(h)));
|
|
169
|
+
if(pick.length!==want.size)throw new CheckpointError('The file changed since these hunks were listed. Refresh the changes and try again.',409,'stale_hunks');
|
|
170
|
+
const out=applyReverse(current.toString('utf8'),pick);
|
|
171
|
+
await writeFile(abs,out);
|
|
172
|
+
// Every hunk reverted: the file is back to the checkpoint.
|
|
173
|
+
return {path:rel,status:pick.length===all.length?'restored':'partially_restored',checkpoint:cp.id,hunks:pick.length};
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
/** Drops checkpoints of turns after `turn` (they belong to turns that no longer exist after a chat restore). */
|
|
177
|
+
async forgetAfter(turn,{keep:id=null}={}){
|
|
178
|
+
return this.run(async()=>{const list=await this.list(),gone=c=>c.turn>turn&&c.id!==id;const keep=list.filter(c=>!gone(c));for(const c of list)if(gone(c))await this.git(['update-ref','-d','refs/checkpoints/'+c.id]).catch(()=>{});await this.#save(keep)});
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function safeRel(root,file){
|
|
183
|
+
if(typeof file!=='string'||!file||file.includes('\0'))throw new CheckpointError('Choose a file');
|
|
184
|
+
const abs=path.resolve(root,file),r=path.resolve(root);
|
|
185
|
+
if(!abs.startsWith(r+path.sep))throw new CheckpointError('That file is outside this folder');
|
|
186
|
+
const rel=path.relative(r,abs).split(path.sep).join('/');
|
|
187
|
+
if(rel.split('/').includes('.git'))throw new CheckpointError('That file is outside this folder');
|
|
188
|
+
return rel;
|
|
189
|
+
}
|
|
190
|
+
/** Hunks from a -U0 unified diff: [{oldStart, oldLines, newStart, newLines}] (with `lines`, also the removed lines). */
|
|
191
|
+
export function parseHunks(diff,{lines=false}={}){
|
|
192
|
+
const out=[];let cur=null;
|
|
193
|
+
for(const l of String(diff||'').split('\n')){
|
|
194
|
+
const m=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(l);
|
|
195
|
+
if(m){cur={oldStart:Number(m[1]),oldLines:m[2]==null?1:Number(m[2]),newStart:Number(m[3]),newLines:m[4]==null?1:Number(m[4])};if(lines)cur.removed=[];out.push(cur);continue}
|
|
196
|
+
if(!cur||!lines)continue;
|
|
197
|
+
if(l.startsWith('-'))cur.removed.push({text:l.slice(1),nl:true});
|
|
198
|
+
else if(l.startsWith('\\')&&cur.removed.length&&cur.lastWasRemoved)cur.removed[cur.removed.length-1].nl=false;
|
|
199
|
+
cur.lastWasRemoved=l.startsWith('-')||(l.startsWith('\\')&&cur.lastWasRemoved);
|
|
200
|
+
}
|
|
201
|
+
for(const h of out)delete h.lastWasRemoved;
|
|
202
|
+
return out;
|
|
203
|
+
}
|
|
204
|
+
/** Puts the removed lines of `hunks` back in place of their added lines. */
|
|
205
|
+
export function applyReverse(text,hunks){
|
|
206
|
+
const lines=text.match(/[^\n]*\n|[^\n]+$/g)||[];
|
|
207
|
+
for(const h of [...hunks].sort((a,b)=>b.newStart-a.newStart)){
|
|
208
|
+
const at=h.newLines===0?h.newStart:h.newStart-1;
|
|
209
|
+
const old=h.removed.map(r=>r.text+(r.nl?'\n':''));
|
|
210
|
+
// A hunk ending the file without a newline, restored in the middle: the line before it needs its newline back.
|
|
211
|
+
lines.splice(at,h.newLines,...old);
|
|
212
|
+
}
|
|
213
|
+
// Lines that now sit before restored text must end with a newline.
|
|
214
|
+
for(let i=0;i<lines.length-1;i++)if(!lines[i].endsWith('\n'))lines[i]+='\n';
|
|
215
|
+
return lines.join('');
|
|
216
|
+
}
|
|
217
|
+
export {ID as CHECKPOINT_ID};
|