Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Time-skip v2: plan, lever, agent A to the end, agent B forked at the lever with an improvement plan, A vs B, keep one
Niko1221d615708a7b70
diff --git a/apps/host/scripts/agent-http.mjs b/apps/host/scripts/agent-http.mjsindex cdafa03e8..956f8ac49 100644--- a/apps/host/scripts/agent-http.mjs+++ b/apps/host/scripts/agent-http.mjs@@ -127,7 +127,7 @@ if (command === 'connect') {let last = '', stopped = false;for (;;) {const { run } = await j(`/api/timeskip/status?id=${id}`);- const line = `${run.phase}${run.activity ? ` | ${run.activity.text}${run.activity.args?.step ? ` | assistant: ${run.activity.args.step}` : ''}` : ''}`;+ const line = `${run.phase}${run.activity ? ` | ${run.activity.text}${run.activity.args?.step && typeof run.activity.args.step === 'string' ? ` | assistant: ${run.activity.args.step}` : ''}` : ''}${run.lever ? ` | lever: step ${run.lever.step}/${run.lever.total} ${run.lever.defaulted ? '(default) ' : ''}- ${run.lever.why}` : ''}${run.a?.line ? ` | A: ${run.a.state} ${run.a.line.slice(0, 50)}` : ''}${run.b?.state ? ` | B: ${run.b.state} ${(run.b.line ?? '').slice(0, 50)}` : ''}`;if (line !== last) { console.log(`${stamp()} ${line}`); last = line; }if (stopAfter && !stopped && (Date.now() - t0) / 1000 >= Number(stopAfter)) {console.log(`${stamp()} -- pressing Stop (the chat Stop route)`);diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjsindex 849f789cd..36ea31a66 100644--- a/apps/host/server/agent/agent-bridge.mjs+++ b/apps/host/server/agent/agent-bridge.mjs@@ -892,6 +892,9 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =}const mustBeOpen = plan => { if (plan.state !== 'proposed' && plan.state !== 'approved') throw new AgentUnavailable('This plan has already been used. Ask for a new one with /plan.', 'plan-used'); };+ /** A short note added to every step of the chat's plan (the Time-skip B path: where its work comes from). */+ function setPlanBriefing(chatId, text) { plans.update(chatId, p => { p.briefing = String(text ?? '').slice(0, 600); }); }+/** The plan of a chat, or null. */const planState = chatId => planView(plans.get(chatId));@@ -1072,7 +1075,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =/** Let go of a chat's Harness session mapping (a task starts every run in a session of its own). */function forget(chatId) { if (chats.get(chatId)?.turn) return; delete sessionMap[chatId]; chats.delete(chatId); persist(); }- return { goalState, goalControl, harnessDir, status, runTurn, goalCommand, planCommand, researchCommand, llmTarget, planGoal, planControl, planState, queueMessage, cancelQueued, takeQueue, forget, approve, setMode, stop, pendingFor, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) };+ return { goalState, goalControl, harnessDir, status, runTurn, goalCommand, planCommand, researchCommand, llmTarget, setPlanBriefing, planGoal, planControl, planState, queueMessage, cancelQueued, takeQueue, forget, approve, setMode, stop, pendingFor, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) };}/** A goal that stopped by itself, in words. */diff --git a/apps/host/server/agent/plan.mjs b/apps/host/server/agent/plan.mjsindex 7e4ee35d1..c544a1e4a 100644--- a/apps/host/server/agent/plan.mjs+++ b/apps/host/server/agent/plan.mjs@@ -113,6 +113,7 @@ export function stepObjective(plan, index) {`Overall aim: ${plan.title}.`,`You are on step ${index + 1} of ${n}: ${s.text}${s.detail ? ` (${s.detail})` : ''}.`,done ? `Already done: ${done}.` : '',+ plan.briefing ? String(plan.briefing) : '','Do only this step, check that it worked, and then finish the goal.',index + 1 < n ? 'The next steps are handled separately: do not start them.' : '',].filter(Boolean).join(' ');diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjsindex 3645dcf61..e9377f29b 100644--- a/apps/host/server/index.mjs+++ b/apps/host/server/index.mjs@@ -52,6 +52,7 @@ import { isPrivateHost } from './agent/llm-shape.mjs';import { RequestQueue } from './request-queue.mjs';import { selectSkills, skillInstructions } from './skill-selection.mjs';import { createModelProviders } from './model-providers.mjs';+import { createForkTimeskip } from './timeskip-fork.mjs';import { createChatFolders, openFile, resolveChatFile, previewFile, rawFile, createAttachments, withAttachments } from './chat-files.mjs';import { createLlmProxy, samplingFromExpert } from './agent/llm-shape.mjs';import { checkUpdates, checkComponentUpdates } from './updates.mjs';@@ -65,7 +66,7 @@ import { randomBytes, timingSafeEqual } from 'node:crypto';import { nativeGateway } from './native-gateway.mjs';import { proxyCompletion } from './inference.mjs';import { validateChatImages } from './chat-images.mjs';-import { createTimeSkip, measureFolder, timeskipRevisionMessage } from './timeskip.mjs';+import { createTimeSkip, measureFolder, timeskipRevisionMessage, imageTypeOf } from './timeskip.mjs';const HERE = fileURLToPath(new URL('.', import.meta.url));const ROOT = resolve(HERE, '..');@@ -808,6 +809,8 @@ function createTuning({ repoRoot, python, pythonArgs = [], env = process.env } =const tuning = createTuning({ repoRoot: REPO_ROOT, python: TS_PYTHON, pythonArgs: PYTHON.args });+/* Time-skip: plan, lever, A all the way, B forked at the lever (notes-split-agent8.md). The older revise-the-draft job above stays reachable with legacy:true. */+const forkTs = createForkTimeskip({ agent, dir: join(store.DATA_DIR, 'timeskip-fork'), notify: (type, data) => hub.send(type, data) });const timeskip = createTimeSkip({repoRoot: REPO_ROOT,python: TS_PYTHON,@@ -1007,10 +1010,11 @@ async function api(req, res, path, method, url) {// These routes only start it, follow it and apply its result; they never compute a status or a// score of their own, so the UI cannot show progress the job did not report.if (path === '/api/timeskip' && method === 'GET') {- return json(res, 200, { runs: timeskip.list(), stateDir: timeskip.stateDir() });+ return json(res, 200, { runs: [...forkTs.list(), ...timeskip.list()], stateDir: timeskip.stateDir() });}if (path === '/api/timeskip/status' && method === 'GET') {const id = url.searchParams.get('id');+ if (id && forkTs.has(id)) return json(res, 200, { run: forkTs.status(id) });const run = id ? timeskip.status(id) : null;if (!run) return error(res, 404, 'No such Time-skip run.');return json(res, 200, { run: { ...run, activity: trialActivity(run) } });@@ -1020,6 +1024,20 @@ async function api(req, res, path, method, url) {const workspaceId = typeof body.workspaceId === 'string' ? body.workspaceId : null;const workspace = String(body.workspace ?? '').trim() || ((workspaceId ? workspaces.find(w => w.id === workspaceId)?.path : null) ?? WORKSPACE);const prompt = String(body.prompt ?? '').trim().slice(0, 4000);+ if (body.legacy !== true) {+ if (!prompt) return error(res, 400, 'Say what you want made or improved after /time-skip.');+ if (!existsSync(workspace)) return error(res, 400, 'Time-skip works on a folder of your own. Choose a folder for this chat, then try again.');+ const cwd = chatFolders.get(typeof body.sessionId === 'string' ? body.sessionId : '') ?? workspace;+ if (resolve(cwd) === resolve(ROOT) || resolve(cwd).startsWith(resolve(ROOT) + sep)) return error(res, 400, 'Time-skip works on a folder of your own. Choose a workspace folder for this chat, then try again.');+ if (measureFolder(cwd).tooBig) return error(res, 400, 'This folder is too big to try a change on a copy. Open a smaller folder for this chat, then try again.');+ let choice, slots = 1;+ if (body.remoteModel?.connectionId && body.remoteModel?.modelId) { choice = { connectionId: String(body.remoteModel.connectionId), modelId: String(body.remoteModel.modelId) }; slots = Number(body.slots) >= 1 ? Math.floor(Number(body.slots)) : 1; }+ else { try { const inst = native.resolveInstance(native.state().defaultId); choice = { instanceId: inst.id }; slots = inst.metrics?.live?.slots?.length || inst.parallel || 1; } catch { return error(res, 503, 'Load a model first, then try Time-skip again.'); } }+ const chatId = typeof body.sessionId === 'string' && body.sessionId ? body.sessionId : null;+ if (chatId && forkTs.byChat(chatId)) return error(res, 409, 'A Time-skip is already running in this chat.');+ const run = forkTs.start({ prompt, workspace: cwd, chatId, choice, thinking: typeof body.thinking === 'string' ? body.thinking : 'Low', slots });+ return json(res, 200, { run, simulated: false });+ }const reviseCommand = body.useAgent === false ? null : TIMESKIP_REVISE;// The folder of the app itself is never a person's work: "Keep the update" would write into the installation.if (resolve(workspace) === resolve(ROOT) || resolve(workspace).startsWith(resolve(ROOT) + sep)) return error(res, 400, 'Time-skip works on a folder of your own. Choose a workspace folder for this chat, then try again.');@@ -1043,13 +1061,15 @@ async function api(req, res, path, method, url) {return json(res, 200, { run: { ...result.run, activity: trialActivity(result.run) }, simulated: false });}if (path === '/api/timeskip/files' && method === 'GET') {- const found = timeskip.files(url.searchParams.get('id'));+ const fid = url.searchParams.get('id');+ const found = forkTs.has(fid) ? forkTs.files(fid) : timeskip.files(fid);if (!found) return error(res, 404, 'No such Time-skip run.');return json(res, 200, found);}/* One picture of a run, original or updated, for the Compare view. Only pictures inside the run's own folders; served as an image and nothing else. */if (path === '/api/timeskip/file' && method === 'GET') {- const found = timeskip.image(url.searchParams.get('id'), url.searchParams.get('path'), url.searchParams.get('version'));+ const iid = url.searchParams.get('id');+ const found = forkTs.has(iid) ? (() => { const p = forkTs.image(iid, url.searchParams.get('path'), url.searchParams.get('version')); return p ? { path: p, type: imageTypeOf(p) } : null; })() : timeskip.image(iid, url.searchParams.get('path'), url.searchParams.get('version'));if (!found) return error(res, 404, 'No such picture in this Time-skip run.');res.writeHead(200, { 'content-type': found.type, 'cache-control': 'private, max-age=300', 'x-content-type-options': 'nosniff', 'content-security-policy': "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:" });createReadStream(found.path).pipe(res);@@ -1057,6 +1077,7 @@ async function api(req, res, path, method, url) {}if (path === '/api/timeskip/stop' && method === 'POST') {const body = await readBody(req);+ if (forkTs.has(String(body.id ?? ''))) return json(res, 200, { stopped: await forkTs.stop(String(body.id)) });return json(res, 200, { stopped: await stopTrial(String(body.id ?? '')) });}// One revision attempt for a job this host started: the app's assistant works inside the candidate folder.@@ -1101,6 +1122,10 @@ async function api(req, res, path, method, url) {}if (path === '/api/timeskip/apply' && method === 'POST') {const body = await readBody(req);+ if (forkTs.has(String(body.id ?? ''))) {+ try { return json(res, 200, { apply: forkTs.apply({ id: String(body.id), which: body.which === 'a' ? 'a' : 'b', restore: Boolean(body.restore) }) }); }+ catch (e) { return error(res, 400, e.message); }+ }const result = await timeskip.apply({id: body.id, workspace: body.workspace ?? null,dryRun: Boolean(body.dryRun), restore: Boolean(body.restore), attempt: body.attempt ?? null,diff --git a/apps/host/server/timeskip-fork.mjs b/apps/host/server/timeskip-fork.mjsnew file mode 100644index 000000000..6b17e7518--- /dev/null+++ b/apps/host/server/timeskip-fork.mjs@@ -0,0 +1,281 @@+/**+ * Time-skip = /plan + /goal + a smart subagent fork at the step that matters most (notes-split-agent8.md, item 11).+ *+ * 1. The request is dissected into a plan with steps (the same read-only plan turn as /plan), in a COPY of the project folder (A).+ * 2. One short question picks the lever: the single step where stopping, checking the results so far and improving or diverting+ * matters most for the final result (with its reason; a fixed rule when the answer is unusable).+ * 3. Agent A runs the plan as a goal, step by step, all the way: RESULT A.+ * 4. When A has finished the step before the lever, the host copies A to B and a read-only helper writes an improvement plan from the+ * plan, A's results so far and the lever's reason. Agent B gets that plan (and .timeskip/context.md as its attachment) and finishes+ * its own improved path in B: RESULT B. With one model slot B starts when A is done and the person is told so.+ * 5. A and B are compared side by side; the person keeps one (Keep A / Keep B), with a rollback copy.+ * The person's own folder is never touched until Keep.+ */++import { randomUUID } from 'node:crypto';+import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { dirname, join, relative, resolve, sep } from 'node:path';+import { diffRun, runImagePath, isNoisePath } from './timeskip.mjs';++const SKIP = new Set(['.git', '.strata', '.timeskip', 'node_modules', '__pycache__']);+const TERMINAL = new Set(['completed', 'failed', 'cancelled', 'interrupted']);++/** Copy a project folder for a trial, without dependency/VCS folders. */+export function copyProject(from, to) {+ mkdirSync(to, { recursive: true });+ cpSync(from, to, { recursive: true, force: true, filter: src => !SKIP.has(src.split(sep).pop()) || resolve(src) === resolve(from) });+}++/** The question that picks the lever. */+export function leverPrompt(request, steps) {+ return [+ 'Below is a plan for a request. Find the ONE biggest lever in it: the single step where stopping, checking the results so far and improving or changing direction would matter most for the quality of the final result.',+ 'Rules: never step 1 (nothing exists yet to check); prefer the step right after the first real result exists and before the expensive or hard-to-undo part; choose exactly one step.',+ '',+ `Request: ${request}`,+ 'Plan:',+ ...steps.map((s, i) => `${i + 1}. ${s.text}${s.detail ? ` (${s.detail})` : ''}`),+ '',+ 'Answer with only this JSON on one line, no other words: {"step": <number>, "why": "<one short plain sentence: why checking here matters most>"}',+ ].join('\n');+}++/** The model's answer as { step, why }, or null. The step is 1-based and must be inside the plan and not the first. */+export function parseLever(text, total) {+ const m = /\{[^{}]*"step"[^{}]*\}/s.exec(String(text ?? ''));+ if (!m) return null;+ try {+ const j = JSON.parse(m[0]);+ const step = Number(j.step);+ if (!Number.isInteger(step) || step < 2 || step > total) return null;+ const why = String(j.why ?? '').replace(/\s+/g, ' ').trim().slice(0, 220);+ return { step, why: why || 'This is where the results so far are worth checking.' };+ } catch { return null; }+}++/** A fixed rule for the lever when the model's answer cannot be used: the step after the first step that makes something. */+export function defaultLever(steps) {+ const n = steps.length;+ const making = steps.findIndex((s, i) => i >= 1 && /\b(write|create|build|draw|implement|generate|make|design|code|add)\b/i.test(s.text));+ let step = making >= 0 ? Math.min(n, making + 2) : Math.ceil(n / 2) + 1;+ step = Math.max(2, Math.min(n, step));+ return { step, why: 'Chosen by a default rule (the answer from the model could not be used): the first results exist after the step before it.', defaulted: true };+}++/** The improvement plan request for B: what is done, what the lever is, and what to write. */+export function improvementPrompt({ request, steps, lever, doneSummaries }) {+ return [+ 'You are improving work that is already in progress in this folder. Read .timeskip/context.md and the files first (you may only look, not change anything).',+ `Original request: ${request}`,+ 'Original plan:',+ ...steps.map((s, i) => `${i + 1}. ${s.text}`),+ `Steps 1 to ${lever.step - 1} are done in this folder${doneSummaries.length ? ': ' + doneSummaries.join(' ') : '.'}`,+ `Step ${lever.step} ("${steps[lever.step - 1]?.text}") is the checkpoint, chosen because: ${lever.why}`,+ '',+ 'Write an IMPROVEMENT PLAN: the numbered steps that should now finish the work, improving or changing direction wherever the results so far show a better way. 2 to 8 short steps. Put a short heading line before the list.',+ ].join('\n');+}++const stepObjectiveBriefing = ctx => ctx;++export function createForkTimeskip({ agent, dir, notify = () => {}, now = Date.now }) {+ mkdirSync(dir, { recursive: true });+ const runs = new Map(); // id -> internal run++ const pub = r => ({+ id: r.id, kind: 'fork', phase: r.phase, workspace: r.workspace, prompt: r.prompt, startedAt: r.startedAt / 1000, finishedAt: r.finishedAt ? r.finishedAt / 1000 : null,+ attempts: [], checkpoints: [], selectedCheckpoint: null, decision: null, needsUserReview: r.phase === 'completed' && !!r.b?.root,+ error: r.error, plan: r.plan, lever: r.lever, a: r.a, b: r.b, labels: { original: 'A', updated: 'B' }, activity: r.activity,+ });+ const saveFile = r => join(dir, r.id, 'run.json');+ const persist = r => { try { mkdirSync(join(dir, r.id), { recursive: true }); const tmp = saveFile(r) + '.tmp'; writeFileSync(tmp, JSON.stringify(pub(r))); renameSync(tmp, saveFile(r)); } catch { /* memory only */ } };+ let lastSent = new Map();+ const announce = r => {+ persist(r);+ const view = { id: r.id, phase: r.phase, activity: r.activity, plan: r.plan, lever: r.lever, a: r.a, b: r.b };+ const key = JSON.stringify(view);+ if (lastSent.get(r.id) !== key) { lastSent.set(r.id, key); notify('timeskip', JSON.parse(key)); }+ };+ const say = (r, code, text, args = {}) => { r.activity = { code, text, args }; announce(r); };+ // The page's older phase names keep working (queued/checkpointing/generating/checking/completed); the new fields say the rest.+ const setPhase = (r, phase) => { r.phase = phase; announce(r); };++ async function ask(r, chatId, line, ws, choice, thinking, mode = 'plan') {+ let text = '';+ await agent.runTurn({ chatId, message: line, workspacePath: ws, choice, mode, thinking, onFrame: f => { if (f.type === 'delta') text += f.text; } });+ return text;+ }++ async function runFlow(r, { choice, thinking, slots }) {+ const aChat = `ts:${r.id}:A`, bChat = `ts:${r.id}:B`, leverChat = `ts:${r.id}:lever`;+ r.chats = [aChat, bChat, leverChat];+ const stopped = () => r.stopping;+ try {+ // 1. plan+ setPhase(r, 'checkpointing'); say(r, 'planning', 'Planning the work…');+ copyProject(r.workspace, r.a.root);+ await agent.planCommand({ chatId: aChat, line: r.prompt, workspacePath: r.a.root, choice, thinking, mode: 'plan', onFrame: f => { if (f.type === 'status' && f.text) say(r, 'planning', f.text, f.args ?? {}); } });+ if (stopped()) return;+ const plan = agent.planState(aChat);+ if (!plan || plan.steps.length < 2) throw new Error('The assistant could not split this request into steps. Describe the steps you want, or use /goal instead.');+ agent.planControl({ chatId: aChat, planId: plan.id, action: 'approve' });+ r.plan = { id: plan.id, title: plan.title, steps: plan.steps.map(s => ({ id: s.id, text: s.text, detail: s.detail })) };+ announce(r);+ // 2. the lever+ say(r, 'choosing-lever', 'Choosing the step that matters most…');+ let lever = null;+ if (plan.steps.length >= 3) {+ try { const said = await ask(r, leverChat, leverPrompt(r.prompt, plan.steps), r.a.root, choice, 'Low'); if (process.env.TS_DEBUG) console.log('lever said:', JSON.stringify(said).slice(0, 300)); lever = parseLever(said, plan.steps.length); } catch (e) { lever = null; if (process.env.TS_DEBUG) console.log('lever failed', e.message); }+ if (stopped()) return;+ lever ??= defaultLever(plan.steps);+ }+ r.lever = lever ? { step: lever.step, total: plan.steps.length, text: plan.steps[lever.step - 1].text, why: lever.why, defaulted: !!lever.defaulted } : null;+ if (!r.lever) { r.b = { state: 'none', note: 'This plan is too short to be worth forking: only A runs.' }; }+ announce(r);++ // 3. A runs all the way; B forks when A has finished the step before the lever+ let bDone = null;+ const doneSummaries = [];+ const startB = async () => {+ r.b.state = 'planning'; r.b.waiting = false; say(r, 'b-planning', 'B: planning the improved path…');+ await agent.planCommand({ chatId: bChat, line: improvementPrompt({ request: r.prompt, steps: plan.steps, lever, doneSummaries }), workspacePath: r.b.root, choice, thinking, mode: 'plan', onFrame: () => {} });+ if (stopped()) return;+ const bp = agent.planState(bChat);+ if (!bp || bp.steps.length < 2) { r.b.state = 'failed'; r.b.note = 'The improvement plan could not be written, so only A is shown.'; announce(r); return; }+ agent.setPlanBriefing(bChat, 'This work continues from a first attempt that is already in this folder; its notes are in .timeskip/context.md (read them first). Improve on it where it is weak instead of starting over.');+ agent.planControl({ chatId: bChat, planId: bp.id, action: 'approve' });+ r.b.plan = bp.steps.map(s => ({ id: s.id, text: s.text }));+ r.b.state = 'running'; r.b.total = bp.steps.length; announce(r);+ await agent.planGoal({ chatId: bChat, planId: bp.id, workspacePath: r.b.root, mode: 'bypass', choice, thinking,+ onFrame: f => {+ if (f.type === 'plan-step') { r.b.step = f.index; r.b.total = f.total; r.b.text = f.text; r.b.line = f.line; say(r, 'b-step', `B, ${f.line}`, { step: f.index, steps: f.total }); }+ } });+ const end = agent.planState(bChat);+ r.b.state = end?.state === 'done' ? 'done' : 'failed';+ if (r.b.state === 'failed') r.b.note = stopped() ? 'Stopped.' : 'B did not finish, so only A is shown.';+ announce(r);+ };+ let forked = false;+ const forkNow = () => {+ if (forked || !r.lever) return;+ forked = true;+ copyProject(r.a.root, r.b.root);+ mkdirSync(join(r.b.root, '.timeskip'), { recursive: true });+ writeFileSync(join(r.b.root, '.timeskip', 'context.md'), [+ `# Work so far (copied from the first attempt, A)`, '', `Request: ${r.prompt}`, '', 'Plan:', ...plan.steps.map((s, i) => `${i + 1}. ${s.text}`), '',+ `Steps 1 to ${lever.step - 1} are done in this folder.`, ...r.a.summaries.map(s => `- ${s}`), '', `Checkpoint step ${lever.step}: ${plan.steps[lever.step - 1].text}`, `Why this step: ${lever.why}`, ''].join('\n'));+ r.b = { ...r.b, root: r.b.root, state: 'waiting', waiting: slots < 2, step: 0, total: 0 };+ doneSummaries.push(...r.a.summaries);+ announce(r);+ if (slots >= 2) bDone = startB();+ };+ r.b ??= {};+ if (r.lever) { r.b = { state: 'pending', root: join(dir, r.id, 'B'), waiting: slots < 2 }; }+ r.a.state = 'running'; r.a.total = plan.steps.length; setPhase(r, 'generating'); announce(r);+ await agent.planGoal({ chatId: aChat, planId: plan.id, workspacePath: r.a.root, mode: 'bypass', choice, thinking,+ onFrame: f => {+ if (f.type === 'plan-step') {+ r.a.step = f.index; r.a.total = f.total; r.a.text = f.text; r.a.line = f.line;+ if (f.state === 'done') { r.a.summaries.push(`${f.index}. ${f.text}${f.summary ? ': ' + f.summary : ''}`); if (r.lever && f.index === r.lever.step - 1) { try { forkNow(); } catch (e) { r.b = { ...r.b, state: 'failed', note: 'B could not be prepared, so only A is shown.' }; } } }+ say(r, 'a-step', `A, ${f.line}`, { step: f.index, steps: f.total });+ }+ } });+ if (stopped()) return;+ const aEnd = agent.planState(aChat);+ r.a.state = aEnd?.state === 'done' ? 'done' : 'failed';+ announce(r);+ if (r.a.state !== 'done') throw new Error('A did not finish the plan, so there is nothing to compare. Your files were not changed.');+ if (r.lever && !forked) { forkNow(); }+ if (r.lever && slots < 2 && r.b.state === 'waiting') { say(r, 'b-waiting', 'A is done. B starts now (one model slot: B waited for A).'); bDone = startB(); }+ if (bDone) await bDone.catch(e => { r.b.state = 'failed'; r.b.note = 'B stopped: ' + String(e.message ?? e).slice(0, 160); });+ if (stopped()) return;+ setPhase(r, 'checking'); say(r, 'comparing', 'Comparing A and B…');+ r.finishedAt = now(); r.activity = null; setPhase(r, 'completed');+ } catch (e) {+ if (stopped()) return;+ r.error = String(e.message ?? e).slice(0, 400); r.finishedAt = now(); r.activity = null; setPhase(r, 'failed');+ } finally {+ for (const c of r.chats) { try { agent.forget?.(c); } catch { /* best effort */ } }+ }+ }++ return {+ /** Start a run; resolves at once with the first snapshot. */+ start({ prompt, workspace, chatId = null, choice, thinking = 'Low', slots = 1 }) {+ const id = randomUUID().replaceAll('-', '');+ const r = { id, chatId, prompt: String(prompt ?? '').trim().slice(0, 4000), workspace: resolve(workspace), phase: 'queued', startedAt: now(), finishedAt: null, error: null, plan: null, lever: null, b: null, activity: { code: 'planning', text: 'Planning the work…', args: {} }, stopping: false,+ a: { state: 'pending', root: join(dir, id, 'A'), step: 0, total: 0, summaries: [] }, chats: [] };+ runs.set(id, r);+ announce(r);+ r.done = runFlow(r, { choice, thinking, slots });+ return pub(r);+ },+ has: id => runs.has(String(id)),+ status: id => { const r = runs.get(String(id)); return r ? pub(r) : null; },+ list: () => [...runs.values()].map(pub),+ byChat: chatId => [...runs.values()].find(r => r.chatId === chatId && !TERMINAL.has(r.phase))?.id ?? null,+ async stop(id) {+ const r = runs.get(String(id)); if (!r) return false;+ if (TERMINAL.has(r.phase)) return false;+ r.stopping = true;+ await Promise.allSettled((r.chats ?? []).map(c => agent.stop(c, { waitMs: 8000 })));+ r.finishedAt = now(); r.activity = null; r.phase = 'cancelled'; if (r.a) r.a.state = r.a.state === 'done' ? 'done' : 'stopped'; if (r.b?.state && r.b.state !== 'done') r.b.state = 'stopped';+ announce(r);+ try { await r.done; } catch { /* ended */ }+ try { rmSync(join(dir, r.id), { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ }+ return true;+ },+ /** A against B (or the original against A when there was no fork). */+ files(id) {+ const r = runs.get(String(id)); if (!r || !TERMINAL.has(r.phase) || r.phase === 'cancelled') return null;+ return diffRun(recordOf(r));+ },+ image(id, rel, version) { const r = runs.get(String(id)); return r ? imageOf(r, rel, version) : null; },+ /** Keep A or B: copy what differs into the person's folder, keeping the replaced files for "put the original back". */+ apply({ id, which = 'b', restore = false }) {+ const r = runs.get(String(id));+ if (!r) throw new Error('No such Time-skip run.');+ const back = join(dir, r.id, 'rollback');+ if (restore) {+ if (!existsSync(back)) throw new Error('There is nothing to put back.');+ cpSync(back, r.workspace, { recursive: true, force: true });+ for (const rel of readIndex(back).created) { try { rmSync(join(r.workspace, rel), { force: true }); } catch { /* gone */ } }+ rmSync(back, { recursive: true, force: true });+ return { restored: true };+ }+ if (r.phase !== 'completed') throw new Error('This run has not finished.');+ const from = which === 'a' ? r.a.root : (r.b?.root && r.b.state === 'done' ? r.b.root : null);+ if (!from) throw new Error('B is not available: only A can be kept.');+ if (existsSync(back)) throw new Error('A result is already in your files. Put the original back first.');+ mkdirSync(back, { recursive: true });+ const created = []; let copied = 0;+ for (const rel of walk(from)) {+ if (isNoisePath(rel)) continue;+ const src = join(from, rel), dst = join(r.workspace, rel);+ if (existsSync(dst) && Buffer.compare(readFileSync(src), readFileSync(dst)) === 0) continue;+ if (existsSync(dst)) { mkdirSync(dirname(join(back, rel)), { recursive: true }); cpSync(dst, join(back, rel)); } else created.push(rel);+ mkdirSync(dirname(dst), { recursive: true }); cpSync(src, dst); copied += 1;+ }+ writeFileSync(join(back, '.index.json'), JSON.stringify({ created }));+ return { applied: which, files: copied };+ },+ };++ function recordOf(r) {+ if (r.b?.root && r.b.state === 'done') return { checkpoints: [{ id: 'cp-a', label: 'baseline', path: r.a.root }, { id: 'cp-b', label: 'b', path: r.b.root }], selected_checkpoint: 'cp-b', attempts: [] };+ return { checkpoints: [{ id: 'cp-orig', label: 'baseline', path: r.workspace }], selected_checkpoint: 'cp-orig', attempts: [{ index: 1, path: r.a.root }] };+ }+ function imageOf(r, rel, version) { return runImagePath(recordOf(r), rel, version); }+}++function* walkGen(root, base = root) {+ let entries; try { entries = readdirSync(root, { withFileTypes: true }); } catch { return; }+ for (const e of entries) {+ const full = join(root, e.name);+ if (e.isDirectory()) { if (!SKIP.has(e.name)) yield* walkGen(full, base); }+ else if (e.isFile()) yield relative(base, full).split(sep).join('/');+ }+}+const walk = root => [...walkGen(root)];+function readIndex(back) { try { return JSON.parse(readFileSync(join(back, '.index.json'), 'utf8')); } catch { return { created: [] }; } }+void stepObjectiveBriefing; void statSync;diff --git a/apps/host/tests/helpers/scripted-worker.mjs b/apps/host/tests/helpers/scripted-worker.mjsindex b8db5cc6e..174377524 100644--- a/apps/host/tests/helpers/scripted-worker.mjs+++ b/apps/host/tests/helpers/scripted-worker.mjs@@ -108,6 +108,13 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model =`, sandbox_permissions: 'workspace-write', justification: 'The user asked for this file to be written.' }: { command: shellCommand(file, value), description: `Append one line to ${file}`, sandbox_permissions: 'workspace-write', justification: 'The user asked for this file to be written.' });}+ // Time-skip's two own questions (they quote the plan, whose steps carry directives, so they are recognised by their words first).+ {+ const t = messages.filter(m => m.role === 'user').map(text).join(' ');+ const answered = messages.some(m => m.role === 'assistant');+ if (/biggest lever/.test(t) && !answered && last.role !== 'tool') return say(['{"step": 2, "why": "The layout decided in step 1 shapes everything after it."}']);+ if (/IMPROVEMENT PLAN/.test(t) && !answered && last.role !== 'tool') return say(['## Better path\n\n', '1. Improve the first attempt SCRIPT:goalstep\n', '2. Polish and check SCRIPT:goalstep\n']);+ }if (directive?.[1] === 'goalstep') {// A goal round: read the goal, mark it complete, then say so.if (!toolMessages.length) return toolCall('get_goal', {});diff --git a/apps/host/tests/timeskip-fork.test.mjs b/apps/host/tests/timeskip-fork.test.mjsnew file mode 100644index 000000000..b84431a49--- /dev/null+++ b/apps/host/tests/timeskip-fork.test.mjs@@ -0,0 +1,104 @@+// Time-skip v2: plan, lever, A all the way, B forked at the lever with an improvement plan, compare, keep.+import test from 'node:test';+import assert from 'node:assert/strict';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { startScriptedWorker } from './helpers/scripted-worker.mjs';+import { createAgentBridge } from '../server/agent/agent-bridge.mjs';+import { resolveHarness } from '../server/agent/harness-runtime.mjs';+import { createForkTimeskip, leverPrompt, parseLever, defaultLever, improvementPrompt, copyProject } from '../server/timeskip-fork.mjs';++const HARNESS = process.env.STRATA_HARNESS_DIR;+const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;++test('the lever answer is read strictly; a bad answer gets a fixed rule with its reason said plainly', () => {+ assert.deepEqual(parseLever('Sure! {"step": 3, "why": "The shape is set here."} done', 5), { step: 3, why: 'The shape is set here.' });+ assert.equal(parseLever('{"step": 1, "why": "x"}', 5), null, 'never step 1');+ assert.equal(parseLever('{"step": 9, "why": "x"}', 5), null);+ assert.equal(parseLever('no json', 5), null);+ assert.equal(parseLever('{"step": 2}', 5).why.length > 5, true);+ const steps = ['Look around', 'Write the page', 'Add controls', 'Check it'].map(text => ({ text }));+ const d = defaultLever(steps);+ assert.deepEqual([d.step, d.defaulted], [3, true]); assert.match(d.why, /default rule/);+ assert.ok(defaultLever([{ text: 'a' }, { text: 'b' }, { text: 'c' }]).step >= 2);+ assert.match(leverPrompt('make x', steps), /ONE biggest lever/); assert.match(leverPrompt('make x', steps), /"step"/);+ const ip = improvementPrompt({ request: 'make x', steps, lever: { step: 3, why: 'shape' }, doneSummaries: ['1. Look around: done.'] });+ assert.match(ip, /IMPROVEMENT PLAN/); assert.match(ip, /Steps 1 to 2 are done/); assert.match(ip, /shape/); assert.match(ip, /\.timeskip\/context\.md/);+});++test('copyProject leaves out dependency and VCS folders', () => {+ const dir = mkdtempSync(join(tmpdir(), 'strata-cp-'));+ try {+ const from = join(dir, 'p'); mkdirSync(join(from, 'node_modules'), { recursive: true }); mkdirSync(join(from, 'src'), { recursive: true }); mkdirSync(join(from, '.git'));+ writeFileSync(join(from, 'node_modules', 'x.js'), 'x'); writeFileSync(join(from, 'src', 'a.txt'), 'a'); writeFileSync(join(from, '.git', 'h'), 'h');+ copyProject(from, join(dir, 'c'));+ assert.ok(existsSync(join(dir, 'c', 'src', 'a.txt'))); assert.ok(!existsSync(join(dir, 'c', 'node_modules'))); assert.ok(!existsSync(join(dir, 'c', '.git')));+ } finally { rmSync(dir, { recursive: true, force: true }); }+});++async function rig(t, slots) {+ const worker = await startScriptedWorker({});+ const dir = mkdtempSync(join(tmpdir(), 'strata-tsf-'));+ const project = join(dir, 'project'); mkdirSync(project); writeFileSync(join(project, 'keep.txt'), 'original');+ const bridge = createAgentBridge({ dataDir: join(dir, 'data'), localInstances: () => [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots }], connections: () => [], env: process.env, startTimeoutMs: 90_000 });+ const events = [];+ const ts = createForkTimeskip({ agent: bridge, dir: join(dir, 'ts'), notify: (type, data) => events.push(data) });+ t.after(async () => { await bridge.close(); await worker.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } });+ return { ts, events, project, dir, worker };+}+const until = async (fn, ms = 90_000) => { const t0 = Date.now(); while (Date.now() - t0 < ms) { const v = fn(); if (v) return v; await new Promise(r => setTimeout(r, 100)); } throw new Error('timed out'); };++test('plan -> lever (with its why) -> A runs every step -> B forks after step 1 with an improvement plan -> A and B are compared, and Keep B changes the folder', { skip }, async (t) => {+ const r = await rig(t, 2);+ const run = r.ts.start({ prompt: 'SCRIPT:planreply', workspace: r.project, choice: { instanceId: 'i' }, slots: 2 });+ assert.ok(['queued', 'checkpointing'].includes(run.phase), 'a run starts at once and does not wait for the work');+ const done = await until(() => { const s = r.ts.status(run.id); return ['completed', 'failed'].includes(s.phase) ? s : null; });+ assert.equal(done.phase, 'completed', done.error);+ assert.equal(done.plan.steps.length, 3);+ assert.deepEqual([done.lever.step, done.lever.total, done.lever.defaulted], [2, 3, false]); assert.match(done.lever.why, /layout/);+ assert.deepEqual([done.a.state, done.a.step, done.a.total], ['done', 3, 3]);+ assert.equal(done.b.state, 'done'); assert.equal(done.b.plan.length, 2);+ assert.equal(done.needsUserReview, true);+ assert.deepEqual(done.labels, { original: 'A', updated: 'B' });+ // events told the story in order+ const phases = r.events.map(e => e.phase);+ assert.ok(phases.indexOf('checkpointing') < phases.indexOf('generating') && phases.indexOf('generating') < phases.indexOf('completed'));+ assert.ok(r.events.some(e => e.lever && e.lever.step === 2), 'the lever and its reason were sent');+ assert.ok(r.events.some(e => e.a?.line && /Step 1 of 3/.test(e.a.line)) && r.events.some(e => e.b?.line && /Step 1 of 2/.test(e.b.line)), "A's and B's progress were sent");+ assert.ok(r.events.some(e => /^B, /.test(e.activity?.text ?? '')), 'the activity line names B');+ // B was copied from A at the fork and got the context attachment; the project is untouched+ assert.ok(existsSync(join(r.dir, 'ts', run.id, 'B', '.timeskip', 'context.md')));+ assert.match(readFileSync(join(r.dir, 'ts', run.id, 'B', '.timeskip', 'context.md'), 'utf8'), /Why this step: The layout/);+ assert.equal(readFileSync(join(r.project, 'keep.txt'), 'utf8'), 'original');+ // the compare is A against B+ const found = r.ts.files(run.id);+ assert.ok(Array.isArray(found.files));+ // keep B, then put the original back+ const kept = r.ts.apply({ id: run.id, which: 'b' });+ assert.equal(kept.applied, 'b');+ assert.throws(() => r.ts.apply({ id: run.id, which: 'a' }), /already in your files/);+ assert.deepEqual(r.ts.apply({ id: run.id, restore: true }), { restored: true });+ assert.equal(readFileSync(join(r.project, 'keep.txt'), 'utf8'), 'original');+});++test('with one model slot B waits for A, says so, and still finishes', { skip }, async (t) => {+ const r = await rig(t, 1);+ const run = r.ts.start({ prompt: 'SCRIPT:planreply', workspace: r.project, choice: { instanceId: 'i' }, slots: 1 });+ const done = await until(() => { const s = r.ts.status(run.id); return ['completed', 'failed'].includes(s.phase) ? s : null; });+ assert.equal(done.phase, 'completed', done.error);+ assert.ok(r.events.some(e => e.b?.waiting === true), 'B was shown as waiting');+ assert.ok(r.events.some(e => /B waited for A/.test(e.activity?.text ?? '')));+ assert.equal(done.b.state, 'done');+});++test('Stop ends both agents, removes the copies and leaves the folder alone', { skip }, async (t) => {+ const r = await rig(t, 2);+ const run = r.ts.start({ prompt: 'SCRIPT:planreply', workspace: r.project, choice: { instanceId: 'i' }, slots: 2 });+ await until(() => r.ts.status(run.id).a.state === 'running');+ assert.equal(await r.ts.stop(run.id), true);+ assert.equal(r.ts.status(run.id).phase, 'cancelled');+ assert.ok(!existsSync(join(r.dir, 'ts', run.id)));+ assert.equal(readFileSync(join(r.project, 'keep.txt'), 'utf8'), 'original');+ assert.equal(r.ts.files(run.id), null);+});