Files edited: only report what the turn itself wrote (a cut-short first look no longer makes the rest of the folder new files); never look in app, engine, component, AppData or temp folders

This commit is contained in:
Niko1221 committed 2026-10-18 20:33:55 +02:00
1 parent 66ad879d18
commit e09eccc839
3 files changed
+108 -11

No files matched your search

+21 -2
View File
@@ -16,6 +16,8 @@
*/
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { homedir, tmpdir } from 'node:os';
import { fileURLToPath } from 'node:url';
import { randomUUID } from 'node:crypto';
import { GatewayClient } from './gateway-client.mjs';
import { HarnessProcess, resolveHarness, redact, stopStaleAgent } from './harness-runtime.mjs';
@@ -73,6 +75,9 @@ export function imageParts(images) {
/** A timer that never keeps the process alive by itself. */
const after = (ms, fn) => { const t = setTimeout(fn, ms); t.unref?.(); return t; };
/** The app's own host folder: never a place an answer's files can be (this file lives in <host>/server/agent). */
const HOST_DIR = fileURLToPath(new URL('../..', import.meta.url));
const deferred = () => { let resolve; const promise = new Promise(r => { resolve = r; }); return { promise, resolve }; };
/**
@@ -91,6 +96,18 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
const sessionsFile = join(root, 'sessions.json');
mkdirSync(root, { recursive: true });
/**
* Where the turn's file tracker must never look (deliverables.mjs): the app, the engine and its components, Strata's own data, AppData
* and temp. `forbid` ones also switch tracking off when the chat's folder is one of them or inside one.
*/
function trackerFolders() {
const user = env.USERPROFILE ?? env.HOME ?? homedir();
const forbid = [HOST_DIR, componentsDir, bundledDir].filter(Boolean);
const exclude = [dataDir, tmpdir(), env.LOCALAPPDATA, env.APPDATA, env.ProgramData, env.ProgramFiles, env['ProgramFiles(x86)'], env.TEMP, env.TMP,
join(user, 'AppData'), join(user, '.cache'), join(user, '.config'), join(user, '.local'), join(user, 'Library')].filter(Boolean);
return { forbid, exclude };
}
/** chatId -> { sessionId, cwd, createdAt } */
let sessionMap = {};
if (existsSync(sessionsFile)) {
@@ -296,7 +313,8 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
const written = { all: '', step: '' };
const raw = frame => { try { send(frame); } catch { send = () => {}; attached = false; } };
// What the turn made (files) and compact activity lines (notes-split-agent8.md): derived from the cards the turn already sends.
const tracker = new DeliverableTracker(workspacePath);
const tracker = new DeliverableTracker(workspacePath, trackerFolders());
let toolsRan = false; // a turn that ran no tool wrote nothing, so there is nothing to look for at its end
try { tracker.snapshot(); } catch { /* a folder that cannot be read has no deliverables */ }
const groups = new ActivityGroups({ emit: raw });
const skills = new SkillsUsed({ emit: raw, info: skillInfoFrom(skillsDir()) });
@@ -305,6 +323,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
if (frame.own) { const { own, ...rest } = frame; frame = rest; }
if (frame.type === 'delta' && frame.text) groups.text();
if (frame.type === 'agent-tool' && frame.tool) {
if (['done', 'error'].includes(frame.tool.state) && !['read', 'read_image', 'glob', 'grep', 'web_fetch', 'web_search'].includes(frame.tool.name)) toolsRan = true;
let made = null;
if (frame.tool.state === 'done' && (frame.tool.name === 'write' || frame.tool.name === 'edit')) { try { made = tracker.check(frame.tool.args?.file_path ?? frame.tool.args?.path); } catch { made = null; } }
raw(frame);
@@ -390,7 +409,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
if (turn.stopping && !failure) projector.ended = { kind: 'aborted', reason: { kind: 'user' } };
reporter.clear();
const extra = [];
try { for (const d of tracker.sweep()) { emit(d); groups.addFile(d); } } catch { /* never blocks the end of a turn */ }
try { if (toolsRan) for (const d of tracker.sweep()) { emit(d); groups.addFile(d); } } catch { /* never blocks the end of a turn */ }
groups.end();
if (researchTopic && !failure && !turn.stopping) { const sources = parseSources(written.all); if (sources.length) extra.push({ type: 'research', topic: researchTopic, sources }); }
try { extra.push(...settlePlan(failure)); } catch { /* a plan frame must never break the end of a turn */ }
+43 -8
View File
@@ -11,7 +11,7 @@
*/
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { basename, extname, join, relative, resolve, sep } from 'node:path';
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
const SKIP_DIR = /^(?:\.|node_modules$|__pycache__$|\$)/;
const MAX_FILES = 4000, MAX_TEXT = 200_000, MAX_TOTAL = 24_000_000, BUDGET_MS = 1500;
@@ -40,24 +40,47 @@ export function lineDelta(before, after) {
return { added, removed };
}
/** A file made or changed this long before the turn started still counts (clock rounding on some file systems). */
const START_SLACK_MS = 2000;
const same = process.platform === 'win32' || process.platform === 'darwin' ? p => p.toLowerCase() : p => p;
/** True when `child` is `parent` or inside it. */
export function isWithin(parent, child) {
const rel = relative(same(resolve(parent)), same(resolve(child)));
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
}
export class DeliverableTracker {
constructor(root, { now = Date.now } = {}) {
/**
* `exclude`: folders that are never searched when they lie inside the chat's folder (the app, the engine and its components, AppData,
* temp). `forbid`: folders the chat's own folder must not be, or be inside (the app, the engine and its components): then nothing is
* tracked at all. The turn only reports files the turn itself wrote: an explicit file-tool call, or (for scripts) a file whose modified
* or creation time is after the turn started.
*/
constructor(root, { now = Date.now, exclude = [], forbid = [] } = {}) {
this.root = root ? resolve(root) : null;
this.now = now;
if (this.root && forbid.filter(Boolean).some(p => isWithin(p, this.root))) this.root = null;
// only the folders that lie inside the chat's folder matter for the search
this.exclude = this.root ? [...exclude, ...forbid].filter(Boolean).map(p => resolve(p)).filter(p => p !== this.root && isWithin(this.root, p)) : [];
this.startedAt = Date.now();
this.before = new Map(); // rel path -> { size, mtimeMs, lines|null }
this.sent = new Map(); // rel path -> signature of what was last reported
this.truncated = false;
}
#snapshotting = false;
/** A folder inside the chat's folder that is never searched. */
#excluded(full) { return this.exclude.some(p => isWithin(p, full)); }
#walk(fn) {
if (!this.root) return;
const t0 = this.now(); let count = 0;
const walk = dir => {
let entries; try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
for (const e of entries) {
if (count >= MAX_FILES || this.now() - t0 > BUDGET_MS) { this.truncated = true; return; }
if (count >= MAX_FILES || this.now() - t0 > BUDGET_MS) { this.truncated = true; if (this.#snapshotting) this.snapshotTruncated = true; return; }
const full = join(dir, e.name);
if (e.isDirectory()) { if (!SKIP_DIR.test(e.name)) walk(full); }
if (e.isDirectory()) { if (!SKIP_DIR.test(e.name) && !this.#excluded(full)) walk(full); }
else if (e.isFile()) { count += 1; fn(full); }
}
};
@@ -71,12 +94,13 @@ export class DeliverableTracker {
/** Remember what the folder holds now. */
snapshot() {
this.before.clear(); this.bytes = 0;
this.before.clear(); this.bytes = 0; this.startedAt = Date.now(); this.snapshotTruncated = false; this.#snapshotting = true;
this.#walk(full => {
let st; try { st = statSync(full); } catch { return; }
const rel = relative(this.root, full).split(sep).join('/');
this.before.set(rel, { size: st.size, mtimeMs: st.mtimeMs, lines: this.#read(full, st.size, fileType(rel)) });
});
this.#snapshotting = false;
}
/** The deliverable for one path now, compared with the snapshot (and the last report), or null when nothing changed. */
@@ -84,7 +108,7 @@ export class DeliverableTracker {
if (!this.root) return null;
const full = resolve(this.root, String(rawPath ?? ''));
const rel = relative(this.root, full).split(sep).join('/');
if (!rel || rel.startsWith('..') || rel.split('/').some(seg => SKIP_DIR.test(seg))) return null;
if (!rel || rel.startsWith('..') || isAbsolute(rel) || rel.split('/').some(seg => SKIP_DIR.test(seg)) || this.#excluded(dirname(full))) return null;
let st; try { st = statSync(full); } catch { return null; }
if (!st.isFile()) return null;
const old = this.before.get(rel);
@@ -102,10 +126,21 @@ export class DeliverableTracker {
return { type: 'deliverable', path: rel, abs: full, name: basename(rel), kind: type, status: old ? 'changed' : 'created', size: st.size, lines: lines ? lines.length : null, added, removed };
}
/** Files the tools did not announce (a script wrote them): everything new or changed since the snapshot and not yet reported. */
/**
* Files the tools did not announce (a script wrote them): what was made or changed since the snapshot and not yet reported. A file only
* counts when its modified or creation time is after the turn started, so a folder the snapshot could not finish (it stops after
* MAX_FILES files or BUDGET_MS) never turns the rest of the folder into "new files" (the 308 CUDA headers of the QA report).
*/
sweep() {
const out = [];
this.#walk(full => { const d = this.check(relative(this.root, full)); if (d) out.push(d); });
const since = this.startedAt - START_SLACK_MS;
this.#walk(full => {
let st; try { st = statSync(full); } catch { return; }
// modified during the turn; or created during it (a copy that kept its old modified time), which is only certain when the first look saw the whole folder
const fresh = st.mtimeMs >= since || (!this.snapshotTruncated && (st.birthtimeMs || 0) >= since);
if (!fresh) return;
const d = this.check(relative(this.root, full)); if (d) out.push(d);
});
return out;
}
}
+44 -1
View File
@@ -1,7 +1,7 @@
// Deliverable events and compact activity groups.
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync } from 'node:fs';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync, utimesSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DeliverableTracker, ActivityGroups, fileType, groupLine, lineDelta } from '../server/agent/deliverables.mjs';
@@ -43,6 +43,49 @@ test('a created file, a changed file and a script-made file are reported once ea
} finally { rmSync(dir, { recursive: true, force: true }); }
});
test('a snapshot cut short by its time budget never turns the rest of the folder into "new files" (QA report: Edited 308 files)', () => {
const dir = mkdtempSync(join(tmpdir(), 'strata-dl3-'));
try {
// a big, old tree (the CUDA headers of the report) that was there long before the turn
const old = new Date(Date.now() - 3600_000);
for (const d of ['algorithm', 'atomic', 'barrier']) {
mkdirSync(join(dir, d));
for (let i = 0; i < 30; i++) { const p = join(dir, d, 'f' + i + '.h'); writeFileSync(p, 'line' + NL); utimesSync(p, old, old); }
}
// the first look runs out of time after a few files; the look at the end of the turn has all the time it wants
let calls = 0;
const t = new DeliverableTracker(dir, { now: () => (++calls > 12 ? 1e9 : 0) });
t.snapshot();
assert.equal(t.truncated, true, 'the setup: the snapshot was cut short');
t.now = () => 0;
assert.deepEqual(t.sweep(), [], 'nothing the turn did not touch is reported');
// a file the turn really makes is still found, and an old file the turn really changes
writeFileSync(join(dir, 'barrier', 'made.txt'), 'x' + NL);
assert.deepEqual(t.sweep().map(d => d.path), ['barrier/made.txt']);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
test('the tracker never looks inside the app, engine, component, AppData or temp folders, nor when the chat folder is the app itself', () => {
const dir = mkdtempSync(join(tmpdir(), 'strata-dl4-'));
try {
const ws = join(dir, 'work'), engine = join(ws, 'engine'), temp = join(ws, 'Temp'), appData = join(ws, 'AppData'), mine = join(ws, 'mine');
for (const d of [ws, engine, temp, appData, mine]) mkdirSync(d);
const t = new DeliverableTracker(ws, { forbid: [engine], exclude: [temp, appData, join(dir, 'elsewhere')] });
t.snapshot();
for (const d of [engine, temp, appData, mine]) writeFileSync(join(d, 'new.h'), 'a' + NL);
assert.deepEqual(t.sweep().map(d => d.path), ['mine/new.h']);
assert.equal(t.check('engine/new.h'), null); assert.equal(t.check('Temp/new.h'), null); assert.equal(t.check('AppData/new.h'), null);
// a chat whose folder IS the engine folder (or inside it) tracks nothing
const inside = new DeliverableTracker(engine, { forbid: [engine] }); inside.snapshot();
writeFileSync(join(engine, 'another.h'), 'b' + NL);
assert.deepEqual(inside.sweep(), []); assert.equal(inside.check('another.h'), null);
// the temp folder as the chat's own folder is fine (the exclusion is for folders inside the chat folder)
const own = new DeliverableTracker(temp, { exclude: [temp] }); own.snapshot();
writeFileSync(join(temp, 'ok.txt'), 'c' + NL);
assert.deepEqual(own.sweep().map(d => d.path), ['ok.txt']);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
test('activity groups: consecutive tools are one growing group closed by text, with counts, files and the diff stat', () => {
const out = [];
const g = new ActivityGroups({ emit: f => out.push(f) });