/** * Cross-provider literal pins (AC-3.13, GAP-13, [DR-08]) — P3c-S5. * * WHY A CROSS-PROVIDER FILE AND NOT THREE PER-PROVIDER ONES * --------------------------------------------------------- * Every claim here is a claim about the DIFFERENCE between providers, and a * difference cannot be asserted from inside one of its sides. `32767` present in * the Jira module is a weak fact; `32767` present in Jira and Linear and ABSENT * from GitHub is the fact §14.2 actually resolves — GAP-13's `60k`→`{cap}` * conflict is settled by "the GitHub path renders the 60k sentence VERBATIM and * every other provider renders its own cap", which is one table with three * columns and no blanks. * * The absence half is the interesting half. A provider module that names another * provider's signal has copied a backpressure MODEL across a boundary where the * model does not hold: `X-RateLimit-Remaining` is a pre-emptive remaining count * that neither tool-call provider publishes, so a rung keyed on it can never * engage and reads as coverage while providing none. Absence is therefore pinned * as hard as presence, per (provider, literal) pair, with a swapped-literal probe * driving the same collector in both directions. * * BOTH SIDES ARE READ, AND THEY ARE NOT INTERCHANGEABLE * ---------------------------------------------------- * A source-only pin is satisfied by a literal sitting in module-level prose, which * the build emits nowhere — `_linear.mds`'s `## Known Unknowns` section is exactly * such prose, and it names `32767` — so the generated tree is asserted separately. * A generated-only pin would go quiet the moment a module stopped compiling. Every * assertion below names the side it reads, and every dist read is fail-loud with a * build hint (R3). * * The [DR-08] batch negative ranges over all three providers for the same reason: * it is the direct cross-provider analogue of Phase 2's GitHub batch assertion, * and the shape table it drives lives in tests/helpers.ts so the per-provider * suites and this one cannot disagree about what a per-item fetch looks like. */ import { describe, it, expect } from 'vitest'; import { existsSync, readFileSync } from 'fs'; import * as path from 'path'; import { compiledSkillRefsDir, skillsDir } from '../src/core/assets.js'; import { MCP_BACKED_PROVIDER_SUBDIRS, MIN_VARIANT_PAIRS, TRACKER_OPS, VARIANT_MODULES, } from '../src/core/mds-variants.js'; import { PER_ITEM_FETCH_SHAPES, ROOT, collectPerItemFetchVerbs, resolveAgentSource, withoutHostSteps, } from './helpers.js'; // --------------------------------------------------------------------------- // The providers, read from the registry rather than listed // --------------------------------------------------------------------------- /** One registered tracker provider: its token, its source module, its sub-directory. */ interface Provider { readonly token: string; readonly source: string; readonly subdir: string; } /** * Every registered tracker provider. * * Derived from VARIANT_MODULES' provider rows, so a provider registered later * joins this scan by construction and the non-vacuity arm below reports one whose * literals nobody declared. */ const PROVIDERS: readonly Provider[] = VARIANT_MODULES .filter(mod => mod.kind === 'fanout' && mod.subdir.startsWith('tracker/')) .map(mod => ({ token: mod.subdir.slice('tracker/'.length), source: mod.source, subdir: mod.subdir, })); function readSource(relPath: string): string { const abs = path.join(ROOT, relPath); if (!existsSync(abs)) { throw new Error( `${relPath} is absent — a provider module named by the registry is not on disk, so every ` + `literal pin for that provider would compare against nothing`, ); } return readFileSync(abs, 'utf-8'); } function readGenerated(relPath: string): string { const abs = path.join(compiledSkillRefsDir(), ...relPath.split('/')); if (!existsSync(abs)) { throw new Error( `${relPath} is absent at ${abs} — run \`npm run build\` first (this guard reads compiled ` + `reference files and cannot be skipped)`, ); } return readFileSync(abs, 'utf-8'); } /** * The hand-authored GitHub API reference of the `devflow:git` skill. * * Read from `src/assets/skills/git/references/`, not from the compiled tree: this * file is installed as authored and the build emits nothing for it, so a reader * looking under `dist/` would find nothing and the pin would be inert. */ function readGithubApiReference(): string { const abs = path.join(skillsDir(), 'git', 'references', GITHUB_API_FILE); if (!existsSync(abs)) { throw new Error( `${GITHUB_API_FILE} is absent at ${abs} — it is the only reference a non-tracker GitHub ` + `batch op can reach, so every pin against it would compare against nothing`, ); } return readFileSync(abs, 'utf-8'); } /** The whole generated tree of one provider, concatenated. */ function providerTree(provider: Provider): string { // Without the host steps: `create-release` states GitHub's 60000-character release-notes cap, and // `ensure-pr-ready` states GitHub pull-request mechanics, under every tracker because the release // and the pull request are GitHub's whatever the tracker is (see `withoutHostSteps`). return TRACKER_OPS.map(op => withoutHostSteps(readGenerated(`${provider.subdir}/${op}.md`))).join('\n'); } // --------------------------------------------------------------------------- // The matrix: one row per literal, one cell per provider // --------------------------------------------------------------------------- /** * A literal that is a PROVIDER FACT, and which providers state it. * * `present` lists the provider tokens whose module must carry the literal; every * other registered provider must NOT. Expressing it that way rather than as a * per-provider list is what makes the matrix complete by construction: a provider * registered later is automatically in the absent set of every row until somebody * puts it in a `present` list on purpose. */ interface ProviderLiteral { readonly literal: string; readonly present: readonly string[]; readonly why: string; } const PROVIDER_LITERALS: readonly ProviderLiteral[] = [ { literal: '60000', present: ['github'], why: 'GitHub\'s comment-body cap, and the number inside the sentence §14.2 fixes as rendering ' + 'VERBATIM on the GitHub path (`NOTE: body exceeded 60k after redaction — truncated/stub ' + 'posted`). GAP-13\'s conflict is resolved by one cap per provider, so this number appearing ' + 'anywhere else is a provider quoting a cap that is not its own', }, { literal: '32767', present: ['jira', 'linear'], why: 'the tool-call providers\' comment-body cap. The truncation floor derives from it, so an ' + 'absent cap leaves the preservation order with no bound to preserve against. On Linear it ' + 'is BORROWED rather than measured, which is why that module carries `## Known Unknowns` and ' + 'a filed probe issue — the number is pinned either way, because a borrowed bound still has ' + 'to be the same bound everywhere it is stated', }, { literal: 'X-RateLimit-Remaining', present: ['github'], why: 'a PRE-EMPTIVE remaining-request count. It is the signal D4\'s backpressure rung is keyed ' + 'on, and neither tool-call provider publishes one: a module naming it states a rung that ' + 'can never engage, which reads as coverage and is none', }, { literal: 'Retry-After', present: ['jira'], why: 'Jira\'s only backpressure signal, and it is reactive: reported, never slept on, STOP on ' + '429. GitHub has the pre-emptive count instead and Linear signals through an error ' + 'body, so a second provider naming this header would be honouring a value it never receives', }, { literal: 'never slept on', present: ['jira'], why: 'the disambiguation the one DURATION-shaped backpressure signal needs. "STOP the fan-out" ' + 'beside a value an agent could wait out reads as a contradiction, and a `Retry-After` can ' + 'outlast the spawn — an agent that slept on one is killed before it reports the throttle ' + 'at all. The other two providers hand the agent no waitable value, so the clause would be ' + 'answering a question their signals never ask', }, { literal: 'RATELIMITED', present: ['linear'], why: 'Linear\'s rate-limit signal, which arrives as an HTTP 400 carrying this token rather than ' + 'as a 429. D4\'s status-shaped rule answers a generic 4xx with "degrade this item and ' + 'continue", so without this literal the fan-out runs straight into the penalty window', }, // #364 (PR5): associate-release's release MARKER is a different object per // provider, and each module names only its own. The contract names none of them // (RELEASE_MARKER_LITERALS below keeps both out of git.md and the tool-call // contract); Linear's marker is a plain label, so it owns no row here. { literal: 'fixVersion', present: ['jira'], why: 'Jira\'s release marker: a project version held in the multi-valued `fixVersions` field, ' + 'which associate-release reads and writes back as a union so another release stays. A ' + 'second provider naming it is writing a field its tracker does not have', }, { literal: 'milestone', present: ['github'], why: 'GitHub\'s release marker, and a SINGLE-valued one: associate-release never replaces it, ' + 'which is why an item holding another release is left alone there. A tool-call provider ' + 'naming it has borrowed GitHub\'s marker model, not its own', }, ]; /** * The provider literals that name a release MARKER, which the provider-neutral * half — `dist/agents/git.md` and the tool-call contract — must never name: the * contract says "the release's tracker marker" and each provider module says what * that is. Checked against the matrix above, so a row cannot be dropped from one * list and kept in the other. */ const RELEASE_MARKER_LITERALS: readonly string[] = ['fixVersion', 'milestone']; /** * Named collector: marker literals in a provider-neutral file, case-insensitive — * `Milestone` in a heading is as provider-specific as `milestone` in a step. */ export function collectNeutralMarkerLeaks(label: string, text: string): string[] { const lower = text.toLowerCase(); return RELEASE_MARKER_LITERALS .filter(literal => lower.includes(literal.toLowerCase())) .map(literal => `${label}: names "${literal}", a provider fact`); } /** Named collector: (provider, literal) pairs whose presence is wrong. */ export function collectLiteralViolations( label: string, text: string, token: string, literals: readonly ProviderLiteral[], ): string[] { return literals .filter(entry => text.includes(entry.literal) !== entry.present.includes(token)) .map(entry => `${label}: ${entry.present.includes(token) ? 'missing' : 'forbidden'} ` + `"${entry.literal}" — ${entry.why}`); } describe('provider literals: the cross-provider matrix (AC-3.13, GAP-13)', () => { it('the scan holds every registered provider and a non-empty matrix', () => { expect( PROVIDERS.length, 'fewer than three providers — the matrix\'s absence half is what makes it a matrix, and ' + 'with one column there is nothing for a literal to be absent from (GAP-42)', ).toBeGreaterThanOrEqual(3); expect( PROVIDERS.map(p => p.token).sort(), 'the provider set must come from the registry, so a provider cannot be silently omitted', ).toEqual(['github', 'jira', 'linear']); expect(PROVIDER_LITERALS.length, 'the literal matrix is empty').toBeGreaterThan(0); for (const entry of PROVIDER_LITERALS) { expect( entry.present.length, `"${entry.literal}" is present for no provider — a row nothing states is a row that ` + `forbids a literal nobody wrote`, ).toBeGreaterThan(0); expect( entry.present.every(token => PROVIDERS.some(p => p.token === token)), `"${entry.literal}" names a provider the registry does not carry`, ).toBe(true); expect(entry.why.trim().length, 'a row without a reason is a grep').toBeGreaterThan(0); } }); it('every provider module source states exactly its own literals', () => { const violations: string[] = []; for (const provider of PROVIDERS) { violations.push(...collectLiteralViolations( provider.source, readSource(provider.source), provider.token, PROVIDER_LITERALS, )); } expect( violations, `provider literal violation(s) in a module source:\n ${violations.join('\n ')}`, ).toEqual([]); }); it('and so does every provider\'s GENERATED tree, which is what a spawn reads', () => { // Not the same claim as the one above. A literal can sit in module-level prose // — `_linear.mds`'s `## Known Unknowns` names the borrowed cap there — and prose // above the first section marker is emitted nowhere, so a source-side pin alone // would be satisfied by a number no spawn ever sees. const violations: string[] = []; for (const provider of PROVIDERS) { violations.push(...collectLiteralViolations( `${provider.subdir}/**`, providerTree(provider), provider.token, PROVIDER_LITERALS, )); } expect( violations, `provider literal violation(s) across a generated tree:\n ${violations.join('\n ')}`, ).toEqual([]); }); it('known-bad probe: a swapped literal is reported in both directions', () => { // Drives the SAME collector the two arms above use, over seeded text, so a // collector that had stopped reporting anything takes this probe red with them. const smuggled = collectLiteralViolations('seed', 'cap 60000 and Retry-After honoured', 'linear', PROVIDER_LITERALS) .map(v => v.split(' — ')[0]); expect( smuggled, 'a GitHub cap smuggled into a Linear module, Jira\'s header with it, and Linear\'s own cap ' + 'and signal dropped — all four must be reported', ).toEqual([ 'seed: forbidden "60000"', 'seed: missing "32767"', 'seed: forbidden "Retry-After"', 'seed: missing "RATELIMITED"', ]); // …and the mirror: a GitHub module carrying a tool-call provider's cap. expect( collectLiteralViolations('seed', 'cap 32767; X-RateLimit-Remaining < 10 stops the fan-out; 60000; milestone', 'github', PROVIDER_LITERALS) .map(v => v.split(' — ')[0]), 'the GitHub column must reject the borrowed cap while accepting its own two signals', ).toEqual(['seed: forbidden "32767"']); // …and a fully correct row reports nothing, so the collector is not a blanket refusal. expect( collectLiteralViolations('seed', 'cap 32767; a 400 RATELIMITED stops the fan-out', 'linear', PROVIDER_LITERALS), 'a correct Linear row must be silent', ).toEqual([]); // …and the duration clause in both directions. A Jira row that names the header // while dropping "never slept on" is exactly the ambiguity the clause resolves: // STOP beside a waitable value, with nothing saying which wins. expect( collectLiteralViolations('seed', 'cap 32767; Retry-After on a 429 stops the fan-out; fixVersions', 'jira', PROVIDER_LITERALS) .map(v => v.split(' — ')[0]), 'a Jira row naming the header but dropping the do-not-sleep clause must be reported', ).toEqual(['seed: missing "never slept on"']); expect( collectLiteralViolations('seed', 'cap 32767; a 400 RATELIMITED stops the fan-out; never slept on', 'linear', PROVIDER_LITERALS) .map(v => v.split(' — ')[0]), 'a provider whose signal hands the agent no waitable value must not carry the clause', ).toEqual(['seed: forbidden "never slept on"']); }); it('known-bad probe: a release marker swapped across providers is reported in both directions', () => { // #364: each associate-release reference names its own provider's marker. expect( collectLiteralViolations('seed', 'cap 32767; Retry-After, never slept on; set the milestone', 'jira', PROVIDER_LITERALS) .map(v => v.split(' — ')[0]), 'a Jira row that assigns a milestone and never names fixVersions must be reported twice', ).toEqual(['seed: missing "fixVersion"', 'seed: forbidden "milestone"']); expect( collectLiteralViolations('seed', 'cap 32767; a 400 RATELIMITED stops the fan-out; add to fixVersions', 'linear', PROVIDER_LITERALS) .map(v => v.split(' — ')[0]), 'Linear\'s marker is a label; Jira\'s field name there is a borrowed model', ).toEqual(['seed: forbidden "fixVersion"']); expect( collectLiteralViolations('seed', 'cap 60000; X-RateLimit-Remaining < 50; a label', 'github', PROVIDER_LITERALS) .map(v => v.split(' — ')[0]), 'a GitHub row that dropped its milestone must be reported', ).toEqual(['seed: missing "milestone"']); }); }); describe('provider literals: the provider-neutral contract names no release marker (#364)', () => { function neutralCorpus(): Array<{ label: string; text: string }> { const git = resolveAgentSource('git'); return [ { label: 'agents/git.md', text: git.content }, { label: 'tracker/_mcp.md', text: readGenerated('tracker/_mcp.md') }, { label: 'src/assets/mds/tracker/_mcp.mds', text: readSource('src/assets/mds/tracker/_mcp.mds') }, // The operation contracts and inline steps every provider's reference expands (D-OP-CONTRACT-ONCE) // are provider-neutral by construction: a marker named here would be named under all three. { label: 'src/assets/mds/git/_ops.mds', text: readSource('src/assets/mds/git/_ops.mds') }, { label: 'src/assets/mds/git/_ops_steps.mds', text: readSource('src/assets/mds/git/_ops_steps.mds') }, ]; } it('every marker literal is a provider fact in the matrix, owned by exactly one provider', () => { for (const literal of RELEASE_MARKER_LITERALS) { const row = PROVIDER_LITERALS.find(entry => entry.literal === literal); expect(row, `"${literal}" has no PROVIDER_LITERALS row — nothing pins which provider owns it`).toBeDefined(); expect(row!.present, `"${literal}" must be one provider's marker`).toHaveLength(1); } }); it('git.md, the tool-call contract and the shared operation text name neither marker', () => { const corpus = neutralCorpus(); expect(corpus.every(entry => entry.text.length > 0), 'an empty neutral file clears this vacuously').toBe(true); expect( corpus.map(entry => entry.text).join('\n'), 'the corpus must hold the op whose marker this is about, or the arm reads the wrong files', ).toContain('@define associate_release_contract():'); const leaks = corpus.flatMap(entry => collectNeutralMarkerLeaks(entry.label, entry.text)); expect( leaks, `a provider's release marker named in the provider-neutral half:\n ${leaks.join('\n ')}`, ).toEqual([]); }); it('known-bad probe: a marker seeded into git.md or the contract is reported', () => { const [git, contract] = neutralCorpus(); expect(collectNeutralMarkerLeaks(git.label, `${git.text}\nAssign the release Milestone.`)) .toEqual(['agents/git.md: names "milestone", a provider fact']); expect(collectNeutralMarkerLeaks(contract.label, `${contract.text}\n| fixVersion edit | x |`)) .toEqual(['tracker/_mcp.md: names "fixVersion", a provider fact']); }); }); // --------------------------------------------------------------------------- // [DR-08] — no per-item fetch verb in any provider's batch reference // --------------------------------------------------------------------------- describe('provider literals: fetch-issues-batch is one query on every provider [DR-08]', () => { it('no provider\'s batch reference names a per-item fetch verb or capability', () => { const offenders: string[] = []; for (const provider of PROVIDERS) { const rel = `${provider.subdir}/fetch-issues-batch.md`; for (const site of collectPerItemFetchVerbs(readGenerated(rel))) { offenders.push(`${rel}:${site}`); } } expect( offenders, `a per-item fetch inside a batch reference re-grows the N+1 Phase 2 removed from GitHub, on ` + `whichever provider it appears. §14.4 fixes fetch_batch as a SINGLE-QUERY capability for ` + `every provider, and AC-3.8's parity scan cannot see the difference between one query and ` + `fifty — it asserts the file exists and is non-empty [DR-08]:\n ${offenders.join('\n ')}`, ).toEqual([]); }); it('every tool-call provider carries the bound ON ITS QUERY, with the truncation report', () => { // The positive half, and it is deliberately NOT asserted on the GitHub column. // §14.4 fixes `≤50` with `TRUNCATED` for every provider, but WHERE the bound is // stated differs with the sink: GitHub's lives in the always-loaded agent step // (`**Input:** … process at most 50`), because a `gh` invocation takes the list // the agent already trimmed. A tool-call provider's query is composed inside the // mechanics, so a bound stated only in the agent is a bound the composed query // does not carry — which is the unbounded read this arm exists to forbid. The // asymmetry is a property of the two sinks, not a gap in the table. const toolCall = PROVIDERS.filter(p => (MCP_BACKED_PROVIDER_SUBDIRS as readonly string[]).includes(p.subdir)); expect( toolCall.length, 'no tool-call provider is registered, so this arm ranges over nothing', ).toBeGreaterThan(0); for (const provider of toolCall) { const rel = `${provider.subdir}/fetch-issues-batch.md`; const content = readGenerated(rel); expect(content, `${rel}: the ≤50 bound §14.4 fixes for every provider`).toContain('≤50'); expect( content, `${rel}: over the bound the remainder must be reported, never silently dropped`, ).toContain('TRUNCATED ({n} not processed)'); } }); it('known-bad probe: both per-item shape classes are reported by the same collector', () => { // Mechanic (b) — §8.12 row 25's seeded fixture, driven through the shared // collector. Both classes are seeded, because a table covering one would pass a // probe for that one while inert against the other. const seededToolName = [ '## Operation: fetch-issues-batch', '2. For each key in the resolved list, call getJiraIssue(issueKey) and collect the result.', ].join('\n'); expect( collectPerItemFetchVerbs(seededToolName).map(v => v.split(': ')[1]), 'a tool-name per-item fetch must be reported', ).toContain('getJiraIssue'); const seededCapability = [ '## Operation: fetch-issues-batch', '2. Resolve each entry through the *fetch by key* capability, one call per issue.', ].join('\n'); expect( collectPerItemFetchVerbs(seededCapability).length, 'a capability-phrased per-item fetch must be reported too — it is the shape this repo\'s ' + 'own capability-first doctrine steers an author towards', ).toBeGreaterThan(0); // …and the shape the plural op anchor is NOT: `fetch-issues-batch` must not be // read as `fetch-issue`, or every batch reference reports itself and the arm is // unfixable. expect( collectPerItemFetchVerbs('## Operation: fetch-issues-batch'), 'the op anchor line must not be reported — the plural is not the singular', ).toEqual([]); expect(PER_ITEM_FETCH_SHAPES.length, 'the shape table is empty').toBeGreaterThan(0); }); }); // --------------------------------------------------------------------------- // backlink-shipped-issues, read as a FILE (GAP-18, M1/M4) // --------------------------------------------------------------------------- // // WHY A PER-FILE ARM WHEN THE MATRIX ABOVE ALREADY SCANS THE TREE. The matrix // concatenates each provider's ten op files, which is the right corpus for "does // this provider state its own signal and no other provider's". It cannot say // WHICH file states it, and for this one operation the file is the claim: // // - `X-RateLimit-Remaining` is the D4 full-STOP signal for the only tracker // fan-out on the GitHub path. It used to be restated on this operation's // `**Degradation (D4):**` line in the always-loaded agent, where every spawn // read a GitHub header whatever provider it had resolved — and neither // tool-call provider publishes a pre-emptive remaining count, so the rung // could not engage for two of three providers. That line now defers to the // always-loaded contract, which names "the resolved provider's reference" as // the place the signal lives. THIS is that reference, so the threshold // drifting into a sibling op file would leave the contract pointing at a file // that does not carry it — and the tree-level pin would stay green. // - the `#` strip is a shell-injection control, not a style note (GAP-18). The // pre-flight admits `^#?[1-9][0-9]{0,8}$`, so `#42` is an ADMITTED entry, and // this file is the one that interpolates the entry into `gh issue view // {number}` and `gh issue comment {number}`. A `#` at word start opens a shell // comment, so the un-normalised spelling truncates the command at the // reference — the op would stop back-linking silently rather than fail. On // main the digits-only gate in the agent made this unreachable; moving the // grammar here widened the admitted set by one normalised form, and the // normalisation is what the wider grammar owes. // // Every claim is a row with its reason, and the probe below removes each row's own // token from a copy of the file and drives the same collector over it — so a row // whose pattern has stopped matching the shipped wording cannot pass quietly. // // EVERY ROW PINS A TOKEN, NEVER A SENTENCE. These generated references are priced // against the per-provider loaded-set ceilings in tests/tracker/byte-budget.test.ts, // so a condensing pass over this prose is an expected event rather than a // hypothetical — and a row that pins a whole sentence makes the ceiling and the // guard contradict each other. The guard then loses in the only way that matters: it // goes RED naming a clause that is still present, because the rewrite moved a comma // or split one sentence into two. That pins layout rather than meaning, one level // down: where a sentence happens to break. // // So each row's shape is the shortest phrase that carries its claim, and a claim // with two halves is TWO rows rather than one ordered regex with a bridge between // them: a bridge of hand-picked width has no contract behind it, and it silently // encodes the punctuation the halves are separated by today. Two constraints on the // token itself, both load-bearing here: it must be UNIQUE in the file, or the probe // below deletes one occurrence and the row stays green over the other; and it must // not be a phrase the file uses elsewhere in another sense — `before the loop` reads // as the normalisation rule and again in the `**Setup (once, before the loop)**` // heading, so pinning it would let the rule be deleted while the heading kept the // row green. /** One token a generated reference owes, and the shape that recognises it. */ interface FileClaim { readonly label: string; readonly pattern: RegExp; readonly why: string; } const GITHUB_BACKLINK_FILE = 'tracker/github/backlink-shipped-issues.md'; const GITHUB_API_FILE = 'github-api.md'; const GITHUB_BACKLINK_CLAIMS: readonly FileClaim[] = [ { label: 'the normalisation happens once', pattern: /[Nn]ormalise once/, why: 'a strip performed per-command is a strip an author can forget on one of the two commands; ' + 'the pre-flight is the single place every entry passes through', }, { label: 'and never inside the per-issue loop', pattern: /[Nn]ever inside it/, why: 'the placement half of the same rule, and the half a reader can get wrong while still ' + 'normalising "once" per iteration. Pinned separately because a condensing pass may keep ' + 'either clause and drop the other', }, { label: 'exactly one leading `#` is stripped', pattern: /[Ee]xactly one\*{0,2} leading `#`/, why: 'GAP-18: the pre-flight IS the shell-injection guard for an interpolated ref, and "exactly ' + 'one" is its bound — a greedy strip would silently accept `##42`. The emphasis markers are ' + 'optional in the shape because bolding is presentation and the bound is the claim', }, { label: 'only the stripped digits reach a command', pattern: /[Ii]nterpolate only the stripped digits/, why: 'the bound above governs nothing unless the stripped form is named as the only one that is ' + 'interpolated — that is what makes the gate cover the commands rather than just the parse', }, { label: 'the shell-comment reason the strip exists for', pattern: /opens a shell comment/, why: 'without the reason the sentence reads as cosmetic normalisation and the next condensing ' + 'pass deletes it. The failure it prevents is silent: a truncated `gh` command back-links ' + 'nothing and reports no error', }, { label: 'the anchored github reference grammar the strip normalises for', pattern: /\^#\?\[1-9]\[0-9]\{0,8}\$/, why: '§14.1 fixes this provider\'s grammar, anchored at both ends. The `#?` is why a ' + 'normalisation is owed at all: an anchored digits-only grammar would need none', }, { label: "GitHub's full-STOP rate-limit threshold", pattern: /`X-RateLimit-Remaining` header < 10/, why: 'D4 says STOP rather than wait, and the always-loaded contract defers the signal to this ' + 'reference. Stated anywhere else, the contract points at a file that does not carry it', }, ]; /** Named collector: claims the text does not make. */ export function collectMissingFileClaims( label: string, text: string, claims: readonly FileClaim[], ): string[] { return claims .filter(claim => !claim.pattern.test(text)) .map(claim => `${label}: missing ${claim.label} — ${claim.why}`); } describe('provider literals: the github backlink reference, per file (GAP-18)', () => { it('states the strip-one-`#` normalisation before it interpolates, and its own STOP threshold', () => { const violations = collectMissingFileClaims( GITHUB_BACKLINK_FILE, readGenerated(GITHUB_BACKLINK_FILE), GITHUB_BACKLINK_CLAIMS, ); expect( violations, `the github backlink reference is missing sentence(s) it owes:\n ${violations.join('\n ')}`, ).toEqual([]); }); it('known-bad probe: each claim, deleted from a copy, is reported by the same collector', () => { // Mechanic (b): the bad shape is built inside this `it` from the shipped bytes, // so no committed file is touched to show red. Per ROW rather than once, because // a table is only as good as the shapes it can be SHOWN to express — // and a row whose pattern drifted off the shipped wording would otherwise sit // here matching nothing while the main arm passed on the other four. const pristine = readGenerated(GITHUB_BACKLINK_FILE); expect( collectMissingFileClaims('pristine', pristine, GITHUB_BACKLINK_CLAIMS), 'the collector must be silent on the shipped file, or the probe below proves nothing', ).toEqual([]); for (const claim of GITHUB_BACKLINK_CLAIMS) { const wounded = pristine.replace(claim.pattern, ''); expect( wounded, `the pattern for "${claim.label}" matched nothing in the shipped file, so deleting it was ` + `a no-op and the row cannot be shown live`, ).not.toBe(pristine); expect( collectMissingFileClaims('wounded', wounded, GITHUB_BACKLINK_CLAIMS) .map(v => v.split(' — ')[0]), `removing "${claim.label}" must be reported by the same collector`, ).toContain(`wounded: missing ${claim.label}`); } expect(GITHUB_BACKLINK_CLAIMS.length, 'the claim table is empty').toBeGreaterThan(0); }); it('the STOP threshold is stated on the github path ONLY, per file and never in the agent', () => { // The absence half, narrowed from the tree to the file — and extended to the // WHOLE always-loaded agent, which is where the misalignment lived. No operation // of git.md names a GitHub rate-limit header: D4 states the STOP rule and the // 1s → 3s bound provider-neutrally, and both thresholds are GitHub facts that // belong in a GitHub reference. The two batch ops D4 names reach them by two // routes — `backlink-shipped-issues` through its generated tracker mechanics, // `resolve-review-threads` (a non-tracker op, so it has none) through // `references/github-api.md`, which SKILL.md's always-loaded throttling row names. const toolCall = PROVIDERS.filter( p => (MCP_BACKED_PROVIDER_SUBDIRS as readonly string[]).includes(p.subdir), ); expect(toolCall.length, 'no tool-call provider is registered').toBeGreaterThan(0); for (const provider of toolCall) { const rel = `${provider.subdir}/backlink-shipped-issues.md`; expect( readGenerated(rel), `${rel} names a pre-emptive remaining count this provider never sends — a rung keyed on ` + `it can never engage, which reads as coverage and is none`, ).not.toContain('X-RateLimit-Remaining'); } const git = resolveAgentSource('git'); expect( git.content.length, 'the agent measured 0 characters — the absence assertion below would pass by reading nothing', ).toBeGreaterThan(0); expect( git.content, `${git.path}: always-loaded text names GitHub's rate-limit header. Every spawn loads it ` + `whatever provider it resolved, and two of three providers publish no such count — the ` + `signal belongs in ${GITHUB_BACKLINK_FILE} for the tracker fan-out and in ` + `${GITHUB_API_FILE} for the review-thread batch, both of which the always-loaded D4 ` + `contract and the git skill defer to`, ).not.toContain('X-RateLimit-Remaining'); // …and the control. An absence arm is equally green on a tree scrubbed of the // thresholds entirely, which would disable backpressure rather than relocate it, // so each threshold is asserted PRESENT at the destination the arm above names. // Per destination rather than over a concatenation: a union is satisfied by one // file carrying both, which is the state this split exists to prevent. expect( readGenerated(GITHUB_BACKLINK_FILE), `${GITHUB_BACKLINK_FILE} is where the tracker fan-out reads its rung; without it the ` + 'always-loaded contract defers to a file that does not carry the signal', ).toContain('`X-RateLimit-Remaining` < 50'); expect( readGithubApiReference(), `${GITHUB_API_FILE} is the only reference a resolve-review-threads spawn can reach for ` + 'this signal — it loads no tracker mechanics — so a rung missing here is a rung that op ' + 'can never learn', ).toContain('`X-RateLimit-Remaining` < 50'); }); }); // --------------------------------------------------------------------------- // Non-vacuity: the corpus this file measures is the real one // --------------------------------------------------------------------------- describe('provider literals: the corpus is real', () => { it('every provider contributes a full op roster to the scan', () => { expect(TRACKER_OPS.length, 'empty op roster').toBeGreaterThanOrEqual(MIN_VARIANT_PAIRS); for (const provider of PROVIDERS) { const tree = providerTree(provider); expect( tree.length, `${provider.subdir}: the generated tree measured 0 characters — every absence assertion ` + `above would pass by reading nothing`, ).toBeGreaterThan(0); for (const op of TRACKER_OPS) { expect( readGenerated(`${provider.subdir}/${op}.md`).split('\n')[0], `${provider.subdir}/${op}.md: line 1 must be this op's anchor`, ).toBe(`## Operation: ${op}`); } } }); }); // --------------------------------------------------------------------------- // Shared provider-independent rules: ONE authoring owner // --------------------------------------------------------------------------- // // The rows above pin what DIFFERS between providers. This block pins the // opposite half: a rule that is the same for every tool-call provider is // AUTHORED once and expanded into each of them, so the two copies a reader sees // in the generated tree cannot drift from each other. // // WHY THE RULES ARE EXPANDED AND NOT HOISTED INTO THE CONTRACT. `tracker/_mcp.md` // is read once per SPAWN and a per-operation mechanics file once per OPERATION, // and two things forbid the hoist that would otherwise be the tidier answer: // // - the D11 clauses are MANDATED per posting mechanic by // tests/guards/mcp-sink-bypass.test.ts. A tool-call sink has no shell // operator between the scrub and the post, so each file has to spell the gate // it is using; a contract that owned those sentences alone would make that // guard unsatisfiable. // - `### Query safety` governs the single operation that composes a query, so // stated in the contract it would be charged to every spawn that never runs // that operation. // // So the rule is emitted per provider ON PURPOSE, and what this block asserts is // that there is still exactly one place it is WRITTEN. `emitted` is a byte-exact // fragment of the expansion, deliberately shorter than the rule: these files are // priced against the per-provider ceilings in tests/tracker/byte-budget.test.ts, // so pinning a whole paragraph would make the ceiling and the guard contradict // each other on the next condensing pass. /** One rule authored once and expanded into every tool-call provider. */ interface SharedRule { /** The `@define` that owns it, declared in `module` and nowhere else. */ readonly define: string; /** A byte-exact fragment of the expansion, as a GENERATED file spells it. */ readonly emitted: string; /** * The authoring module, when it is not the tool-call contract's. * * This field names `_common.mds` for rules outside `_mcp.mds`. The split dates * to MDS 0.4.x, when more defines in `_mcp.mds` made provider builds much * slower. The test checks that each rule has one author across both modules. */ readonly module?: string; readonly why: string; } /** The default authoring module — the tool-call contract's. */ const SHARED_AUTHORING_MODULE = 'src/assets/mds/tracker/_mcp.mds'; /** The second authoring module: shared lines that are not the contract's. */ const COMMON_AUTHORING_MODULE = 'src/assets/mds/tracker/_common.mds'; /** The module a rule is authored in, defaulted so existing rows say nothing new. */ function authoringModuleOf(rule: SharedRule): string { return rule.module ?? SHARED_AUTHORING_MODULE; } const SHARED_RULES: readonly SharedRule[] = [ { define: 'posting_gate_head', emitted: '; this operation names its steps and restates none of its rules.', why: 'the D11 posting sequence. It is restated per mechanic because the sink-bypass guard ' + 'requires every file to name the clauses that make the placeholder a gate — so the one ' + 'thing that can still be centralised is the AUTHORING, and a second author is a second ' + 'reading of which field of the framing line is the byte count', }, { define: 'query_safety', emitted: 'Caller-supplied prose reaches the tracker as a QUERY here and nowhere else in this ' + "provider's mechanics, so the rule is stated here once.", why: 'the query-composition rules, whose own first sentence says the rule is stated ONCE. Two ' + 'authors make that sentence false in the only file a reader can check it against, and the ' + 'escape-order clause is a quoting control: one copy edited is one provider that escapes ' + 'the quote before the backslash', }, { define: 'shipped_marker_rule', emitted: "**The marker is the comment's FIRST LINE and nothing else.**", why: 'the dedup predicate. A copy that relaxed to a substring search over the whole comment ' + 'would hand any quoter the power to suppress a release back-link on that provider alone', }, { define: 'marker_namespace', emitted: 'The namespace is **per comment kind**: this operation owns `devflow:shipped` and no other.', why: 'the namespace rule that keeps the three comment kinds from suppressing one another. It ' + 'is a property of the marker vocabulary, not of any provider', }, { define: 'aggregate_call_budget', emitted: "**Aggregate call budget — the fallback's ceiling.**", why: 'the product bound on the marker-check fallback. The rung that lands differs per provider ' + 'and is passed in; the bound and the truncation report do not, and a second copy is a ' + 'second ceiling', }, { define: 'reference_rendering_gate', emitted: '**Discard, never repair**', why: 'the read-site shape gate for `## Reference Rendering`, and the fallback it routes a ' + 'discard to. The token is interpolated into a branch name and into a PR body from a ' + 'hand-editable machine-wide file, so a second author is a second denylist — and the half ' + 'that decides where a discarded token GOES is what stopped the section degrading forever', }, { define: 'dedup_ladder', emitted: 'Rungs, strongest evidence first, each named for a CAPABILITY and never for a tool', why: 'the four-rung ladder and its bottom rung. A second copy is a second ordering, and the ' + 'rung a provider lands on decides whether a release back-link is suppressed on evidence ' + 'or on a coincidence — the recorded hint may only NARROW the probe, never raise it, and ' + 'that qualification has to be in the same sentence as the rungs it qualifies', }, { define: 'ref_preflight_single', module: COMMON_AUTHORING_MODULE, emitted: 'A **bare number** ⇒ `TRACEABILITY: DEGRADED (ambiguous issue reference)`', why: 'the entry gate for ONE reference a caller named, and the bare-number verdict inside it. ' + 'The grammar keeps a reference out of a query and out of a command, so a second copy is a ' + 'second gate; the fragment pinned here is `bare_number_rule`\'s own sentence, which reaches ' + 'the artifact only through this head — so one row covers both authors', }, { define: 'ref_preflight_list', module: COMMON_AUTHORING_MODULE, emitted: 'a bare number among them goes with them, in silence', why: 'the same gate over a LIST, and the silence a bare number falls into there. A provider ' + 'copy that reported `ambiguous issue reference` per list entry would emit one DEGRADED per ' + 'unparseable line of somebody else\'s commit range — the reason answers a reference a ' + 'caller named, and that distinction has to be in the same sentence as the drop', }, { define: 'ref_preflight_entry', module: COMMON_AUTHORING_MODULE, emitted: 'anchored at both ends of the STRING (a newline fails it)', why: 'the always-loaded entry gate, and the clause that makes its anchoring mean the STRING and ' + 'not a line. A copy that anchored per line admits a payload after a newline, which is the ' + 'whole reason the entry gate is anchored rather than merely matched', }, { define: 'ref_preflight_tail', emitted: '— a `COMPLETE` over zero processed issues is the report a release believes.', why: 'the never-COMPLETE clause on an empty admitted set. It is the sentence that stops a ' + 'release reporting success over zero processed issues, and it is the same sentence ' + 'whatever grammar dropped the entries', }, ]; /** The tool-call providers — the ones that import the shared authoring module. */ const TOOL_CALL_PROVIDERS = PROVIDERS.filter( p => (MCP_BACKED_PROVIDER_SUBDIRS as readonly string[]).includes(p.subdir), ); /** Named collector: corpus entries that spell a shared rule themselves. */ export function collectSecondAuthors( emitted: string, corpus: readonly { readonly label: string; readonly text: string }[], ): string[] { return corpus.filter(e => e.text.includes(emitted)).map(e => e.label); } /** * Does `source` pull in the authoring module `basename`, in EITHER import form? * * MDS spells the same dependency two ways — selective * (`@import { a, b } from "./_mcp.mds"`) and alias (`@import "./_mcp.mds" as mcp`). * The tool-call provider modules use aliases because selective imports made * provider builds much slower in MDS 0.4.x. This check matches the module name * on the `@import` line in either form. */ export function importsModule(source: string, basename: string): boolean { const quoted = basename.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return new RegExp(String.raw`^@import\b.*"\./${quoted}"`, 'm').test(source); } /** * Does `source` invoke `define` at a call site, bare or through an import alias? * * `{{posting_gate_head(` and `{{mcp.posting_gate_head(` are the same invocation of * the same single author; the alias is a lookup path, not a second definition. A * bare `posting_gate_head` in prose is NOT a call site and must not count, which * is what the leading `{{` and the trailing `(` carry — and neither is a * single-brace spelling, which MDS 0.4 prints as literal text. */ export function invokesDefine(source: string, define: string): boolean { return new RegExp(String.raw`\{\{(?:[A-Za-z_][A-Za-z0-9_]*\.)?${define}\(`).test(source); } describe('shared provider-independent rules have exactly one author', () => { /** Each authoring module's source, keyed by path — read once, both modules. */ const authoringSources = new Map( [SHARED_AUTHORING_MODULE, COMMON_AUTHORING_MODULE].map(m => [m, readSource(m)]), ); const providerSources = TOOL_CALL_PROVIDERS.map(p => ({ label: p.source, text: readSource(p.source) })); it('the registry and the corpus it ranges over are both real', () => { expect(SHARED_RULES.length, 'an empty registry asserts nothing').toBeGreaterThan(0); for (const rule of SHARED_RULES) { expect(rule.why.trim().length, `${rule.define}: a row without a reason is a grep`) .toBeGreaterThan(0); expect(rule.emitted.length, `${rule.define}: an empty fragment matches everything`) .toBeGreaterThan(0); } expect( TOOL_CALL_PROVIDERS.map(p => p.token).sort(), 'the shared rules are shared BETWEEN providers, and with one column there is nothing to ' + 'share with — the arms below would all pass over a single module', ).toEqual(['jira', 'linear']); }); it('every shared rule is declared in the authoring module and in no provider module', () => { const problems: string[] = []; for (const rule of SHARED_RULES) { const declaration = `@define ${rule.define}(`; const owner = authoringModuleOf(rule); // Declared exactly once in its OWN module and not at all in the other: // with two authoring modules, "one author" is a claim about both of them. for (const [module, text] of authoringSources) { const declared = text.split(declaration).length - 1; const want = module === owner ? 1 : 0; if (declared !== want) { problems.push(`${module}: declares ${rule.define} ${declared} time(s), want ${want}`); } } for (const entry of providerSources) { if (entry.text.includes(declaration)) { problems.push(`${entry.label}: re-declares ${rule.define}`); } } } expect( problems, `shared-rule declaration problem(s). One author means one \`@define\`:\n ${problems.join('\n ')}`, ).toEqual([]); }); it('no provider module re-inlines a rule it is supposed to invoke', () => { const second: string[] = []; for (const rule of SHARED_RULES) { for (const label of collectSecondAuthors(rule.emitted, providerSources)) { second.push(`${label}: spells ${rule.define} itself — ${rule.why}`); } } expect( second, `a provider module writes a shared rule out instead of invoking it. That is the state this ` + `registry exists to leave: the text is identical on the day it is pasted and diverges on ` + `the first edit, and nothing downstream can tell you which copy is the ` + `intended one:\n ${second.join('\n ')}`, ).toEqual([]); }); it('every tool-call provider imports the authoring module and invokes every rule', () => { const missing: string[] = []; for (const entry of providerSources) { for (const module of authoringSources.keys()) { const basename = module.slice(module.lastIndexOf('/') + 1); if (!importsModule(entry.text, basename)) { missing.push(`${entry.label}: imports nothing from ${basename}`); } } for (const rule of SHARED_RULES) { if (!invokesDefine(entry.text, rule.define)) { missing.push(`${entry.label}: never invokes ${rule.define}`); } } } expect( missing, `a tool-call provider is not using the shared author. A rule nobody invokes is a rule that ` + `will be written out again:\n ${missing.join('\n ')}`, ).toEqual([]); }); it('and the rule reaches every tool-call provider\'s GENERATED tree', () => { // The half the source arms cannot see: an import that compiled to nothing // would satisfy every assertion above while shipping a mechanics file with the // rule missing. const absent: string[] = []; for (const provider of TOOL_CALL_PROVIDERS) { const tree = providerTree(provider); for (const rule of SHARED_RULES) { if (!tree.includes(rule.emitted)) absent.push(`${provider.subdir}/**: no ${rule.define}`); } } expect( absent, `a shared rule never reached a provider's emitted mechanics:\n ${absent.join('\n ')}`, ).toEqual([]); }); it('known-bad probe: the same collector reports a re-inlined copy', () => { // Driven over the REAL provider sources plus one seeded entry, so a collector // that had stopped reporting takes this red with the arm above. for (const rule of SHARED_RULES) { expect( collectSecondAuthors(rule.emitted, [ ...providerSources, { label: 'seed/_probe.mds', text: `prelude\n${rule.emitted}\ntail\n` }, ]), `a seeded second author of ${rule.define} must be reported`, ).toEqual(['seed/_probe.mds']); } }); it('known-bad probe: the import and invocation predicates still report an absence', () => { // Both predicates accept two spellings each. A predicate widened to accept // two things is one edit away from accepting everything, and the arm above // would stay green through that edit — these are the seeded negatives. expect(importsModule('@import "./_mcp.mds" as mcp\n', '_mcp.mds')).toBe(true); expect(importsModule('@import { a, b } from "./_mcp.mds"\n', '_mcp.mds')).toBe(true); expect( importsModule('prose naming `_mcp.mds` and "./_mcp.mds" outside any directive\n', '_mcp.mds'), 'a module NAMED in prose is not a module IMPORTED', ).toBe(false); expect( importsModule('@import { a } from "./_common.mds"\n', '_mcp.mds'), 'importing the other authoring module is not importing this one', ).toBe(false); expect(invokesDefine('x {{posting_gate_head("a")}} y', 'posting_gate_head')).toBe(true); expect(invokesDefine('x {{mcp.posting_gate_head("a")}} y', 'posting_gate_head')).toBe(true); expect( invokesDefine('x {mcp.posting_gate_head("a")} y', 'posting_gate_head'), 'a single-brace spelling is literal text under MDS 0.4, not an invocation', ).toBe(false); expect( invokesDefine('the `posting_gate_head` rule is authored in `_mcp.mds`', 'posting_gate_head'), 'a define NAMED in prose is not a define INVOKED', ).toBe(false); expect( invokesDefine('x {{mcp.query_safety()}} y', 'posting_gate_head'), 'invoking a sibling rule is not invoking this one', ).toBe(false); }); }); // --------------------------------------------------------------------------- // The comment-body cap: ONE value, at every emitted site // --------------------------------------------------------------------------- // // The matrix above pins the cap's PRESENCE per provider, which is the claim that // one provider is not quoting another's number. It cannot see the claim this // block makes: that the value is the SAME at every site inside one provider. A // cap written out at each site is a cap that can drift at one of them — the // archive threshold saying one number and the truncation floor another — while // the presence pin stays green on the sites that did not move. // // Both sides are DERIVED, so no number is spelled here. The declared side is the // body of that module's `comment_cap()` define; the emitted side is every // multi-digit literal in that provider's generated tree. The arm is therefore // also the check that the define is what the sites actually render: a site left // behind as a literal shows up as a second value the moment the define changes. // // Scoped to the providers that OWN a cap define. The CLI provider's tree carries // a date literal alongside its cap, so "every multi-digit literal is the cap" is // not true there; its cap is pinned by its matrix row above, and by the same // count-aware arm the day it acquires a define. /** A multi-digit literal — wide enough to be a cap, too wide to be a page bound. */ const CAP_SHAPED = /[0-9]{4,6}/g; /** Named collector: every multi-digit literal in a corpus, as `{label}:{line}` → value. */ export function collectCapSites( corpus: readonly { readonly label: string; readonly text: string }[], ): { site: string; value: string }[] { const sites: { site: string; value: string }[] = []; for (const entry of corpus) { entry.text.split('\n').forEach((line, i) => { for (const match of line.matchAll(CAP_SHAPED)) { sites.push({ site: `${entry.label}:${i + 1}`, value: match[0] }); } }); } return sites; } /** The body of a module's `comment_cap()` define, or null when it declares none. */ function declaredCap(source: string): string | null { const open = source.indexOf('@define comment_cap():'); if (open === -1) return null; const body = source.slice(source.indexOf('\n', open) + 1); return body.slice(0, body.indexOf('\n@end')).trim(); } describe('the comment-body cap renders one value at every emitted site', () => { const owners = PROVIDERS .map(provider => ({ provider, declared: declaredCap(readSource(provider.source)) })) .filter((row): row is { provider: Provider; declared: string } => row.declared !== null); it('the arm has owners, and each declares a usable cap', () => { expect( owners.map(o => o.provider.token).sort(), 'the cap define is owned by the tool-call providers — with none of them declaring one, ' + 'every arm below ranges over nothing', ).toEqual(['jira', 'linear']); for (const { provider, declared } of owners) { expect(declared, `${provider.source}: comment_cap() must declare a value`).toMatch(/^[1-9][0-9]{3,5}$/); } }); it('every emitted site in an owner\'s tree renders the value its define declares', () => { const problems: string[] = []; for (const { provider, declared } of owners) { const corpus = TRACKER_OPS.map(op => ({ label: `${provider.subdir}/${op}.md`, text: withoutHostSteps(readGenerated(`${provider.subdir}/${op}.md`)), })); const sites = collectCapSites(corpus); // Count-aware: the claim is about every site, so a tree with one site would // make "they all agree" true by arithmetic rather than by evidence. expect( sites.length, `${provider.subdir}: ${sites.length} cap site(s) — with fewer than two, agreement is not ` + `a property of the corpus`, ).toBeGreaterThan(1); for (const { site, value } of sites) { if (value !== declared) problems.push(`${site}: renders ${value}, define declares ${declared}`); } } expect( problems, `a site renders a cap its module's define does not declare. Either the site was left ` + `behind as a literal when the value moved, or a second number has been introduced — and ` + `the truncation floor derives from this number, so two of them means one of the two ` + `preservation orders is bounding against a cap the sink does not enforce:\n ` + problems.join('\n '), ).toEqual([]); }); it('and the owners agree with each other, which is what BORROWED means', () => { // The Linear module states its cap is borrowed from the sibling tool-call // provider rather than measured. That sentence is only true while the two // numbers are equal, and nothing else asserts it. expect( [...new Set(owners.map(o => o.declared))], 'the tool-call providers declare different caps, so the borrowed-cap statement in the ' + 'Linear module is describing a number that no longer matches its source', ).toHaveLength(1); }); it('known-bad probe: one site drifting is reported by the same collector', () => { // The failure the presence-only pin could not see, driven through the real // tree with exactly ONE occurrence mutated. const { provider, declared } = owners[0]; const rel = `${provider.subdir}/manage-debt.md`; const real = readGenerated(rel); const drifted = real.replace(declared, `${declared.slice(0, -1)}8`); expect(drifted, 'the drift seed must change the file').not.toBe(real); const values = collectCapSites([{ label: rel, text: drifted }]).map(s => s.value); expect( [...new Set(values)].length, 'one drifted site must make the value set larger than one — otherwise the arm above is ' + 'satisfied by a tree the collector cannot read', ).toBeGreaterThan(1); expect( values.filter(v => v !== declared), 'and the drifted value must be the one reported', ).not.toEqual([]); // …and the collector does not report the bounds that are not caps. expect( collectCapSites([{ label: 'seed.md', text: 'bounded `≤50` items × `≤2` pages = `≤100`' }]), 'a page or item bound is not a cap site — reporting them would make the value set plural ' + 'for every provider and the arm unfixable', ).toEqual([]); }); }); // --------------------------------------------------------------------------- // fetch-issue, read as a FILE: the numeric branch is gated before it interpolates // --------------------------------------------------------------------------- // // WHY A SECOND PER-FILE ARM. `fetch-issue` and `backlink-shipped-issues` admit the // same references on the same provider, and both interpolate what they admit. The // backlink arm above pins the grammar where the fan-out reads it; this one pins it // where the single lookup does. Before it existed the two ops disagreed about the // ADMITTED SET while sharing a sink shape: the backlink pre-flight required // `^#?[1-9][0-9]{0,8}$`, and the lookup said "if numeric, fetch directly" — a // predicate with no anchors, which `12\n; rm -rf .` satisfies on its first line. // The sink is quoted, so this was defense in depth rather than an open hole; a // security gate is not deferred on the grounds that the sink happens to be quoted. // // Rows pin TOKENS, never sentences, for the reason the backlink table states at // length: these references are priced against the per-provider loaded-set ceilings, // so a condensing pass over this prose is expected rather than hypothetical. const GITHUB_FETCH_FILE = 'tracker/github/fetch-issue.md'; const GITHUB_FETCH_CLAIMS: readonly FileClaim[] = [ { label: 'the anchored grammar the numeric branch is gated on', pattern: /\^#\?\[1-9]\[0-9]\{0,8}\$/, why: 'without anchors the branch is "does this start with a digit", which admits a newline and ' + 'everything after it. The sibling op admits exactly this set, and two ops that interpolate ' + 'the same input must admit the same set', }, { label: 'only the stripped digits are interpolated', pattern: /[Ii]nterpolate only the digits/, why: 'the grammar admits `#42` as well as `42`, so the gate covers the parse and not the command ' + 'unless the stripped form is named as the only one that travels onward', }, { label: 'a rejected value is a search term, not a malformed number', pattern: /SEARCH TERM/, why: 'the operation has a second path, and saying which one a rejected value takes is what stops ' + '"drop it" being read as "degrade the whole op". A gate with no stated else-branch invites ' + 'the author of the next revision to invent one', }, ]; describe('provider literals: the github fetch-issue reference, per file', () => { it('gates the numeric branch on the anchored grammar before it interpolates', () => { const violations = collectMissingFileClaims( GITHUB_FETCH_FILE, readGenerated(GITHUB_FETCH_FILE), GITHUB_FETCH_CLAIMS, ); expect( violations, `the github fetch-issue reference is missing claim(s) it owes:\n ${violations.join('\n ')}`, ).toEqual([]); }); it('known-bad probe: each claim, deleted from a copy, is reported by the same collector', () => { const pristine = readGenerated(GITHUB_FETCH_FILE); expect( collectMissingFileClaims('pristine', pristine, GITHUB_FETCH_CLAIMS), 'the collector must be silent on the shipped file, or the probe below proves nothing', ).toEqual([]); for (const claim of GITHUB_FETCH_CLAIMS) { const wounded = pristine.replace(claim.pattern, ''); expect( wounded, `the pattern for "${claim.label}" matched nothing in the shipped file, so deleting it was ` + 'a no-op and the row cannot be shown live', ).not.toBe(pristine); expect( collectMissingFileClaims('wounded', wounded, GITHUB_FETCH_CLAIMS) .map(v => v.split(' — ')[0]), `removing "${claim.label}" must be reported by the same collector`, ).toContain(`wounded: missing ${claim.label}`); } expect(GITHUB_FETCH_CLAIMS.length, 'the claim table is empty').toBeGreaterThan(0); }); it('known-bad probe: the pre-regression wording — an unanchored numeric branch — goes red', () => { // Not a synthetic shape: this is the sentence the file shipped before the gate, // driven through the same collector. A table that only ever reports a row it // deleted itself cannot say it would have caught the defect it was written for. const unanchored = readGenerated(GITHUB_FETCH_FILE) .replace(/^1b\. .*$/m, '1b. If numeric, fetch directly; if text, search and select.'); expect(unanchored, 'the pre-flight step was not found, so the probe rewrote nothing') .not.toBe(readGenerated(GITHUB_FETCH_FILE)); expect( collectMissingFileClaims(GITHUB_FETCH_FILE, unanchored, GITHUB_FETCH_CLAIMS) .map(v => v.split(' — ')[0]), 'an unanchored numeric branch must be reported on every row the gate is made of', ).toEqual([ `${GITHUB_FETCH_FILE}: missing the anchored grammar the numeric branch is gated on`, `${GITHUB_FETCH_FILE}: missing only the stripped digits are interpolated`, `${GITHUB_FETCH_FILE}: missing a rejected value is a search term, not a malformed number`, ]); }); }); // --------------------------------------------------------------------------- // The one shared line that is deliberately NOT hoisted // --------------------------------------------------------------------------- // // The marker-neutralisation bullet is byte-identical in its CONTENT across all // three tracker modules and is the obvious next candidate for `_common.mds`. It // is excluded on purpose: its indentation differs — five spaces in the GitHub // module, three in the other two — because the list it sits in nests differently // there. A define emits one string, so hoisting it would silently re-indent one // of the three, and indentation is list GRAMMAR rather than whitespace here: a // bullet re-indented out of its parent becomes a sibling, and the containment // instruction stops belonging to the fetch step it qualifies. // // The exclusion is asserted rather than left as a comment, because a comment is // exactly what the next hoisting pass would not read. /** The line every tracker module states for itself, and the indent each uses. */ const CONTAINMENT_LINE = 'Before placing fetched content in the output, neutralise any ' + '`` in it (Principle 8 marker neutralisation).'; const CONTAINMENT_INDENTS: ReadonlyArray<{ token: string; indent: string }> = [ { token: 'github', indent: ' - ' }, { token: 'jira', indent: ' - ' }, { token: 'linear', indent: ' - ' }, ]; /** Named collector: modules whose containment bullet is missing or re-indented. */ export function collectContainmentIndentDrift( sources: ReadonlyArray<{ readonly token: string; readonly text: string }>, ): string[] { const drift: string[] = []; for (const { token, text } of sources) { const expected = CONTAINMENT_INDENTS.find(i => i.token === token); if (expected === undefined) { drift.push(`${token}: no expected indent declared — a provider outside this table is unchecked`); continue; } const line = text.split('\n').find(l => l.includes(CONTAINMENT_LINE)); if (line === undefined) { drift.push(`${token}: the containment bullet is absent`); continue; } if (line !== `${expected.indent}${CONTAINMENT_LINE}`) { drift.push(`${token}: indent is ${JSON.stringify(line.slice(0, line.indexOf('Before')))}, want ${JSON.stringify(expected.indent)}`); } } return drift; } describe('the marker-neutralisation bullet keeps its own indent in every module', () => { const sources = PROVIDERS.map(p => ({ token: p.token, text: readSource(p.source) })); it('the table covers every registered provider', () => { expect( CONTAINMENT_INDENTS.map(i => i.token).sort(), 'a provider with no declared indent would pass this arm by not being looked at', ).toEqual(PROVIDERS.map(p => p.token).sort()); expect( new Set(CONTAINMENT_INDENTS.map(i => i.indent)).size, 'the indents must actually DIFFER — with one indent everywhere the line would be ' + 'hoistable and this whole exclusion would be unmotivated', ).toBeGreaterThan(1); }); it('every module states it at its own indent, and no module defers it to a partial', () => { expect( collectContainmentIndentDrift(sources), 'the containment bullet moved or vanished. It is excluded from `_common.mds` precisely ' + 'because one string cannot carry three indents; a bullet re-indented out of its parent ' + 'stops qualifying the step it belongs to', ).toEqual([]); }); it('known-bad probe: the same collector reports a re-indented and a missing copy', () => { const reindented = sources.map(s => s.token === 'github' ? { token: s.token, text: s.text.replace(` - ${CONTAINMENT_LINE}`, ` - ${CONTAINMENT_LINE}`) } : s); expect( collectContainmentIndentDrift(reindented).join('\n'), 'normalising the GitHub bullet to the other two indents — what a hoist would do — must be reported', ).toContain('github: indent is'); const removed = sources.map(s => s.token === 'jira' ? { token: s.token, text: s.text.split(CONTAINMENT_LINE).join('') } : s); expect( collectContainmentIndentDrift(removed).join('\n'), 'a module that dropped the bullet (for instance by deferring it to a partial) must be reported', ).toContain('jira: the containment bullet is absent'); }); }); // --------------------------------------------------------------------------- // manage-debt item sources // --------------------------------------------------------------------------- // // `manage-debt` adds backlog items only from the two `resolution-summary.md` // sections that carry the Triage verdicts FIX_SEPARATE and TECH_DEBT. The rule is // authored once, in `manage_debt_contract` in `_ops.mds`, and expands at the top // of every provider reference. The contract pins the rule's whole text, a // deliberate exception to the short-fragment convention because it is the rule's // one owner; every other pin of the rule uses one short fragment. Step 3 is // authored once, as `manage_debt_step_3` in `_ops_steps.mds`, and every provider // expands it, so the three built step-3 blocks are identical by construction; // `single-authority.test.ts` proves that. The block is pinned here as an // ALLOWLIST of content: the lead line plus the two bullets. A deny-list of removed // wording would miss the next new source, so a second arm reads the rest of each // reference, sets the rule paragraph aside (it names the review report itself), // and reports any other review source or any `{REVIEW_DIR}` path other than // `resolution-summary.md`. const MANAGE_DEBT_OPS_SOURCE = 'src/assets/mds/git/_ops.mds'; const MANAGE_DEBT_STEP_THREE_LEAD = '3. Extract items to add:'; const MANAGE_DEBT_VERDICTS: readonly string[] = ['FIX_SEPARATE', 'TECH_DEBT']; /** A short fragment unique to the item-source rule: the key of every count and ownership pin. */ const MANAGE_DEBT_RULE_KEY = 'Never add an item that also has an entry in'; /** A line that names a review report, or a review-directory path other than the resolution summary. */ const OTHER_REVIEW_SOURCE = /review report|\{REVIEW_DIR\}(?!\/resolution-summary\.md(?![\w./-]))/i; /** The step-3 block every provider reference carries: the lead line and the two triaged bullets. */ const MANAGE_DEBT_STEP_THREE = [ MANAGE_DEBT_STEP_THREE_LEAD, ' - `## Fix Separately` entries from `{REVIEW_DIR}/resolution-summary.md` (FIX_SEPARATE from Triage agent)', ' - `## Deferred to Tech Debt` entries from `{REVIEW_DIR}/resolution-summary.md` (TECH_DEBT from Triage agent)', ].join('\n'); /** The item of the rule that names what the operation returns when the resolution summary is missing. */ const MANAGE_DEBT_MISSING_SUMMARY = '- If `resolution-summary.md` is missing, return `TRACEABILITY: DEGRADED (resolution summary missing)` ' + 'and do not update the backlog.'; /** * The item-source rule, as the shared contract states it. The whole text is pinned only against the * contract, the rule's one owner, so a rewording changes this pin on purpose. */ const MANAGE_DEBT_RULE = [ 'Update tech debt backlog from `{REVIEW_DIR}/resolution-summary.md`:', '- Add only entries of `## Fix Separately` (FIX_SEPARATE) and `## Deferred to Tech Debt` (TECH_DEBT). ' + 'A section ends at the next heading.', '- An empty section adds none.', MANAGE_DEBT_MISSING_SUMMARY, `- ${MANAGE_DEBT_RULE_KEY} \`## Escalations\`, \`## Blocked\` or \`## Fixed Issues\`.`, '- Read no review report: in `{REVIEW_DIR}`, read only `resolution-summary.md`.', ].join('\n'); /** One file the item-source collectors read: a compiled reference or a provider source. */ interface ManageDebtFile { readonly label: string; readonly text: string; } /** * The lines from the exact step-3 lead line up to, but not including, the first later line that * starts step 4. Null when the lead line is missing. */ export function manageDebtStepThree(text: string): string | null { const lines = text.split('\n'); const start = lines.indexOf(MANAGE_DEBT_STEP_THREE_LEAD); if (start === -1) return null; const rest = lines.slice(start + 1); const next = rest.findIndex(line => /^4\. /.test(line)); return [lines[start], ...(next === -1 ? rest : rest.slice(0, next))].join('\n'); } /** The text without the paragraph that carries the item-source rule. */ function withoutRuleParagraph(text: string): string { return text .split('\n\n') .filter(paragraph => !paragraph.includes(MANAGE_DEBT_RULE_KEY)) .join('\n\n'); } /** Named collector: a reference whose step 3 is absent or lists a source beyond the two triaged ones. */ export function collectStepThreeDrift(files: readonly ManageDebtFile[]): string[] { const drift: string[] = []; for (const { label, text } of files) { const block = manageDebtStepThree(text); if (block === null) { drift.push(`${label}: step 3 is absent`); } else if (block !== MANAGE_DEBT_STEP_THREE) { drift.push(`${label}: step 3 lists a source other than the two triaged sections`); } } return drift; } /** Named collector: a reference that does not carry the item-source rule exactly once. */ export function collectRuleCountDrift(files: readonly ManageDebtFile[]): string[] { const drift: string[] = []; for (const { label, text } of files) { const occurrences = text.split(MANAGE_DEBT_RULE_KEY).length - 1; if (occurrences !== 1) { drift.push(`${label}: the item-source rule ${occurrences === 0 ? 'is absent' : 'occurs more than once'}`); } } return drift; } /** * Named collector: a line outside the rule paragraph that names a review report or a review-directory * path other than `resolution-summary.md`, wherever in the reference it stands. */ export function collectOtherReviewSources(files: readonly ManageDebtFile[]): string[] { const drift: string[] = []; for (const { label, text } of files) { for (const line of withoutRuleParagraph(text).split('\n')) { if (OTHER_REVIEW_SOURCE.test(line)) { drift.push(`${label}: names a review source other than resolution-summary.md: ${line.trim()}`); } } } return drift; } /** Named collector: a verdict that the operations row or the contract does not name. */ export function collectRowVerdictDrift(row: string, contract: string): string[] { const drift: string[] = []; for (const [label, text] of [['row', row], ['contract', contract]] as const) { for (const verdict of MANAGE_DEBT_VERDICTS) { if (!text.includes(verdict)) drift.push(`${label}: names no ${verdict}`); } } return drift; } /** The `manage-debt` line of the Git agent operations table. */ function manageDebtRow(): string { const row = resolveAgentSource('git').content .split('\n') .find(line => line.startsWith('| `manage-debt` |')); if (row === undefined) { throw new Error('the Git agent has no `manage-debt` row in its operations table'); } return row; } /** The `manage_debt_contract` define of the shared operations module, up to its `@end`. */ function manageDebtContract(): string { const source = readSource(MANAGE_DEBT_OPS_SOURCE); const start = source.indexOf('@define manage_debt_contract():'); const end = start === -1 ? -1 : source.indexOf('\n@end', start); if (start === -1 || end === -1) { throw new Error(`${MANAGE_DEBT_OPS_SOURCE} has no closed manage_debt_contract define`); } return source.slice(start, end); } describe('manage-debt item sources', () => { const references: ManageDebtFile[] = PROVIDERS.map(p => ({ label: `${p.subdir}/manage-debt.md`, text: readGenerated(`${p.subdir}/manage-debt.md`), })); const sources: ManageDebtFile[] = PROVIDERS.map(p => ({ label: p.source, text: readSource(p.source), })); const expectEveryProviderScanned = (): void => { expect( PROVIDERS.length, 'fewer than three providers — the scan below would not cover every registered provider', ).toBeGreaterThanOrEqual(3); }; it("every provider's manage-debt reference lists exactly the two triaged sections in step 3 and carries the item-source rule once", () => { expectEveryProviderScanned(); const drift = [...collectStepThreeDrift(references), ...collectRuleCountDrift(references)]; expect( drift, `the manage-debt item sources drifted:\n ${drift.join('\n ')}`, ).toEqual([]); }); it('no manage-debt reference names a review source other than resolution-summary.md outside the rule', () => { expectEveryProviderScanned(); const drift = collectOtherReviewSources(references); expect( drift, `the manage-debt references name another review source:\n ${drift.join('\n ')}`, ).toEqual([]); }); it('the shared contract holds the item-source rule and no provider source restates it', () => { expectEveryProviderScanned(); expect(manageDebtContract(), 'the shared contract must hold the item-source rule').toContain(MANAGE_DEBT_RULE); const restating = collectSecondAuthors(MANAGE_DEBT_RULE_KEY, sources); expect( restating, `the rule has one owner, the shared contract; these provider sources restate it:\n ${restating.join('\n ')}`, ).toEqual([]); }); it('a missing resolution summary returns a DEGRADED line and leaves the backlog unchanged, in the contract and every reference', () => { expectEveryProviderScanned(); expect(manageDebtContract(), 'the contract must state what a missing summary returns').toContain(MANAGE_DEBT_MISSING_SUMMARY); for (const { label, text } of references) { expect(text, `${label} must state what a missing summary returns`).toContain(MANAGE_DEBT_MISSING_SUMMARY); } }); it("the Git agent's manage-debt row and the contract name the same two verdicts", () => { const drift = collectRowVerdictDrift(manageDebtRow(), manageDebtContract()); expect( drift, `the row and the contract must each name FIX_SEPARATE and TECH_DEBT:\n ${drift.join('\n ')}`, ).toEqual([]); }); describe('known-bad probes: each invented drift is reported once', () => { /** The registered file whose label holds `fragment`; throws so a probe never runs on nothing. */ const registered = (files: readonly ManageDebtFile[], fragment: string): ManageDebtFile => { const file = files.find(f => f.label.includes(fragment)); if (file === undefined) { throw new Error(`no registered file matches ${fragment}, so a probe has no file to change`); } return file; }; /** `files` with one file's text replaced; the replacement must differ, or the probe proves nothing. */ const swap = (files: readonly ManageDebtFile[], file: ManageDebtFile, text: string): ManageDebtFile[] => { expect(text, `the change to ${file.label} was a no-op, so the probe cannot be shown live`).not.toBe(file.text); return files.map(f => (f.label === file.label ? { ...f, text } : f)); }; it('the collectors are silent on the shipped tree, so a reported line comes from the probe', () => { expectEveryProviderScanned(); expect( [ ...collectStepThreeDrift(references), ...collectRuleCountDrift(references), ...collectOtherReviewSources(references), ...collectSecondAuthors(MANAGE_DEBT_RULE_KEY, sources), ], 'the collectors must be silent on the shipped tree, or the probes below prove nothing', ).toEqual([]); expect( collectRowVerdictDrift(manageDebtRow(), manageDebtContract()), 'the row collector must be silent on the shipped tree, or the probes below prove nothing', ).toEqual([]); }); it('a third source in step 3 is reported for its provider', () => { const github = registered(references, 'tracker/github/'); const invented = ' - Entries from `{REVIEW_DIR}/other.md`'; expect( collectStepThreeDrift( swap(references, github, github.text.replace(MANAGE_DEBT_STEP_THREE, `${MANAGE_DEBT_STEP_THREE}\n${invented}`)), ), 'an invented third bullet must be reported once, for its provider', ).toEqual([`${github.label}: step 3 lists a source other than the two triaged sections`]); }); it('a reference without the step-3 lead line is reported as absent', () => { const github = registered(references, 'tracker/github/'); expect( collectStepThreeDrift(swap(references, github, github.text.replace(`${MANAGE_DEBT_STEP_THREE_LEAD}\n`, ''))), 'a reference without the step-3 lead line must be reported once', ).toEqual([`${github.label}: step 3 is absent`]); }); it('a reference without the item-source rule is reported as absent', () => { const jira = registered(references, 'tracker/jira/'); expect( collectRuleCountDrift(swap(references, jira, withoutRuleParagraph(jira.text))), 'a reference without the rule must be reported once', ).toEqual([`${jira.label}: the item-source rule is absent`]); }); it('a reference that states the item-source rule twice is reported', () => { const github = registered(references, 'tracker/github/'); expect( collectRuleCountDrift( swap(references, github, github.text.replace(MANAGE_DEBT_RULE, `${MANAGE_DEBT_RULE}\n\n${MANAGE_DEBT_RULE}`)), ), 'a reference that states the rule twice must be reported once', ).toEqual([`${github.label}: the item-source rule occurs more than once`]); }); it('a step that adds entries from another review-directory path is reported', () => { const github = registered(references, 'tracker/github/'); const readsPath = '8. Add entries from `{REVIEW_DIR}/code-review-summary.md`'; expect( collectOtherReviewSources(swap(references, github, `${github.text}\n\n${readsPath}`)), 'a review-directory path other than the resolution summary, added as a step of its own, must be reported', ).toEqual([`${github.label}: names a review source other than resolution-summary.md: ${readsPath}`]); }); it('a step that names the review report is reported', () => { const github = registered(references, 'tracker/github/'); const readsReport = '8. Add the findings of the review report'; expect( collectOtherReviewSources(swap(references, github, `${github.text}\n\n${readsReport}`)), 'a review report named in a step of its own must be reported', ).toEqual([`${github.label}: names a review source other than resolution-summary.md: ${readsReport}`]); }); it('a Git agent row that names neither verdict is reported', () => { expect( collectRowVerdictDrift('| `manage-debt` | Update the backlog |', manageDebtContract()), 'a row that names neither verdict must be reported', ).toEqual(['row: names no FIX_SEPARATE', 'row: names no TECH_DEBT']); }); it('a contract without the FIX_SEPARATE name is reported', () => { expect( collectRowVerdictDrift(manageDebtRow(), manageDebtContract().split('FIX_SEPARATE').join('')), 'a contract without the FIX_SEPARATE name must be reported', ).toEqual(['contract: names no FIX_SEPARATE']); }); it('a provider source that restates the rule with one word changed is reported', () => { const githubSource = registered(sources, '_github.mds'); const nearCopy = MANAGE_DEBT_RULE.replace('Add only entries', 'Add the entries'); expect(nearCopy, 'the near-copy must differ from the rule, or the probe proves nothing').not.toBe(MANAGE_DEBT_RULE); expect( collectSecondAuthors(MANAGE_DEBT_RULE_KEY, swap(sources, githubSource, `${githubSource.text}\n${nearCopy}`)), 'a provider source that restates the rule with one word changed must be reported', ).toEqual([githubSource.label]); }); }); });