diff --git a/bin/gstack-learnings-log b/bin/gstack-learnings-log index 1e9fb33e94..c7727ee6ef 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 b1eb3e5a37..67c0a8f2a9 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 f9564b4840..5e36671551 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/bin/gstack-timeline-read b/bin/gstack-timeline-read index 35db5fb46a..fd13e235ca 100755 --- a/bin/gstack-timeline-read +++ b/bin/gstack-timeline-read @@ -154,7 +154,7 @@ if (countStr) { console.log(''); console.log('## Recent Events'); for (const e of recent) { - const ts = (e.ts || '').replace('T', ' ').replace(/\.\d+Z$/, 'Z'); + const ts = String(e.ts || '').replace('T', ' ').replace(/\.\d+Z$/, 'Z'); const dur = e.duration_s ? ' (' + e.duration_s + 's)' : ''; const outcome = e.outcome ? ' [' + e.outcome + ']' : ''; console.log('- ' + ts + ' /' + e.skill + ' ' + e.event + outcome + dur + (e.branch ? ' on ' + e.branch : '')); 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 0000000000..b37e4bc422 --- /dev/null +++ b/changelog.d/make-pdf-sanitizer-gaps-and-small-fixes.md @@ -0,0 +1,10 @@ +--- +important: security +--- +**make-pdf removes `javascript:` links spelled with tabs, line breaks or entity letters.** 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 are printed on a sideways 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 an upright 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/image-size.ts b/make-pdf/src/image-size.ts index e4690c1b8c..15219c8e73 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(`(?]/.test(str[i]!)) i++; + while (i < offset) { + if (/[\s/]/.test(str[i]!)) { i++; continue; } + if (str[i] === ">") return false; + while (i < offset && !/[\s/>=]/.test(str[i]!)) i++; + if (i === offset) return endsAtSpace; + let j = i; + while (j < offset && /\s/.test(str[j]!)) j++; + if (str[j] !== "=") continue; + j++; + while (j < offset && /\s/.test(str[j]!)) j++; + if (j >= offset) return false; + const q = str[j]; + if (q === '"' || q === "'") { + const close = str.indexOf(q, j + 1); + if (close === -1 || close >= offset) return false; + i = close + 1; + continue; + } + while (j < offset && !/[\s>]/.test(str[j]!)) j++; + if (j === offset) return endsAtSpace; + i = j; + } + return true; +} + function sanitizePass(html: string): string { let s = html; @@ -253,9 +289,14 @@ function sanitizePass(html: string): string { // whole page, text included, so "/on…=" inside a URL or code goes too. // A quoted value goes with its name only when it holds no "<" or ">": // otherwise the quote may belong to a later element, so the last rule - // removes just the name and the rest stays where it was. + // removes just the name and the rest stays where it was. A value holding + // ">" but no "<" also goes when the handler starts an attribute of the tag + // it sits in (
); inside another attribute's + // value (title="docs/onload='x">…') the quote may be text, so it stays. s = s.replace(/(?:\s+|(?<=[/"']))on[a-zA-Z]+\s*=\s*"[^"<>]*"/gi, ""); s = s.replace(/(?:\s+|(?<=[/"']))on[a-zA-Z]+\s*=\s*'[^'<>]*'/gi, ""); + s = s.replace(/(?:\s+|(?<=[/"']))on[a-zA-Z]+\s*=\s*(?:"[^"<]*"|'[^'<]*')/gi, (m, offset: number, str: string) => + startsAttribute(str, offset) ? "" : m); s = s.replace(/(?:\s+|(?<=[/"']))on[a-zA-Z]+\s*=\s*[^\s>"'`<]*/gi, ""); // javascript: URLs in href/src/action/formaction (same attribute starts). @@ -264,8 +305,9 @@ function sanitizePass(html: string): string { '$1"#"', ); // Any other javascript: value (unquoted, or quoted around "<" or ">") loses - // only its scheme, so no quote is added or removed. - s = s.replace(/([\s/"']\s*(?:href|src|action|formaction|xlink:href)\s*=\s*["']?[\s\x01-\x20]*)javascript(?::|:|�*58;?|�*3a;?)/gi, "$1#"); + // only its scheme, so no quote is added or removed. A numeric reference + // with more digits after 58 or 3a is another character, not a colon. + s = s.replace(/([\s/"']\s*(?:href|src|action|formaction|xlink:href)\s*=\s*["']?[\s\x01-\x20]*)javascript(?::|:|�*58(?![0-9]);?|�*3a(?![0-9a-f]);?)/gi, "$1#"); // srcdoc attribute (iframe escape hatch — already stripped via iframe above, // but defense-in-depth). @@ -354,6 +396,28 @@ function sanitizePass(html: string): string { return NAMED_REFS[legacy]; }); + // javascript: spelled the way only the browser reads it: entity letters + // (javascript:), or a tab or line break anywhere in the scheme, which + // URL parsing drops (java script:). Decode the start of each URL + // attribute value as the parser will, drop tabs and line breaks, and when + // it is still javascript: put "#" in front, which makes the whole value a + // fragment. Only the name and the opening quote are matched, so a quote + // that really closes an earlier attribute can't hide a later value, and no + // quote is added or removed. A value longer than the window that is still + // nothing but padding and the start of "javascript:" counts as one. + s = s.replace(/(?<=[\s/"'])(\s*(?:href|src|action|formaction|xlink:href)\s*=\s*)(["']?)/gi, + (m, pre, q, offset: number, str: string) => { + const start = offset + m.length; + let end = q ? str.indexOf(q, start) : str.slice(start, start + 2048).search(/[\s>]/); + end = end === -1 ? str.length : q ? end : start + end; + const truncated = end - start > 2048; + let value = str.slice(start, Math.min(end, start + 2048)); + if (truncated) value = value.replace(/&[#\w]*$/, ""); + const url = decodeStyleAttrEntities(value).replace(/[\t\n\r]/g, "").replace(/^[\x00-\x20]+/, "").toLowerCase(); + const live = url.startsWith("javascript:") || (truncated && "javascript:".startsWith(url)); + return live ? `${pre}${q}#` : m; + }); + // Inline style attributes — quoted AND unquoted. HTML spec: an unquoted // attribute value runs until whitespace or `>`, so //
is live markup Chromium honors; diff --git a/make-pdf/src/smartypants.ts b/make-pdf/src/smartypants.ts index 62a537b6aa..b679e3a09d 100644 --- a/make-pdf/src/smartypants.ts +++ b/make-pdf/src/smartypants.ts @@ -54,7 +54,7 @@ export function smartypants(html: string): string { s = carve(s, TAG_RE); s = carve(s, URL_RE); - s = transformText(s); + s = transformSegments(s, preserved); // Step 2: restore preserved zones. // Use a function to avoid $-substitution gotchas. @@ -65,6 +65,43 @@ export function smartypants(html: string): string { return s; } +const PLACEHOLDER_SPLIT_RE = /(\u0000SMARTPANTS_PRESERVED_\d+\u0000)/; +const BLOCK_TAG_RE = /^<\/?(?:address|article|aside|blockquote|br|caption|dd|div|dl|dt|figcaption|figure|footer|h[1-6]|header|hr|li|main|nav|ol|p|pre|section|table|tbody|td|tfoot|th|thead|tr|ul)\b/i; +const INLINE_TAG_RE = /^<\/?(?:a|abbr|b|cite|del|dfn|em|i|ins|mark|q|s|small|span|strong|sub|sup|u)\b/i; +const QUOTE_START_RE = /^(?:["']|"|'|'|')/; +const OPENING_CONTEXT_RE = /[\s\(\[\{\-\uff1a\uff08\u3010\u300c\u300e\u3008\u300a]/; + +/** + * Transform each run of text between placeholders, reading a quote at the + * start of a run by the visible text before it: a block tag (

,

  • ,

    ) + * 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. A run that starts with a quote is transformed behind a + * one-character prefix that stands for that context; any other run keeps the + * placeholder's own character before it, so "--flag" at the start of a cell + * stays as it was, and a run that ends before a placeholder keeps that + * character after it, so "wait --" before a tag does too. No rule changes the + * character before or after its match, so both come back unchanged and are cut. + */ +function transformSegments(s: string, preserved: string[]): string { + let context = " "; + const parts = s.split(PLACEHOLDER_SPLIT_RE); + return parts.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 prefix = QUOTE_START_RE.test(part) ? context : i === 0 ? "" : "\u0000"; + const suffix = i < parts.length - 1 ? "\u0000" : ""; + const out = transformText(prefix + part + suffix).slice(prefix.length, suffix ? -1 : undefined); + 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 869a6a0af6..f9996a8c43 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 c4795558ec..445cf1bfdf 100644 --- a/make-pdf/test/render.test.ts +++ b/make-pdf/test/render.test.ts @@ -84,6 +84,44 @@ 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 flag at the start of a cell, list item or bold run keeps its dashes", () => { + expect(smartypants(`--og
  • --check
  • --resume

    `)) + .toBe(`--og
  • --check
  • --resume

    `); + }); + + test("dashes at the end of a run before a tag keep their dashes", () => { + expect(smartypants(`

    wait --

    run --x

    `)) + .toBe(`

    wait --

    run --x

    `); + }); + + 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"`); @@ -382,16 +420,22 @@ function browserAttrs(html: string): Array<{ tag: string; name: string; value: s } function decodeAttr(v: string): string { - return v.replace(/&(?:#x([0-9a-f]+)|#(\d+)|(quot|apos|amp));?/gi, (_m, hex, dec, named) => + return v.replace(/&(?:#x([0-9a-f]+)|#(\d+)|(quot|apos|amp)|(Tab|NewLine|colon););?/gi, (m, hex, dec, named, withSemi) => hex ? String.fromCodePoint(parseInt(hex, 16)) : dec ? String.fromCodePoint(parseInt(dec, 10)) - : ({ quot: '"', apos: "'", amp: "&" } as Record)[named.toLowerCase()]!); + : named ? ({ quot: '"', apos: "'", amp: "&" } as Record)[named.toLowerCase()]! + : ({ Tab: "\t", NewLine: "\n", colon: ":" } as Record)[withSemi] ?? m); +} + +/** A URL the way the browser reads it: decoded, tabs and line breaks removed. */ +function browserUrl(v: string): string { + return decodeAttr(v).replace(/[\t\n\r]/g, ""); } function liveScript(html: string): string[] { return browserAttrs(html) .filter((a) => a.name.startsWith("on") || - (/^(?:href|src|xlink:href|action|formaction)$/.test(a.name) && /^\s*javascript:/i.test(decodeAttr(a.value)))) + (/^(?:href|src|xlink:href|action|formaction)$/.test(a.name) && /^[\x00-\x20]*javascript:/i.test(browserUrl(a.value)))) .map((a) => `<${a.tag} ${a.name}=${a.value}>`); } @@ -509,6 +553,91 @@ describe("render() — characters dropped after sanitizing cannot revive script" }); }); +describe("sanitizeUntrustedHtml — handlers and javascript: links in any spelling the browser reads", () => { + // A ">" inside a quoted handler value is still part of that value, so the + // whole handler goes and the attributes after it stay. + test("a handler whose quoted value holds > is removed with its value", () => { + expect(sanitizeUntrustedHtml(`
    Keep me
    `)) + .toBe(`
    Keep me
    `); + expect(sanitizeUntrustedHtml(`
    Keep me
    `)) + .toBe(`
    Keep me
    `); + expect(sanitizeUntrustedHtml(``)) + .toBe(``); + }); + + // Handler-looking text inside another attribute's value is not an + // attribute, so a quote after it may be text: only the name goes. + test("handler text inside an attribute value never swallows the text after the tag", () => { + const out = sanitizeUntrustedHtml(`
    Keep me ' and the rest
    `); + expect(out).toContain("Keep me ' and the rest

  • "); + expect(liveScript(out)).toEqual([]); + }); + + // Ϋ is the character U+03AB, not a colon followed by "b". + test("an entity that only starts like a colon is left alone", () => { + for (const href of ["javascriptΫguide", "javascriptᜋguide", "javascriptΠx"]) { + const html = `g`; + expect(sanitizeUntrustedHtml(html)).toBe(html); + } + expect(liveScript(sanitizeUntrustedHtml(`g`))).toEqual([]); + expect(liveScript(sanitizeUntrustedHtml(`g`))).toEqual([]); + }); + + // Browsers drop tabs and line breaks from a URL and decode entities first, + // so all of these still run as javascript: links. + test("javascript: written with tabs, line breaks or entity letters is neutralized", () => { + const spellings = [ + "java\tscript:alert(1)", "java\nscript:alert(1)", "java\rscript:alert(1)", + "java script:alert(1)", "java script:alert(1)", "java script:alert(1)", "java script:alert(1)", + "javascript:alert(1)", "javascript:alert(1)", "javascript:alert(1)", + " javascript:alert(1)", "javascript:alert(1)", + ]; + for (const v of spellings) { + for (const attr of [`href="${v}"`, `href='${v}'`, `src="${v}"`, `formaction="${v}"`]) { + const out = sanitizeUntrustedHtml(`j`); + expect(liveScript(out)).toEqual([]); + expect(out).toContain(">j"); + } + if (!/\s/.test(v)) expect(liveScript(sanitizeUntrustedHtml(`j`))).toEqual([]); + } + }); + + test("a javascript: value holding < or > keeps its quotes and loses its scheme", () => { + const out = sanitizeUntrustedHtml(`j

    after

    `); + expect(liveScript(out)).toEqual([]); + expect(attrsOf(out, "a")).toEqual(["href", "title"]); + expect(out).toContain("

    after

    "); + }); + + test("a later attribute is checked even when an earlier quote pairs with it", () => { + const out = sanitizeUntrustedHtml(`

    x

    j`); + expect(liveScript(out)).toEqual([]); + for (const v of ["javascript:alert(1)", "java script:alert(1)"]) { + expect(liveScript(sanitizeUntrustedHtml(`b`))).toEqual([]); + } + }); + + test("ordinary links are untouched", () => { + const html = `atj`; + expect(sanitizeUntrustedHtml(html)).toBe(html); + }); + + test("render() neutralizes the same spellings in raw HTML and links", () => { + const md = [ + "
    ", + `a`, + `b`, + "
    ", + "", + "[c](java script:alert(1)) [d](javascript:alert(1))", + "", + ].join("\n"); + const html = render({ markdown: md }).bodyHtml; + expect(liveScript(html)).toEqual([]); + for (const t of [">a", ">b"]) expect(html).toContain(t); + }); +}); + describe("render() — removing script keeps the page's structure", () => { test("handler-looking text inside a quoted attribute never eats the elements after it", () => { for (const md of [ diff --git a/test/gstack-learnings-search.test.ts b/test/gstack-learnings-search.test.ts index 90b6533ade..0bdd46c3e1 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 200ce5a316..5d33dd53ef 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 0f7bc90857..c0eb76b8e2 100644 --- a/test/timeline.test.ts +++ b/test/timeline.test.ts @@ -128,6 +128,24 @@ 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('an event whose ts is a number does not stop the read', () => { + runLog(JSON.stringify({ skill: 'review', event: 'completed', branch: 'main', ts: 1764160000000 })); + runLog(JSON.stringify({ skill: 'qa', event: 'completed', branch: 'main' })); + + const out = runRead(); + expect(out).toContain('/qa completed'); + expect(out).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);