Skip to content

Commit c5e2c83

Browse files
joslattamirdresher
andauthored
fix(cli): keep squad nap from trimming history into an uncommittable archive (#2350)
History compression appended the older sections of history.md to history-archive.md and rewrote history.md without the checks decision archival has. With .squad/ excluded from git, the new archive is ignored, so the trim committed and the archived sections never did. compressHistory now follows the same rules as archiveDecisions: - Rule 1: refuse when history.md would be committed but its archive could not be (isCommittableDestination). A .squad/ ignored as a whole still compresses, since nothing there reaches a commit; - Rule 2: rewrite history.md only after the archive gained every archived section, counted the same way the sections were split; nothing to archive means nothing to trim. Closes #2349 Co-authored-by: Tamir Dresher <tamir.dresher@gmail.com>
1 parent 017e585 commit c5e2c83

3 files changed

Lines changed: 171 additions & 6 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@bradygaster/squad-cli": patch
3+
---
4+
5+
`squad nap` no longer loses agent history when `.squad/` is excluded from git. History compression appended the older sections of a tracked `history.md` to a new `history-archive.md` and then trimmed `history.md`. When `.squad/` is in `.git/info/exclude`, the new archive is ignored, so the trim got committed and the archived sections never did. History compression now follows the same rules as decision archival: it refuses when `history.md` would be committed but its archive could not, and it rewrites `history.md` only after checking that the archive gained every archived section. A `.squad/` that is ignored as a whole still compresses as before.

‎packages/squad-cli/src/cli/core/nap.ts‎

Lines changed: 52 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,7 @@ function compressHistory(
161161
filePath: string,
162162
keepEntries: number,
163163
dryRun: boolean,
164+
repoRoot: string,
164165
): NapAction | null {
165166
if (!storage.existsSync(filePath)) return null;
166167
const size = fileSize(filePath);
@@ -239,17 +240,57 @@ function compressHistory(
239240
const newContent = newLines.join('\n');
240241
const archiveContent = archiveLines.join('\n');
241242
const saved = size - Buffer.byteLength(newContent, 'utf8');
243+
const relPath = path.basename(path.dirname(filePath));
242244

243245
if (!dryRun) {
244246
const archivePath = filePath.replace(/\.md$/, '-archive.md');
245-
// Append to archive
246-
if (archiveContent.trim()) {
247-
storage.appendSync(archivePath, archiveContent + '\n');
247+
248+
// The same rules decision archival follows (see archiveDecisions).
249+
// Rule 2 — nothing to append means nothing to remove.
250+
if (!archiveContent.trim()) {
251+
return {
252+
type: 'compress',
253+
target: filePath,
254+
description: `History compression skipped: ${relPath}/history.md produced no content to archive. Source left intact.`,
255+
bytesSaved: 0,
256+
};
257+
}
258+
259+
// Rule 1 — never move sections out of a history.md git will commit into an
260+
// archive it cannot commit (#1783): the trim would commit and the archive
261+
// would not. A history.md that is itself ignored has nothing to lose.
262+
if (isCommittableDestination(filePath, repoRoot) && !isCommittableDestination(archivePath, repoRoot)) {
263+
return {
264+
type: 'compress',
265+
target: filePath,
266+
description:
267+
`History compression refused: ${archivePath} is untracked and git-ignored, so archived sections ` +
268+
`could never be committed. ${relPath}/history.md left in place.`,
269+
bytesSaved: 0,
270+
};
271+
}
272+
273+
const before = storage.readSync(archivePath) ?? '';
274+
storage.appendSync(archivePath, archiveContent + '\n');
275+
276+
// Rule 2 — verify the append landed, by section count, before rewriting the source.
277+
const after = storage.readSync(archivePath) ?? '';
278+
const expected = countSectionHeadings(before) + archive.length;
279+
const actual = countSectionHeadings(after);
280+
if (actual !== expected) {
281+
return {
282+
type: 'compress',
283+
target: filePath,
284+
description:
285+
`History compression aborted: expected ${expected} sections in ${relPath}/history-archive.md after append, ` +
286+
`measured ${actual}. Source left intact.`,
287+
bytesSaved: 0,
288+
};
248289
}
290+
249291
storage.writeSync(filePath, newContent);
250292
}
251293

252-
const relPath = path.basename(path.dirname(filePath));
253294
return {
254295
type: 'compress',
255296
target: filePath,
@@ -258,6 +299,11 @@ function compressHistory(
258299
};
259300
}
260301

302+
/** `##` headings, matched the way compressHistory splits sections. */
303+
function countSectionHeadings(markdown: string): number {
304+
return markdown.split('\n').filter(line => /^##\s/.test(line)).length;
305+
}
306+
261307
// ─── Log pruning ────────────────────────────────────────────────────────
262308

263309
function pruneLogs(dir: string, dryRun: boolean): NapAction[] {
@@ -548,7 +594,7 @@ export async function runNap(options: NapOptions): Promise<NapResult> {
548594
for (const name of storage.listSync(agentsDir)) {
549595
if (!storage.isDirectorySync(path.join(agentsDir, name))) continue;
550596
const hf = path.join(agentsDir, name, 'history.md');
551-
const action = compressHistory(hf, keepEntries, dryRun);
597+
const action = compressHistory(hf, keepEntries, dryRun, path.dirname(squadDir));
552598
if (action) actions.push(action);
553599
}
554600
}
@@ -604,7 +650,7 @@ export function runNapSync(options: NapOptions): NapResult {
604650
for (const name of storage.listSync(agentsDir)) {
605651
if (!storage.isDirectorySync(path.join(agentsDir, name))) continue;
606652
const hf = path.join(agentsDir, name, 'history.md');
607-
const action = compressHistory(hf, keepEntries, dryRun);
653+
const action = compressHistory(hf, keepEntries, dryRun, path.dirname(squadDir));
608654
if (action) actions.push(action);
609655
}
610656
}

‎test/cli/nap-archival-safety.test.ts‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,3 +282,117 @@ describe('Nap archival — #1760: `###` inside a fence is not a record boundary'
282282
expect(archived).not.toContain('SENTINEL_TAIL');
283283
});
284284
});
285+
286+
// ─── History compression follows the same rules ─────────────────────────
287+
288+
const HISTORY = '.squad/agents/fenster/history.md';
289+
const HISTORY_ARCHIVE = '.squad/agents/fenster/history-archive.md';
290+
291+
/** `##` sections other than Core Context, the unit nap compresses. */
292+
function countSections(markdown: string): number {
293+
return markdown.split('\n').filter((l) => /^## /.test(l) && !/^## Core Context/.test(l)).length;
294+
}
295+
296+
function countSectionsInCommit(repoRoot: string, relPath: string): number {
297+
try {
298+
return countSections(git(['show', `HEAD:${relPath}`], repoRoot));
299+
} catch {
300+
return 0;
301+
}
302+
}
303+
304+
/** history.md above nap's 15 KB HISTORY_THRESHOLD with 12 sections, so 7 get archived. */
305+
function buildHistory(): string {
306+
const filler = 'Learned something worth keeping about this codebase. '.repeat(40);
307+
const lines = ['# Fenster history', '', '## Core Context', '', 'Backend specialist.', ''];
308+
for (let i = 0; i < 12; i++) lines.push(`## Session ${i}`, '', filler, '');
309+
return lines.join('\n');
310+
}
311+
312+
function createHistoryRepo(opts: { excludeSquad: boolean; archiveExists: boolean }): {
313+
repoRoot: string;
314+
squadDir: string;
315+
} {
316+
const repoRoot = mkdtempSync(join(tmpdir(), 'squad-nap-history-'));
317+
tmpDirs.push(repoRoot);
318+
319+
git(['init', '--initial-branch=main'], repoRoot);
320+
git(['config', 'user.email', 'fido@squad.test'], repoRoot);
321+
git(['config', 'user.name', 'FIDO'], repoRoot);
322+
git(['config', 'commit.gpgsign', 'false'], repoRoot);
323+
324+
const squadDir = join(repoRoot, '.squad');
325+
mkdirSync(join(squadDir, 'agents', 'fenster'), { recursive: true });
326+
writeFileSync(join(repoRoot, HISTORY), buildHistory(), 'utf8');
327+
if (opts.archiveExists) {
328+
writeFileSync(join(repoRoot, HISTORY_ARCHIVE), '# Fenster history archive\n', 'utf8');
329+
}
330+
331+
git(['add', '-A'], repoRoot);
332+
git(['commit', '-m', 'seed'], repoRoot);
333+
334+
if (opts.excludeSquad) {
335+
appendFileSync(join(repoRoot, '.git', 'info', 'exclude'), '\n.squad/\n', 'utf8');
336+
}
337+
338+
return { repoRoot, squadDir };
339+
}
340+
341+
describe('Nap history compression — #1783: destination must be committable', () => {
342+
it('does not move sections into a git-ignored archive that cannot be committed', async () => {
343+
const { repoRoot, squadDir } = createHistoryRepo({ excludeSquad: true, archiveExists: false });
344+
const totalBefore = countSectionsInCommit(repoRoot, HISTORY);
345+
expect(totalBefore).toBe(12);
346+
347+
await runNap({ squadDir });
348+
commitLikeAnAgent(repoRoot);
349+
350+
expect(countSectionsInCommit(repoRoot, HISTORY) + countSectionsInCommit(repoRoot, HISTORY_ARCHIVE)).toBe(totalBefore);
351+
});
352+
353+
it('reports the refusal and writes nothing', async () => {
354+
const { repoRoot, squadDir } = createHistoryRepo({ excludeSquad: true, archiveExists: false });
355+
const before = readFileSync(join(repoRoot, HISTORY), 'utf8');
356+
357+
const result = await runNap({ squadDir });
358+
359+
expect(result.actions.find((a) => a.type === 'compress')?.description).toMatch(/^History compression refused/);
360+
expect(readFileSync(join(repoRoot, HISTORY), 'utf8')).toBe(before);
361+
expect(existsSync(join(repoRoot, HISTORY_ARCHIVE))).toBe(false);
362+
expect(git(['status', '--porcelain'], repoRoot).trim()).toBe('');
363+
});
364+
365+
it('still compresses when the archive is already tracked', async () => {
366+
const { repoRoot, squadDir } = createHistoryRepo({ excludeSquad: true, archiveExists: true });
367+
368+
await runNap({ squadDir });
369+
commitLikeAnAgent(repoRoot);
370+
371+
expect(countSectionsInCommit(repoRoot, HISTORY)).toBe(5);
372+
expect(countSectionsInCommit(repoRoot, HISTORY_ARCHIVE)).toBe(7);
373+
});
374+
375+
it('still compresses when .squad/ was never committed and is ignored as a whole', async () => {
376+
const repoRoot = mkdtempSync(join(tmpdir(), 'squad-nap-history-ignored-'));
377+
tmpDirs.push(repoRoot);
378+
git(['init', '--initial-branch=main'], repoRoot);
379+
writeFileSync(join(repoRoot, '.gitignore'), '/.squad/\n', 'utf8');
380+
mkdirSync(join(repoRoot, '.squad', 'agents', 'fenster'), { recursive: true });
381+
writeFileSync(join(repoRoot, HISTORY), buildHistory(), 'utf8');
382+
383+
await runNap({ squadDir: join(repoRoot, '.squad') });
384+
385+
// Nothing under .squad/ reaches a commit, so there is no boundary to protect.
386+
expect(countSections(readFileSync(join(repoRoot, HISTORY), 'utf8'))).toBe(5);
387+
expect(countSections(readFileSync(join(repoRoot, HISTORY_ARCHIVE), 'utf8'))).toBe(7);
388+
});
389+
390+
it('compresses normally when .squad/ is not excluded', async () => {
391+
const { repoRoot, squadDir } = createHistoryRepo({ excludeSquad: false, archiveExists: false });
392+
393+
await runNap({ squadDir });
394+
395+
expect(countSections(readFileSync(join(repoRoot, HISTORY), 'utf8'))).toBe(5);
396+
expect(countSections(readFileSync(join(repoRoot, HISTORY_ARCHIVE), 'utf8'))).toBe(7);
397+
});
398+
});

0 commit comments

Comments
 (0)