Skip to content

Commit d4c5a23

Browse files
Pujitha PaladuguPujitha Paladugutamirdresher
authored
fix(sdk): replace invalid \Z regex anchor in history-shadow (#2374)
* fix(sdk): replace invalid \Z regex anchor in history-shadow Motivation: history-shadow.ts builds section-boundary regexes ending in `\Z`, which JavaScript treats as a literal `Z`, not end-of-string. As a result the last section in a history file was never matched: appending to a terminal section (e.g. References) added a second header, and readHistory returned nothing for it. For non-terminal sections the append dropped the blank line before the next header. Approach: use `(?![\s\S])` as the end-of-input lookahead in both the append and read regexes. In appendToHistory, splice the updated section by index instead of String.replace (avoids `$` replacement patterns in user content) and keep a blank line when another section follows. Validation: added three tests in test/history-shadow.test.ts (terminal append has a single header, blank line preserved before next header, terminal section is read). They fail on the previous code (3 failed) and pass with the fix. Ran `npx vitest run test/history-shadow.test.ts test/state-io.test.ts` (17 passed), eslint on the changed files, and tsc --noEmit on packages/squad-sdk; npm run build succeeds. Report: https://github.com/bradygaster/squad/issues/1500 Signed-off-by: Pujitha Paladugu <10557236+pujitha24@users.noreply.github.com> Assisted-by: claude-sonnet-5-5 (via Claude Code) * test(sdk): update history-shadow characterization tests for \Z fix The H1 characterization tests pinned the old buggy behavior (duplicate References header, no blank line before the next section). With the end-of-input lookahead fix those assertions fail in CI. Re-pin the fixed behavior: terminal append is inline with a single header, and a blank line is preserved before the next header. Signed-off-by: Pujitha Paladugu <10557236+pujitha24@users.noreply.github.com> --------- Signed-off-by: Pujitha Paladugu <10557236+pujitha24@users.noreply.github.com> Co-authored-by: Pujitha Paladugu <10557236+pujitha24@users.noreply.github.com> Co-authored-by: Tamir Dresher <tamir.dresher@gmail.com>
1 parent 8ce43bb commit d4c5a23

4 files changed

Lines changed: 88 additions & 77 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-sdk': patch
3+
---
4+
5+
Fix history-shadow section parsing: replace the invalid `\Z` regex anchor so terminal sections are found (no duplicate `## References` header) and a blank line is kept before the next section.

‎packages/squad-sdk/src/agents/history-shadow.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ export async function appendToHistory(
233233

234234
// Find section or create it
235235
const sectionHeader = `## ${section}`;
236-
const sectionRegex = new RegExp(`^${sectionHeader}\\s*$([\\s\\S]*?)(?=^##\\s|\\Z)`, 'm');
236+
const sectionRegex = new RegExp(`^${sectionHeader}\\s*$([\\s\\S]*?)(?=^##\\s|(?![\\s\\S]))`, 'm');
237237
const match = historyContent.match(sectionRegex);
238238

239239
const timestamp = new Date().toISOString().split('T')[0]; // YYYY-MM-DD
@@ -245,8 +245,11 @@ export async function appendToHistory(
245245
// Section exists, append to it
246246
const fullMatch = match[0];
247247
const sectionContent = match[1];
248-
const updatedSection = `${sectionHeader}\n${sectionContent!.trimEnd()}${entry}`;
249-
updatedContent = historyContent.replace(fullMatch, updatedSection);
248+
const matchEnd = match.index! + fullMatch.length;
249+
// Keep a blank line before the next section header (none needed at end of file)
250+
const separator = matchEnd < historyContent.length ? '\n' : '';
251+
const updatedSection = `${sectionHeader}\n${sectionContent!.trimEnd()}${entry}${separator}`;
252+
updatedContent = historyContent.slice(0, match.index!) + updatedSection + historyContent.slice(matchEnd);
250253
} else {
251254
// Section doesn't exist, create it at the end
252255
updatedContent = historyContent.trimEnd() + `\n\n${sectionHeader}${entry}`;
@@ -328,7 +331,7 @@ export async function readHistory(
328331
};
329332

330333
for (const [sectionName, key] of Object.entries(sections)) {
331-
const sectionRegex = new RegExp(`^##\\s+${sectionName}\\s*$([\\s\\S]*?)(?=^##\\s|\\Z)`, 'm');
334+
const sectionRegex = new RegExp(`^##\\s+${sectionName}\\s*$([\\s\\S]*?)(?=^##\\s|(?![\\s\\S]))`, 'm');
332335
const match = historyContent.match(sectionRegex);
333336

334337
if (match) {

‎test/characterization/history-shadow.characterization.test.ts‎

Lines changed: 37 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,13 @@
66
* lifecycle are already covered by `test/history-shadow.test.ts` and are
77
* intentionally not duplicated here.
88
*
9-
* Current-bug note: the section-boundary regex in `appendToHistory`
10-
* (`packages/squad-sdk/src/agents/history-shadow.ts`) is built as
11-
* `` (?=^##\s|\Z) `` and intends `\Z` to mean "end of string". JavaScript has
12-
* no `\Z` end-of-string escape; it is parsed as the literal character "Z".
13-
* For every section except the last one, a following `## ` header still
14-
* lets the lookahead succeed, so those appends work, but the same
15-
* `trimEnd()`-before-splice step also collapses the blank line that used to
16-
* separate sections. For the terminal section (`References`, which has no
17-
* following header and no literal "Z" in its body) the lookahead can never
18-
* succeed, so the existing header is never matched and a *second*
19-
* `## References` header is appended at the tail of the file instead of the
20-
* entry being inserted inline. Both effects are characterized below exactly
21-
* as they behave today; neither assertion below endorses the behavior as
22-
* desired. See the tracked follow-up issue for the production fix.
9+
* Regression note: the section-boundary regex in `appendToHistory`
10+
* (`packages/squad-sdk/src/agents/history-shadow.ts`) previously ended in
11+
* `\Z`, which JavaScript parses as the literal character "Z", so the terminal
12+
* `References` section was never matched (a duplicate header was appended) and
13+
* non-terminal appends dropped the blank line before the next header. The
14+
* regex now uses `(?![\s\S])` for end-of-input; both behaviors are pinned
15+
* below in their fixed form.
2316
*
2417
* All I/O is contained inside a hermetic temp root; repository `.squad/**`
2518
* is never touched.
@@ -47,18 +40,17 @@ const CANONICAL_SECTIONS: HistorySection[] = [
4740
'References',
4841
];
4942

50-
// The terminal section is characterized separately below: current
51-
// production behavior duplicates its header instead of appending inline
52-
// (see file-level comment). The remaining sections are each followed by
53-
// another section header, so their append path succeeds.
43+
// The terminal section is characterized separately below because it has no
44+
// following header. The remaining sections are each followed by another
45+
// section header.
5446
const NON_TERMINAL_SECTIONS = CANONICAL_SECTIONS.slice(0, -1);
5547
const TERMINAL_SECTION = CANONICAL_SECTIONS[CANONICAL_SECTIONS.length - 1];
5648

5749
const TIMESTAMP_LINE = /^### (\d{4}-\d{2}-\d{2})$/m;
5850

5951
describe('history-shadow characterization (H1)', () => {
6052
it.each(NON_TERMINAL_SECTIONS)(
61-
'appends a block to the %s section, immediately abutting the next header',
53+
'appends a block to the %s section, preserving a blank line before the next header',
6254
async (section) => {
6355
await withHermeticRoot(async (root) => {
6456
const storage = makeWriteGuardedStorage(new FSStorageProvider(), root);
@@ -89,65 +81,37 @@ describe('history-shadow characterization (H1)', () => {
8981
expect(timestampMatch, 'timestamp header missing').not.toBeNull();
9082
const timestamp = timestampMatch![1];
9183

92-
// Current behavior: appendToHistory trims trailing whitespace off
93-
// the prior section content before splicing in the new entry. That
94-
// collapses the blank line that originally separated sections, so
95-
// the entry's own trailing newline becomes the single newline
96-
// immediately preceding the next `## ` header rather than a
97-
// preserved blank line plus a separate separator. The section body,
98-
// as sliced up to that boundary, therefore ends with the entry text
99-
// minus its final newline (that newline is the boundary itself).
100-
const entryWithoutTrailingNewline = `\n### ${timestamp}\n\n${content}`;
101-
expect(sectionBody.endsWith(entryWithoutTrailingNewline)).toBe(true);
84+
// appendToHistory trims the prior section content, splices in the
85+
// entry, and keeps a blank line before the next `## ` header. The
86+
// body sliced up to that header's "\n## " therefore ends with the
87+
// entry plus its own trailing newline (the blank line is the
88+
// remaining newline that is part of the boundary match).
89+
const entryWithTrailingNewline = `\n### ${timestamp}\n\n${content}\n`;
90+
expect(sectionBody.endsWith(entryWithTrailingNewline)).toBe(true);
10291
});
10392
},
10493
);
10594

106-
it(
107-
`current bug: appending to the terminal ${TERMINAL_SECTION} section duplicates its header ` +
108-
'instead of inserting inline',
109-
async () => {
110-
await withHermeticRoot(async (root) => {
111-
const storage = makeWriteGuardedStorage(new FSStorageProvider(), root);
112-
const agent = 'char-agent-terminal';
113-
const content = `sample body for ${TERMINAL_SECTION} section with punctuation: !? and unicode \u2603`;
95+
it(`appends to the terminal ${TERMINAL_SECTION} section inline without duplicating its header`, async () => {
96+
await withHermeticRoot(async (root) => {
97+
const storage = makeWriteGuardedStorage(new FSStorageProvider(), root);
98+
const agent = 'char-agent-terminal';
99+
const content = `sample body for ${TERMINAL_SECTION} section with punctuation: !? and unicode \u2603`;
114100

115-
const shadowPath = await createHistoryShadow(root, agent, undefined, storage);
116-
const before = await fs.readFile(shadowPath, 'utf8');
117-
await appendToHistory(root, agent, TERMINAL_SECTION, content, storage);
118-
const after = await fs.readFile(shadowPath, 'utf8');
119-
120-
const sectionHeader = `## ${TERMINAL_SECTION}`;
121-
122-
// See file-level comment: the `\Z` typo means the section-boundary
123-
// regex never matches for the terminal section, so appendToHistory
124-
// falls back to its "section not found" branch and appends a brand
125-
// new header at the tail instead of writing into the existing one.
126-
const occurrences = after.split(sectionHeader).length - 1;
127-
expect(occurrences, 'current bug duplicates the header').toBe(2);
128-
129-
const firstIndex = after.indexOf(sectionHeader);
130-
const secondIndex = after.indexOf(sectionHeader, firstIndex + sectionHeader.length);
131-
expect(secondIndex).toBeGreaterThan(firstIndex);
132-
133-
// The original section's content is left untouched by the append
134-
// (aside from trailing-whitespace normalization performed by the
135-
// "section not found" branch's own trimEnd(), which happens before
136-
// the duplicate header is spliced in).
137-
const originalSectionSlice = before.slice(before.indexOf(sectionHeader));
138-
const untouchedSlice = after.slice(firstIndex, secondIndex);
139-
expect(untouchedSlice.trimEnd()).toBe(originalSectionSlice.trimEnd());
140-
141-
// The duplicated (second) header starts a fresh section containing
142-
// only the new entry, and is the exact tail of the file.
143-
const timestampMatch = after.match(TIMESTAMP_LINE);
144-
expect(timestampMatch, 'timestamp header missing').not.toBeNull();
145-
const timestamp = timestampMatch![1];
146-
const expectedTail = `${sectionHeader}\n### ${timestamp}\n\n${content}\n`;
147-
expect(after.slice(secondIndex)).toBe(expectedTail);
148-
});
149-
},
150-
);
101+
const shadowPath = await createHistoryShadow(root, agent, undefined, storage);
102+
const before = await fs.readFile(shadowPath, 'utf8');
103+
await appendToHistory(root, agent, TERMINAL_SECTION, content, storage);
104+
const after = await fs.readFile(shadowPath, 'utf8');
105+
106+
const sectionHeader = `## ${TERMINAL_SECTION}`;
107+
expect(after.split(sectionHeader).length - 1, 'header should appear once').toBe(1);
108+
109+
const timestampMatch = after.match(TIMESTAMP_LINE);
110+
expect(timestampMatch, 'timestamp header missing').not.toBeNull();
111+
const timestamp = timestampMatch![1];
112+
expect(after).toBe(`${before.trimEnd()}\n### ${timestamp}\n\n${content}\n`);
113+
});
114+
});
151115

152116
it('appends an unknown section at the end when no matching header exists', async () => {
153117
await withHermeticRoot(async (root) => {

‎test/history-shadow.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,45 @@ describe('history-shadow (#479 race condition fix)', () => {
7272
});
7373
});
7474

75+
describe('section boundaries', () => {
76+
async function writeHistory(content: string): Promise<string> {
77+
const agentDir = path.join(tmpDir, '.squad', 'agents', 'testbot');
78+
await fs.mkdir(agentDir, { recursive: true });
79+
const file = path.join(agentDir, 'history.md');
80+
await fs.writeFile(file, content, 'utf-8');
81+
return file;
82+
}
83+
84+
it('should append to a terminal section without duplicating its header', async () => {
85+
const file = await writeHistory('# Testbot\n\n## Learnings\n\nfirst\n\n## References\n\n- ref one\n');
86+
87+
await appendToHistory(tmpDir, 'testbot', 'References', 'ref two');
88+
89+
const raw = await fs.readFile(file, 'utf-8');
90+
expect(raw.match(/^## References/gm)).toHaveLength(1);
91+
const history = await readHistory(tmpDir, 'testbot');
92+
expect(history.references).toContain('ref one');
93+
expect(history.references).toContain('ref two');
94+
});
95+
96+
it('should keep a blank line before the next section header', async () => {
97+
const file = await writeHistory('# Testbot\n\n## Learnings\n\nfirst\n\n## Decisions\n\nd1\n');
98+
99+
await appendToHistory(tmpDir, 'testbot', 'Learnings', 'second');
100+
101+
const raw = await fs.readFile(file, 'utf-8');
102+
expect(raw).toMatch(/second\n\n## Decisions/);
103+
});
104+
105+
it('should read a terminal section', async () => {
106+
await writeHistory('# Testbot\n\n## Learnings\n\nfirst\n\n## References\n\n- ref one\n');
107+
108+
const history = await readHistory(tmpDir, 'testbot');
109+
expect(history.references).toBe('- ref one');
110+
expect(history.learnings).toBe('first');
111+
});
112+
});
113+
75114
describe('appendToHistory — concurrent callers (race condition)', () => {
76115
it('should not lose data when 5 agents append concurrently', async () => {
77116
await createHistoryShadow(tmpDir, 'sharedbot', 'Shared context');

0 commit comments

Comments
 (0)