Files
msd-core/docs/contributor-standards.md
Tom Boucher 05b170e448 chore(#2928): productionize the CONTEXT.md predicate fact-store and gate it in CI (#2938)
* feat(#2928): port CONTEXT.md predicate fact-store into the src seam

Productionizes the ADR-1671 Option-E reference example as a real module:
src/context-predicates.cts (parser + selector + index builder) compiled to
gsd-core/bin/lib/, plus scripts/gen-context-index.cjs following the repo's
--check/--write drift-guard idiom and wired into lint:generated-sync.

Parser behavior is deliberately prototype-equivalent in this commit so the
next commit's regression matrix binds to the real defects rather than to a
missing module.

Two locked design deviations from the prototype:
- duplicates carry a count, not line numbers
- the committed index carries no line field at all, resolving ADR-1671 open
  question 4: an artifact without line numbers cannot drift on a line shift,
  so promoting --check to a CI gate does not make it routinely red

Also reconciles the one remaining duplicate predicate ID
(RULESET.WORKFLOW_MARKDOWN.FENCES was declared twice; the non-MD040 wording
is removed) so the gate can land fail-closed on duplicates.

Refs #1671

* test(#2928): failing-first matrix for the predicate fact-store

Adds the regression matrix from the phase test plan: parser declaration
forms, fence and comment regions, ID/value grammar boundaries at
limit-1/limit/limit+1, CRLF fidelity, duplicate detection, the drift-guard
CLI, the selector query surface, and four document-shaped fast-check
properties.

Seven rows are RED for behavioral reasons against the ported parser:
indented-bare, star-list, plus-list and numbered-list declaration forms are
dropped; a tilde fence and a four-backtick fence containing a shorter fence
are not skipped; and a multi-line HTML comment is parsed as live. Eleven
selector rows are RED because the query surface is not wired yet.

Negative fixtures come from real repo documents that predate the grammar
(CONTEXT.md, CONTRIBUTING.md's fenced env-assignment examples) per the
fixture-provenance rule, and the property generators are document-shaped
rather than seeded from our own serializer.

Refs #1671

* fix(#2928): consume the shared fence scanner, relocate the index, wire the selector

Drives the failing-first matrix green.

Parser: replaces the ported naive triple-backtick toggle with the shared
markdown-sectionizer fence engine. scanFencedBlocks and FencedBlockRecord
gain an export keyword — the only change to that module, which has 71
upstream dependents — because it already returns line-indexed spans, which
is exactly what a line-reporting parser needs. It also already documents
itself as the second copy of the fence state machine pending consolidation;
adding a third copy here would have been the generative-fix divergence this
repo warns about. A parity suite now pins predicate fence-skipping against
that scanner across eight fence shapes. HTML-comment skipping stays local
because the sectionizer has no comment scanner. Declaration forms widen to
indented-bare, star, plus and numbered list items.

Index location: docs/CONTEXT-INDEX.json, not a module under bin/lib. The
remote matrix run caught the original choice — a committed .cjs there ships
~120KB of CONTEXT.md prose into a runtime module, and two content guards
fired truthfully on it (a leaked .claude install path, and four hardcoded
package-name literals). Neither guard was allowlisted; the artifact moved
instead, mirroring docs/INVENTORY-MANIFEST.json. Nothing at runtime needs to
require it — it is a drift-detection artifact, so the selector parses
CONTEXT.md live and is always current.

Generator: adds a frozen REASON enum and --check --json so the gate's
outcome is asserted structurally instead of by matching prose, and
--context-path/--index-path so tests drive the real CLI against a temp tree
with no filesystem monkeypatching.

Selector: gsd_run query context-predicates with --class/--prefix/--contains,
structured output carrying a matched count, own-property guards, and no
project-root resolution. Registering it exposed that the query dispatch
table and the usage string had drifted: a new parity test found 20 routed
commands missing from the usage list, all added here rather than deferred.

Refs #1671

* test(#2928): lock the newly-public scanFencedBlocks contract

Exporting scanFencedBlocks made it public API for the first time, so it
needs its own contract test independent of the consumer that motivated the
export. Memtrace's co-change analysis flagged the gap: this suite changes
together with markdown-sectionizer.cts 8 times in 90 days and was absent
from the diff.

Covers the documented rules: 0-based indices, -1 for an unterminated fence,
the same-char/>=length/no-trailing-text closer rule, a shorter fence inside
a longer one staying content, CommonMark 4.5 backtick-in-info-string, and
<=3-space indent tolerance.

Refs #1671

* fix(#2928): address both isolated review passes

Two independent reviewers (correctness axis and security axis, neither the
author) found seven findings. All are fixed here with regression tests; none
deferred.

BLOCKER — comment-blind fence scanning caused silent, permanent predicate
loss. The HTML-comment scan and the fence scan ran as two independent passes,
and the fence scanner is comment-blind, so a fence delimiter inside an HTML
comment with no later close read as an unterminated fence and skipped every
remaining line to EOF. Worse, the drift-guard could not catch it: it diffs
against a baseline produced by the same corrupted parse. The two constructs
now interleave in a single pass so each suppresses the other's boundary
detection while active, covered in both directions. The parity suite still
binds this scanner to markdown-sectionizer's for comment-free documents, so
the two cannot diverge unnoticed.

BLOCKER — the selector was not consumed anywhere, leaving the phase's
acceptance criterion unmet. Now wired into the pre-work predicate-citation
step in contributor-standards, which is the repo's actual brief-assembly
path; no code-level brief assembler exists to wire into.

MAJOR — ReDoS with an unauthenticated CI-hang exploit. The predicate-id
regex nested a dot-containing character class inside a dot-prefixed repeat,
so N consecutive dots had exponentially many partitions: 40 dots took 565ms
and growth was exponential. CI runs this parser over a pull request's own
CONTEXT.md, so any contributor could have hung a shared runner with one
line. Replaced with linear per-segment validation. Doubled-dot ids are now
rejected; the real document contains none.

MAJOR — the duplicate-id gate had only ever been proven on synthetic
fixtures. A test now re-inserts the exact line this branch removed and
asserts the real generator names it.

MAJOR — --check together with --write silently let write win, turning the
gate into a writer; a missing path value resolved to the cwd and leaked an
EISDIR stack trace. Both are now clean usage errors.

MINOR — the hoisted skip-list was exported as a live mutable Set; replaced
with a read-only predicate. MINOR — flag-shaped selector values were
unmatchable; the inline --flag=value form now provides the escape hatch.

Refs #1671

* chore(#2928): backfill changeset PR number 2938

---------

Co-authored-by: sim <sim@local>
2026-07-31 13:17:01 -04:00

12 KiB
Raw Blame History

Contributor Standards

Standards for working with CONTEXT.md, docs/adr/, and AI-agent-assisted contributions.

These apply to every PR — fix, enhancement, or feature. They are part of the merge contract, not optional background reading.

Standards hierarchy (canonical, in order):

  1. CONTEXT.md — domain language and module naming
  2. docs/adr/ — accepted architectural decisions
  3. Approved issue scope

CONTEXT.md

What it is

CONTEXT.md is the single source of truth for domain vocabulary. It defines:

  • Domain modules and seams — canonical Module names, seam vocabulary, and Interface names (e.g. Dispatch Policy Module, Command Contract Validation Module, Planning Workspace Module)
  • Recurring PR mistakes — CodeRabbit findings that recur; covers tests, shell guards, changesets, docs
  • Workflow learnings — patterns distilled from triage + PR cycles

Format

CONTEXT.md is written as flat named sections under ## Glossary — Domain modules and seams (for Modules/seams) and ## sections for recurring rules. Machine-oriented predicates use KEY.SUBKEY=value flat format, grouped into the ## section that owns the topic — ## Test rules and lint, ## CodeRabbit + repo-process guards (machine-oriented predicates), or ## Workspace seams (machine-oriented predicates).

Adding a new Module or seam:

  • Add a ### <Module Name> entry under ## Glossary — Domain modules and seams.
  • Write one paragraph. State what the Module owns. Be concrete — list the Interface names and policy boundaries it covers.
  • Do not add synonyms; pick one name and use it everywhere.

Extending an existing predicate:

  • Add a KEY.SUBKEY=value line inside the relevant predicate section — for a test or lint rule that is ## Test rules and lint.
  • Do not create a new top-level section for a variation on an existing concept.

When to add a new predicate vs extend an existing one:

  • New predicate: the concept has a distinct identity, distinct owner, and is not covered by any existing section.
  • Extend existing: the new fact qualifies, constrains, or amends an already-named Module. Add it as a sub-entry or amendment paragraph.

Contributor requirements

  • Read CONTEXT.md in full before naming anything (modules, interfaces, seams, tests, PRs).
  • Use CONTEXT.md vocabulary consistently in code comments, tests, issue/PR text, and docs.
  • Do not invent synonyms. If you need a concept that is not in the glossary, note it explicitly in the issue or PR rather than using ad-hoc language.
  • Do not rewrite CONTEXT.md as part of drive-by cleanup; propose focused updates tied to the approved issue scope.
  • CONTEXT.md is maintainer-owned. Contributors can propose additions via issue discussion, but final wording is the maintainer's call.

Example (correct)

A PR that adds a new query adapter should use the term Native Dispatch Adapter Module (from CONTEXT.md), not "native adapter," "query native handler," or any other variant.


ADRs

What they are

docs/adr/ contains Architecture Decision Records. Each ADR is a concise record of one accepted decision: the problem, the decision, and the consequences. Accepted ADRs are the current standard.

Currently accepted ADRs:

File Decision
0001-dispatch-policy-module.md Dispatch Policy Module as the single seam for query execution outcomes
0002-command-contract-validation-module.md Command Contract Validation Module / command contract centralization
0003-model-catalog-module.md Model Catalog Module as the single source of truth for agent profiles and runtime tier defaults
0004-worktree-workstream-seam-module.md Planning Workspace Module as single seam for worktree and workstream state
0005-sdk-architecture-seam-map.md SDK Architecture seam map for query/runtime surfaces
0006-planning-path-projection-module.md Planning Path Projection Module for SDK query handlers
0007-sdk-package-seam-module.md SDK Package Seam Module owns SDK-to-gsd-core compatibility

When an ADR is required

An ADR is required when a decision:

  • Introduces or removes a Module seam that other code will depend on.
  • Changes the policy contract of an existing accepted ADR.
  • Establishes a new architectural invariant (naming convention, test contract, CI enforcement).

An ADR is optional (a comment in the relevant issue or PR is sufficient) when:

  • The change is a bugfix that lands squarely within an existing accepted decision.
  • The change is a docs or test improvement with no architectural surface.

Naming conventions

New ADRs and PRDs use issue#-prefix slug naming. This is a contributor requirement, not a suggestion.

docs/adr/<issue#>-<kebab-slug>.md    (new ADRs)
docs/prd/<issue#>-<kebab-slug>.md    (new PRDs)

Example: docs/adr/2264-golden-parity-redesign.md.

Why: GitHub issue numbers are server-assigned and atomic — the reservation mechanism already exists because the issue-first rule requires it. Promoting the issue# to the artifact ID eliminates the entire collision class that the NNNN-* local-compute scheme created (see the 0010-* × 2 and 0011-* × 3 duplicates on disk).

Migration policy: Legacy ADRs keep their numbers as immutable historical record — see the authoritative legacy-range statement in docs/adr/README.md for exactly which zero-padded files that covers (and which zero-padded files are actually modern, mis-padded). Do not renumber legacy files. The new convention applies to all ADRs and PRDs created on or after the merge of the implementing PR (#3485 — a pre-rename number from get-shit-done-redux; it does not resolve in open-gsd/gsd-core, whose issue numbering restarted at the rename).

For the end-to-end workflow — opening the issue, waiting for approval, creating the file, and submitting the PR — see CONTRIBUTING.md — "Proposing an ADR or PRD".

The legacy four-digit scheme (0003-model-catalog-module.md) applies only to pre-existing files.

Required sections

Every ADR must open with:

# <Title>

- **Status:** Accepted | Proposed | Deprecated
- **Date:** YYYY-MM-DD

Body: one-paragraph decision summary, then ## Decision (specifics), then ## Consequences (behavioral changes downstream callers can rely on).

Amendments are appended as ## Amendment (YYYY-MM-DD): <topic> sections — the original body is never rewritten.

Status block format

- **Status:** Accepted
- **Date:** 2026-05-09

Status values: Proposed (under discussion), Accepted (current standard), Deprecated (superseded — include a forward reference to the replacement).

Cross-reference style

Reference sibling ADRs by filename, not by title prose: see \0001-dispatch-policy-module.md``. This survives title edits.

ADR README index

docs/adr/README.md maintains the canonical index table and the naming convention documentation. The table in this document (above) covers accepted ADRs for contributor reference. If an ADR is added, update both tables in the same PR.

Governance

  • ADR creation and final wording is maintainer-owned. Contributors must not open ADR files as part of a contribution PR.
  • Contributors can — and should — give input on proposed ADR direction in the linked issue discussion.
  • Once an ADR is Accepted, reopening the decision must be explicit (a dedicated issue with rationale), not implied by a drive-by PR change.
  • If your PR intentionally revisits an accepted ADR decision, call it out explicitly in the issue and the PR body: "This revisits ADR-0002 because…"

AI-agent-assisted work

When AI assistance is appropriate

AI assistance is appropriate for every contribution type. The bar for correctness and review quality does not change because the code was AI-assisted.

Pre-work requirements

Before any AI agent writes a single line of code or docs, it must read:

  1. CONTEXT.md in full.
  2. The ADRs relevant to the area being changed (check docs/adr/).
  3. The approved issue scope.

If you are dispatching an AI agent, include these reads in the agent's prompt explicitly. An agent that invents synonyms for CONTEXT.md vocabulary or contradicts an accepted ADR without flagging it has failed the pre-work requirement.

Citing a machine-oriented predicate in a brief. CONTEXT.md's KEY.SUBKEY=value predicates (see below) must be cited by ID verbatim, never paraphrased (META.RULE.brief-must-cite-doc, META.RULE.brief-no-paraphrase). Rather than grepping the file by eye for the predicate set a brief needs, pull it with the selector, which parses the live file on every call:

node gsd-tools.cjs query context-predicates --class <CLASS> | --prefix <dotted.prefix> | --contains <text>

See query context-predicates for the full flag and output reference.

In the PR body, state which ADR or standards section was followed. If using an AI assistant, this statement is your responsibility as the author — not the agent's.

Worktree isolation

Agent-written code must use an isolated worktree to prevent branch pollution. The standard pattern:

git worktree add ../my-feature-worktree fix/NNNN-short-description

Never commit agent output directly to main or to an already-open feature branch without review.

Model selection

Sonnet for most tasks — implementation, test writing, docs, triage. Use the current Sonnet model unless the task requires deep reasoning over a large context.

Opus for architecture-level tasks — ADR authorship (maintainer only), cross-cutting refactors, adversarial review of complex PRs. Using a more capable model when a capable model suffices wastes context and delays the cycle.

General-purpose vs specialist agents: prefer the specialist agent for the domain (e.g. a TypeScript-aware agent for SDK surface changes, a docs-aware agent for contributor docs) over a general-purpose agent. Specialist agents load less irrelevant context.

TDD discipline

For any Behavior-Adding Task (see CONTEXT.md):

  1. RED — commit a failing test that names the expected behavior before writing the implementation.
  2. GREEN — write the minimum implementation that makes the test pass.
  3. REFACTOR — polish without changing behavior; tests must still pass.

Commit each phase separately. A PR that has no failing-test commit for a new behavior will be asked to add one before merge.

Adversarial review requirement

Before opening a PR:

  • Read each changed section as if you are a hostile reviewer. Does it stand alone? Does it cite existing artefacts accurately? Is anything aspirational that is not actually current practice?
  • Mark aspirational items as [proposed] in the text if they describe future intent rather than current behavior.
  • Check that every cross-reference (file path, ADR number, CONTEXT.md term) resolves to something that actually exists on disk.

CR-loop discipline

After a reviewer thread is addressed:

  • Fix the code or docs in a new commit (never amend a pushed commit).
  • Resolve the thread via GraphQL mutation — do not rely on auto-resolve and do not post a reply comment:
gh api graphql -f query='mutation { resolveReviewThread(input:{threadId:"PRRT_..."}) { thread { isResolved } } }'

Address every reviewer finding claim-by-claim. Do not dismiss a thread because one sub-claim is a false positive — read all sub-claims before deciding.

Standards followed — block (proposed)

The maintainer is evaluating whether to require a ## Standards followed block in every issue and PR body. Current proposal:

  • Enhancements and features: required. List the ADR(s) and CONTEXT.md section(s) consulted.
  • Bug fixes: lighter-weight. A one-line note suffices: "Follows ADR-0002 command contract."

This is marked [proposed] — it is not yet a merge gate. Feedback on workflow impact is welcome in issue #3232.