Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
doc-links(adr): architecture decision records as ADR nodes with their facts and SUPERSEDES
Martin Vogel6b0761160dc9
diff --git a/Makefile.cbm b/Makefile.cbmindex 4e365971b..3204c1566 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -376,6 +376,7 @@ EXTRACTION_SRCS = \$(CBM_DIR)/doclink.c \$(CBM_DIR)/doclink_cs.c \$(CBM_DIR)/doclink_md.c \+ $(CBM_DIR)/doc_adr.c \$(CBM_DIR)/sql_values.c \$(CBM_DIR)/helpers.c \$(CBM_DIR)/cpp_branch_views.c \diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.hindex 63265cebc..561862b2c 100644--- a/internal/cbm/cbm.h+++ b/internal/cbm/cbm.h@@ -288,6 +288,12 @@ typedef struct {* are bound to the owning result's source identity before cross-file use. */uint32_t test_name_start_byte, test_name_end_byte;uint32_t test_body_start_byte, test_body_end_byte;+ /* Documents only: facts a document definition adds to its node's+ * properties, as a NULL-terminated key, value, key, value, ... list (an+ * ADR's id, status, date, deciders, title). Keys are fixed literals; the+ * values are escaped where the properties are written. Tail field:+ * zero-init stays valid. */+ const char **extra_props;} CBMDefinition;/* Argument captured from a call expression */diff --git a/internal/cbm/doc_adr.c b/internal/cbm/doc_adr.cnew file mode 100644index 000000000..6913e340d--- /dev/null+++ b/internal/cbm/doc_adr.c@@ -0,0 +1,1352 @@+/*+ * doc_adr.c — architecture decision records: detection, facts, supersedes.+ *+ * A Markdown file that is an ADR gets one more definition: label "ADR", name+ * its canonical id ("ADR-12"; another prefix as written, "DEC-5"; a dated+ * record without a number keeps its file stem), qualified name+ * "<module>.__adr__", and the record's facts as node properties (adr_id,+ * title, status, date, deciders, superseded_by). Its File DEFINES it like any+ * definition, its sections link to code like any document's (doclink_md.c),+ * and its own "supersedes X" / "replaces X" statements become tokens of the+ * `supersedes` family, whose source is the ADR node: the resolver turns them+ * into SUPERSEDES edges between ADR nodes.+ *+ * "Superseded by Y" is written in the OLD record, about another file: an edge+ * from Y's node would be owned by a file whose text does not hold it, so it+ * stays a fact of this record (status superseded, superseded_by) and the link+ * itself is a MENTIONS edge of the status section.+ *+ * Detection (the field tests' rules, 99.2 % on 379 files): a file in a+ * conventional ADR directory (adr, adrs, decisions, decision-records, ...)+ * whose name carries an id or whose text has ADR structure; any `adr-NNN-*`+ * file; a numbered or dated file with ADR structure. Never README, index or+ * template files without an id, never test fixtures. Structure: a status, and+ * a context, decision, consequences, decision outcome or considered options+ * section. ADR-log configuration files (.adr-dir, log4brains) are not read:+ * per-file detection, a pure function of the path and the text.+ */+#include "doclink.h"++#include "arena.h"+#include "foundation/constants.h"+#include "helpers.h" /* cbm_memmem */++#include <stdbool.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++enum {+ ADR_ID_DIGITS = 5, /* an ADR number has at most this many digits */+ ADR_PREFIX_MIN = 2, /* `DEC-5`: a prefix of 2 ... */+ ADR_PREFIX_MAX = 12, /* ... to 12 letters */+ ADR_DOC_MAX = 500, /* the node's docstring: the decision, collapsed */+ ADR_FIELD_MAX = 256, /* a fact value is cut at a character boundary */+ ADR_FM_SCAN = 400, /* front matter ends within this many lines */+ ADR_HEAD_SCAN = 40, /* header fields within this many lines when there is no heading */+ ADR_NAME_MAX = 64, /* canonical id buffer */+ ADR_YEAR_MIN = 1900,+ ADR_YEAR_MAX = 2099,+ ADR_MONTHS = 12,+ ADR_DAYS = 31,+ ADR_YEAR_DIGITS = 4,+ ADR_MD_DIGITS = 2,+ ADR_DATE8 = 8,+ ADR_ISO_LEN = 10, /* yyyy-mm-dd */+ ADR_MONTH_ABBR = 3,+ ADR_BOM_LEN = 3, /* EF BB BF */+ ADR_RELATION_SPAN = 400, /* a relation's targets follow it in this many bytes */+};++/* ── Text helpers ────────────────────────────────────────────────── */++static bool adr_blank(char c) {+ return c == ' ' || c == '\t' || c == '\r';+}++static bool adr_digit(char c) {+ return c >= '0' && c <= '9';+}++static bool adr_alpha(char c) {+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');+}++static char adr_lower(char c) {+ return (c >= 'A' && c <= 'Z') ? (char)(c - 'A' + 'a') : c;+}++/* s[0..n) starts with `word`, ignoring case. */+static bool adr_starts_ci(const char *s, size_t n, const char *word) {+ size_t w = strlen(word);+ if (n < w) {+ return false;+ }+ for (size_t i = 0; i < w; i++) {+ if (adr_lower(s[i]) != word[i]) {+ return false;+ }+ }+ return true;+}++static bool adr_eq_ci(const char *s, size_t n, const char *word) {+ return n == strlen(word) && adr_starts_ci(s, n, word);+}++/* Trim blanks and Markdown emphasis/code marks around a value. */+static void adr_trim(const char **s, size_t *n) {+ const char *p = *s;+ size_t len = *n;+ while (len > 0 && (adr_blank(*p) || *p == '*' || *p == '_' || *p == '`' || *p == '"')) {+ p++;+ len--;+ }+ while (len > 0 &&+ (adr_blank(p[len - SKIP_ONE]) || p[len - SKIP_ONE] == '*' || p[len - SKIP_ONE] == '_' ||+ p[len - SKIP_ONE] == '`' || p[len - SKIP_ONE] == '"')) {+ len--;+ }+ *s = p;+ *n = len;+}++/* A copy of s[0..n) with Markdown links reduced to their text, `**`, `__`+ * and backticks dropped, blanks collapsed, cut at `cap` bytes on a UTF-8+ * boundary. NULL when nothing is left. */+static char *adr_plain(CBMArena *a, const char *s, size_t n, size_t cap) {+ char *out = (char *)cbm_arena_alloc(a, (n < cap ? n : cap) + SKIP_ONE);+ if (!out) {+ return NULL;+ }+ size_t w = 0;+ bool space = false;+ for (size_t i = 0; i < n && w < cap; i++) {+ char c = s[i];+ if (c == '[') {+ continue; /* [text](target): keep the text */+ }+ if (c == ']' && i + SKIP_ONE < n && s[i + SKIP_ONE] == '(') {+ const char *close = memchr(s + i, ')', n - i);+ if (close) {+ i = (size_t)(close - s);+ continue;+ }+ }+ if (c == '*' || c == '`' || (c == '_' && i + SKIP_ONE < n && s[i + SKIP_ONE] == '_')) {+ continue;+ }+ if (adr_blank(c) || c == '\n') {+ space = w > 0;+ continue;+ }+ if (space && w < cap) {+ out[w++] = ' ';+ }+ space = false;+ if (w < cap) {+ out[w++] = c;+ }+ }+ while (w > 0 && ((unsigned char)out[w - SKIP_ONE] & 0xC0) == 0x80) {+ w--; /* never end inside a character */+ }+ if (w > 0 && ((unsigned char)out[w - SKIP_ONE] & 0xC0) == 0xC0) {+ w--;+ }+ out[w] = '\0';+ return w > 0 ? out : NULL;+}++/* ── Lines ───────────────────────────────────────────────────────── */++typedef struct {+ const char *s; /* the line, not NUL-terminated */+ int n;+ bool text; /* not front matter, not fenced code, not an HTML comment */+} adr_line_t;++typedef struct {+ adr_line_t *v;+ int count;+ int fm_end; /* the first line after the front matter (0: none) */+} adr_lines_t;++static bool adr_trim_eq(const char *s, int n, const char *word) {+ const char *p = s;+ size_t len = (size_t)n;+ while (len > 0 && adr_blank(*p)) {+ p++;+ len--;+ }+ while (len > 0 && adr_blank(p[len - SKIP_ONE])) {+ len--;+ }+ return len == strlen(word) && memcmp(p, word, len) == 0;+}++static bool adr_split_lines(CBMArena *a, const char *src, int len, adr_lines_t *out) {+ int count = 0;+ for (int i = 0; i < len; i++) {+ count += src[i] == '\n';+ }+ count++;+ out->v = (adr_line_t *)cbm_arena_alloc(a, (size_t)count * sizeof(*out->v));+ if (!out->v) {+ return false;+ }+ out->count = 0;+ out->fm_end = 0;+ int pos = 0;+ if (len >= ADR_BOM_LEN && memcmp(src, "\xEF\xBB\xBF", ADR_BOM_LEN) == 0) {+ pos = ADR_BOM_LEN; /* a byte-order mark is no part of the first line */+ }+ while (pos <= len && out->count < count) {+ const char *nl = pos < len ? memchr(src + pos, '\n', (size_t)(len - pos)) : NULL;+ int end = nl ? (int)(nl - src) : len;+ int n = end - pos;+ if (n > 0 && src[pos + n - SKIP_ONE] == '\r') {+ n--;+ }+ out->v[out->count++] = (adr_line_t){.s = src + pos, .n = n, .text = true};+ pos = end + SKIP_ONE;+ }+ /* front matter */+ if (out->count > 0 && adr_trim_eq(out->v[0].s, out->v[0].n, "---")) {+ for (int k = 1; k < out->count && k < ADR_FM_SCAN; k++) {+ if (adr_trim_eq(out->v[k].s, out->v[k].n, "---") ||+ adr_trim_eq(out->v[k].s, out->v[k].n, "...")) {+ out->fm_end = k + SKIP_ONE;+ break;+ }+ }+ }+ for (int k = 0; k < out->fm_end; k++) {+ out->v[k].text = false;+ }+ /* fences and HTML comments */+ char fence = 0;+ int fence_len = 0;+ bool comment = false;+ for (int k = out->fm_end; k < out->count; k++) {+ adr_line_t *l = &out->v[k];+ int i = 0;+ while (i < l->n && adr_blank(l->s[i])) {+ i++;+ }+ int run = 0;+ while (i + run < l->n && (l->s[i + run] == '`' || l->s[i + run] == '~') &&+ l->s[i + run] == l->s[i]) {+ run++;+ }+ if (fence) {+ l->text = false;+ if (run >= fence_len && l->s[i] == fence) {+ fence = 0;+ }+ continue;+ }+ if (run >= PAIR_LEN + SKIP_ONE) {+ fence = l->s[i];+ fence_len = run;+ l->text = false;+ continue;+ }+ if (comment) {+ l->text = false;+ if (cbm_memmem(l->s, (size_t)l->n, "-->", PAIR_LEN + SKIP_ONE)) {+ comment = false;+ }+ continue;+ }+ if (l->n - i >= 4 && memcmp(l->s + i, "<!--", 4) == 0 &&+ !cbm_memmem(l->s + i + 4, (size_t)(l->n - i - 4), "-->", PAIR_LEN + SKIP_ONE)) {+ comment = true;+ l->text = false;+ }+ }+ return true;+}++/* ── Front matter (top-level scalars and lists) ──────────────────── */++/* The value of front-matter key `key` (a list joined with ", "), or NULL. */+static char *adr_fm_value(CBMArena *a, const adr_lines_t *L, const char *key) {+ size_t kl = strlen(key);+ for (int k = SKIP_ONE; k < L->fm_end - SKIP_ONE; k++) {+ const adr_line_t *l = &L->v[k];+ if ((size_t)l->n <= kl || l->s[0] == ' ' || l->s[0] == '\t' ||+ !adr_starts_ci(l->s, (size_t)l->n, key) || l->s[kl] != ':') {+ continue;+ }+ const char *v = l->s + kl + SKIP_ONE;+ size_t vn = (size_t)l->n - kl - SKIP_ONE;+ adr_trim(&v, &vn);+ if (vn > 0 && v[0] == '[' && v[vn - SKIP_ONE] == ']') {+ v++;+ vn -= PAIR_LEN;+ }+ if (vn > 0) {+ return adr_plain(a, v, vn, ADR_FIELD_MAX);+ }+ /* a block list on the following lines */+ char buf[ADR_FIELD_MAX + SKIP_ONE];+ size_t w = 0;+ for (int j = k + SKIP_ONE; j < L->fm_end - SKIP_ONE; j++) {+ const adr_line_t *it = &L->v[j];+ int i = 0;+ while (i < it->n && adr_blank(it->s[i])) {+ i++;+ }+ if (i == 0 || i >= it->n || it->s[i] != '-') {+ break;+ }+ const char *iv = it->s + i + SKIP_ONE;+ size_t ivn = (size_t)(it->n - i - SKIP_ONE);+ adr_trim(&iv, &ivn);+ if (ivn > 0 && w + ivn + PAIR_LEN < sizeof(buf)) {+ if (w > 0) {+ buf[w++] = ',';+ buf[w++] = ' ';+ }+ memcpy(buf + w, iv, ivn);+ w += ivn;+ }+ }+ return w > 0 ? adr_plain(a, buf, w, ADR_FIELD_MAX) : NULL;+ }+ return NULL;+}++/* ── Headings (the file's Section definitions) ───────────────────── */++typedef struct {+ int line; /* 0-based index into the lines */+ int level; /* 1..6 */+ const char *title;+ size_t title_n;+} adr_head_t;++static int adr_head_cmp(const void *a, const void *b) {+ const adr_head_t *x = (const adr_head_t *)a;+ const adr_head_t *y = (const adr_head_t *)b;+ return (x->line > y->line) - (x->line < y->line);+}++/* The level of the heading on line k: `#` count, or 1/2 for a setext+ * underline of `=`/`-` on the next line; 0 when the line is no heading. */+static int adr_heading_level(const adr_lines_t *L, int k, const char **title, size_t *title_n) {+ const adr_line_t *l = &L->v[k];+ int i = 0;+ while (i < l->n && i < (PAIR_LEN + SKIP_ONE) && l->s[i] == ' ') {+ i++;+ }+ int hashes = 0;+ while (i + hashes < l->n && l->s[i + hashes] == '#') {+ hashes++;+ }+ if (hashes > 0 && hashes <= (PAIR_LEN * PAIR_LEN + PAIR_LEN) &&+ (i + hashes == l->n || adr_blank(l->s[i + hashes]))) {+ const char *t = l->s + i + hashes;+ size_t tn = (size_t)(l->n - i - hashes);+ while (tn > 0 && (t[tn - SKIP_ONE] == '#' || adr_blank(t[tn - SKIP_ONE]))) {+ tn--;+ }+ adr_trim(&t, &tn);+ *title = t;+ *title_n = tn;+ return hashes;+ }+ if (k + SKIP_ONE < L->count) {+ const adr_line_t *u = &L->v[k + SKIP_ONE];+ int j = 0;+ while (j < u->n && u->s[j] == ' ') {+ j++;+ }+ char c = j < u->n ? u->s[j] : 0;+ int run = 0;+ while (j + run < u->n && u->s[j + run] == c) {+ run++;+ }+ bool rest_blank = true;+ for (int r = j + run; r < u->n; r++) {+ rest_blank = rest_blank && adr_blank(u->s[r]);+ }+ if ((c == '=' || c == '-') && run >= SKIP_ONE && rest_blank) {+ const char *t = l->s;+ size_t tn = (size_t)l->n;+ adr_trim(&t, &tn);+ *title = t;+ *title_n = tn;+ return c == '=' ? SKIP_ONE : PAIR_LEN;+ }+ }+ return 0;+}++/* Section kinds the facts and the detection read. */+typedef enum {+ ADR_SEC_OTHER = 0,+ ADR_SEC_STATUS,+ ADR_SEC_CONTEXT,+ ADR_SEC_DECISION,+ ADR_SEC_OUTCOME,+ ADR_SEC_OPTIONS,+ ADR_SEC_CONSEQUENCES,+} adr_sec_t;++static adr_sec_t adr_section_kind(const char *t, size_t n) {+ /* a leading "1." / "2.3 " numbering is no part of the title */+ size_t i = 0;+ while (i < n && (adr_digit(t[i]) || t[i] == '.')) {+ i++;+ }+ if (i > 0 && i < n && t[i] == ' ') {+ t += i + SKIP_ONE;+ n -= i + SKIP_ONE;+ }+ while (n > 0 && (t[n - SKIP_ONE] == ':' || adr_blank(t[n - SKIP_ONE]))) {+ n--;+ }+ if (adr_eq_ci(t, n, "status") || adr_starts_ci(t, n, "status:")) {+ return ADR_SEC_STATUS;+ }+ if (adr_eq_ci(t, n, "context") || adr_starts_ci(t, n, "context and problem") ||+ adr_eq_ci(t, n, "problem") || adr_eq_ci(t, n, "problem statement") ||+ adr_eq_ci(t, n, "background") || adr_eq_ci(t, n, "motivation")) {+ return ADR_SEC_CONTEXT;+ }+ if (adr_eq_ci(t, n, "decision outcome")) {+ return ADR_SEC_OUTCOME;+ }+ if (adr_eq_ci(t, n, "decision") || adr_eq_ci(t, n, "decisions") ||+ adr_eq_ci(t, n, "the decision")) {+ return ADR_SEC_DECISION;+ }+ if (adr_eq_ci(t, n, "considered options") || adr_eq_ci(t, n, "options considered") ||+ adr_eq_ci(t, n, "alternatives") || adr_eq_ci(t, n, "alternatives considered")) {+ return ADR_SEC_OPTIONS;+ }+ if (adr_eq_ci(t, n, "consequences") || adr_starts_ci(t, n, "positive consequences") ||+ adr_starts_ci(t, n, "negative consequences")) {+ return ADR_SEC_CONSEQUENCES;+ }+ return ADR_SEC_OTHER;+}++/* ── File names ──────────────────────────────────────────────────── */++typedef enum {+ ADR_ID_NONE = 0,+ ADR_ID_ADR, /* adr-012-title.md */+ ADR_ID_NUMBER, /* 0012-title.md */+ ADR_ID_PREFIX, /* DEC-005-title.md */+ ADR_ID_DATE, /* 2023-04-05-title.md, 20230405-title.md */+} adr_id_kind_t;++typedef struct {+ adr_id_kind_t kind;+ unsigned number;+ char prefix[ADR_PREFIX_MAX + SKIP_ONE];+ char date[ADR_ISO_LEN + SKIP_ONE];+} adr_id_t;++/* Digits at s, at most ADR_ID_DIGITS, followed by a separator or the end. */+static bool adr_number_at(const char *s, size_t n, size_t *used, unsigned *value) {+ size_t i = 0;+ unsigned v = 0;+ while (i < n && adr_digit(s[i])) {+ if (i >= ADR_ID_DIGITS + ADR_ID_DIGITS) {+ return false;+ }+ v = (v * CBM_DECIMAL_BASE) + (unsigned)(s[i] - '0');+ i++;+ }+ size_t significant = i;+ for (size_t z = 0; z < i && s[z] == '0' && significant > SKIP_ONE; z++) {+ significant--;+ }+ if (i == 0 || significant > ADR_ID_DIGITS) {+ return false;+ }+ if (i < n && s[i] != '-' && s[i] != '_' && s[i] != ' ' && s[i] != '.') {+ return false;+ }+ *used = i;+ *value = v;+ return true;+}++static bool adr_date_prefix(const char *s, size_t n, char *iso) {+ /* yyyy-mm-dd or yyyymmdd, then '-' or '_' */+ if (n > ADR_ISO_LEN && adr_digit(s[0]) && s[4] == '-' && s[7] == '-' &&+ (s[ADR_ISO_LEN] == '-' || s[ADR_ISO_LEN] == '_')) {+ for (int i = 0; i < ADR_ISO_LEN; i++) {+ if (i != 4 && i != 7 && !adr_digit(s[i])) {+ return false;+ }+ }+ memcpy(iso, s, ADR_ISO_LEN);+ iso[ADR_ISO_LEN] = '\0';+ return (s[0] == '1' && s[1] == '9') || (s[0] == '2' && s[1] == '0');+ }+ if (n > ADR_DATE8 && (s[ADR_DATE8] == '-' || s[ADR_DATE8] == '_')) {+ for (int i = 0; i < ADR_DATE8; i++) {+ if (!adr_digit(s[i])) {+ return false;+ }+ }+ snprintf(iso, ADR_ISO_LEN + SKIP_ONE, "%.4s-%.2s-%.2s", s, s + 4, s + 6);+ return (s[0] == '1' && s[1] == '9') || (s[0] == '2' && s[1] == '0');+ }+ return false;+}++static void adr_filename_id(const char *base, adr_id_t *id) {+ memset(id, 0, sizeof(*id));+ size_t n = strlen(base);+ size_t used = 0;+ unsigned v = 0;+ if (adr_starts_ci(base, n, "adr")) {+ size_t i = PAIR_LEN + SKIP_ONE;+ if (i < n && (base[i] == '-' || base[i] == '_' || base[i] == ' ')) {+ i++;+ }+ if (adr_number_at(base + i, n - i, &used, &v)) {+ id->kind = ADR_ID_ADR;+ id->number = v;+ return;+ }+ }+ if (adr_date_prefix(base, n, id->date)) {+ id->kind = ADR_ID_DATE;+ return;+ }+ if (adr_number_at(base, n, &used, &v) && used < n) {+ id->kind = ADR_ID_NUMBER;+ id->number = v;+ return;+ }+ size_t p = 0;+ while (p < n && adr_alpha(base[p])) {+ p++;+ }+ if (p >= ADR_PREFIX_MIN && p <= ADR_PREFIX_MAX && p < n && (base[p] == '-' || base[p] == '_') &&+ adr_number_at(base + p + SKIP_ONE, n - p - SKIP_ONE, &used, &v) &&+ p + SKIP_ONE + used < n) {+ id->kind = ADR_ID_PREFIX;+ id->number = v;+ for (size_t i = 0; i < p; i++) {+ id->prefix[i] =+ (base[i] >= 'a' && base[i] <= 'z') ? (char)(base[i] - 'a' + 'A') : base[i];+ }+ id->prefix[p] = '\0';+ }+}++static const char *const ADR_CONV_DIRS[] = {"adr",+ "adrs",+ "decisions",+ "decision-records",+ "decision_records",+ "architecture-decisions",+ "architecture_decisions",+ "architectural-decisions",+ "architecture-decision-records",+ "decision-log",+ NULL};++static const char *const ADR_FIXTURE_DIRS[] = {+ "test", "tests", "__tests__", "integration-tests", "integration_tests",+ "e2e-tests", "e2e_tests", "testdata", "test-data", "test_data",+ "fixture", "fixtures", "__fixtures__", "__mocks__", "mock",+ "mocks", NULL};++static const char *const ADR_NON_ADR_STEMS[] = {"readme", "index", "_index", "toc",+ "summary", "contributing", "process", "changelog",+ "glossary", "license", NULL};++static bool adr_in(const char *s, size_t n, const char *const *list) {+ for (size_t i = 0; list[i]; i++) {+ if (adr_eq_ci(s, n, list[i])) {+ return true;+ }+ }+ return false;+}++/* Does a directory of `rel` match the list? */+static bool adr_dir_in(const char *rel, const char *const *list) {+ const char *s = rel;+ for (const char *slash = strchr(s, '/'); slash; slash = strchr(s, '/')) {+ if (adr_in(s, (size_t)(slash - s), list)) {+ return true;+ }+ s = slash + SKIP_ONE;+ }+ return false;+}++/* README, index, template ... (only for a name without an id). */+static bool adr_non_adr_name(const char *base) {+ size_t n = strlen(base);+ const char *dot = strchr(base, '.');+ size_t stem = dot ? (size_t)(dot - base) : n;+ if (adr_in(base, stem, ADR_NON_ADR_STEMS)) {+ return true;+ }+ for (size_t i = 0; i + strlen("template") <= n; i++) {+ bool start = i == 0 || base[i - SKIP_ONE] == '-' || base[i - SKIP_ONE] == '_' ||+ base[i - SKIP_ONE] == '.';+ size_t e = i + strlen("template");+ bool end = e == n || base[e] == '-' || base[e] == '_' || base[e] == '.';+ if (start && end && adr_starts_ci(base + i, n - i, "template")) {+ return true;+ }+ }+ return false;+}++/* ── Status, dates, people ───────────────────────────────────────── */++static const struct {+ const char *status;+ const char *words[8];+} ADR_STATUS_WORDS[] = {+ {"superseded", {"supersed", "replaced by", NULL}},+ {"deprecated", {"deprecat", "obsolete", NULL}},+ {"rejected", {"reject", "declined", NULL}},+ {"abandoned", {"abandon", "withdrawn", "cancelled", "canceled", NULL}},+ {"implemented", {"implemented", "done", "completed", "complete", NULL}},+ {"accepted", {"accept", "approved", "adopted", "agreed", "decided", "active", "final", NULL}},+ {"proposed",+ {"propos", "in review", "under review", "pending", "rfc", "under consideration", NULL}},+ {"draft", {"draft", "wip", "work in progress", "in progress", NULL}},+};++/* The normalized status of a status text: the first status word (at a word+ * start, not after "not ", "non-" or "un"), "unknown" when none. */+static const char *adr_norm_status(const char *s) {+ size_t n = strlen(s);+ for (size_t i = 0; i < n; i++) {+ if (i > 0 && (adr_alpha(s[i - SKIP_ONE]) || adr_digit(s[i - SKIP_ONE]))) {+ continue;+ }+ bool negated = (i >= 4 && adr_starts_ci(s + i - 4, 4, "not ")) ||+ (i >= 4 && adr_starts_ci(s + i - 4, 4, "non-"));+ for (size_t k = 0; k < sizeof(ADR_STATUS_WORDS) / sizeof(ADR_STATUS_WORDS[0]); k++) {+ for (size_t w = 0; ADR_STATUS_WORDS[k].words[w]; w++) {+ /* a whole word, or a stem ("accept" in "accepted") */+ if (adr_starts_ci(s + i, n - i, ADR_STATUS_WORDS[k].words[w]) && !negated &&+ !(i >= PAIR_LEN && adr_starts_ci(s + i - PAIR_LEN, PAIR_LEN, "un"))) {+ return ADR_STATUS_WORDS[k].status;+ }+ }+ }+ }+ return "unknown";+}++static const char *const ADR_MONTHS_ABBR[ADR_MONTHS] = {"jan", "feb", "mar", "apr", "may", "jun",+ "jul", "aug", "sep", "oct", "nov", "dec"};++static int adr_month(const char *s, size_t n) {+ if (n < ADR_MONTH_ABBR) {+ return 0;+ }+ for (int m = 0; m < ADR_MONTHS; m++) {+ if (adr_starts_ci(s, n, ADR_MONTHS_ABBR[m])) {+ return m + SKIP_ONE;+ }+ }+ return 0;+}++static int adr_num(const char *s, size_t n, size_t *used) {+ size_t i = 0;+ int v = 0;+ while (i < n && adr_digit(s[i]) && i < ADR_YEAR_DIGITS + SKIP_ONE) {+ v = (v * CBM_DECIMAL_BASE) + (s[i] - '0');+ i++;+ }+ *used = i;+ return v;+}++/* An explicit date in s: yyyy-mm-dd (or / .), yyyymmdd, "d Month yyyy",+ * "Month d, yyyy", or "Month yyyy" (month precision). Ambiguous numeric+ * day/month orders give nothing. */+static bool adr_parse_date(const char *s, char *out, size_t cap) {+ size_t n = strlen(s);+ for (size_t i = 0; i < n; i++) {+ if (i > 0 && (adr_digit(s[i - SKIP_ONE]) || adr_alpha(s[i - SKIP_ONE]))) {+ continue;+ }+ size_t u = 0;+ int y = adr_num(s + i, n - i, &u);+ if (u == ADR_YEAR_DIGITS && y >= ADR_YEAR_MIN && y <= ADR_YEAR_MAX && i + u < n &&+ (s[i + u] == '-' || s[i + u] == '/' || s[i + u] == '.')) {+ size_t u2 = 0;+ int mo = adr_num(s + i + u + SKIP_ONE, n - i - u - SKIP_ONE, &u2);+ size_t at = i + u + SKIP_ONE + u2;+ if (u2 >= SKIP_ONE && u2 <= ADR_MD_DIGITS && at < n && s[at] == s[i + u]) {+ size_t u3 = 0;+ int d = adr_num(s + at + SKIP_ONE, n - at - SKIP_ONE, &u3);+ if (u3 >= SKIP_ONE && u3 <= ADR_MD_DIGITS && mo >= 1 && mo <= ADR_MONTHS &&+ d >= 1 && d <= ADR_DAYS) {+ snprintf(out, cap, "%04d-%02d-%02d", y, mo, d);+ return true;+ }+ }+ }+ /* yyyy Month d: "2019 Jul 31" */+ if (u == ADR_YEAR_DIGITS && y >= ADR_YEAR_MIN && y <= ADR_YEAR_MAX && i + u < n &&+ (s[i + u] == ' ' || s[i + u] == ',')) {+ const char *p = s + i + u;+ while (p < s + n && (*p == ' ' || *p == ',')) {+ p++;+ }+ int mo = adr_month(p, (size_t)(s + n - p));+ if (mo) {+ while (p < s + n && adr_alpha(*p)) {+ p++;+ }+ while (p < s + n && (*p == '.' || *p == ' ' || *p == ',')) {+ p++;+ }+ size_t ud = 0;+ int d = adr_num(p, (size_t)(s + n - p), &ud);+ if (ud >= SKIP_ONE && ud <= ADR_MD_DIGITS && d >= 1 && d <= ADR_DAYS) {+ snprintf(out, cap, "%04d-%02d-%02d", y, mo, d);+ return true;+ }+ }+ }+ /* a/b/yyyy, a.b.yyyy: only when one of a, b is above 12 */+ if (u >= SKIP_ONE && u <= ADR_MD_DIGITS && i + u < n &&+ (s[i + u] == '/' || s[i + u] == '.')) {+ char sep = s[i + u];+ size_t u2 = 0;+ int b = adr_num(s + i + u + SKIP_ONE, n - i - u - SKIP_ONE, &u2);+ size_t at = i + u + SKIP_ONE + u2;+ size_t u3 = 0;+ int yy = (u2 >= SKIP_ONE && u2 <= ADR_MD_DIGITS && at < n && s[at] == sep)+ ? adr_num(s + at + SKIP_ONE, n - at - SKIP_ONE, &u3)+ : 0;+ if (u3 == ADR_YEAR_DIGITS && yy >= ADR_YEAR_MIN && yy <= ADR_YEAR_MAX) {+ int mo = 0;+ int d = 0;+ if (y > ADR_MONTHS && b >= 1 && b <= ADR_MONTHS && y <= ADR_DAYS) {+ d = y;+ mo = b;+ } else if (b > ADR_MONTHS && y >= 1 && y <= ADR_MONTHS && b <= ADR_DAYS) {+ mo = y;+ d = b;+ }+ if (mo) {+ snprintf(out, cap, "%04d-%02d-%02d", yy, mo, d);+ return true;+ }+ }+ }+ if (u == ADR_DATE8) {+ int yy = y / 10000;+ int mo = (y / 100) % 100;+ int d = y % 100;+ if (yy >= ADR_YEAR_MIN && yy <= ADR_YEAR_MAX && mo >= 1 && mo <= ADR_MONTHS && d >= 1 &&+ d <= ADR_DAYS) {+ snprintf(out, cap, "%04d-%02d-%02d", yy, mo, d);+ return true;+ }+ }+ /* d Month yyyy */+ if (u >= SKIP_ONE && u <= ADR_MD_DIGITS && i + u < n && s[i + u] == ' ') {+ const char *m = s + i + u + SKIP_ONE;+ int mo = adr_month(m, n - (size_t)(m - s));+ if (mo) {+ const char *p = m;+ while (p < s + n && adr_alpha(*p)) {+ p++;+ }+ while (p < s + n && (*p == '.' || *p == ',' || *p == ' ')) {+ p++;+ }+ size_t uy = 0;+ int yy = adr_num(p, (size_t)(s + n - p), &uy);+ if (uy == ADR_YEAR_DIGITS && yy >= ADR_YEAR_MIN && yy <= ADR_YEAR_MAX && y >= 1 &&+ y <= ADR_DAYS) {+ snprintf(out, cap, "%04d-%02d-%02d", yy, mo, y);+ return true;+ }+ }+ }+ /* Month d, yyyy / Month yyyy */+ int mo = u == 0 ? adr_month(s + i, n - i) : 0;+ if (mo) {+ const char *p = s + i;+ while (p < s + n && adr_alpha(*p)) {+ p++;+ }+ while (p < s + n && (*p == '.' || *p == ' ')) {+ p++;+ }+ size_t ud = 0;+ int d = adr_num(p, (size_t)(s + n - p), &ud);+ if (ud >= SKIP_ONE && ud <= ADR_MD_DIGITS) {+ const char *q = p + ud;+ while (q < s + n && (adr_alpha(*q) || *q == ',' || *q == ' ')) {+ q++; /* "5th, " */+ }+ size_t uy = 0;+ int yy = adr_num(q, (size_t)(s + n - q), &uy);+ if (uy == ADR_YEAR_DIGITS && yy >= ADR_YEAR_MIN && yy <= ADR_YEAR_MAX && d >= 1 &&+ d <= ADR_DAYS) {+ snprintf(out, cap, "%04d-%02d-%02d", yy, mo, d);+ return true;+ }+ } else if (ud == ADR_YEAR_DIGITS && d >= ADR_YEAR_MIN && d <= ADR_YEAR_MAX) {+ snprintf(out, cap, "%04d-%02d", d, mo);+ return true;+ }+ }+ }+ return false;+}++/* ── Header fields ───────────────────────────────────────────────── */++/* `Status: Accepted`, `* Status: Accepted`, `**Status:** Accepted`,+ * `| Status | Accepted |`: the value of `key` on line l, or NULL. */+static char *adr_field(CBMArena *a, const adr_line_t *l, const char *key) {+ char buf[ADR_FIELD_MAX * PAIR_LEN];+ size_t w = 0;+ for (int i = 0; i < l->n && w + SKIP_ONE < sizeof(buf); i++) {+ if (l->s[i] == '*' || (l->s[i] == '_' && i + SKIP_ONE < l->n && l->s[i + 1] == '_')) {+ continue; /* emphasis around the key */+ }+ buf[w++] = l->s[i];+ }+ buf[w] = '\0';+ const char *p = buf;+ while (*p && adr_blank(*p)) {+ p++;+ }+ bool table = *p == '|';+ if (table) {+ p++;+ while (*p && adr_blank(*p)) {+ p++;+ }+ } else if ((*p == '-' || *p == '+') && adr_blank(p[SKIP_ONE])) {+ p += PAIR_LEN;+ while (*p && adr_blank(*p)) {+ p++;+ }+ }+ size_t kl = strlen(key);+ if (!adr_starts_ci(p, strlen(p), key)) {+ return NULL;+ }+ p += kl;+ while (*p && adr_blank(*p)) {+ p++;+ }+ if (*p != (table ? '|' : ':')) {+ return NULL;+ }+ p++;+ const char *end = table ? strchr(p, '|') : NULL;+ size_t vn = end ? (size_t)(end - p) : strlen(p);+ adr_trim(&p, &vn);+ return vn > 0 ? adr_plain(a, p, vn, ADR_FIELD_MAX) : NULL;+}++/* ── The record ──────────────────────────────────────────────────── */++typedef struct {+ CBMExtractCtx *ctx;+ adr_lines_t L;+ adr_head_t *heads;+ int nheads;+ int title_head; /* index into heads, or -1 */+} adr_doc_t;++/* The paragraph after heading h (its first non-blank text lines). */+static char *adr_first_paragraph(CBMArena *a, const adr_doc_t *d, int h, size_t cap) {+ int start = d->heads[h].line + SKIP_ONE;+ int end = h + SKIP_ONE < d->nheads ? d->heads[h + SKIP_ONE].line : d->L.count;+ int k = start;+ while (k < end &&+ (!d->L.v[k].text || d->L.v[k].n == 0 || adr_trim_eq(d->L.v[k].s, d->L.v[k].n, "") ||+ d->L.v[k].s[0] == '=' || d->L.v[k].s[0] == '-')) {+ k++;+ }+ if (k >= end) {+ return NULL;+ }+ const char *s = d->L.v[k].s;+ int last = k;+ while (last + SKIP_ONE < end && d->L.v[last + SKIP_ONE].text &&+ !adr_trim_eq(d->L.v[last + SKIP_ONE].s, d->L.v[last + SKIP_ONE].n, "")) {+ last++;+ }+ const char *e = d->L.v[last].s + d->L.v[last].n;+ return adr_plain(a, s, (size_t)(e - s), cap);+}++/* The text of section h, as one collapsed string. */+static char *adr_section_text(CBMArena *a, const adr_doc_t *d, int h, size_t cap) {+ int start = d->heads[h].line + SKIP_ONE;+ int end = h + SKIP_ONE < d->nheads ? d->heads[h + SKIP_ONE].line : d->L.count;+ if (start >= end) {+ return NULL;+ }+ const char *s = d->L.v[start].s;+ const char *e = d->L.v[end - SKIP_ONE].s + d->L.v[end - SKIP_ONE].n;+ return e > s ? adr_plain(a, s, (size_t)(e - s), cap) : NULL;+}++static int adr_find_section(const adr_doc_t *d, adr_sec_t kind) {+ for (int h = 0; h < d->nheads; h++) {+ if (adr_section_kind(d->heads[h].title, d->heads[h].title_n) == kind) {+ return h;+ }+ }+ return CBM_NOT_FOUND;+}++/* The value of header field `key` between the title and the first body+ * heading (the first lines when there is no heading). */+static char *adr_header_field(CBMArena *a, const adr_doc_t *d, const char *key) {+ int from = d->title_head >= 0 ? d->heads[d->title_head].line + SKIP_ONE : d->L.fm_end;+ int to = d->L.count;+ for (int h = 0; h < d->nheads; h++) {+ if (h != d->title_head && d->heads[h].line >= from) {+ to = d->heads[h].line;+ break;+ }+ }+ if (to == d->L.count && to - from > ADR_HEAD_SCAN) {+ to = from + ADR_HEAD_SCAN;+ }+ for (int k = from; k < to; k++) {+ if (!d->L.v[k].text) {+ continue;+ }+ char *v = adr_field(a, &d->L.v[k], key);+ if (v) {+ return v;+ }+ }+ return NULL;+}++/* ── Relations ───────────────────────────────────────────────────── */++/* `ADR-12`, `ADR 012`, `adr_7`: the number, and the reference's length. */+static bool adr_id_ref(const char *s, size_t n, unsigned *number, size_t *len) {+ if (n < PAIR_LEN * PAIR_LEN || !adr_starts_ci(s, n, "adr") ||+ (s[3] != '-' && s[3] != '_' && s[3] != ' ')) {+ return false;+ }+ size_t used = 0;+ unsigned v = 0;+ size_t i = PAIR_LEN * PAIR_LEN;+ size_t d = 0;+ while (i + d < n && adr_digit(s[i + d])) {+ d++;+ }+ if (d == 0 || (i + d < n && (adr_alpha(s[i + d]) || s[i + d] == '_'))) {+ return false;+ }+ if (!adr_number_at(s + i, d, &used, &v)) {+ return false;+ }+ *number = v;+ *len = i + d;+ return true;+}++static void adr_push_relation(adr_doc_t *d, const char *adr_qn, const char *raw, size_t n,+ uint32_t line) {+ CBMArena *a = d->ctx->arena;+ char *text = cbm_arena_strndup(a, raw, n);+ if (!text) {+ d->ctx->result->doc_links.failed = true;+ return;+ }+ CBMDocLink link = {.source_qn = adr_qn,+ .raw = text,+ .line = line,+ .def_line = SKIP_ONE,+ .syntax = (uint16_t)CBM_DOCLINK_MD_SUPERSEDES,+ .flags = 0};+ cbm_doclinks_push(&d->ctx->result->doc_links, a, link);+}++/* The targets after a relation phrase, up to the end of its sentence: link+ * destinations and ADR ids. Forward relations become tokens; for a backward+ * one ("superseded by") the targets are joined into `*joined`. */+static void adr_targets(adr_doc_t *d, const char *adr_qn, const char *s, size_t n, uint32_t line,+ bool forward, char *joined, size_t jcap) {+ size_t end = n < ADR_RELATION_SPAN ? n : ADR_RELATION_SPAN;+ for (size_t i = 0; i + SKIP_ONE < end; i++) {+ if ((s[i] == '.' && (i + SKIP_ONE == end || adr_blank(s[i + SKIP_ONE])) &&+ !(i > 0 && adr_digit(s[i - SKIP_ONE]))) ||+ s[i] == ';') {+ end = i;+ break;+ }+ }+ for (size_t i = 0; i < end; i++) {+ const char *target = NULL;+ size_t tn = 0;+ const char *rb = s[i] == '[' ? memchr(s + i, ']', end - i) : NULL;+ if (rb && rb + SKIP_ONE < s + end && rb[SKIP_ONE] == '(') {+ /* [text](destination): one reference, the destination; ids in+ * the link text name the same record */+ const char *dest = rb + PAIR_LEN;+ const char *close = memchr(dest, ')', (size_t)(s + end - dest));+ if (close) {+ target = dest;+ tn = (size_t)(close - dest);+ i = (size_t)(close - s);+ }+ } else {+ unsigned num = 0;+ size_t len = 0;+ if ((i == 0 || !adr_alpha(s[i - SKIP_ONE])) && adr_id_ref(s + i, end - i, &num, &len)) {+ target = s + i;+ tn = len;+ i += len - SKIP_ONE;+ }+ }+ if (!target || tn == 0) {+ continue;+ }+ if (forward) {+ adr_push_relation(d, adr_qn, target, tn, line);+ } else if (joined) {+ size_t w = strlen(joined);+ bool seen = false;+ for (const char *p = joined; *p && !seen; p++) {+ seen = strncmp(p, target, tn) == 0 && (p[tn] == '\0' || p[tn] == ',') &&+ (p == joined || p[-SKIP_ONE] == ' ');+ }+ if (!seen && w + tn + PAIR_LEN < jcap) {+ if (w > 0) {+ joined[w++] = ',';+ joined[w++] = ' ';+ }+ memcpy(joined + w, target, tn);+ joined[w + tn] = '\0';+ }+ }+ }+}++/* Only list markers, quote marks, table bars and emphasis before position i+ * of the line: the phrase opens the line's statement. */+static bool adr_line_head(const adr_line_t *l, int i) {+ for (int k = 0; k < i; k++) {+ char c = l->s[k];+ if (!adr_blank(c) && c != '-' && c != '*' && c != '+' && c != '>' && c != '_' && c != '|') {+ return false;+ }+ }+ return true;+}++/* "supersedes" and "superseded by" are ADR words wherever they stand;+ * "replaces" and "replaced by" are ordinary verbs of technical prose ("this+ * middleware replaces the recovery described in ADR-22") and state a relation+ * only where they open a line or list item ("Replaces ADR-3"). */+static void adr_relations(adr_doc_t *d, const char *adr_qn, char *superseded_by, size_t cap) {+ static const struct {+ const char *phrase;+ bool forward;+ bool line_head;+ } phrases[] = {{"superseded by", false, false},+ {"replaced by", false, true},+ {"supersedes", true, false},+ {"replaces", true, true}};+ for (int k = d->L.fm_end; k < d->L.count; k++) {+ const adr_line_t *l = &d->L.v[k];+ if (!l->text) {+ continue;+ }+ for (int i = 0; i < l->n; i++) {+ if (i > 0 && adr_alpha(l->s[i - SKIP_ONE])) {+ continue;+ }+ for (size_t p = 0; p < sizeof(phrases) / sizeof(phrases[0]); p++) {+ size_t pl = strlen(phrases[p].phrase);+ if (adr_starts_ci(l->s + i, (size_t)(l->n - i), phrases[p].phrase) &&+ (i + (int)pl == l->n || !adr_alpha(l->s[i + (int)pl])) &&+ (!phrases[p].line_head || adr_line_head(l, i))) {+ adr_targets(d, adr_qn, l->s + i + pl, (size_t)(l->n - i - (int)pl),+ (uint32_t)(k + SKIP_ONE), phrases[p].forward, superseded_by, cap);+ i += (int)pl - SKIP_ONE;+ break;+ }+ }+ }+ }+}++/* A template's choice list, `{proposed | accepted}` or `[a | b]`: the field+ * was never filled in. A filled-in value that kept its braces (`{proposed}`)+ * is a value. */+static bool adr_placeholder(const char *s) {+ for (const char *p = s; *p; p++) {+ if (*p != '{' && *p != '[') {+ continue;+ }+ char close = *p == '{' ? '}' : ']';+ for (const char *q = p + SKIP_ONE; *q && *q != close; q++) {+ if (*q == '|') {+ return true;+ }+ }+ }+ return false;+}++/* The first date in the record's change-log section ("Changelog", "Change+ * log", "History", "Revision history"): `* 2019-12-12: Initial version`. */+static bool adr_changelog_date(const adr_doc_t *d, char *out, size_t cap) {+ for (int h = 0; h < d->nheads; h++) {+ const char *t = d->heads[h].title;+ size_t n = d->heads[h].title_n;+ while (n > 0 && (t[n - SKIP_ONE] == ':' || adr_blank(t[n - SKIP_ONE]))) {+ n--;+ }+ if (!adr_eq_ci(t, n, "changelog") && !adr_eq_ci(t, n, "change log") &&+ !adr_eq_ci(t, n, "history") && !adr_eq_ci(t, n, "revision history")) {+ continue;+ }+ int end = h + SKIP_ONE < d->nheads ? d->heads[h + SKIP_ONE].line : d->L.count;+ for (int k = d->heads[h].line + SKIP_ONE; k < end; k++) {+ char line[ADR_FIELD_MAX];+ const adr_line_t *l = &d->L.v[k];+ if (!l->text || l->n == 0) {+ continue;+ }+ snprintf(line, sizeof(line), "%.*s", l->n, l->s);+ if (adr_parse_date(line, out, cap)) {+ return true;+ }+ }+ return false;+ }+ return false;+}++/* ── The driver ──────────────────────────────────────────────────── */++static bool adr_ends_ci(const char *s, const char *suffix) {+ size_t n = strlen(s);+ size_t k = strlen(suffix);+ return n > k && adr_eq_ci(s + n - k, k, suffix);+}++static bool adr_markdown_path(const char *rel) {+ return adr_ends_ci(rel, ".md") || adr_ends_ci(rel, ".mdx") || adr_ends_ci(rel, ".markdown");+}++void cbm_adr_extract(CBMExtractCtx *ctx) {+ if (!ctx || !ctx->result || !ctx->source || ctx->source_len <= 0 || !ctx->rel_path ||+ !adr_markdown_path(ctx->rel_path)) {+ return;+ }+ const char *rel = ctx->rel_path;+ const char *base = strrchr(rel, '/');+ base = base ? base + SKIP_ONE : rel;+ adr_id_t id;+ adr_filename_id(base, &id);+ bool conv = adr_dir_in(rel, ADR_CONV_DIRS);+ if ((id.kind == ADR_ID_NONE && adr_non_adr_name(base)) || adr_dir_in(rel, ADR_FIXTURE_DIRS)) {+ return;+ }+ if (!conv && id.kind == ADR_ID_NONE) {+ return; /* structure alone never makes a record */+ }+ CBMArena *scratch = ctx->scratch ? ctx->scratch : ctx->arena;+ CBMArena *a = ctx->arena;+ adr_doc_t d = {.ctx = ctx, .title_head = CBM_NOT_FOUND};+ if (!adr_split_lines(scratch, ctx->source, ctx->source_len, &d.L)) {+ ctx->result->doc_links.failed = true;+ return;+ }+ /* headings: the Section definitions, read back at their lines */+ int nsec = 0;+ for (int i = 0; i < ctx->result->defs.count; i++) {+ const CBMDefinition *def = &ctx->result->defs.items[i];+ nsec += def->label && strcmp(def->label, "Section") == 0;+ }+ d.heads =+ nsec > 0 ? (adr_head_t *)cbm_arena_alloc(scratch, (size_t)nsec * sizeof(*d.heads)) : NULL;+ if (nsec > 0 && !d.heads) {+ ctx->result->doc_links.failed = true;+ return;+ }+ for (int i = 0; i < ctx->result->defs.count; i++) {+ const CBMDefinition *def = &ctx->result->defs.items[i];+ if (!def->label || strcmp(def->label, "Section") != 0 || def->start_line < SKIP_ONE ||+ (int)def->start_line > d.L.count) {+ continue;+ }+ int k = (int)def->start_line - SKIP_ONE;+ const char *t = NULL;+ size_t tn = 0;+ int level = adr_heading_level(&d.L, k, &t, &tn);+ if (level > 0) {+ d.heads[d.nheads++] =+ (adr_head_t){.line = k, .level = level, .title = t, .title_n = tn};+ }+ }+ qsort(d.heads, (size_t)d.nheads, sizeof(*d.heads), adr_head_cmp);+ for (int h = 0; h < d.nheads; h++) {+ if (d.heads[h].level == SKIP_ONE) {+ d.title_head = h;+ break;+ }+ }+ /* status: front matter, header field, the Status section */+ char *status_raw = adr_fm_value(a, &d.L, "status");+ if (!status_raw) {+ status_raw = adr_header_field(a, &d, "status");+ }+ int status_sec = adr_find_section(&d, ADR_SEC_STATUS);+ if (!status_raw && status_sec >= 0) {+ const adr_head_t *sh = &d.heads[status_sec];+ const char *colon = memchr(sh->title, ':', sh->title_n);+ if (colon && colon + SKIP_ONE < sh->title + sh->title_n) {+ status_raw =+ adr_plain(a, colon + SKIP_ONE, (size_t)(sh->title + sh->title_n - colon - SKIP_ONE),+ ADR_FIELD_MAX);+ } else {+ status_raw = adr_first_paragraph(a, &d, status_sec, ADR_FIELD_MAX);+ }+ }+ bool placeholder = status_raw && adr_placeholder(status_raw);+ bool structure = status_raw && (adr_find_section(&d, ADR_SEC_CONTEXT) >= 0 ||+ adr_find_section(&d, ADR_SEC_DECISION) >= 0 ||+ adr_find_section(&d, ADR_SEC_CONSEQUENCES) >= 0 ||+ adr_find_section(&d, ADR_SEC_OUTCOME) >= 0 ||+ adr_find_section(&d, ADR_SEC_OPTIONS) >= 0);+ bool is_adr = (conv && (id.kind != ADR_ID_NONE || structure)) || id.kind == ADR_ID_ADR ||+ ((id.kind == ADR_ID_NUMBER || id.kind == ADR_ID_DATE) && structure);+ if (!is_adr) {+ return;+ }+ /* the record's facts */+ char name[ADR_NAME_MAX];+ if (id.kind == ADR_ID_ADR || id.kind == ADR_ID_NUMBER) {+ snprintf(name, sizeof(name), "ADR-%u", id.number);+ } else if (id.kind == ADR_ID_PREFIX) {+ snprintf(name, sizeof(name), "%s-%u", id.prefix, id.number);+ } else {+ const char *dot = strrchr(base, '.');+ size_t stem = dot ? (size_t)(dot - base) : strlen(base);+ snprintf(name, sizeof(name), "%.*s",+ (int)(stem < sizeof(name) - SKIP_ONE ? stem : sizeof(name) - SKIP_ONE), base);+ }+ char *title = NULL;+ if (d.title_head >= 0) {+ title =+ adr_plain(a, d.heads[d.title_head].title, d.heads[d.title_head].title_n, ADR_FIELD_MAX);+ }+ if (!title) {+ title = adr_fm_value(a, &d.L, "title");+ }+ char date[ADR_ISO_LEN + SKIP_ONE] = "";+ /* date: front matter, header field, "last updated", the change log's+ * first date, the file name */+ char *date_raw = adr_fm_value(a, &d.L, "date");+ if (!date_raw) {+ date_raw = adr_header_field(a, &d, "date");+ }+ if (!date_raw) {+ date_raw = adr_header_field(a, &d, "last updated");+ }+ if (!(date_raw && adr_parse_date(date_raw, date, sizeof(date))) &&+ !(!date_raw && adr_changelog_date(&d, date, sizeof(date))) && id.date[0]) {+ memcpy(date, id.date, sizeof(id.date));+ }+ static const char *const people_keys[] = {"deciders", "decision-makers", "decision_makers",+ "authors", "author", NULL};+ char *deciders = NULL;+ for (size_t k = 0; !deciders && people_keys[k]; k++) {+ deciders = adr_fm_value(a, &d.L, people_keys[k]);+ }+ for (size_t k = 0; !deciders && people_keys[k]; k++) {+ deciders = adr_header_field(a, &d, people_keys[k]);+ }+ if (deciders && adr_placeholder(deciders)) {+ deciders = NULL; /* a template placeholder */+ }+ int decision = adr_find_section(&d, ADR_SEC_DECISION);+ if (decision < 0) {+ decision = adr_find_section(&d, ADR_SEC_OUTCOME);+ }+ if (decision < 0) {+ decision = adr_find_section(&d, ADR_SEC_CONTEXT);+ }+ char *doc = decision >= 0 ? adr_section_text(a, &d, decision, ADR_DOC_MAX) : NULL;+ char *qn = cbm_fqn_compute(a, ctx->project, rel, CBM_ADR_QN_NAME);+ char *adr_name = cbm_arena_strdup(a, name);+ char *adr_date = date[0] ? cbm_arena_strdup(a, date) : NULL;+ char superseded_by[ADR_FIELD_MAX] = "";+ char *fm_by = adr_fm_value(a, &d.L, "superseded-by");+ if (!fm_by) {+ fm_by = adr_fm_value(a, &d.L, "superseded_by");+ }+ if (fm_by) {+ snprintf(superseded_by, sizeof(superseded_by), "%s", fm_by);+ }+ if (!qn || !adr_name) {+ ctx->result->doc_links.failed = true;+ return;+ }+ adr_relations(&d, qn, superseded_by, sizeof(superseded_by));+ const char *status = placeholder || !status_raw ? NULL : adr_norm_status(status_raw);+ const char *facts[][PAIR_LEN] = {+ {"adr_id", adr_name},+ {"title", title},+ {"status", status},+ {"status_text", placeholder ? NULL : status_raw},+ {"date", adr_date},+ {"deciders", deciders},+ {"superseded_by", superseded_by[0] ? cbm_arena_strdup(a, superseded_by) : NULL},+ };+ /* sized by the facts themselves: room for every pair and the terminator */+ size_t nfacts = sizeof(facts) / sizeof(facts[0]);+ const char **kv =+ (const char **)cbm_arena_alloc(a, ((nfacts * PAIR_LEN) + SKIP_ONE) * sizeof(char *));+ if (!kv) {+ ctx->result->doc_links.failed = true;+ return;+ }+ size_t w = 0;+ for (size_t f = 0; f < nfacts; f++) {+ if (facts[f][SKIP_ONE] && facts[f][SKIP_ONE][0]) {+ kv[w++] = facts[f][0];+ kv[w++] = facts[f][SKIP_ONE];+ }+ }+ kv[w] = NULL;+ CBMDefinition def;+ memset(&def, 0, sizeof(def));+ def.name = adr_name;+ def.qualified_name = qn;+ def.label = "ADR";+ def.file_path = rel;+ def.start_line = SKIP_ONE;+ def.end_line = (uint32_t)d.L.count;+ def.is_exported = true;+ def.docstring = doc;+ def.extra_props = kv;+ cbm_defs_push(&ctx->result->defs, a, def);+}diff --git a/internal/cbm/doclink.c b/internal/cbm/doclink.cindex bf7f695f6..a67364e34 100644--- a/internal/cbm/doclink.c+++ b/internal/cbm/doclink.c@@ -69,7 +69,8 @@ void cbm_doclink_test_note_doc_work(uint64_t copied, uint64_t parse_input, uint6* doclink.h (language, name, external, and the ship gate). */static const CBMDocLinkFamily DOCLINK_FAMILIES[CBM_DOCLINK_SYNTAX_COUNT] = {-#define DOCLINK_FAMILY_ROW(id, lang, name, external, ships) [id] = {lang, name, external, ships},+#define DOCLINK_FAMILY_ROW(id, lang, name, external, ships, edge) \+ [id] = {lang, name, external, ships, edge},CBM_DOCLINK_FAMILY_LIST(DOCLINK_FAMILY_ROW)#undef DOCLINK_FAMILY_ROW};@@ -87,6 +88,11 @@ const char *cbm_doclink_syntax_name(int syntax) {return f ? f->name : "";}+const char *cbm_doclink_syntax_edge(int syntax) {+ const CBMDocLinkFamily *f = cbm_doclink_family(syntax);+ return f && f->edge ? f->edge : "MENTIONS";+}+bool cbm_doclink_syntax_is_external(int syntax) {const CBMDocLinkFamily *f = cbm_doclink_family(syntax);return f && f->external;diff --git a/internal/cbm/doclink.h b/internal/cbm/doclink.hindex 6e5bb035f..99995202e 100644--- a/internal/cbm/doclink.h+++ b/internal/cbm/doclink.h@@ -43,9 +43,9 @@/* Every link family, across languages: one line per (language, reference* form), and the ONE place a language leg adds its families --*- * X(enum value, language, name, external, ships)+ * X(enum value, language, name, external, ships, edge)*- * name the "syntax" MENTIONS-edge property and doc_link_unresolved+ * name the "syntax" edge property and doc_link_unresolved* column, so it is public surface; with the language it is the* tier a release audit judges. Names repeat across languages* (`see` is C#'s, Java's, Kotlin's ...): the value, not the name,@@ -56,26 +56,33 @@* still resolve, but a resolved one stays a doc_link_unresolved* row with reason below_bar_tier (an unresolved one keeps its own* reason). Nothing else about the family changes.+ * edge the type of the edge a resolved reference becomes: MENTIONS+ * (documentation names code), SUPERSEDES (an ADR states that it+ * supersedes another). The edge's source is always the+ * definition the reference is written in, so a file owns the+ * edges its text produces, whatever their type.** The enum below and the family table (doclink.c) are both generated from this* list, so a value cannot exist without its name and its gate. */-#define CBM_DOCLINK_FAMILY_LIST(X) \- /* csharp */ \- X(CBM_DOCLINK_CS_SEE, CBM_LANG_CSHARP, "see", false, true) \- X(CBM_DOCLINK_CS_SEEALSO, CBM_LANG_CSHARP, "seealso", false, true) \- X(CBM_DOCLINK_CS_EXCEPTION, CBM_LANG_CSHARP, "exception", false, true) \- X(CBM_DOCLINK_CS_INHERITDOC, CBM_LANG_CSHARP, "inheritdoc", false, true) \- /* markdown (doclink_md.c): what a document's text names explicitly */ \- X(CBM_DOCLINK_MD_LINK, CBM_LANG_MARKDOWN, "link", false, true) \- X(CBM_DOCLINK_MD_PATH, CBM_LANG_MARKDOWN, "path", false, true) \- X(CBM_DOCLINK_MD_CODE_PATH, CBM_LANG_MARKDOWN, "code_path", false, true) \- X(CBM_DOCLINK_MD_CODE_NAME, CBM_LANG_MARKDOWN, "code_name", false, true) \- /* any language (CBM_LANG_COUNT): a URL is never an edge */ \- X(CBM_DOCLINK_HREF, CBM_LANG_COUNT, "href", true, false)+#define CBM_DOCLINK_FAMILY_LIST(X) \+ /* csharp */ \+ X(CBM_DOCLINK_CS_SEE, CBM_LANG_CSHARP, "see", false, true, "MENTIONS") \+ X(CBM_DOCLINK_CS_SEEALSO, CBM_LANG_CSHARP, "seealso", false, true, "MENTIONS") \+ X(CBM_DOCLINK_CS_EXCEPTION, CBM_LANG_CSHARP, "exception", false, true, "MENTIONS") \+ X(CBM_DOCLINK_CS_INHERITDOC, CBM_LANG_CSHARP, "inheritdoc", false, true, "MENTIONS") \+ /* markdown (doclink_md.c): what a document's text names explicitly */ \+ X(CBM_DOCLINK_MD_LINK, CBM_LANG_MARKDOWN, "link", false, true, "MENTIONS") \+ X(CBM_DOCLINK_MD_PATH, CBM_LANG_MARKDOWN, "path", false, true, "MENTIONS") \+ X(CBM_DOCLINK_MD_CODE_PATH, CBM_LANG_MARKDOWN, "code_path", false, true, "MENTIONS") \+ X(CBM_DOCLINK_MD_CODE_NAME, CBM_LANG_MARKDOWN, "code_name", false, true, "MENTIONS") \+ /* an ADR's own "supersedes" / "replaces" statement (doc_adr.c): ADR -> ADR */ \+ X(CBM_DOCLINK_MD_SUPERSEDES, CBM_LANG_MARKDOWN, "supersedes", false, true, "SUPERSEDES") \+ /* any language (CBM_LANG_COUNT): a URL is never an edge */ \+ X(CBM_DOCLINK_HREF, CBM_LANG_COUNT, "href", true, false, "MENTIONS")typedef enum {CBM_DOCLINK_NONE = 0,-#define CBM_DOCLINK_FAMILY_VALUE(id, lang, name, external, ships) id,+#define CBM_DOCLINK_FAMILY_VALUE(id, lang, name, external, ships, edge) id,CBM_DOCLINK_FAMILY_LIST(CBM_DOCLINK_FAMILY_VALUE)#undef CBM_DOCLINK_FAMILY_VALUECBM_DOCLINK_SYNTAX_COUNT@@ -99,8 +106,12 @@ typedef struct {const char *name;bool external;bool ships;+ const char *edge; /* the type of the edge a resolved reference becomes */} CBMDocLinkFamily;+/* "MENTIONS" or "SUPERSEDES"; "MENTIONS" for an unknown value. */+const char *cbm_doclink_syntax_edge(int syntax);+/* The family of a syntax value; NULL for a value that names none. */const CBMDocLinkFamily *cbm_doclink_family(int syntax);@@ -272,4 +283,16 @@ bool cbm_doclink_md_classify_span(const char *text, size_t len, char *buf, size_* and the lines, or false. */bool cbm_doclink_md_line_fragment(const char *frag, uint32_t *first, uint32_t *last);+/* ── ADRs (doc_adr.c) ──────────────────────────────────────────────── */++/* When the Markdown file being extracted is an architecture decision record:+ * push its ADR definition (name its canonical id, qualified name+ * "<module>.__adr__", facts as extra properties) and a `supersedes` token for+ * each of its own supersedes / replaces statements. Called by the Markdown+ * scan, after the Section definitions exist. */+void cbm_adr_extract(CBMExtractCtx *ctx);++/* The qualified-name tail of an ADR node: "<module QN>" + this. */+#define CBM_ADR_QN_NAME "__adr__"+#endif /* CBM_DOCLINK_H */diff --git a/internal/cbm/doclink_md.c b/internal/cbm/doclink_md.cindex 0cd2d350f..5a0f70bdb 100644--- a/internal/cbm/doclink_md.c+++ b/internal/cbm/doclink_md.c@@ -61,6 +61,7 @@ enum {MD_NUM_DIGITS = 9, /* a line number has at most this many digits */MD_PAIR = 2, /* ints per pair entry */MD_URL_SCHEMES = 3, /* http, https, ftp */+ MD_BOM_LEN = 3, /* EF BB BF */};/* UTF-8 well-formedness (RFC 3629, table 3-7 of the Unicode standard). */@@ -1764,6 +1765,9 @@ void cbm_doclink_md_scan_file(CBMExtractCtx *ctx) {const char *src = ctx->source;int n = ctx->source_len;int pos = 0;+ if (n >= MD_BOM_LEN && memcmp(src, "\xEF\xBB\xBF", MD_BOM_LEN) == 0) {+ pos = MD_BOM_LEN; /* a byte-order mark is no part of the first line */+ }while (pos < n && !s.failed) {const char *nl = memchr(src + pos, '\n', (size_t)(n - pos));int end = nl ? (int)(nl - src) : n;@@ -1785,4 +1789,6 @@ void cbm_doclink_md_scan_file(CBMExtractCtx *ctx) {md_list_free(&s.bal);md_list_free(&s.gts);md_list_free(&s.blanks);+ /* an architecture decision record: its node, facts and supersedes */+ cbm_adr_extract(ctx);}diff --git a/internal/cbm/result_compact.c b/internal/cbm/result_compact.cindex 9691b6c96..438a5d535 100644--- a/internal/cbm/result_compact.c+++ b/internal/cbm/result_compact.c@@ -276,6 +276,7 @@ static void cr_walk_def(cr_ctx_t *c, CBMDefinition *d) {cr_str(c, &d->http_client);cr_str(c, &d->http_base_url);cr_str(c, &d->variants);+ cr_list(c, &d->extra_props);}static void cr_walk_call(cr_ctx_t *c, CBMCall *call) {diff --git a/src/pipeline/doc_links.c b/src/pipeline/doc_links.cindex bdad5249a..df012626f 100644--- a/src/pipeline/doc_links.c+++ b/src/pipeline/doc_links.c@@ -339,6 +339,10 @@ typedef struct {static int mention_cmp(const void *a, const void *b) {const doclink_mention_t *x = (const doclink_mention_t *)a;const doclink_mention_t *y = (const doclink_mention_t *)b;+ int edge = strcmp(cbm_doclink_syntax_edge(x->syntax), cbm_doclink_syntax_edge(y->syntax));+ if (edge != 0) {+ return edge;+ }if (x->src != y->src) {return x->src < y->src ? -1 : 1;}@@ -372,7 +376,8 @@ void cbm_doclinks_test_fail_edge_insert_after(int nth) {#endif/* Insert one MENTIONS edge; 0 when it could not be stored. */-static int64_t doclinks_insert_edge(cbm_gbuf_t *gb, int64_t src, int64_t tgt, const char *props) {+static int64_t doclinks_insert_edge(cbm_gbuf_t *gb, int64_t src, int64_t tgt, const char *type,+ const char *props) {#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMSint n = atomic_load(&doclinks_test_edge_fail_after);while (n > 0) {@@ -384,10 +389,10 @@ static int64_t doclinks_insert_edge(cbm_gbuf_t *gb, int64_t src, int64_t tgt, co}}#endif- return cbm_gbuf_insert_edge(gb, src, tgt, "MENTIONS", props);+ return cbm_gbuf_insert_edge(gb, src, tgt, type, props);}-/* Emit one MENTIONS edge per (source, target): first line, its syntax, the+/* Emit one edge per (edge type, source, target): first line, its syntax, the* mention count, and tier exact when any mention bound exactly. A failed* insert fails the layer: the edge is not there. */static void emit_mentions(cbm_doclinks_t *dl, const char *rel, doclink_mention_t *m, int n,@@ -397,7 +402,9 @@ static void emit_mentions(cbm_doclinks_t *dl, const char *rel, doclink_mention_twhile (i < n) {int j = i;bool exact = false;- while (j < n && m[j].src == m[i].src && m[j].tgt == m[i].tgt) {+ const char *type = cbm_doclink_syntax_edge(m[i].syntax);+ while (j < n && m[j].src == m[i].src && m[j].tgt == m[i].tgt &&+ strcmp(cbm_doclink_syntax_edge(m[j].syntax), type) == 0) {exact = exact || m[j].exact;j++;}@@ -412,7 +419,7 @@ static void emit_mentions(cbm_doclinks_t *dl, const char *rel, doclink_mention_t"\"count\":%d%s}",m[i].via, cbm_doclink_syntax_name(m[i].syntax), exact ? "exact" : "unique",m[i].line, j - i, lines);- if (doclinks_insert_edge(edge_out, m[i].src, m[i].tgt, props) == 0) {+ if (doclinks_insert_edge(edge_out, m[i].src, m[i].tgt, type, props) == 0) {mark_failed(dl, rel, "alloc"); /* an edge that is not there is not counted */} else {atomic_fetch_add_explicit(&dl->edges, 1, memory_order_relaxed);diff --git a/src/pipeline/doc_links_md.c b/src/pipeline/doc_links_md.cindex 6251cb336..07db1d4f3 100644--- a/src/pipeline/doc_links_md.c+++ b/src/pipeline/doc_links_md.c@@ -39,6 +39,7 @@#include "graph_buffer/graph_buffer.h"#include <stdint.h>+#include <stdio.h>#include <stdlib.h>#include <string.h>@@ -47,7 +48,8 @@ enum {MDR_TRIES = 2, /* relative to the document, relative to the root */MDR_BASENAME_INIT = 1024, /* first capacity of the file-name table */MDR_HEX_BASE = 16,- MDR_PCT_LEN = 3, /* `%XX` */+ MDR_PCT_LEN = 3, /* `%XX` */+ MDR_ADR_DIGITS = 5, /* an ADR number has at most this many digits */};/* Labels whose nodes are code a range or a member can name. */@@ -94,7 +96,8 @@ typedef struct {CBMArena arena; /* the strings and records of pkgs and top */mdr_def_t *defs; /* every code definition, sorted by (file, start line, id) */int ndefs;- CBMHashTable *folders; /* directory path -> its Folder node */+ CBMHashTable *adr_by_file; /* file path -> its ADR node (doc_adr.c) */+ CBMHashTable *folders; /* directory path -> its Folder node */} mdr_index_t;static const char *mdr_base(const char *path) {@@ -213,6 +216,15 @@ static bool mdr_build_defs(mdr_index_t *x, const cbm_gbuf_t *graph) {}}qsort(x->defs, (size_t)x->ndefs, sizeof(*x->defs), mdr_def_cmp);+ const cbm_gbuf_node_t **adrs = NULL;+ int nadr = 0;+ if (cbm_gbuf_find_by_label(graph, "ADR", &adrs, &nadr) == 0) {+ for (int i = 0; i < nadr; i++) {+ if (adrs[i]->file_path && adrs[i]->file_path[0]) {+ cbm_ht_set(x->adr_by_file, adrs[i]->file_path, (void *)adrs[i]);+ }+ }+ }return true;}@@ -276,9 +288,10 @@ static void *mdr_build(const cbm_doclink_build_in_t *in) {x->basenames = cbm_ht_create_in(CBM_MEM_CLASS_HASH_TABLE, MDR_BASENAME_INIT);x->pkgs = cbm_ht_create_in(CBM_MEM_CLASS_HASH_TABLE, MDR_BASENAME_INIT);x->top = cbm_ht_create_in(CBM_MEM_CLASS_HASH_TABLE, MDR_BASENAME_INIT);+ x->adr_by_file = cbm_ht_create_in(CBM_MEM_CLASS_HASH_TABLE, MDR_BASENAME_INIT);x->folders = cbm_ht_create_in(CBM_MEM_CLASS_HASH_TABLE, MDR_BASENAME_INIT);if ((in->run_file_count > 0 && !x->run_paths) || !x->basenames || !x->pkgs || !x->top ||- !x->folders || !x->project || !mdr_build_pkgs(x, in->graph) ||+ !x->adr_by_file || !x->folders || !x->project || !mdr_build_pkgs(x, in->graph) ||!mdr_build_defs(x, in->graph)) {mdr_destroy(x);return NULL;@@ -322,6 +335,7 @@ static void mdr_destroy(void *index) {cbm_ht_free(x->basenames);cbm_ht_free(x->pkgs);cbm_ht_free(x->top);+ cbm_ht_free(x->adr_by_file);cbm_ht_free(x->folders);cbm_arena_destroy(&x->arena);cbm_free(CBM_MEM_CLASS_OTHER, x->defs);@@ -1042,6 +1056,76 @@ static bool mdr_link_path(const char *raw, char *buf, size_t cap, mdr_ref_t *r)return buf[0] != '\0';}+/* `ADR-12`, `ADR 012`, `adr_7` (the whole text): the canonical node name. */+static bool mdr_adr_id(const char *raw, char *name, size_t cap) {+ size_t n = strlen(raw);+ if (n < PAIR_LEN * PAIR_LEN || mdr_norm_c((unsigned char)raw[0]) != 'a' ||+ mdr_norm_c((unsigned char)raw[SKIP_ONE]) != 'd' ||+ mdr_norm_c((unsigned char)raw[PAIR_LEN]) != 'r' ||+ (raw[PAIR_LEN + SKIP_ONE] != '-' && raw[PAIR_LEN + SKIP_ONE] != '_' &&+ raw[PAIR_LEN + SKIP_ONE] != ' ')) {+ return false;+ }+ unsigned v = 0;+ size_t digits = 0;+ for (size_t i = PAIR_LEN * PAIR_LEN; i < n; i++) {+ if (raw[i] < '0' || raw[i] > '9' || digits >= MDR_ADR_DIGITS) {+ return false;+ }+ v = (v * CBM_DECIMAL_BASE) + (unsigned)(raw[i] - '0');+ digits++;+ }+ return digits > 0 && snprintf(name, cap, "ADR-%u", v) > 0;+}++/* An ADR's own "supersedes X": X by its id, or the file a link names, to its+ * ADR node. */+static void mdr_resolve_adr(const mdr_index_t *x, const cbm_gbuf_t *graph, const char *doc,+ const char *raw, cbm_doclink_outcome_t *out) {+ char name[MDR_PATH_CAP];+ out->kind = CBM_DOCLINK_UNRESOLVED;+ out->reason = CBM_DOCLINK_REASON_MISSING;+ if (mdr_adr_id(raw, name, sizeof(name))) {+ const cbm_gbuf_node_t **nodes = NULL;+ int count = 0;+ const cbm_gbuf_node_t *hit = NULL;+ int hits = 0;+ if (cbm_gbuf_find_by_name(graph, name, &nodes, &count) == 0) {+ for (int i = 0; i < count; i++) {+ if (nodes[i]->label && strcmp(nodes[i]->label, "ADR") == 0) {+ hit = nodes[i];+ hits++;+ }+ }+ }+ if (hits == SKIP_ONE) {+ mdr_edge(out, hit, 0, 0);+ } else if (hits > SKIP_ONE) {+ out->reason = CBM_DOCLINK_REASON_AMBIGUOUS; /* two ADR logs number alike */+ }+ return;+ }+ char buf[MDR_PATH_CAP];+ mdr_ref_t r = {.link = true};+ if (!mdr_link_path(raw, buf, sizeof(buf), &r)) {+ return;+ }+ mdr_resolve_path(x, graph, doc, &r, out);+ if (out->kind != CBM_DOCLINK_EDGE) {+ return; /* missing, ambiguous, or no file of this repository */+ }+ const cbm_gbuf_node_t *adr =+ out->target->file_path+ ? (const cbm_gbuf_node_t *)cbm_ht_get(x->adr_by_file, out->target->file_path)+ : NULL;+ if (!adr) {+ out->kind = CBM_DOCLINK_UNRESOLVED; /* the file is there, but it is no record */+ out->reason = CBM_DOCLINK_REASON_MISSING;+ return;+ }+ mdr_edge(out, adr, 0, 0);+}+static void mdr_resolve(const void *index, void *state, int run_file, const CBMDocLink *link,const cbm_gbuf_t *graph, cbm_doclink_outcome_t *out) {(void)state;@@ -1055,6 +1139,9 @@ static void mdr_resolve(const void *index, void *state, int run_file, const CBMDchar buf[MDR_PATH_CAP];mdr_ref_t r = {0};switch (link->syntax) {+ case CBM_DOCLINK_MD_SUPERSEDES:+ mdr_resolve_adr(x, graph, doc, link->raw, out);+ return;case CBM_DOCLINK_MD_LINK:r.link = true;if (!mdr_link_path(link->raw, buf, sizeof(buf), &r)) {diff --git a/src/pipeline/pass_definitions.c b/src/pipeline/pass_definitions.cindex 74fd06d96..60e1a6bcc 100644--- a/src/pipeline/pass_definitions.c+++ b/src/pipeline/pass_definitions.c@@ -323,6 +323,10 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)append_json_string(buf, bufsize, &pos, "route_method", def->route_method);append_json_string(buf, bufsize, &pos, "http_client", def->http_client);append_json_string(buf, bufsize, &pos, "http_base_url", def->http_base_url);+ /* A document definition's facts (an ADR's id, status, date, ...): key, value pairs. */+ for (const char **kv = def->extra_props; kv && kv[0] && kv[SKIP_ONE]; kv += PAIR_LEN) {+ append_json_string(buf, bufsize, &pos, kv[0], kv[SKIP_ONE]);+ }/* MinHash fingerprint — append if present and buffer has room. */if (def->fingerprint && def->fingerprint_k > 0 &&diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.cindex 4b35fae6f..940bef7a7 100644--- a/src/pipeline/pass_parallel.c+++ b/src/pipeline/pass_parallel.c@@ -551,6 +551,10 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)append_json_string(buf, bufsize, &pos, "route_method", def->route_method);append_json_string(buf, bufsize, &pos, "http_client", def->http_client);append_json_string(buf, bufsize, &pos, "http_base_url", def->http_base_url);+ /* A document definition's facts (an ADR's id, status, date, ...): key, value pairs. */+ for (const char **kv = def->extra_props; kv && kv[0] && kv[SKIP_ONE]; kv += PAIR_LEN) {+ append_json_string(buf, bufsize, &pos, kv[0], kv[SKIP_ONE]);+ }/* MinHash fingerprint — append if present and buffer has room.* Hex-encoded K=64 uint32 = 512 chars + key/quotes ≈ 520 chars. */diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.cindex dea2d7a9d..38e1cb4b2 100644--- a/src/pipeline/pipeline.c+++ b/src/pipeline/pipeline.c@@ -1895,7 +1895,8 @@ static void log_result_census(const char *tag, CBMFileResult **cache, int file_c}str_def_fp += def->fingerprint ? (size_t)def->fingerprint_k * sizeof(uint32_t) : 0;str_def_misc += census_len(def->route_path) + census_len(def->route_method) +- census_len(def->impl_trait) + census_len(def->http_base_url);+ census_len(def->impl_trait) + census_len(def->http_base_url) ++ census_list(def->extra_props);}for (int c = 0; c < r->calls.count; c++) {const CBMCall *call = &r->calls.items[c];diff --git a/tests/test_doc_links_md.c b/tests/test_doc_links_md.cindex 5f33416de..4ec817f8a 100644--- a/tests/test_doc_links_md.c+++ b/tests/test_doc_links_md.c@@ -410,10 +410,161 @@ TEST(doc_links_md_incremental) {PASS();}+/* ── ADRs ────────────────────────────────────────────────────────── */++static void md_write_adrs(const char *tmp, const char *first_status) {+ char first[1024];+ snprintf(first, sizeof(first),+ "---\n"+ "status: %s\n"+ "date: 2024-03-05\n"+ "deciders: Ana, Bo\n"+ "---\n"+ "# Use X for storage\n"+ "\n"+ "## Context and Problem Statement\n"+ "\n"+ "We need storage.\n"+ "\n"+ "## Decision Outcome\n"+ "\n"+ "We use X, see `app/routing.py`.\n"+ "\n"+ "Superseded by [ADR-0002](0002-use-y.md).\n",+ first_status);+ th_write_file(TH_PATH(tmp, "docs/adr/0001-use-x.md"), first);+ th_write_file(TH_PATH(tmp, "docs/adr/0002-use-y.md"),+ "# 2. Use Y instead\n"+ "\n"+ "Date: 12 May 2024\n"+ "\n"+ "## Status\n"+ "\n"+ "Accepted\n"+ "\n"+ "Supersedes [ADR-0001](0001-use-x.md).\n"+ "\n"+ "## Context\n"+ "\n"+ "X was slow.\n"+ "\n"+ "## Decision\n"+ "\n"+ "We use Y.\n");+ th_write_file(TH_PATH(tmp, "docs/adr/0003-cache.md"),+ "# Cache reads\n"+ "\n"+ "## Status\n"+ "\n"+ "Proposed\n"+ "\n"+ "- Replaces ADR-2\n"+ "\n"+ "## Decision\n"+ "\n"+ "The cache replaces the reader described in [ADR-1](0001-use-x.md).\n");+ th_write_file(TH_PATH(tmp, "docs/adr/README.md"), "# Decisions\n\n## Status\n\nAccepted\n");+ th_write_file(TH_PATH(tmp, "docs/adr/template.md"),+ "# Title\n\n## Status\n\n{proposed | accepted}\n\n## Decision\n\nTBD\n");+}++/* Properties of the ADR node of `file`; "" when there is none. */+static void md_adr_props(const char *db, const char *file, char *out, size_t cap) {+ out[0] = '\0';+ sqlite3 *h = NULL;+ if (sqlite3_open_v2(db, &h, SQLITE_OPEN_READONLY, NULL) == SQLITE_OK) {+ sqlite3_stmt *st = NULL;+ if (sqlite3_prepare_v2(h,+ "SELECT name || ' ' || properties FROM nodes WHERE label = 'ADR' "+ "AND file_path = ?1",+ -1, &st, NULL) == SQLITE_OK) {+ sqlite3_bind_text(st, 1, file, -1, SQLITE_TRANSIENT);+ if (sqlite3_step(st) == SQLITE_ROW) {+ snprintf(out, cap, "%s", (const char *)sqlite3_column_text(st, 0));+ }+ }+ sqlite3_finalize(st);+ }+ sqlite3_close(h);+}++TEST(doc_links_md_adr) {+ char tmp[256];+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_dlmd_adr_XXXXXX");+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));+ md_write_fixture(tmp);+ md_write_adrs(tmp, "superseded");+ char db[512];+ snprintf(db, sizeof(db), "%s/adr.db", tmp);+ ASSERT_EQ(dm_index(tmp, db, NULL), 0);+ char props[2048];++ /* three records; README and template are none */+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM nodes WHERE label = 'ADR'"), 3);+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM edges e JOIN nodes t ON t.id = e.target_id "+ "WHERE e.type = 'DEFINES' AND t.label = 'ADR'"),+ 3);+ /* facts: front matter */+ md_adr_props(db, "docs/adr/0001-use-x.md", props, sizeof(props));+ ASSERT_TRUE(strncmp(props, "ADR-1 ", strlen("ADR-1 ")) == 0);+ ASSERT_NOT_NULL(strstr(props, "\"status\":\"superseded\""));+ ASSERT_NOT_NULL(strstr(props, "\"date\":\"2024-03-05\""));+ ASSERT_NOT_NULL(strstr(props, "\"deciders\":\"Ana, Bo\""));+ ASSERT_NOT_NULL(strstr(props, "\"title\":\"Use X for storage\""));+ ASSERT_NOT_NULL(strstr(props, "\"superseded_by\":\"0002-use-y.md\""));+ ASSERT_NOT_NULL(strstr(props, "We use X")); /* the decision, searchable */+ /* facts: header field date, Status section */+ md_adr_props(db, "docs/adr/0002-use-y.md", props, sizeof(props));+ ASSERT_TRUE(strncmp(props, "ADR-2 ", strlen("ADR-2 ")) == 0);+ ASSERT_NOT_NULL(strstr(props, "\"status\":\"accepted\""));+ ASSERT_NOT_NULL(strstr(props, "\"date\":\"2024-05-12\""));+ md_adr_props(db, "docs/adr/README.md", props, sizeof(props));+ ASSERT_STR_EQ(props, "");++ /* SUPERSEDES: by link, and by id at a line head; never from prose that+ * uses "replaces" as a verb, never from the superseded record */+ const char *sup = "SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id = e.source_id "+ "JOIN nodes t ON t.id = e.target_id WHERE e.type = 'SUPERSEDES' "+ "AND s.file_path = '%s' AND t.file_path = '%s'";+ char q[512];+ snprintf(q, sizeof(q), sup, "docs/adr/0002-use-y.md", "docs/adr/0001-use-x.md");+ ASSERT_EQ(dm_count(db, q), 1);+ snprintf(q, sizeof(q), sup, "docs/adr/0003-cache.md", "docs/adr/0002-use-y.md");+ ASSERT_EQ(dm_count(db, q), 1);+ snprintf(q, sizeof(q), sup, "docs/adr/0003-cache.md", "docs/adr/0001-use-x.md");+ ASSERT_EQ(dm_count(db, q), 0);+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM edges WHERE type = 'SUPERSEDES'"), 2);+ /* the record's sections still link to code */+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id = e.source_id "+ "JOIN nodes t ON t.id = e.target_id WHERE e.type = 'MENTIONS' "+ "AND s.file_path = 'docs/adr/0001-use-x.md' "+ "AND t.file_path = 'app/routing.py'"),+ 1);++ /* incremental == full: a status edit, then a new record that a statement+ * names by id */+ char full_db[512];+ snprintf(full_db, sizeof(full_db), "%s/adr-full.db", tmp);+ md_write_adrs(tmp, "deprecated");+ ASSERT_EQ(dm_step(tmp, db, full_db, "ADR status edit", CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR),+ 0);+ md_adr_props(db, "docs/adr/0001-use-x.md", props, sizeof(props));+ ASSERT_NOT_NULL(strstr(props, "\"status\":\"deprecated\""));+ th_write_file(TH_PATH(tmp, "docs/adr/0004-later.md"), "# Later\n\n## Status\n\nAccepted\n\n"+ "Supersedes ADR-3.\n\n## Decision\n\n"+ "Later.\n");+ ASSERT_EQ(dm_step(tmp, db, full_db, "ADR added", CBM_INCREMENTAL_ROUTE_FORCED_FULL), 0);+ snprintf(q, sizeof(q), sup, "docs/adr/0004-later.md", "docs/adr/0003-cache.md");+ ASSERT_EQ(dm_count(db, q), 1);+ th_cleanup(tmp);+ PASS();+}+SUITE(doc_links_md) {RUN_TEST(doc_links_md_extract_tokens);RUN_TEST(doc_links_md_repeated_headings);RUN_TEST(doc_links_md_classify_span);RUN_TEST(doc_links_md_resolve);RUN_TEST(doc_links_md_incremental);+ RUN_TEST(doc_links_md_adr);}