syntaxai/tdd.md · main · src / d21_handlers_sama.ts
// c21 — handlers: the /sama cluster. All routes that live under
// /sama/* plus the SKILL raw download and the bundled CLI download.
// Extracted from c21_app.ts per the SAMA Atomic rule (the dispatcher
// passed the 700-line split threshold).
//
// Each export is a handler function the dispatcher in c21_app.ts
// references inline so Bun.serve still sees literal route keys for
// path-parameter type inference.
import {
renderNotFound,
htmlResponse,
escape,
} from "./b51_render_layout.ts";
import { renderDocsPage } from "./b51_render_docs_layout.ts";
import { ALL_SAMA } from "./a31_sama.ts";
import { parseUrl } from "./c14_request_parse.ts";
import {
fetchRepoTree,
fetchRepoRawFile,
} from "./c14_github.ts";
import { verifySama, type SamaReport } from "./b32_sama_verify.ts";
import { LIVE_REPO_OWNER, LIVE_REPO_NAME } from "./a31_site_config.ts";
// -------- /skills/sama.md (raw download) --------
export const skillsSamaMdHandler = async (): Promise<Response> => {
const md = await Bun.file("./content/sama/skill.md").text();
return new Response(md, {
headers: {
"Content-Type": "text/markdown; charset=utf-8",
"Cache-Control": "public, max-age=300",
},
});
};
// -------- /sama/skill (HTML viewer of the SKILL.md) --------
export const samaSkillHandler = async (): Promise<Response> => {
const raw = await Bun.file("./content/sama/skill.md").text();
// Strip the YAML frontmatter for the HTML render — the .md raw
// download keeps it (that's the agent-installable format).
const stripped = raw.replace(/^---\n[\s\S]*?\n---\n+/, "");
const installNote = `> **Drop into your agent.** Save the raw markdown to your skills directory:
>
> \`\`\`bash
> mkdir -p ~/.claude/skills
> curl -fsSL https://tdd.md/skills/sama.md -o ~/.claude/skills/sama.md
> \`\`\`
>
> The frontmatter at the top of the file (\`name\`, \`description\`) is what your agent's loader keys off — don't edit it. [View raw markdown →](/skills/sama.md)
`;
const body = `${installNote}\n\n${stripped}\n\n---\n\n[← /sama](/sama) · [the four disciplines](/sama) · [back to tdd.md](/)\n`;
const html = await renderDocsPage({
title: "SAMA skill — drop into your agent — tdd.md",
description: "An obra/superpowers-style SKILL.md for the SAMA file-naming convention. Save it to ~/.claude/skills/sama.md and your agent will load the layer-prefix discipline on demand.",
bodyMarkdown: body,
ogPath: "https://tdd.md/sama/skill",
active: "sama",
pathForDocs: "/sama/skill",
});
return htmlResponse(html);
};
// -------- /sama/v2/verify (the v2 dogfood — runs the v2 verifier
// against this repo using sama.profile.toml) --------
import { buildSamaV2Input } from "./c14_sama_profile.ts";
import { verifySamaV2 } from "./b32_sama_v2_verify.ts";
import { computeCoreMetrics } from "./b32_sama_v2_metrics.ts";
import type { FanSummary, SamaV2Metrics, SamaV2Report } from "./a31_sama_v2.ts";
// Render §5 metrics block beneath the existing 7-check verdict.
// Numbers come straight from computeCoreMetrics on the same input
// the verifier consumed — operational definitions on /sama/v2 §5.
const fmtFan = (s: FanSummary): string =>
`${s.mean.toFixed(2)} / ${s.p50} / ${s.p95} / ${s.max}`;
const fmtPct = (n: number): string => `${(n * 100).toFixed(1)}%`;
const renderMetricsBlock = (m: SamaV2Metrics): string => `## §5 Core metrics
> *Snapshot of this run. Operational definitions at [/sama/v2 §5](/sama/v2#5-operational--core-metrics-definitions). The baseline these numbers anchor is what later claims (skeleton scaffolds, agent A/B experiments, external-repo audits) will be measured against as a delta.*
| metric | value |
|---|---|
| **graphDepth** | ${m.graphDepth} |
| **boundaryRatio** | ${fmtPct(m.boundaryRatio)} |
| **workingSetFit** | ${fmtPct(m.workingSetFit)} |
### fan distribution per layer
| layer | fan-in (mean / p50 / p95 / max) | fan-out (mean / p50 / p95 / max) |
|---|---|---|
| 0 — Pure | ${fmtFan(m.fanByLayer[0].fanIn)} | ${fmtFan(m.fanByLayer[0].fanOut)} |
| 1 — Core | ${fmtFan(m.fanByLayer[1].fanIn)} | ${fmtFan(m.fanByLayer[1].fanOut)} |
| 2 — Adapter | ${fmtFan(m.fanByLayer[2].fanIn)} | ${fmtFan(m.fanByLayer[2].fanOut)} |
| 3 — Entry | ${fmtFan(m.fanByLayer[3].fanIn)} | ${fmtFan(m.fanByLayer[3].fanOut)} |
### violation counts (trailing signal — emitted even when checks pass)
| check | count |
|---|---|
| #1 Sorted | ${m.violationCounts.sorted} |
| #2 Architecture | ${m.violationCounts.architecture} |
| #3 Modeled (tests) | ${m.violationCounts.modeledTests} |
| #4 Modeled (boundary) | ${m.violationCounts.modeledBoundary} |
| #5 Atomic | ${m.violationCounts.atomic} |
| #6 Law (§1.2) | ${m.violationCounts.law} |
| #7 Consistency (§3) | ${m.violationCounts.consistency} |
`;
const renderV2Report = (report: SamaV2Report, metrics: SamaV2Metrics): string => {
const summary = report.overallPassed
? `✓ conforms · profile \`${report.profile}\` · ${report.examined} files examined · ${report.checks.length}/${report.checks.length} checks pass`
: `${report.checks.filter((c) => c.passed).length}/${report.checks.length} checks pass · profile \`${report.profile}\` · ${report.examined} files examined`;
const rows = report.checks
.map((c) => {
const mark = c.passed ? "✓ pass" : `✗ ${c.violations.length} violation${c.violations.length === 1 ? "" : "s"}`;
return `| #${c.id} ${c.name} | ${mark} | ${c.examined} |`;
})
.join("\n");
const details = report.checks
.filter((c) => !c.passed)
.map((c) => {
const head = `### ✗ #${c.id} ${c.name}\n`;
const noteBlock = c.note ? `\n*${c.note}*\n` : "";
const list = c.violations
.map((v) => `- \`${v.file}\` — ${v.detail}`)
.join("\n");
return `${head}${noteBlock}\n${list}\n`;
})
.join("\n");
return `# SAMA v2 — \`syntaxai/tdd.md\` dogfood
> ${summary}
The verifier in [\`src/b32_sama_v2_verify.ts\`](/GIT/tdd.md/blob/main/src/b32_sama_v2_verify.ts) ingests [\`sama.profile.toml\`](/GIT/tdd.md/blob/main/sama.profile.toml) and runs the seven §4 conformance checks against the current source tree on this server. No clone, no token; the server reads its own \`src/\` and the committed profile, runs the same logic the sibling unit tests cover, and renders the verdict below. The §5 core metrics emitter ([\`src/b32_sama_v2_metrics.ts\`](/GIT/tdd.md/blob/main/src/b32_sama_v2_metrics.ts)) runs on the same input and shares the parse-boundary detector with the Modeled-boundary check.
| check | verdict | examined |
|---|---|---|
${rows}
${details ? `## Open violations\n\n${details}\n` : ""}
${renderMetricsBlock(metrics)}
[← /sama/v2](/sama/v2) · [← /sama](/sama) · [the v1 dogfood](/sama/verify?repo=syntaxai/tdd.md)
`;
};
export const samaV2VerifyHandler = async (): Promise<Response> => {
let body: string;
try {
const input = await buildSamaV2Input();
const report = verifySamaV2(input);
const metrics = computeCoreMetrics(input);
body = renderV2Report(report, metrics);
} catch (err) {
body = `# SAMA v2 verify — error\n\nThe verifier failed before producing a verdict:\n\n\`\`\`\n${(err as Error).message}\n\`\`\`\n\n[← /sama/v2](/sama/v2)`;
}
const html = await renderDocsPage({
title: "SAMA v2 verify · syntaxai/tdd.md — tdd.md",
description:
"Live dogfood: tdd.md's own source tree run through the SAMA v2 verifier. Reads sama.profile.toml + src/*.ts, applies the seven §4 conformance checks, renders the verdict.",
bodyMarkdown: body,
ogPath: "https://tdd.md/sama/v2/verify",
active: "sama",
pathForDocs: "/sama/v2/verify",
});
return htmlResponse(html);
};
// -------- /sama/v2 (the SAMA v2 Core Specification — draft) --------
export const samaV2Handler = async (): Promise<Response> => {
const md = await Bun.file("./content/sama/v2.md").text();
const html = await renderDocsPage({
title: "SAMA v2 — Core Specification (draft) — tdd.md",
description:
"Draft of the SAMA v2 Core Specification: four canonical layers (Pure / Core / Adapter / Entry), one frozen import law, profiles as the only extension mechanism. Defines the binary conformance gate and the SAMA-independent core metrics for cross-repo empirical measurement.",
bodyMarkdown: md,
ogPath: "https://tdd.md/sama/v2",
active: "sama",
pathForDocs: "/sama/v2",
});
return htmlResponse(html);
};
// -------- /sama/v2/example-crud (worked-example profile for an HTTP CRUD service) --------
export const samaV2ExampleCrudHandler = async (): Promise<Response> => {
const md = await Bun.file("./content/sama/v2-example-crud.md").text();
const html = await renderDocsPage({
title: "SAMA v2 — worked example: HTTP CRUD service — tdd.md",
description:
"One concrete instantiation of the SAMA v2 spec: an e-commerce orders API. Profile declaration, directory layout, per-layer code signatures, and the common mistakes each §4 check catches.",
bodyMarkdown: md,
ogPath: "https://tdd.md/sama/v2/example-crud",
active: "sama",
pathForDocs: "/sama/v2/example-crud",
});
return htmlResponse(html);
};
// -------- /sama/v2/example-wordpress (worked-example profile for a WP plugin) --------
export const samaV2ExampleWordpressHandler = async (): Promise<Response> => {
const md = await Bun.file("./content/sama/v2-example-wordpress.md").text();
const html = await renderDocsPage({
title: "SAMA v2 — worked example: WordPress plugin — tdd.md",
description:
"The SAMA v2 spec applied to a WordPress plugin: $wpdb in Layer 2 only, hooks in Layer 3, no WP function calls in Layer 0/1. Profile, directory layout, per-layer PHP signatures, and the common WordPress mistakes each §4 check catches.",
bodyMarkdown: md,
ogPath: "https://tdd.md/sama/v2/example-wordpress",
active: "sama",
pathForDocs: "/sama/v2/example-wordpress",
});
return htmlResponse(html);
};
// -------- /sama/verify (form + report + dogfood short-circuit) --------
const VERIFY_FORM_MD = `# SAMA verify
> Paste a public GitHub repo. tdd.md will run the four [SAMA disciplines](/sama) against the default branch — *Sorted* (lower never imports higher), *Architecture* (known layer prefixes), *Modeled* (sibling tests, types in c31_*), *Atomic* (~700-line split + placeholder-test detection) — and return a report. No clone, no token; just one tree-listing API call plus raw-content reads. Cached for an hour per repo.
<form method="get" action="/sama/verify" class="sama-verify-form">
<label>
public GitHub repo:
<input type="text" name="repo" placeholder="owner/name" required pattern="[^/\\s]+/[^/\\s]+" />
</label>
<button type="submit">verify</button>
</form>
Try it on this site: [\`syntaxai/tdd.md\`](/sama/verify?repo=syntaxai/tdd.md) · or any public repo of your own.
Limits: anonymous GitHub API quota is 60 requests/hour per IP. Each verify uses one tree-listing call; the rest of the work goes through raw.githubusercontent.com (uncapped). If the verifier returns "rate limit", come back later or use a token-authenticated proxy.
[← /sama](/sama)
`;
const verifyLocalDogfood = async (owner: string, name: string): Promise<SamaReport> => {
const { readdirSync, readFileSync } = await import("node:fs");
const srcDir = "./src";
const tsFiles = readdirSync(srcDir, { withFileTypes: true })
.filter((e) => e.isFile() && e.name.endsWith(".ts"))
.map((e) => e.name)
.sort();
const contents = new Map<string, string>();
for (const f of tsFiles) {
if (/^c\d{2}_/.test(f)) {
contents.set(f, readFileSync(`${srcDir}/${f}`, "utf8"));
}
}
return verifySama({
repoOwner: owner,
repoName: name,
defaultBranch: "main",
srcPaths: tsFiles,
contents,
});
};
const verifyRemoteRepo = async (owner: string, name: string): Promise<SamaReport> => {
const tree = await fetchRepoTree(owner, name);
const srcEntries = tree.entries
.filter((e) => e.type === "blob" && e.path.startsWith("src/") && e.path.endsWith(".ts"))
.slice(0, 200);
const srcPaths = srcEntries.map((e) => e.path.slice("src/".length));
const samaPaths = srcPaths.filter((p) => /^c\d{2}_/.test(p));
const contents = new Map<string, string>();
const fetches = await Promise.all(
samaPaths.map(async (p) => [p, await fetchRepoRawFile(owner, name, tree.defaultBranch, `src/${p}`)] as const),
);
for (const [p, c] of fetches) {
if (c !== null) contents.set(p, c);
}
return verifySama({
repoOwner: owner,
repoName: name,
defaultBranch: tree.defaultBranch,
srcPaths,
contents,
});
};
const renderVerifyReport = async (report: SamaReport): Promise<string> => {
const summary = report.overallPassed
? `> ✓ All four checks passed for [\`${report.repoSlug}\`](https://github.com/${report.repoSlug}) on \`${report.defaultBranch}\` (${report.samaFiles} SAMA files / ${report.testFiles} tests / ${report.totalSrcFiles} total in src/).`
: `> ⚠ ${report.checks.filter((c) => !c.passed).length} of 4 checks failed for [\`${report.repoSlug}\`](https://github.com/${report.repoSlug}) on \`${report.defaultBranch}\`.`;
const checkBlocks = report.checks
.map((c) => {
const status = c.passed ? "✓ pass" : `✗ ${c.violations.length} violation${c.violations.length === 1 ? "" : "s"}`;
const violationsBlock = c.violations.length === 0
? ""
: `\n\n${c.violations.slice(0, 20).map((v) => `- \`${escape(v.file)}\` — ${escape(v.detail)}`).join("\n")}${c.violations.length > 20 ? `\n- _...and ${c.violations.length - 20} more_` : ""}`;
const noteBlock = c.note ? `\n\n_${escape(c.note)}_` : "";
return `### ${c.letter} — ${c.property} · ${status}\n\nExamined ${c.examined} file${c.examined === 1 ? "" : "s"}.${violationsBlock}${noteBlock}`;
})
.join("\n\n");
const reportMd = `# SAMA verify · \`${report.repoSlug}\`
${summary}
${checkBlocks}
---
[← verify another repo](/sama/verify) · [the four SAMA disciplines →](/sama) · [SAMA skill for your agent →](/sama/skill)
`;
return renderDocsPage({
title: `SAMA verify · ${report.repoSlug} — tdd.md`,
description: `SAMA verification for ${report.repoSlug}: ${report.overallPassed ? "all four checks passed" : `${report.checks.filter((c) => !c.passed).length}/4 checks failed`}.`,
bodyMarkdown: reportMd,
ogPath: `https://tdd.md/sama/verify?repo=${report.repoSlug}`,
active: "sama",
pathForDocs: "/sama/verify",
editPathOverride: null,
});
};
export const samaVerifyHandler = async (req: { url: string }): Promise<Response> => {
const urlR = parseUrl(req.url);
const repoArg = urlR.ok ? (urlR.value.searchParams.get("repo") ?? "").trim() : "";
if (!repoArg) {
const html = await renderDocsPage({
title: "SAMA verify — tdd.md",
description: "Paste a public GitHub repo, get the four SAMA disciplines verified mechanically: sorted (lower never imports higher), architecture (known layer prefixes), modeled (sibling tests), atomic (700-line + placeholder-test detection).",
bodyMarkdown: VERIFY_FORM_MD,
ogPath: "https://tdd.md/sama/verify",
active: "sama",
pathForDocs: "/sama/verify",
});
return htmlResponse(html);
}
const m = /^([^\/\s]+)\/([^\/\s]+)$/.exec(repoArg);
if (!m) {
const html = await renderDocsPage({
title: "SAMA verify · bad input — tdd.md",
description: "SAMA verify expects an owner/name repo identifier.",
bodyMarkdown: `# SAMA verify\n\n> Couldn't parse \`${repoArg}\`. Use the form: \`owner/name\`.\n\n[← back](/sama/verify)\n`,
pathForDocs: "/sama/verify",
editPathOverride: null,
ogPath: "https://tdd.md/sama/verify",
active: "sama",
noindex: true,
});
return htmlResponse(html, 400);
}
const [, owner, name] = m;
let report: SamaReport;
try {
// Dogfood short-circuit: tdd.md is a private repo, so the GitHub
// API can't see it. When asked to verify ourselves, read the
// source from the bundled `./src/` directory inside the container.
const isSelf = owner === LIVE_REPO_OWNER && name === LIVE_REPO_NAME;
report = isSelf ? await verifyLocalDogfood(owner!, name!) : await verifyRemoteRepo(owner!, name!);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
const html = await renderDocsPage({
title: `SAMA verify · ${owner}/${name} · error — tdd.md`,
description: `SAMA verify could not inspect ${owner}/${name}.`,
bodyMarkdown: `# SAMA verify · \`${owner}/${name}\`\n\n> Couldn't fetch the repo: ${escape(msg)}\n\nMost common causes: the repo is private, the name is wrong, or you've hit GitHub's anonymous rate limit (60/hour). [← try another repo](/sama/verify)\n`,
ogPath: `https://tdd.md/sama/verify?repo=${owner}/${name}`,
active: "sama",
noindex: true,
pathForDocs: "/sama/verify",
editPathOverride: null,
});
return htmlResponse(html, 502);
}
const html = await renderVerifyReport(report);
return htmlResponse(html);
};
// -------- /sama (landing) --------
const SAMA_LANDING_MD = `# SAMA
> **Architecture as code, for code AI writes.** A formal v2 specification, a deterministic verifier that runs against this very repo on every deploy, and an n=8 cross-repo measurement baseline. The v1 practitioner pages are preserved below.

## the v2 specification (current)
The formal, normative spec — frozen core + profile mechanism, written so a deterministic verifier in any language can ingest it — lives at **[/sama/v2](/sama/v2)** (v2.0 draft). Four canonical layers, one import law, a binary §4 conformance gate, and §5 core metrics for cross-repo empirical measurement. The TypeScript verifier that implements §4 is itself checked by the verifier; the website is the spec is the verifier is the test suite.
The verifier at **[/sama/v2/verify](/sama/v2/verify)** runs the seven §4 conformance checks against this very repository's source on every deploy. Right now it reports **✓ conforms · 7/7 checks pass**.

## the empirical chain
Compliance is binary. The interesting question is the *delta* — what changes when the rules are followed, measured across multiple repos. §5 of the spec defines five language-neutral core metrics so the delta can be measured rather than asserted. The polyglot \`workingSetFit\` emitter has now been run against eight projects at pinned commit SHAs:

- **[Seven measured workingSetFit datapoints — what the baseline distribution actually looks like](/blog/2026-05/sama-v2-workingset-cross-repo-baseline)** — n=2 → n=7 across mature compiled-language CLI tools. Range 27pp, mean 60.68%, sample stddev 10.13pp.
- **[Pointing SAMA v2 at \`dive\`](/blog/2026-05/sama-v2-go-project-dive)** · **[Pointing SAMA v2 at \`ripgrep\`](/blog/2026-05/sama-v2-rust-project-ripgrep)** — two non-SAMA mature CLI codebases audited and scored on two §5 axes (workingSetFit + graphDepth) at pinned SHAs.
- **[The §5 metrics emitter post](/blog/2026-05/sama-v2-metrics-emitter)** — why measurement matters more than compliance, with the original metric build-out.
- **[The three v2.1 dialects at /sama/v2 §6.A](/sama/v2#6a-v21-dialects-provisional)** — provisional extensions (directory-layout, inline-tests, declarative-exemption) that the Rust + Go audits surfaced.
**tdd.md** (the only SAMA-disciplined repo measured to date) lands at **80.00%** — 6.4pp above the top of the non-SAMA baseline. Suggestive, but n=1 vs n=7 is far from a SAMA-worth-following claim. §6 of the spec is explicit that promotion requires cross-repo deltas across multiple SAMA-disciplined repos.
## drop into your agent
For agents that load skills from \`~/.claude/skills/\` (Claude Code, obra/superpowers, etc.):
\`\`\`bash
mkdir -p ~/.claude/skills
curl -fsSL https://tdd.md/skills/sama.md -o ~/.claude/skills/sama.md
\`\`\`
The skill captures the load-bearing parts of the v2 spec in obra/superpowers SKILL.md format with frontmatter, an iron-rule statement, and a verification checklist your agent runs before merging. **[Read it formatted →](/sama/skill)** · **[Raw markdown →](/skills/sama.md)**
---
## v1 practitioner pages (preserved)
The four discipline pages below are the v1 practitioner-facing version of SAMA. They predate the v2 specification and remain accessible as background reading; the formal, normative version of every rule lives in [/sama/v2](/sama/v2). The v1 pages frame the same four properties in less spec-flavoured prose, with one-page-per-discipline depth and a working CI grep at the bottom of *Sorted*.
### the four disciplines
| letter | discipline | one-line rule |
|---|---|---|
%ROWS%
### reading order
If you're new to this:
1. Start with **[Sorted](/sama/discipline/sorted)** — it has the verification grep that everything else is built around.
2. Then **[Architecture](/sama/discipline/architecture)** — what each layer prefix means.
3. Then **[Modeled](/sama/discipline/modeled)** — where types and tests live.
4. Then **[Atomic](/sama/discipline/atomic)** — the split rule that keeps the rest honest as the codebase grows.
Each page is short, opinionated, and ends with the common mistakes you'll see if the discipline lapses.
### the v1 \`sama\` CLI
For local CI and pre-commit hooks. The v1 CLI verifies the original four disciplines; the v2 verifier with the seven §4 conformance checks runs on the web at [/sama/v2/verify](/sama/v2/verify).
\`\`\`bash
mkdir -p ~/.local/bin
curl -fsSL https://tdd.md/tools/sama-cli -o ~/.local/bin/sama
chmod +x ~/.local/bin/sama
sama --help
\`\`\`
Two subcommands:
\`\`\`bash
sama check # verify the current repo's src/
sama check --json # JSON output for piping into CI tooling
sama verify-repo owner/name # verify a public GitHub repo (no token)
\`\`\`
Exit codes: \`0\` on pass, \`1\` if any check fails, \`2\` on error. The CLI is a single Bun bundle (~14 KB). [Bun](https://bun.sh) needs to be on \`PATH\`.
#### pre-commit hook
\`\`\`bash
#!/usr/bin/env bash
# Block commits that violate the v1 SAMA disciplines.
exec sama check
\`\`\`
#### GitHub Action
\`\`\`yaml
# .github/workflows/sama.yml
name: sama
on: [push, pull_request]
jobs:
verify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v2
- run: |
curl -fsSL https://tdd.md/tools/sama-cli -o sama
chmod +x sama
./sama check
\`\`\`
### the case behind it (v1 essays)
Two long-form pieces that argued *why* SAMA was shaped this way, written before the v2 spec drafted:
- [**The Claude Code harness postmortem read through TDD + SAMA**](/blog/2026-05/claude-code-harness-postmortem) — ThePaSch's r/ClaudeAI audit read against the iron law and the verification grep.
- [**Three patterns ten threads converge on**](/blog/2026-05/agentic-coding-corpus-three-patterns) — a six-month corpus of r/ClaudeAI, r/ClaudeCode, r/AgentsOfAI failure-mode threads with per-pattern mitigation tables.
### why these four together
Each property fixes a different failure mode:
- *Sorted* fails when imports go in any direction → grep proves the rule.
- *Architecture* fails when responsibilities blur → the prefix is the contract.
- *Modeled* fails when types and tests scatter → siblings are mandatory.
- *Atomic* fails when files swell → the ~700-line split keeps atoms small.
The blog post [*Red, tokens, atoms*](/blog/2026-05/three-constraints-agentic-coding) argues SAMA also compounds with TDD and Claude Code's token-saving discipline.
[← back to tdd.md](/) · [the blog](/blog) · [the guides](/guides)
`;
export const samaLandingHandler = async (): Promise<Response> => {
const rows = ALL_SAMA
.map((d) => `| **[${d.letter} — ${d.title}](/sama/${d.slug})** | ${d.rule} |`)
.join("\n");
const body = SAMA_LANDING_MD.replace("%ROWS%", rows);
const html = await renderDocsPage({
title: "SAMA — sorted, architecture, modeled, atomic — tdd.md",
description: "SAMA is a four-property file-naming and module convention for codebases that AI agents work in: sorted by layer prefix, architecture as a contract, models with siblings, atomic files. One page per discipline.",
bodyMarkdown: body,
ogPath: "https://tdd.md/sama",
active: "sama",
pathForDocs: "/sama",
editPathOverride: null,
});
return htmlResponse(html);
};
// -------- /sama/:slug (per-discipline content page) --------
export const samaSlugHandler = async (req: { params: { slug: string } }): Promise<Response> => {
const slug = req.params.slug;
const entry = ALL_SAMA.find((d) => d.slug === slug);
if (!entry) {
const html = await renderNotFound(`/sama/${slug}`);
return htmlResponse(html, 404);
}
const file = Bun.file(`./content/sama/${slug}.md`);
if (!(await file.exists())) {
const html = await renderNotFound(`/sama/${slug}`);
return htmlResponse(html, 404);
}
const rawMd = await file.text();
// Stripe-style "older version" banner — prepended to every v1
// discipline page so a reader landing directly on /sama/discipline/sorted etc.
// sees the v2-spec pointer before the v1 prose.
const v1Banner = `> **You are reading the v1 practitioner version of this property.** The formal, normative v2 specification — frozen core, profile mechanism, deterministic verifier, and §5 cross-repo measurement chain — lives at **[/sama/v2](/sama/v2)**. This page is preserved as background reading.\n\n`;
const md = v1Banner + rawMd;
const html = await renderDocsPage({
title: `SAMA · ${entry.letter} — ${entry.title} — tdd.md`,
description: entry.description,
bodyMarkdown: md,
ogPath: `https://tdd.md/sama/${slug}`,
active: "sama",
pathForDocs: `/sama/${slug}`,
});
return htmlResponse(html);
};
// -------- /tools/sama-cli (binary download) --------
export const samaCliResponse = (): Response =>
new Response(Bun.file("./public/sama-cli"), {
headers: {
"Content-Type": "text/javascript; charset=utf-8",
"Content-Disposition": 'inline; filename="sama"',
"Cache-Control": "public, max-age=300",
},
});