From b075f4309abf3ccf6491d3271f40421b5d2ed8b0 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 26 Nov 2026 14:36:23 +0000 Subject: [PATCH 1/7] Learnings search survives a malformed row and keeps this project's own answer; multi-line timeline events stay readable Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-learnings-log | 3 ++ bin/gstack-learnings-search | 15 +++++--- bin/gstack-timeline-log | 15 ++++---- test/gstack-learnings-search.test.ts | 54 ++++++++++++++++++++++++++++ test/learnings.test.ts | 19 ++++++++++ test/timeline.test.ts | 9 +++++ 6 files changed, 102 insertions(+), 13 deletions(-) diff --git a/bin/gstack-learnings-log b/bin/gstack-learnings-log index 1e9fb33e946..c7727ee6efa 100755 --- a/bin/gstack-learnings-log +++ b/bin/gstack-learnings-log @@ -89,6 +89,9 @@ if (j.source && !ALLOWED_SOURCES.includes(j.source)) { process.exit(1); } +// files is a list of paths; one path given as a string is stored as a one-item list. +if (typeof j.files === 'string') j.files = [j.files]; + // Content sanitization: shared injection patterns (lib/jsonl-store.ts, D2A) — // one audited list across learnings + decisions, no drift. if (j.insight && hasInjection(j.insight)) { diff --git a/bin/gstack-learnings-search b/bin/gstack-learnings-search index b1eb3e5a377..67c0a8f2a9f 100755 --- a/bin/gstack-learnings-search +++ b/bin/gstack-learnings-search @@ -153,6 +153,7 @@ for (const taggedLine of lines) { const line = tabIndex === -1 ? taggedLine : taggedLine.slice(tabIndex + 1); const e = JSON.parse(line); if (!e.key || !e.type) continue; + e.files = Array.isArray(e.files) ? e.files.map(String) : typeof e.files === 'string' ? [e.files] : []; // Apply confidence decay: observed/inferred lose 1pt per 30 days let conf = e.confidence || 5; @@ -182,12 +183,16 @@ for (const taggedLine of lines) { } catch {} } -// Dedup: latest winner per key+type +// Dedup: latest winner per key+type. This project's own entry always beats +// another project's entry for the same key+type, whatever their dates: other +// projects add learnings, they never replace this project's answer. const seen = new Map(); for (const e of entries) { const dk = e.key + '|' + e.type; const existing = seen.get(dk); - if (!existing || new Date(e.ts) > new Date(existing.ts)) { + const ownBeatsCross = existing && existing._crossProject && !e._crossProject; + const sameOrigin = existing && existing._crossProject === e._crossProject; + if (!existing || ownBeatsCross || (sameOrigin && new Date(e.ts) > new Date(existing.ts))) { seen.set(dk, e); } } @@ -202,7 +207,7 @@ if (type) results = results.filter(e => e.type === type); // must not become a sort key. const tokenHits = new Map(); if (queryTokens.length > 0) results = results.filter(e => { - const haystacks = [String(e.key || '').toLowerCase(), String(e.insight || '').toLowerCase(), ...(Array.isArray(e.files) ? e.files : []).map(f => String(f).toLowerCase())]; + const haystacks = [String(e.key || '').toLowerCase(), String(e.insight || '').toLowerCase(), ...e.files.map(f => f.toLowerCase())]; const hits = [...new Set(queryTokens)].filter(tok => haystacks.some(h => h.includes(tok))).length; tokenHits.set(e, hits); return hits > 0; @@ -245,8 +250,8 @@ for (const [t, arr] of Object.entries(byType)) { console.log('## ' + t.charAt(0).toUpperCase() + t.slice(1) + 's'); for (const e of arr) { const cross = e._crossProject ? ' [cross-project]' : ''; - const files = e.files?.length ? ' (files: ' + e.files.join(', ') + ')' : ''; - console.log('- [' + e.key + '] (confidence: ' + e._effectiveConfidence + '/10, ' + e.source + ', ' + (e.ts || '').split('T')[0] + ')' + cross); + const files = e.files.length ? ' (files: ' + e.files.join(', ') + ')' : ''; + console.log('- [' + e.key + '] (confidence: ' + e._effectiveConfidence + '/10, ' + e.source + ', ' + String(e.ts || '').split('T')[0] + ')' + cross); console.log(' ' + e.insight + files); } console.log(''); diff --git a/bin/gstack-timeline-log b/bin/gstack-timeline-log index f9564b48409..5e36671551d 100755 --- a/bin/gstack-timeline-log +++ b/bin/gstack-timeline-log @@ -56,14 +56,13 @@ case "$VALIDATE_OUT" in *) echo "gstack-timeline-log: bun printed no verdict while validating the event; nothing was logged" >&2; exit 1 ;; esac -# Inject timestamp if not present -if ! printf '%s' "$INPUT" | bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e "const j=JSON.parse(await Bun.stdin.text()); if(!j.ts) process.exit(1)" 2>/dev/null; then - STAMPED=$(printf '%s' "$INPUT" | bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e " - const j = JSON.parse(await Bun.stdin.text()); - j.ts = new Date().toISOString(); - console.log(JSON.stringify(j)); - " 2>/dev/null) && [ -n "$STAMPED" ] && INPUT=$STAMPED || true -fi +# Inject timestamp if not present, and store the event as one line: a +# multi-line event appended as given is unreadable to every JSONL reader. +STAMPED=$(printf '%s' "$INPUT" | bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e " + const j = JSON.parse(await Bun.stdin.text()); + if (!j.ts) j.ts = new Date().toISOString(); + console.log(JSON.stringify(j)); +" 2>/dev/null) && [ -n "$STAMPED" ] && INPUT=$STAMPED || true echo "$INPUT" >> "$GSTACK_HOME/projects/$SLUG/timeline.jsonl" diff --git a/test/gstack-learnings-search.test.ts b/test/gstack-learnings-search.test.ts index 90b6533ade9..0bdd46c3e1d 100644 --- a/test/gstack-learnings-search.test.ts +++ b/test/gstack-learnings-search.test.ts @@ -95,6 +95,39 @@ describe('gstack-learnings-search cross-project trust gating', () => { // B5 (#2790): both query scripts ended in `2>/dev/null || exit 0`, so a // missing bun or a crashed embedded script printed nothing and exited 0, // exactly like "nothing recorded". +// Value: protects=with cross-project learnings on (the recommended answer), a review or QA run still reads this +// project's own learning for a key; fails_when=a newer trusted learning with the same key+type in another project +// replaces this project's entry, so the agent is told another repo's answer (pytest instead of bun test); +// why_new=the latest-wins dedup ran across projects; seam=none +describe('gstack-learnings-search cross-project rows never replace this project\'s own', () => { + const ownCwd = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-search-own-cwd-')); + const ownDir = path.join(tmpHome, 'projects', path.basename(ownCwd).replace(/[^a-zA-Z0-9._-]/g, '')); + const row = (over: Record) => JSON.stringify({ skill: 'qa', type: 'tool', key: 'test-command', confidence: 9, source: 'user-stated', trusted: true, files: [], ...over }); + beforeAll(() => { + fs.mkdirSync(ownDir, { recursive: true }); + fs.writeFileSync(path.join(ownDir, 'learnings.jsonl'), [ + row({ ts: '2026-05-01T00:00:00Z', insight: 'This repo runs its tests with bun test' }), + ].join('\n') + '\n'); + fs.appendFileSync(path.join(otherProjDir, 'learnings.jsonl'), [ + row({ ts: '2026-06-01T00:00:00Z', insight: 'That repo runs its tests with pytest' }), + row({ ts: '2026-06-02T00:00:00Z', key: 'foreign-only-tool', insight: 'A tool learning only the other project has' }), + ].join('\n') + '\n'); + }); + afterAll(() => fs.rmSync(ownCwd, { recursive: true, force: true })); + const search = (args: string[]) => execFileSync(BIN, args, { timeout: 30_000, env: { ...process.env, GSTACK_HOME: tmpHome }, cwd: ownCwd, encoding: 'utf-8' }); + + test('this project\'s entry wins over a newer same-key entry from another project', () => { + const out = search(['--cross-project', '--all']); + expect(out).toContain('This repo runs its tests with bun test'); + expect(out).not.toContain('That repo runs its tests with pytest'); + }); + + test('other projects still add the keys this project lacks', () => { + const out = search(['--cross-project', '--all']); + expect(out).toMatch(/\[foreign-only-tool\].*\[cross-project\]/); + }); +}); + describe('B5: query scripts never report a failed read as an empty result', () => { const TOOLS = ['bash', 'sh', 'env', 'dirname', 'basename', 'git', 'tr', 'sed', 'cat', 'head', 'tail', 'grep', 'find', 'ls', 'mkdir', 'mktemp', 'mv', 'rm', 'cp', 'awk', 'wc', 'sort', 'uname', 'date', 'cut', 'readlink', 'realpath', 'stat', 'touch', 'id', 'printf']; @@ -231,4 +264,25 @@ describe('B6: rank by matched tokens and disclose truncation', () => { for (const k of ['healthy-0', 'healthy-1', 'healthy-2']) expect(got).toContain(k); }); } + + // Value: protects=skills read every learning at start, so one malformed row must not hide the rest; + // fails_when=a row whose files is a string or whose ts is a number crashes the + // formatter and exits 1 after printing only part of the list; why_new=gstack-learnings-log stores files and ts + // as given, so '"files":"src/a.ts"' made every later search fail; seam=none + for (const [label, over] of [ + ['files is a string', { files: 'src/a.ts' }], + ['ts is a number', { ts: 1700000000000 }], + ] as const) { + test(`a row whose ${label} cannot blank the whole store`, () => { + write(badDir, [ + row({ ts: '2026-05-01T00:00:00Z', type: 'pitfall', key: 'healthy-pitfall', insight: 'a healthy pitfall', files: ['src/b.ts'] }), + row({ key: 'malformed-row', insight: 'the malformed row', ...over }), + row({ ts: '2026-05-02T00:00:00Z', type: 'tool', key: 'healthy-tool', insight: 'a healthy tool' }), + ]); + const r = runIn(badCwd, ['--all']); + expect(r.status).toBe(0); + expect(keys(r.stdout)).toEqual(expect.arrayContaining(['healthy-pitfall', 'healthy-tool'])); + expect(r.stdout).toContain('(files: src/b.ts)'); + }); + } }); diff --git a/test/learnings.test.ts b/test/learnings.test.ts index 200ce5a3164..5d33dd53ef4 100644 --- a/test/learnings.test.ts +++ b/test/learnings.test.ts @@ -254,6 +254,13 @@ describe('gstack-learnings-log edge cases', () => { const parsed = JSON.parse(fs.readFileSync(f!, 'utf-8').trim()); expect(parsed.files).toEqual(['src/auth.ts', 'src/db.ts']); }); + + test('stores a single files string as a one-item list', () => { + runLog(JSON.stringify({ skill: 'review', type: 'pitfall', key: 'files-string', insight: 'test', confidence: 7, source: 'observed', files: 'src/auth.ts' })); + + const parsed = JSON.parse(fs.readFileSync(findLearningsFile()!, 'utf-8').trim()); + expect(parsed.files).toEqual(['src/auth.ts']); + }); }); describe('gstack-learnings-search edge cases', () => { @@ -303,6 +310,18 @@ describe('gstack-learnings-search edge cases', () => { expect(output).not.toContain('no-type'); }); + test('a stored row whose files is not a list does not break the search', () => { + runLog(JSON.stringify({ skill: 'review', type: 'pattern', key: 'good-row', insight: 'good entry', confidence: 7, source: 'observed' })); + const f = findLearningsFile(); + expect(f).not.toBeNull(); + fs.appendFileSync(f!, JSON.stringify({ skill: 'review', type: 'pitfall', key: 'string-files', insight: 'files as a string', confidence: 7, source: 'observed', files: 'src/auth.ts', ts: new Date().toISOString() }) + '\n'); + + const output = runSearch(); + expect(output).toContain('good-row'); + expect(output).toContain('[string-files]'); + expect(output).toContain('files as a string (files: src/auth.ts)'); + }); + test('confidence decay floors at 0 (never negative)', () => { // Entry from 1 year ago with confidence 3 — decay would be 12, clamped to 0 const ts = new Date(Date.now() - 365 * 86400000).toISOString(); diff --git a/test/timeline.test.ts b/test/timeline.test.ts index 0f7bc90857f..1456ceb4688 100644 --- a/test/timeline.test.ts +++ b/test/timeline.test.ts @@ -128,6 +128,15 @@ describe('gstack-timeline-log', () => { expect(parsed.ts).toBe('2025-06-15T10:00:00Z'); }); + test('a multi-line event with its own ts is stored as one line and read back', () => { + runLog(JSON.stringify({ skill: 'review', event: 'completed', branch: 'main', ts: new Date().toISOString() }, null, 2)); + + const lines = fs.readFileSync(findTimelineFile()!, 'utf-8').trim().split('\n'); + expect(lines).toHaveLength(1); + expect(JSON.parse(lines[0]).skill).toBe('review'); + expect(runRead()).toContain('/review completed'); + }); + test('validates required fields (skill, event) - exits 0 if missing skill', () => { const result = runLog('{"event":"started","branch":"main"}'); expect(result.exitCode).toBe(0); From 205ccbb04f8b119018dfa417148bc8819c360ace Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 26 Nov 2026 14:37:15 +0000 Subject: [PATCH 2/7] make-pdf: quotes that open a paragraph or heading curl the right way, and wide SVGs are measured by width, not stroke-width Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- make-pdf/src/image-size.ts | 2 +- make-pdf/src/smartypants.ts | 32 +++++++++++++++++++++++++++++- make-pdf/test/image-policy.test.ts | 6 ++++++ make-pdf/test/render.test.ts | 28 ++++++++++++++++++++++++++ 4 files changed, 66 insertions(+), 2 deletions(-) diff --git a/make-pdf/src/image-size.ts b/make-pdf/src/image-size.ts index e4690c1b8c7..15219c8e736 100644 --- a/make-pdf/src/image-size.ts +++ b/make-pdf/src/image-size.ts @@ -105,7 +105,7 @@ export function svgTagDims(markup: string): { width: number; height: number } | const tag = markup.match(/]*>/i)?.[0]; if (!tag) return null; const attr = (name: string): number | null => { - const m = tag.match(new RegExp(`\\b${name}\\s*=\\s*["']\\s*([0-9.]+)(px)?\\s*["']`, "i")); + const m = tag.match(new RegExp(`(?,
  • ,

    ) + * or the start of the document opens, an inline tag that wraps text (, + * ) is skipped, and anything else (code, a URL, an image, an unknown tag) + * counts as a word. Each run is transformed behind a one-character prefix + * that stands for that context; every rule keeps the character before its + * match, so the prefix comes back unchanged and is cut. + */ +function transformSegments(s: string, preserved: string[]): string { + let context = " "; + return s.split(PLACEHOLDER_SPLIT_RE).map((part, i) => { + if (i % 2 === 1) { + const zone = preserved[parseInt(part.slice("\u0000SMARTPANTS_PRESERVED_".length), 10)] ?? ""; + if (BLOCK_TAG_RE.test(zone)) context = " "; + else if (!INLINE_TAG_RE.test(zone)) context = "x"; + return part; + } + if (!part) return part; + const out = transformText(context + part).slice(1); + context = OPENING_CONTEXT_RE.test(part[part.length - 1]!) ? " " : "x"; + return out; + }).join(""); +} + /** * Transform plain text (no HTML, no code, no URLs). * diff --git a/make-pdf/test/image-policy.test.ts b/make-pdf/test/image-policy.test.ts index 869a6a0af64..f9996a8c43f 100644 --- a/make-pdf/test/image-policy.test.ts +++ b/make-pdf/test/image-policy.test.ts @@ -207,6 +207,12 @@ describe("auto-landscape: diagram figures", () => { ); expect(r.hasLandscape).toBe(true); }); + // stroke-width="2" sat before width= on the root, and the width lookup + // matched inside it: a 3000px diagram measured 2px wide and stayed portrait. + test("measures width and height, not stroke-width or data-height", () => { + const r = applyImagePolicy(fig(`stroke-width="2" data-height="9" width="3000" height="600"`), OPTS); + expect(r.hasLandscape).toBe(true); + }); test("diagnostic blocks are never promoted", () => { const html = ``; const r = applyImagePolicy(html, OPTS); diff --git a/make-pdf/test/render.test.ts b/make-pdf/test/render.test.ts index c4795558ecb..a76ea4d5b40 100644 --- a/make-pdf/test/render.test.ts +++ b/make-pdf/test/render.test.ts @@ -84,6 +84,34 @@ describe("smartypants", () => { expect(out).toContain(""); }); + // A quote that opens a paragraph, heading or list item sits right after a + // tag, and was read as a closing quote: "Hello," rendered as ”Hello,”. + test("opens a quote at the start of a paragraph, heading or list item", () => { + expect(smartypants(`

    "Hello," she said.

    `)).toBe(`

    \u201cHello,\u201d she said.

    `); + expect(smartypants(`

    "Quoted" title

    `)).toBe(`

    \u201cQuoted\u201d title

    `); + expect(smartypants(`
      \n
    • 'one'
    • \n
    `)).toBe(`
      \n
    • \u2018one\u2019
    • \n
    `); + expect(smartypants(`

    x

    "y"

    `)).toBe(`

    x

    \u201cy\u201d

    `); + expect(smartypants(`

    "quoted" word

    `)).toBe(`

    \u201cquoted\u201d word

    `); + }); + + test("reads a quote after an inline tag by the text before the tag", () => { + expect(smartypants(`

    He said "stop" twice.

    `)).toBe(`

    He said \u201cstop\u201d twice.

    `); + expect(smartypants(`

    Garry's book

    `)).toBe(`

    Garry\u2019s book

    `); + }); + + test("a quote after an image or an unknown tag still closes", () => { + expect(smartypants(`

    "check out " today

    `)).toBe(`

    \u201ccheck out \u201d today

    `); + expect(smartypants(`

    "see " here

    `)).toBe(`

    \u201csee \u201d here

    `); + }); + + test("renders a document whose paragraph and heading open with a quote", () => { + const html = render({ markdown: `# "Quoted" title\n\n"Hello," she said.\n` }).html; + expect(html).toContain(`\u201cQuoted\u201d title`); + expect(html).toContain(`

    \u201cHello,\u201d she said.

    `); + expect(html).not.toContain(`\u201dQuoted`); + expect(html).not.toContain(`\u201dHello`); + }); + test("does NOT touch HTML attribute values", () => { const out = smartypants(`link`); expect(out).toContain(`href="it's-a-test.html"`); From b227329e0d906446dfe3e6355cb036492f156ecf Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 26 Nov 2026 14:42:51 +0000 Subject: [PATCH 3/7] make-pdf removes javascript: links written with tabs, line breaks or entity letters Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- ...make-pdf-sanitizer-gaps-and-small-fixes.md | 10 +++ make-pdf/src/render.ts | 38 ++++++-- make-pdf/src/smartypants.ts | 12 ++- make-pdf/test/render.test.ts | 89 ++++++++++++++++++- 4 files changed, 135 insertions(+), 14 deletions(-) create mode 100644 changelog.d/make-pdf-sanitizer-gaps-and-small-fixes.md diff --git a/changelog.d/make-pdf-sanitizer-gaps-and-small-fixes.md b/changelog.d/make-pdf-sanitizer-gaps-and-small-fixes.md new file mode 100644 index 00000000000..b58a68a2dfe --- /dev/null +++ b/changelog.d/make-pdf-sanitizer-gaps-and-small-fixes.md @@ -0,0 +1,10 @@ +--- +important: security +--- +**make-pdf removes `javascript:` links however they're spelled.** Untrusted Markdown could still produce a live `javascript:` link in the HTML make-pdf prints by putting a tab or line break inside the scheme (`java script:`) or by writing its letters as entities (`javascript:`). Those links now become harmless `#` fragments. Two smaller fixes in the same code: removing a click handler whose value contains `>` no longer mangles the rest of the tag, and an entity such as `Ϋ` that only starts like a colon no longer rewrites an ordinary link. + +- **Quotes at the start of a paragraph, heading, list item or table cell now curl the right way in make-pdf.** `"Hello," she said` used to render as `”Hello,”`, including in the page title and running header. +- **Wide SVG diagrams get a landscape page again.** make-pdf read an SVG's `stroke-width` (or `data-height`) as its size, so a 3000px-wide diagram looked 2px wide and stayed on a portrait page. +- **One malformed learning no longer breaks every later `gstack-learnings-search`.** A row with `files` saved as a single string (or `ts` as a number) crashed the search until someone edited the file by hand. Search now reads those rows, and `gstack-learnings-log` stores a single path as a one-item list. +- **Cross-project learnings add to this project's own and never replace them.** A newer learning with the same key from another repo used to replace this repo's answer, for example its test command. +- **A pretty-printed timeline event that already has a timestamp is saved as one line**, so `gstack-timeline-read` no longer skips it without a word. diff --git a/make-pdf/src/render.ts b/make-pdf/src/render.ts index 5564d8e3f81..4892e072a16 100644 --- a/make-pdf/src/render.ts +++ b/make-pdf/src/render.ts @@ -251,11 +251,12 @@ function sanitizePass(html: string): string { // handler's name is always removed, even before a value that starts with // "<" (onerror=