diff --git a/rust/delivery.rs b/rust/delivery.rs index c6a62de..5f5dfce 100644 --- a/rust/delivery.rs +++ b/rust/delivery.rs @@ -1692,7 +1692,7 @@ impl Driver<'_, T, O> { domain::put(&mut event, "same_selected_model", Value::Boolean(true))?; format!("Fresh perspective {count}: the previous coder {reason}. This fixed-profile continuation uses the same selected model, not an invented alternate route. Use a materially different approach; do not repeat earlier failed moves") }; - let facts = orchestration.attempts.iter().filter(|attempt| attempt.seat == "coder") + let mut facts = orchestration.attempts.iter().filter(|attempt| attempt.seat == "coder") .filter_map(|attempt| attempt.failure.as_ref().map(|error| { let model = attempt.response.as_ref().map(|response| response.model.to_utf8()).transpose()?; Ok(continuation::safe_line(&Text::from(format!( @@ -1701,6 +1701,31 @@ impl Driver<'_, T, O> { attempt.handoff.map_or("failed", seats::Handoff::as_str), error.message, ).as_str()), boundary)) })).collect::, Error>>()?; + let modified = boundary.written_files(); + if !modified.is_empty() { + facts.push(continuation::safe_line(&Text::from(format!( + "Worktree edits already on disk (inspect with git_diff instead of re-reading from scratch): {}", + modified.join(", "), + ).as_str()), boundary)); + } + if let Some(last) = boundary.last_tests() { + let cmd = last.observed_commands().last().map_or("run_test", String::as_str); + if last.observed_exit() == 0 { + facts.push(continuation::safe_line(&Text::from(format!( + "Latest observed test run ({cmd}) PASSED (exit 0) on current disk edits — verify checklist and finalize without redoing passing work.", + ).as_str()), boundary)); + } else { + let stdout_s = last.result.get("stdout").and_then(Value::as_string).and_then(|t| t.to_utf8().ok()).unwrap_or_default(); + let stderr_s = last.result.get("stderr").and_then(Value::as_string).and_then(|t| t.to_utf8().ok()).unwrap_or_default(); + let excerpt = seats::coder::extract_diagnostic_excerpt(&format!("{stdout_s}\n{stderr_s}")); + let one_line = excerpt.replace(['\r', '\n'], " | "); + let truncated: String = one_line.chars().take(420).collect(); + facts.push(continuation::safe_line(&Text::from(format!( + "Latest observed test failure ({cmd}, exit {}): {truncated}", + last.observed_exit(), + ).as_str()), boundary)); + } + } guidance = Some(continuation::continuation(&heading, boundary, &facts, false)?); capsule = execution::continuity::next_context(boundary, &options.loaded.config, coder.capsule(), &[], &projection)?; orchestration.archives.push(coder.archive_continuation(boundary, None, &projection).await?); diff --git a/rust/execution/counterfactual.rs b/rust/execution/counterfactual.rs index 93e2599..49cca09 100644 --- a/rust/execution/counterfactual.rs +++ b/rust/execution/counterfactual.rs @@ -231,12 +231,19 @@ pub(crate) async fn run_one( args.push("--import".to_owned()); args.push(tools::TS_IMPORT_HOOK.to_owned()); } + let name_pattern = node_test_name_pattern(&target.names); + let is_flat_file = fs::read_to_string(directory.join(&target.file)) + .ok() + .is_some_and(|src| !src.contains("describe(")); args.extend([ "--test".to_owned(), "--test-reporter=tap".to_owned(), format!("--test-timeout={per_test_timeout}"), - target.file.clone(), ]); + if is_flat_file && let Some(ref pat) = name_pattern { + args.push(format!("--test-name-pattern={pat}")); + } + args.push(target.file.clone()); let run = owner .run( directory, @@ -267,14 +274,18 @@ pub(crate) async fn run_one( .map(|nm| nm.join("vitest").join("vitest.mjs")) .find(|p| p.is_file()) { - let vargs = vec![ + let mut vargs = vec![ vitest.display().to_string(), "run".to_owned(), "--no-file-parallelism".to_owned(), "--no-cache".to_owned(), "--reporter=tap-flat".to_owned(), - target.file.clone(), ]; + if let Some(ref pat) = name_pattern { + vargs.push("-t".to_owned()); + vargs.push(pat.clone()); + } + vargs.push(target.file.clone()); return owner .run( directory, @@ -380,6 +391,24 @@ fn observed(run: &backend::Run, name: &str, owner: backend::Owner<'_>) -> Result ])) } +pub(crate) fn node_test_name_pattern(names: &[Text]) -> Option { + let mut parts = Vec::new(); + for name in names { + let Ok(raw) = name.to_utf8() else { + return None; + }; + let trimmed = raw.trim(); + if trimmed.is_empty() || trimmed.len() > 240 { + return None; + } + parts.push(regex_lite::escape(trimmed)); + } + if parts.is_empty() { + return None; + } + Some(format!("(?:{})", parts.join("|"))) +} + pub async fn run( boundary: &tools::Boundary, approval: &backend::Approval, diff --git a/rust/execution/tools.rs b/rust/execution/tools.rs index 04e20f3..86b3bee 100644 --- a/rust/execution/tools.rs +++ b/rust/execution/tools.rs @@ -152,7 +152,7 @@ pub(crate) fn find_modern_node(fallback: &Path) -> PathBuf { fallback.to_path_buf() } -pub(crate) const TS_IMPORT_HOOK: &str = r#"data:text/javascript,import{registerHooks}from"node:module";import*as T from"node:test";import*as A from"node:assert/strict";import{inspect}from"node:util";import*as F from"node:fs";import*as P from"node:path";import{fileURLToPath,pathToFileURL}from"node:url";const S=Symbol("m");const mk=f=>({[S]:f});const eq=(a,b,st)=>{if(b&&typeof b==="object"&&typeof b[S]==="function")return b[S](a);if(Object.is(a,b))return true;if(!a||!b||typeof a!=="object"||typeof b!=="object")return false;if(a instanceof RegExp&&b instanceof RegExp)return a.source===b.source&&a.flags===b.flags;if(a instanceof Date&&b instanceof Date)return Object.is(a.getTime(),b.getTime());if(Array.isArray(a)!==Array.isArray(b))return false;if(Array.isArray(a))return a.length===b.length&&a.every((v,i)=>eq(v,b[i],st));if(st&&Object.getPrototypeOf(a)!==Object.getPrototypeOf(b))return false;const ka=Object.keys(a),kb=Object.keys(b);const ea=st?ka:ka.filter(k=>a[k]!==undefined),eb=st?kb:kb.filter(k=>b[k]!==undefined);if(ea.length!==eb.length)return false;return eb.every(k=>Object.prototype.hasOwnProperty.call(a,k)&&eq(a[k],b[k],st));};const cmp=(a,b,st,neg)=>{const ok=eq(a,b,st);if(neg?ok:!ok)A.fail(`Expected ${inspect(a,{depth:6})} ${neg?"not ":""}to equal ${inspect(b,{depth:6})}`);};const mo=(a,b)=>{if(Object.is(a,b))return true;if(!a||!b||typeof a!=="object"||typeof b!=="object")return false;if(Array.isArray(b))return Array.isArray(a)&&a.length===b.length&&b.every((v,i)=>mo(a[i],v));return Object.keys(b).every(k=>k in a&&mo(a[k],b[k]));};const m=(a,neg)=>({toBe:b=>neg?A.notStrictEqual(a,b):A.strictEqual(a,b),toEqual:b=>cmp(a,b,false,neg),toStrictEqual:b=>cmp(a,b,true,neg),toMatchObject:b=>{const ok=mo(a,b);if(neg?ok:!ok)A.fail(`Expected ${inspect(a,{depth:6})} ${neg?"not ":""}to match object ${inspect(b,{depth:6})}`);},toBeUndefined:()=>neg?A.notStrictEqual(a,undefined):A.strictEqual(a,undefined),toBeNull:()=>neg?A.notStrictEqual(a,null):A.strictEqual(a,null),toBeTruthy:()=>A.ok(neg?!a:Boolean(a)),toBeFalsy:()=>A.ok(neg?Boolean(a):!a),toBeNaN:()=>A.ok(neg?!Number.isNaN(a):Number.isNaN(a)),toBeGreaterThan:b=>A.ok(neg?!(a>b):a>b),toBeGreaterThanOrEqual:b=>A.ok(neg?!(a>=b):a>=b),toBeLessThan:b=>A.ok(neg?!(aA.ok(neg?!(a<=b):a<=b),toBeCloseTo:(b,p=2)=>{const ok=Math.abs(a-b)A.ok(neg?!(a instanceof c):a instanceof c),toContain:b=>{const ok=typeof a==="string"?a.includes(b):Array.isArray(a)&&a.includes(b);A.ok(neg?!ok:ok);},toContainEqual:b=>{const ok=Array.isArray(a)&&a.some(x=>eq(x,b,false));A.ok(neg?!ok:ok);},toHaveLength:b=>neg?A.notStrictEqual(a.length,b):A.strictEqual(a.length,b),toMatch:b=>{const ok=b instanceof RegExp?b.test(String(a)):String(a).includes(String(b));A.ok(neg?!ok:ok);},toHaveProperty:(k,v)=>{const parts=Array.isArray(k)?k:String(k).split(".");let cur=a,has=true;for(const p of parts){if(cur!=null&&Object.prototype.hasOwnProperty.call(Object(cur),p))cur=cur[p];else{has=false;break;}}const ok=arguments.length>1?has&&eq(cur,v,false):has;A.ok(neg?!ok:ok);},toThrow:b=>neg?A.doesNotThrow(a,b):A.throws(a,b)});const expect=Object.assign(a=>Object.assign(m(a,false),{not:m(a,true)}),{any:c=>mk(v=>c===String?typeof v==="string"||v instanceof String:c===Number?typeof v==="number"||v instanceof Number:c===Boolean?typeof v==="boolean"||v instanceof Boolean:c===Function?typeof v==="function":c===Object?v!==null&&typeof v==="object":c===Symbol?typeof v==="symbol":c===BigInt?typeof v==="bigint":v instanceof c),anything:()=>mk(v=>v!==null&&v!==undefined),objectContaining:o=>mk(v=>v!==null&&typeof v==="object"&&Object.keys(o).every(k=>k in v&&eq(v[k],o[k],false))),arrayContaining:arr=>mk(v=>Array.isArray(v)&&arr.every(x=>v.some(y=>eq(y,x,false)))),stringContaining:s=>mk(v=>typeof v==="string"&&v.includes(s))});const RealDate=Date;let fakeNow=null;class FakeDate extends RealDate{constructor(...xs){if(xs.length===0&&fakeNow!==null)super(fakeNow);else super(...xs);}static now(){return fakeNow!==null?fakeNow:RealDate.now();}}const vi={fn:(impl)=>{function f(...xs){f.mock.calls.push(xs);f.mock.contexts.push(this);const r=impl?impl.apply(this,xs):undefined;f.mock.results.push({type:"return",value:r});return r;}f.mock={calls:[],contexts:[],results:[]};return f;},useFakeTimers:()=>{globalThis.Date=FakeDate;return vi;},useRealTimers:()=>{fakeNow=null;globalThis.Date=RealDate;return vi;},setSystemTime:d=>{fakeNow=d instanceof RealDate?d.getTime():typeof d==="number"?d:new RealDate(d).getTime();globalThis.Date=FakeDate;return vi;},clearAllMocks:()=>vi,restoreAllMocks:()=>{fakeNow=null;globalThis.Date=RealDate;return vi;}};const mkEach=fn=>rows=>(name,cb)=>{for(let i=0;iString(args[j++]??""));fn(label,()=>cb(...args));}};const testFn=Object.assign((...xs)=>T.test(...xs),{each:mkEach(T.test),skip:T.test.skip,only:T.test.only});const itFn=Object.assign((...xs)=>T.it(...xs),{each:mkEach(T.it),skip:T.it.skip,only:T.it.only});const descFn=Object.assign((...xs)=>T.describe(...xs),{each:mkEach(T.describe),skip:T.describe.skip,only:T.describe.only});const api={describe:descFn,it:itFn,test:testFn,beforeEach:T.beforeEach,afterEach:T.afterEach,beforeAll:T.before,afterAll:T.after,expect,vi};globalThis.__rosterTestApi=api;if(!globalThis.describe)Object.assign(globalThis,api);let wsMap=null;const regPkg=(map,dir)=>{const pj=P.join(dir,"package.json");if(F.existsSync(pj)){try{const pkg=JSON.parse(F.readFileSync(pj,"utf8"));if(pkg&&typeof pkg.name==="string"&&!map.has(pkg.name))map.set(pkg.name,{dir,pkg});}catch{}}};const loadWs=start=>{if(wsMap)return wsMap;wsMap=new Map();let d=start;for(let i=0;i<10;i++){regPkg(wsMap,d);for(const sub of["pkgs","packages","libs"]){const base=P.join(d,sub);if(F.existsSync(base)&&F.statSync(base).isDirectory()){for(const ent of F.readdirSync(base))regPkg(wsMap,P.join(base,ent));}}const up=P.dirname(d);if(up===d)break;d=up;}return wsMap;};const pickExp=v=>typeof v==="string"?v:(v&&typeof v==="object"?pickExp(v.import||v.default||v.module||v.types):null);registerHooks({resolve(s,c,n){try{return n(s,c);}catch(e){if(s==="vitest"||s==="@jest/globals")return{shortCircuit:true,url:"data:text/javascript,export const{describe,it,test,beforeEach,afterEach,beforeAll,afterAll,expect,vi}=globalThis.__rosterTestApi;"};if(s==="ava")return{shortCircuit:true,url:"data:text/javascript,import*as T from'node:test';import*as A from'node:assert/strict';const mkT=()=>({is:(a,b)=>A.strictEqual(a,b),not:(a,b)=>A.notStrictEqual(a,b),deepEqual:(a,b)=>A.deepStrictEqual(a,b),notDeepEqual:(a,b)=>A.notDeepStrictEqual(a,b),true:v=>A.strictEqual(v,true),false:v=>A.strictEqual(v,false),truthy:v=>A.ok(v),falsy:v=>A.ok(!v),pass:()=>{},fail:m=>A.fail(m),regex:(s,r)=>A.match(String(s),r),notRegex:(s,r)=>A.doesNotMatch(String(s),r),throws:(fn,e)=>A.throws(fn,e),notThrows:(fn)=>A.doesNotThrow(fn),throwsAsync:async(fn,e)=>{try{await(typeof fn==='function'?fn():fn);A.fail('Expected rejection');}catch(err){if(e&&e.instanceOf&&!(err instanceof e.instanceOf))throw err;if(e&&e.message&&(e.message instanceof RegExp?!e.message.test(err.message):!String(err.message).includes(String(e.message))))throw err;return err;}},notThrowsAsync:async(fn)=>await(typeof fn==='function'?fn():fn),like:(a,b)=>{for(const k of Object.keys(b))A.deepStrictEqual(a[k],b[k]);},plan:()=>{},log:()=>{},timeout:()=>{},teardown:()=>{},context:{}});const run=(title,fn)=>T.test(title,()=>fn(mkT()));const ava=Object.assign(run,{serial:Object.assign(run,{skip:T.test.skip,only:T.test.only,before:T.before,after:T.after,beforeEach:T.beforeEach,afterEach:T.afterEach}),skip:T.test.skip,only:T.test.only,failing:T.test.skip,todo:T.test.todo,before:fn=>T.before(()=>fn(mkT())),after:fn=>T.after(()=>fn(mkT())),beforeEach:fn=>T.beforeEach(()=>fn(mkT())),afterEach:fn=>T.afterEach(()=>fn(mkT())),macro:x=>x});export default ava;export{ava as test};"};if(c.parentURL&&c.parentURL.startsWith("file:")){const xs=s.endsWith(".js")?[s.slice(0,-3)+".ts"]:(s.startsWith(".")&&!/\.[cm]?[jt]s$/.test(s)?[s+".ts",s+"/index.ts"]:[]);for(const x of xs){try{return n(x,c);}catch{}}const bm=s.match(/^(.*\/)(?:lib|dist|build)\/([^/]+?)(?:\.(?:esm|cjs|mjs|umd|min))?\.[cm]?js$/);if(bm){const bd=P.resolve(P.dirname(fileURLToPath(c.parentURL)),bm[1]);for(const f of[P.join(bd,"src",bm[2]+".ts"),P.join(bd,"src",bm[2]+".mts"),P.join(bd,"src","index.ts"),P.join(bd,"src","index.mts")]){if(F.existsSync(f))return{shortCircuit:true,url:pathToFileURL(f).href};}}if(!s.startsWith(".")&&!s.startsWith("/")&&!s.startsWith("node:")){const map=loadWs(P.dirname(fileURLToPath(c.parentURL)));for(const[name,info]of map){if(s===name||s.startsWith(name+"/")){const sub=s===name?".":"."+s.slice(name.length);let target=info.pkg.exports&&typeof info.pkg.exports==="object"?pickExp(info.pkg.exports[sub]):null;if(!target&&sub===".")target=info.pkg.module||info.pkg.main||"./src/index.ts";if(target){const full=P.resolve(info.dir,target);const rel=target.replace(/^\.\//,"");const stripped=rel.replace(/^(?:dist|lib|build)\//,"");const srcFull=P.resolve(info.dir,"src",rel);const srcStripped=P.resolve(info.dir,"src",stripped);const cands=full.endsWith(".js")?[srcStripped.slice(0,-3)+".ts",full.slice(0,-3)+".ts",srcFull.slice(0,-3)+".ts",full]:[srcStripped,srcStripped+".ts",P.join(srcStripped,"index.ts"),full,full+".ts",P.join(full,"index.ts"),srcFull,srcFull+".ts",P.join(srcFull,"index.ts")];for(const f of cands){if(F.existsSync(f))return{shortCircuit:true,url:pathToFileURL(f).href};}}}}const nm=process.env.ROSTER_NODE_MODULES;if(nm){try{return n(s,{...c,parentURL:pathToFileURL(P.join(nm,"_")).href});}catch{}}}}throw e;}}});"#; +pub(crate) const TS_IMPORT_HOOK: &str = r#"data:text/javascript,import{registerHooks}from"node:module";import*as T from"node:test";import*as A from"node:assert/strict";import{inspect}from"node:util";import*as F from"node:fs";import*as P from"node:path";import{fileURLToPath,pathToFileURL}from"node:url";const S=Symbol("m");const mk=f=>({[S]:f});const eq=(a,b,st)=>{if(b&&typeof b==="object"&&typeof b[S]==="function")return b[S](a);if(Object.is(a,b))return true;if(!a||!b||typeof a!=="object"||typeof b!=="object")return false;if(a instanceof RegExp&&b instanceof RegExp)return a.source===b.source&&a.flags===b.flags;if(a instanceof Date&&b instanceof Date)return Object.is(a.getTime(),b.getTime());if(Array.isArray(a)!==Array.isArray(b))return false;if(Array.isArray(a))return a.length===b.length&&a.every((v,i)=>eq(v,b[i],st));if(st&&Object.getPrototypeOf(a)!==Object.getPrototypeOf(b))return false;const ka=Object.keys(a),kb=Object.keys(b);const ea=st?ka:ka.filter(k=>a[k]!==undefined),eb=st?kb:kb.filter(k=>b[k]!==undefined);if(ea.length!==eb.length)return false;return eb.every(k=>Object.prototype.hasOwnProperty.call(a,k)&&eq(a[k],b[k],st));};const cmp=(a,b,st,neg)=>{const ok=eq(a,b,st);if(neg?ok:!ok)A.fail(`Expected ${inspect(a,{depth:6})} ${neg?"not ":""}to equal ${inspect(b,{depth:6})}`);};const mo=(a,b)=>{if(Object.is(a,b))return true;if(!a||!b||typeof a!=="object"||typeof b!=="object")return false;if(Array.isArray(b))return Array.isArray(a)&&a.length===b.length&&b.every((v,i)=>mo(a[i],v));return Object.keys(b).every(k=>k in a&&mo(a[k],b[k]));};const m=(a,neg)=>({toBe:b=>neg?A.notStrictEqual(a,b):A.strictEqual(a,b),toEqual:b=>cmp(a,b,false,neg),toStrictEqual:b=>cmp(a,b,true,neg),toMatchObject:b=>{const ok=mo(a,b);if(neg?ok:!ok)A.fail(`Expected ${inspect(a,{depth:6})} ${neg?"not ":""}to match object ${inspect(b,{depth:6})}`);},toBeUndefined:()=>neg?A.notStrictEqual(a,undefined):A.strictEqual(a,undefined),toBeNull:()=>neg?A.notStrictEqual(a,null):A.strictEqual(a,null),toBeTruthy:()=>A.ok(neg?!a:Boolean(a)),toBeFalsy:()=>A.ok(neg?Boolean(a):!a),toBeNaN:()=>A.ok(neg?!Number.isNaN(a):Number.isNaN(a)),toBeGreaterThan:b=>A.ok(neg?!(a>b):a>b),toBeGreaterThanOrEqual:b=>A.ok(neg?!(a>=b):a>=b),toBeLessThan:b=>A.ok(neg?!(aA.ok(neg?!(a<=b):a<=b),toBeCloseTo:(b,p=2)=>{const ok=Math.abs(a-b)A.ok(neg?!(a instanceof c):a instanceof c),toContain:b=>{const ok=typeof a==="string"?a.includes(b):Array.isArray(a)&&a.includes(b);A.ok(neg?!ok:ok);},toContainEqual:b=>{const ok=Array.isArray(a)&&a.some(x=>eq(x,b,false));A.ok(neg?!ok:ok);},toHaveLength:b=>neg?A.notStrictEqual(a.length,b):A.strictEqual(a.length,b),toMatch:b=>{const ok=b instanceof RegExp?b.test(String(a)):String(a).includes(String(b));A.ok(neg?!ok:ok);},toHaveProperty:(k,v)=>{const parts=Array.isArray(k)?k:String(k).split(".");let cur=a,has=true;for(const p of parts){if(cur!=null&&Object.prototype.hasOwnProperty.call(Object(cur),p))cur=cur[p];else{has=false;break;}}const ok=arguments.length>1?has&&eq(cur,v,false):has;A.ok(neg?!ok:ok);},toThrow:b=>neg?A.doesNotThrow(a,b):A.throws(a,b)});const expect=Object.assign(a=>Object.assign(m(a,false),{not:m(a,true)}),{any:c=>mk(v=>c===String?typeof v==="string"||v instanceof String:c===Number?typeof v==="number"||v instanceof Number:c===Boolean?typeof v==="boolean"||v instanceof Boolean:c===Function?typeof v==="function":c===Object?v!==null&&typeof v==="object":c===Symbol?typeof v==="symbol":c===BigInt?typeof v==="bigint":v instanceof c),anything:()=>mk(v=>v!==null&&v!==undefined),objectContaining:o=>mk(v=>v!==null&&typeof v==="object"&&Object.keys(o).every(k=>k in v&&eq(v[k],o[k],false))),arrayContaining:arr=>mk(v=>Array.isArray(v)&&arr.every(x=>v.some(y=>eq(y,x,false)))),stringContaining:s=>mk(v=>typeof v==="string"&&v.includes(s))});const RealDate=Date;let fakeNow=null;class FakeDate extends RealDate{constructor(...xs){if(xs.length===0&&fakeNow!==null)super(fakeNow);else super(...xs);}static now(){return fakeNow!==null?fakeNow:RealDate.now();}}const vi={fn:(impl)=>{function f(...xs){f.mock.calls.push(xs);f.mock.contexts.push(this);f.mock.instances.push(this);const r=impl?impl.apply(this,xs):undefined;f.mock.results.push({type:"return",value:r});return r;}f.mock={calls:[],contexts:[],instances:[],results:[]};return f;},useFakeTimers:()=>{globalThis.Date=FakeDate;return vi;},useRealTimers:()=>{fakeNow=null;globalThis.Date=RealDate;return vi;},setSystemTime:d=>{fakeNow=d instanceof RealDate?d.getTime():typeof d==="number"?d:new RealDate(d).getTime();globalThis.Date=FakeDate;return vi;},clearAllMocks:()=>vi,restoreAllMocks:()=>{fakeNow=null;globalThis.Date=RealDate;return vi;}};const mkEach=fn=>rows=>(name,cb)=>{for(let i=0;iString(args[j++]??""));fn(label,()=>cb(...args));}};const testFn=Object.assign((...xs)=>T.test(...xs),{each:mkEach(T.test),skip:T.test.skip,only:T.test.only});const itFn=Object.assign((...xs)=>T.it(...xs),{each:mkEach(T.it),skip:T.it.skip,only:T.it.only});const descFn=Object.assign((...xs)=>T.describe(...xs),{each:mkEach(T.describe),skip:T.describe.skip,only:T.describe.only});const api={describe:descFn,it:itFn,test:testFn,beforeEach:T.beforeEach,afterEach:T.afterEach,beforeAll:T.before,afterAll:T.after,expect,vi};globalThis.__rosterTestApi=api;if(!globalThis.describe)Object.assign(globalThis,api);let wsMap=null;const regPkg=(map,dir)=>{const pj=P.join(dir,"package.json");if(F.existsSync(pj)){try{const pkg=JSON.parse(F.readFileSync(pj,"utf8"));if(pkg&&typeof pkg.name==="string"&&!map.has(pkg.name))map.set(pkg.name,{dir,pkg});}catch{}}};const loadWs=start=>{if(wsMap)return wsMap;wsMap=new Map();let d=start;for(let i=0;i<10;i++){regPkg(wsMap,d);for(const sub of["pkgs","packages","libs"]){const base=P.join(d,sub);if(F.existsSync(base)&&F.statSync(base).isDirectory()){for(const ent of F.readdirSync(base))regPkg(wsMap,P.join(base,ent));}}const up=P.dirname(d);if(up===d)break;d=up;}return wsMap;};const pickExp=v=>typeof v==="string"?v:(v&&typeof v==="object"?pickExp(v.import||v.default||v.module||v.types):null);registerHooks({resolve(s,c,n){if(s==="vitest"||s==="@jest/globals")return{shortCircuit:true,url:"data:text/javascript,export const{describe,it,test,beforeEach,afterEach,beforeAll,afterAll,expect,vi}=globalThis.__rosterTestApi;"};if(s==="ava")return{shortCircuit:true,url:"data:text/javascript,import*as T from'node:test';import*as A from'node:assert/strict';const mkT=()=>({is:(a,b)=>A.strictEqual(a,b),not:(a,b)=>A.notStrictEqual(a,b),deepEqual:(a,b)=>A.deepStrictEqual(a,b),notDeepEqual:(a,b)=>A.notDeepStrictEqual(a,b),true:v=>A.strictEqual(v,true),false:v=>A.strictEqual(v,false),truthy:v=>A.ok(v),falsy:v=>A.ok(!v),pass:()=>{},fail:m=>A.fail(m),regex:(s,r)=>A.match(String(s),r),notRegex:(s,r)=>A.doesNotMatch(String(s),r),throws:(fn,e)=>A.throws(fn,e),notThrows:(fn)=>A.doesNotThrow(fn),throwsAsync:async(fn,e)=>{try{await(typeof fn==='function'?fn():fn);A.fail('Expected rejection');}catch(err){if(e&&e.instanceOf&&!(err instanceof e.instanceOf))throw err;if(e&&e.message&&(e.message instanceof RegExp?!e.message.test(err.message):!String(err.message).includes(String(e.message))))throw err;return err;}},notThrowsAsync:async(fn)=>await(typeof fn==='function'?fn():fn),like:(a,b)=>{for(const k of Object.keys(b))A.deepStrictEqual(a[k],b[k]);},plan:()=>{},log:()=>{},timeout:()=>{},teardown:()=>{},context:{}});const run=(title,fn)=>T.test(title,{concurrency:true},()=>fn(mkT()));const runSerial=(title,fn)=>T.test(title,()=>fn(mkT()));const ava=Object.assign(run,{serial:Object.assign(runSerial,{skip:T.test.skip,only:T.test.only,before:T.before,after:T.after,beforeEach:T.beforeEach,afterEach:T.afterEach}),skip:T.test.skip,only:T.test.only,failing:T.test.skip,todo:T.test.todo,before:fn=>T.before(()=>fn(mkT())),after:fn=>T.after(()=>fn(mkT())),beforeEach:fn=>T.beforeEach(()=>fn(mkT())),afterEach:fn=>T.afterEach(()=>fn(mkT())),macro:x=>x});export default ava;export{ava as test};"};try{return n(s,c);}catch(e){if(c.parentURL&&c.parentURL.startsWith("file:")){const xs=s.endsWith(".js")?[s.slice(0,-3)+".ts"]:(s.startsWith(".")&&!/\.[cm]?[jt]s$/.test(s)?[s+".ts",s+"/index.ts"]:[]);for(const x of xs){try{return n(x,c);}catch{}}const bm=s.match(/^(.*\/)(?:lib|dist|build)\/([^/]+?)(?:\.(?:esm|cjs|mjs|umd|min))?\.[cm]?js$/);if(bm){const bd=P.resolve(P.dirname(fileURLToPath(c.parentURL)),bm[1]);for(const f of[P.join(bd,"src",bm[2]+".ts"),P.join(bd,"src",bm[2]+".mts"),P.join(bd,"src","index.ts"),P.join(bd,"src","index.mts")]){if(F.existsSync(f))return{shortCircuit:true,url:pathToFileURL(f).href};}}if(!s.startsWith(".")&&!s.startsWith("/")&&!s.startsWith("node:")){const map=loadWs(P.dirname(fileURLToPath(c.parentURL)));for(const[name,info]of map){if(s===name||s.startsWith(name+"/")){const sub=s===name?".":"."+s.slice(name.length);let target=info.pkg.exports&&typeof info.pkg.exports==="object"?pickExp(info.pkg.exports[sub]):null;if(!target&&sub===".")target=info.pkg.module||info.pkg.main||"./src/index.ts";if(target){const full=P.resolve(info.dir,target);const rel=target.replace(/^\.\//,"");const stripped=rel.replace(/^(?:dist|lib|build)\//,"");const srcFull=P.resolve(info.dir,"src",rel);const srcStripped=P.resolve(info.dir,"src",stripped);const cands=full.endsWith(".js")?[srcStripped.slice(0,-3)+".ts",full.slice(0,-3)+".ts",srcFull.slice(0,-3)+".ts",full]:[srcStripped,srcStripped+".ts",P.join(srcStripped,"index.ts"),full,full+".ts",P.join(full,"index.ts"),srcFull,srcFull+".ts",P.join(srcFull,"index.ts")];for(const f of cands){if(F.existsSync(f))return{shortCircuit:true,url:pathToFileURL(f).href};}}}}const nm=process.env.ROSTER_NODE_MODULES;if(nm){try{return n(s,{...c,parentURL:pathToFileURL(P.join(nm,"_")).href});}catch{}}}}throw e;}}});"#; pub(crate) fn unverified_cleanup(failure: &process::Failure, descendants_possible: bool) -> bool { !failure.cleanup_complete @@ -1853,19 +1853,33 @@ impl Boundary { } } } - let mut excerpt = Vec::new(); - let mut in_gap = false; + let mut excerpt: Vec = Vec::new(); + let mut gap_start: Option = None; for (idx, &keep) in include.iter().enumerate() { if keep { - in_gap = false; - excerpt.push(all_lines[idx]); - } else if !in_gap { - in_gap = true; - excerpt.push( - "// ... [unrelated lines omitted; use offset/max_lines if needed] ...", - ); + if let Some(start) = gap_start.take() { + excerpt.push(format!( + "// ... [lines {}..={} omitted of {}; call read_file with offset={} and max_lines=200] ...", + start + 1, + idx, + total, + start + 1 + )); + } + excerpt.push(all_lines[idx].to_owned()); + } else if gap_start.is_none() { + gap_start = Some(idx); } } + if let Some(start) = gap_start { + excerpt.push(format!( + "// ... [lines {}..={} omitted of {}; call read_file with offset={} and max_lines=200] ...", + start + 1, + total, + total, + start + 1 + )); + } let joined = excerpt.join("\n"); if joined.len() < source.len() { return Ok((file, snapshot, Value::string(&joined))); @@ -3183,7 +3197,11 @@ impl Boundary { } } - async fn python_checks(&self, scope: &[String]) -> Result { + async fn python_checks( + &self, + scope: &[String], + filter: Option<&str>, + ) -> Result { let python = self.find_python(); let pycache_prefix = std::env::temp_dir() .join("roster-pycache") @@ -3356,13 +3374,18 @@ impl Boundary { "no:cacheprovider".to_owned(), ]; args.extend(test_files.clone()); - let has_internal_device_tests = test_files.iter().any(|f| { - f.contains("calibration") || f.contains("execution") || f.contains("contract") - }); - if has_internal_device_tests { - let filter = "not calibration and not parallel and not remote and not adapter and not wide_rows and not strided_destination and not shared_scalar and not device_budget and not discrete and not tuning_races and not integrated_device and not windows_device and not source_mutation and not history_plane and not dense_qwen and not prompt_scoring and not manifest and not verification_keeps and not rectangular_round and not resident and not durations and not protobuf and not vector and not signature_references and not invalid_execution_signature and not export_includes"; + if let Some(f) = filter { args.push("-k".to_owned()); - args.push(filter.to_owned()); + args.push(f.to_owned()); + } else { + let has_internal_device_tests = test_files.iter().any(|f| { + f.contains("calibration") || f.contains("execution") || f.contains("contract") + }); + if has_internal_device_tests { + let filter = "not calibration and not parallel and not remote and not adapter and not wide_rows and not strided_destination and not shared_scalar and not device_budget and not discrete and not tuning_races and not integrated_device and not windows_device and not source_mutation and not history_plane and not dense_qwen and not prompt_scoring and not manifest and not verification_keeps and not rectangular_round and not resident and not durations and not protobuf and not vector and not signature_references and not invalid_execution_signature and not export_includes"; + args.push("-k".to_owned()); + args.push(filter.to_owned()); + } } result .commands @@ -3570,7 +3593,11 @@ impl Boundary { names } - async fn dotnet_checks(&self, scope: &[String]) -> Result { + async fn dotnet_checks( + &self, + scope: &[String], + filter: Option<&str>, + ) -> Result { let bin_name = if cfg!(windows) { "dotnet.exe" } else { @@ -3834,7 +3861,10 @@ impl Boundary { args.push(format!("-p:TargetFrameworks={framework}")); } } - if !filters.is_empty() { + if let Some(f) = filter { + args.push("--filter".to_owned()); + args.push(format!("FullyQualifiedName~{f}")); + } else if !filters.is_empty() { let filter_expr = filters .iter() .map(|stem| format!("FullyQualifiedName~{stem}")) @@ -3950,7 +3980,11 @@ impl Boundary { }) } - async fn java_checks(&self, scope: &[String]) -> Result { + async fn java_checks( + &self, + scope: &[String], + filter: Option<&str>, + ) -> Result { let _javac = Self::find_javac().ok_or_else(|| { unsupported( "Java verification requires an installed JDK (javac); only a JRE or no JDK was found on this host", @@ -4001,7 +4035,9 @@ impl Boundary { "-DfailIfNoTests=false".to_owned(), "-Drat.skip=true".to_owned(), ]); - if !filters.is_empty() { + if let Some(f) = filter { + online_args.push(format!("-Dtest={f}")); + } else if !filters.is_empty() { online_args.push(format!("-Dtest={}", filters.join(","))); } let mut offline_args = vec!["-B".to_owned(), "-o".to_owned()]; @@ -4125,14 +4161,19 @@ impl Boundary { false } - async fn node_checks(&self, scope: &[String], full: bool) -> Result { + async fn node_checks( + &self, + scope: &[String], + full: bool, + filter: Option<&str>, + ) -> Result { if !self.root.join("package.json").is_file() && scope .iter() .chain(self.written.iter()) .any(|file| file.ends_with(".py")) { - return self.python_checks(scope).await; + return self.python_checks(scope, filter).await; } if !self.root.join("package.json").is_file() && scope @@ -4140,7 +4181,7 @@ impl Boundary { .chain(self.written.iter()) .any(|file| file.ends_with(".cs")) { - return self.dotnet_checks(scope).await; + return self.dotnet_checks(scope, filter).await; } if !self.root.join("package.json").is_file() && scope @@ -4148,7 +4189,7 @@ impl Boundary { .chain(self.written.iter()) .any(|file| file.ends_with(".java")) { - return self.java_checks(scope).await; + return self.java_checks(scope, filter).await; } let mut effective_scope = scope.to_vec(); for w in &self.written { @@ -4372,6 +4413,9 @@ impl Boundary { jobs.to_string(), format!("--test-timeout={per_test_timeout}"), ]); + if let Some(f) = filter { + args.push(format!("--test-name-pattern={}", regex_lite::escape(f))); + } let scoped_tests = !full || (!tests.is_empty() && (has_ts_tests @@ -4424,6 +4468,10 @@ impl Boundary { "--no-cache".to_owned(), "--reporter=tap-flat".to_owned(), ]; + if let Some(f) = filter { + vargs.push("-t".to_owned()); + vargs.push(f.to_owned()); + } if !tests.is_empty() { vargs.extend(tests.iter().cloned()); } @@ -4568,9 +4616,34 @@ impl Boundary { Ok(required.native || required.node && policy::tests_mode(&self.task)? != "none") } + pub(crate) fn validate_test_filter(raw: &str) -> Result { + let trimmed = raw.trim(); + if trimmed.is_empty() || trimmed.len() > 120 { + return Err(usage("run_test filter must be 1..=120 safe characters")); + } + if !trimmed.chars().all(|ch| { + ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | '.' | ':' | '/' | '#' | ' ') + }) { + return Err(usage( + "run_test filter may contain only letters, digits, spaces, and _-.:/#", + )); + } + Ok(trimmed.to_owned()) + } + pub async fn verify(&mut self, full: bool) -> Result { + self.verify_filtered(full, None).await + } + + pub async fn verify_filtered( + &mut self, + full: bool, + filter: Option<&str>, + ) -> Result { self.check()?; - self.last_tests = None; + if filter.is_none() { + self.last_tests = None; + } if self.options.role != Role::Coder || !self.options.allow_run_test || !self.recipe_allows("run_test") @@ -5063,8 +5136,15 @@ impl Boundary { .iter() .any(|file| file.starts_with("benches/") || file.contains("/benches/")); let mut fetched_online = false; - for args in cargo_steps { + for mut args in cargo_steps { let is_metadata = args.first().map(String::as_str) == Some("metadata"); + let is_test = args.first().map(String::as_str) == Some("test"); + if is_test && let Some(f) = filter { + if !args.iter().any(|arg| arg == "--") { + args.push("--".to_owned()); + } + args.push(f.to_owned()); + } let is_all_targets_check = args.first().map(String::as_str) == Some("check") && args.iter().any(|arg| arg == "--all-targets"); commands.push(format!("cargo {}", args.join(" "))); @@ -5184,7 +5264,7 @@ impl Boundary { stdout = "docs-only: tests skipped".to_owned(); } if requirements.node && exit == 0 { - let checks = self.node_checks(&requirements.files, full).await?; + let checks = self.node_checks(&requirements.files, full, filter).await?; if native && checks.skipped { return Err(unsupported( "Mixed Rust/JavaScript scope needs actual matching Node checks as well as Cargo evidence", @@ -5284,6 +5364,11 @@ impl Boundary { pending: false, }); } + if filter.is_some() { + domain::put(&mut result, "filtered", Value::Boolean(true))?; + self.check()?; + return Ok(result); + } self.last_tests = Some(observed); if fresh_pass { self.fresh_after_restore = false; @@ -5518,7 +5603,7 @@ impl Boundary { "list_dir" => ("List readable worktree entries.", &[], &["path"]), "search_text" => ("Search readable regular files for literal text; returns at most 50 lines.", &["query"], &["path"]), "glob_files" => ("Find at most 100 readable worktree paths with a simple wildcard pattern.", &["pattern"], &[]), - "run_test" => ("Run scoped Node 20 tests, or explicitly host-approved locked offline Cargo checks for Rust; no shell grant.", &[], &[]), + "run_test" => ("Run scoped native tests for the repository language (Rust/Cargo, Node/TS, Python/pytest, Java/Maven, or C#/.NET). Pass optional filter to run a single test during inner TDD loops; run without filter before finalizing.", &[], &["filter"]), "run_command" => ("Only git status, scoped git diff, or scoped node --test; no arbitrary flags, shell or network grant.", &["argv"], &[]), _ => ("Read a scoped Git diff without external diff or text conversion.", &[], &["path"]), }; @@ -5595,8 +5680,20 @@ impl Boundary { "glob_files" => self.glob_files(args)?, "write_file" | "edit_file" | "delete_file" => self.mutate(name, args, observer).await?, "run_test" => { - fields(args, &[], &[], "Tool arguments must contain no fields")?; - self.verify(false).await? + fields( + args, + &[], + &["filter"], + "run_test accepts only an optional filter string", + )?; + let filter = args + .get("filter") + .map(|value| { + let raw = text(value, "run_test filter must be text")?; + Self::validate_test_filter(&raw) + }) + .transpose()?; + self.verify_filtered(false, filter.as_deref()).await? } "git_diff" => self.git_read(name, args).await?, "run_command" => { diff --git a/rust/seats/coder.rs b/rust/seats/coder.rs index e41f74f..21c3223 100644 --- a/rust/seats/coder.rs +++ b/rust/seats/coder.rs @@ -603,6 +603,25 @@ pub(crate) fn extract_diagnostic_excerpt(output: &str) -> String { ) } +pub(crate) fn failure_signature(exit_code: i32, output: &str) -> (i32, String) { + let excerpt = extract_diagnostic_excerpt(output); + let key_line = excerpt + .lines() + .map(str::trim) + .find(|line| { + !line.is_empty() + && *line != "Key diagnostics:" + && *line != "Tail:" + && !line.starts_with("---") + && !line.starts_with("===") + }) + .unwrap_or("unknown") + .chars() + .take(140) + .collect::(); + (exit_code, key_line) +} + fn message_chars(msg: &Value) -> usize { let content_len = msg .get("content") @@ -1292,6 +1311,8 @@ impl Driver<'_, T, O> { let mut hard_wrap_up_sent = false; let mut edit_epoch: u64 = 0; let mut recent_reads: BTreeMap = BTreeMap::new(); + let mut last_failure_sig: Option<(i32, String)> = None; + let mut repeat_failure_streak: usize = 0; boundary.require_git().await?; let validation = boundary.git_validation()?.clone(); progress.validation = Some(validation.clone()); @@ -1884,7 +1905,38 @@ impl Driver<'_, T, O> { }) }) }); - let executed = if force_write + let budget_gate_passed = task_timeout_ms.is_some_and(|limit_ms| { + let elapsed_now = u128::from(options.elapsed_ms) + .saturating_add(coder_started.elapsed().as_millis()); + elapsed_now >= u128::from((limit_ms * 82) / 100) + }) && !boundary.written_files().is_empty() + && boundary + .last_tests() + .is_some_and(|proof| proof.observed_exit() == 0) + && matches!( + call.name.as_str(), + "read_file" + | "list_dir" + | "glob_files" + | "search_text" + | "write_file" + | "edit_file" + | "delete_file" + | "run_test" + ); + let executed = if budget_gate_passed { + attempt.reject_pending(call); + Ok(Value::object(vec![ + ("executed", Value::Boolean(false)), + ("budget_gate", Value::Boolean(true)), + ( + "note", + Value::string( + "Wall-clock reserve (82%) reached and unfiltered tests already pass (exit 0) on current disk edits. Stop reading/editing/re-testing; update any remaining checklist items via update_checklist if needed, then emit your concise final summary immediately so independent Reviewer can verify within budget.", + ), + ), + ])) + } else if force_write && [ "read_file", "list_dir", @@ -2055,10 +2107,46 @@ impl Driver<'_, T, O> { .get("exit_code") .is_some_and(|exit| *exit != Value::Number(0.0)) { + let code = response + .get("exit_code") + .and_then(|v| match v { + Value::Number(n) => Some(*n as i32), + _ => None, + }) + .unwrap_or(1); + let out_s = response + .get("stdout") + .and_then(Value::as_string) + .and_then(|t| t.to_utf8().ok()) + .unwrap_or_default(); + let err_s = response + .get("stderr") + .and_then(Value::as_string) + .and_then(|t| t.to_utf8().ok()) + .unwrap_or_default(); + let sig = failure_signature(code, &format!("{out_s}\n{err_s}")); + if last_failure_sig.as_ref() == Some(&sig) { + repeat_failure_streak += 1; + } else { + last_failure_sig = Some(sig.clone()); + repeat_failure_streak = 1; + } messages.push(message( "user", progress.repair(&response, chat.last_response(), config)?, )); + if repeat_failure_streak >= 2 { + messages.push(message( + "user", + Text::from(format!( + "Stuck detector: the same failure signature repeated ({}x: {}). Stop tweaking symptoms; call git_diff to inspect your exact edits against base code, question your core assumption, and switch to a structurally different approach.", + repeat_failure_streak, sig.1 + ).as_str()), + )); + } + } else if test_call(call) { + last_failure_sig = None; + repeat_failure_streak = 0; } if refresh { for revoked in decoded.calls.iter().skip(index + 1) { diff --git a/rust/seats/tests.rs b/rust/seats/tests.rs index 1e8679d..2515c00 100644 --- a/rust/seats/tests.rs +++ b/rust/seats/tests.rs @@ -2397,4 +2397,21 @@ fn pytest_missing_fixture_detector_distinguishes_plugin_errors_from_real_failure "Diff in /repo/src/lib.rs:1:\n", &["src/lib.rs".to_owned()], )); + assert_eq!( + tools::Boundary::validate_test_filter(" test_retry_extend ").ok(), + Some("test_retry_extend".to_owned()) + ); + assert!(tools::Boundary::validate_test_filter("foo; rm -rf /").is_err()); + assert!(tools::Boundary::validate_test_filter("").is_err()); + let pat = crate::execution::counterfactual::node_test_name_pattern(&[ + Text::from("extend() keeps retry.limit"), + Text::from("other [case]"), + ]); + assert_eq!( + pat, + Some("(?:extend\\(\\) keeps retry\\.limit|other \\[case\\])".to_owned()) + ); + let sig = coder::failure_signature(1, "noise\nerror[E0308]: mismatched types\nmore"); + assert_eq!(sig.0, 1); + assert!(sig.1.contains("error[E0308]: mismatched types")); }