create-anpunkit 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/template/.claude/agents/e2e-runner.md +42 -25
- package/template/.claude/agents/implementer.md +13 -7
- package/template/.claude/agents/planner.md +66 -3
- package/template/.claude/agents/spec-author.md +118 -0
- package/template/.claude/agents/test-author.md +74 -64
- package/template/.claude/anpunkit-manifest.json +38 -18
- package/template/.claude/commands/overview.md +17 -0
- package/template/.claude/commands/phase.md +110 -63
- package/template/.cursor/commands/overview.md +17 -0
- package/template/.cursor/commands/phase.md +109 -62
- package/template/.gitattributes +1 -0
- package/template/AGENTS.md +163 -60
- package/template/CLAUDE.md +1 -0
- package/template/README.md +26 -15
- package/template/commands.src/overview.md +17 -0
- package/template/commands.src/phase.md +110 -63
- package/template/docs/DESIGN_LOG.md +192 -1
- package/template/index.html +1 -2
- package/template/scripts/spec-conformance.sh +93 -0
- package/template/scripts/spec-staleness.sh +115 -0
- package/template/tests/helpers/spec-assert.py +162 -0
- package/template/tests/helpers/spec-assert.ts +158 -0
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# spec-conformance.sh — block GREEN until the phase spec is fully filled and every
|
|
3
|
+
# case is verified by a boundary test (v2.2). Runs between RED and GREEN, replacing
|
|
4
|
+
# the v2.1 human TEST REVIEW gate. (§5.55, rule 18)
|
|
5
|
+
#
|
|
6
|
+
# Two checks, both loud-fail (nonzero), no side effects:
|
|
7
|
+
# 1. NO `TBD` remains in docs/spec-phase-<n>.md or any fixture it references.
|
|
8
|
+
# 2. EVERY case-id in the spec table is cited by a test via `# spec: <case-id>`
|
|
9
|
+
# (or `// spec: <case-id>`) under tests/ or e2e/.
|
|
10
|
+
#
|
|
11
|
+
# bash scripts/spec-conformance.sh <phase-n>
|
|
12
|
+
#
|
|
13
|
+
# The case→test citation here, plus the placement convention (contract/transition
|
|
14
|
+
# tests live in tests/regression/), is what closes the rule-14 chain: reachable
|
|
15
|
+
# transition → filled case (rule 14) → cited boundary test (this) → regression corpus.
|
|
16
|
+
set -euo pipefail
|
|
17
|
+
cd "${CLAUDE_PROJECT_DIR:-.}"
|
|
18
|
+
|
|
19
|
+
N="${1:-}"
|
|
20
|
+
[ -n "$N" ] || { echo "spec-conformance: usage: spec-conformance.sh <phase-n>" >&2; exit 2; }
|
|
21
|
+
|
|
22
|
+
SPEC="docs/spec-phase-${N}.md"
|
|
23
|
+
[ -f "$SPEC" ] || { echo "spec-conformance: $SPEC not found." >&2; exit 2; }
|
|
24
|
+
|
|
25
|
+
FAIL=0
|
|
26
|
+
|
|
27
|
+
# ---- 1. no TBD left in the spec ----
|
|
28
|
+
if grep -nE '\bTBD\b' "$SPEC" >/dev/null 2>&1; then
|
|
29
|
+
echo "spec-conformance: FAIL — unfilled 'TBD' marker(s) remain in $SPEC:" >&2
|
|
30
|
+
grep -nE '\bTBD\b' "$SPEC" | sed 's/^/ /' >&2
|
|
31
|
+
echo " Every case must be filled (or escalated as CASE-SET-DIVERGENCE) before GREEN." >&2
|
|
32
|
+
FAIL=1
|
|
33
|
+
fi
|
|
34
|
+
|
|
35
|
+
# ---- referenced fixtures: must exist + carry no TBD ----
|
|
36
|
+
FIXREFS="$(grep -oE 'fixtures/[A-Za-z0-9_./-]+\.json' "$SPEC" | sort -u || true)"
|
|
37
|
+
if [ -n "$FIXREFS" ]; then
|
|
38
|
+
while IFS= read -r fx; do
|
|
39
|
+
[ -n "$fx" ] || continue
|
|
40
|
+
if [ ! -f "$fx" ]; then
|
|
41
|
+
echo "spec-conformance: FAIL — referenced fixture missing: $fx" >&2
|
|
42
|
+
FAIL=1
|
|
43
|
+
elif grep -nE '\bTBD\b' "$fx" >/dev/null 2>&1; then
|
|
44
|
+
echo "spec-conformance: FAIL — 'TBD' marker in fixture: $fx" >&2
|
|
45
|
+
FAIL=1
|
|
46
|
+
fi
|
|
47
|
+
done <<EOF
|
|
48
|
+
$FIXREFS
|
|
49
|
+
EOF
|
|
50
|
+
fi
|
|
51
|
+
|
|
52
|
+
# ---- 2. every case-id cited by a boundary test ----
|
|
53
|
+
# case-ids = the FIRST table-column cell of each row, matching PH<n>-... exactly.
|
|
54
|
+
# (Parse the column, not a free grep — else `fixtures/PH1-ORDER-01-input.json`
|
|
55
|
+
# would yield a bogus `PH1-ORDER-01-input` case-id.)
|
|
56
|
+
CASE_IDS="$(grep -E '^\|' "$SPEC" \
|
|
57
|
+
| awk -F'|' '{ id=$2; gsub(/^[ \t]+|[ \t]+$/,"",id); print id }' \
|
|
58
|
+
| grep -E "^PH${N}-[A-Za-z0-9_-]+$" | sort -u || true)"
|
|
59
|
+
if [ -z "$CASE_IDS" ]; then
|
|
60
|
+
echo "spec-conformance: WARN — no PH${N}-* case-ids found in $SPEC (empty spec?)." >&2
|
|
61
|
+
fi
|
|
62
|
+
|
|
63
|
+
SEARCH_DIRS=""
|
|
64
|
+
[ -d tests ] && SEARCH_DIRS="$SEARCH_DIRS tests"
|
|
65
|
+
[ -d e2e ] && SEARCH_DIRS="$SEARCH_DIRS e2e"
|
|
66
|
+
|
|
67
|
+
if [ -n "$CASE_IDS" ]; then
|
|
68
|
+
if [ -z "$SEARCH_DIRS" ]; then
|
|
69
|
+
echo "spec-conformance: FAIL — case-ids exist but no tests/ or e2e/ dir to cite them." >&2
|
|
70
|
+
FAIL=1
|
|
71
|
+
else
|
|
72
|
+
while IFS= read -r cid; do
|
|
73
|
+
[ -n "$cid" ] || continue
|
|
74
|
+
# cite convention: `spec: <case-id>` with a non-id char (or EOL) after, so
|
|
75
|
+
# PH2-ORDER-01 does not match PH2-ORDER-011.
|
|
76
|
+
if grep -rEq -- "spec:[[:space:]]*${cid}([^0-9A-Za-z_-]|$)" $SEARCH_DIRS 2>/dev/null; then
|
|
77
|
+
:
|
|
78
|
+
else
|
|
79
|
+
echo "spec-conformance: FAIL — case ${cid} has no boundary test citing it (# spec: ${cid})." >&2
|
|
80
|
+
FAIL=1
|
|
81
|
+
fi
|
|
82
|
+
done <<EOF
|
|
83
|
+
$CASE_IDS
|
|
84
|
+
EOF
|
|
85
|
+
fi
|
|
86
|
+
fi
|
|
87
|
+
|
|
88
|
+
if [ "$FAIL" -ne 0 ]; then
|
|
89
|
+
echo "spec-conformance: BLOCKED — fix the above before GREEN." >&2
|
|
90
|
+
exit 1
|
|
91
|
+
fi
|
|
92
|
+
echo "spec-conformance: OK — phase ${N} spec fully filled; every case-id cited by a boundary test."
|
|
93
|
+
exit 0
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# spec-staleness.sh — guard the per-phase spec header against upstream drift (v2.2).
|
|
3
|
+
#
|
|
4
|
+
# The behavioral contract docs/spec-phase-<n>.md carries a GENERATED header that
|
|
5
|
+
# transcludes the phase's PLAN.md `- acceptance:` line + the in-scope DATAFLOW.md
|
|
6
|
+
# transition rows, plus an embedded hash. If PLAN.md / DATAFLOW.md change after the
|
|
7
|
+
# skeleton was stamped (e.g. via /replan), the stored hash no longer matches the
|
|
8
|
+
# upstream → the spec must be regenerated/re-filled before SPEC REVIEW. (§5.55, rule 17)
|
|
9
|
+
#
|
|
10
|
+
# Hashing lives ONLY here (no duplication in agent prompts):
|
|
11
|
+
# bash scripts/spec-staleness.sh stamp <n> # compute + embed the hash (at /overview, on regenerate)
|
|
12
|
+
# bash scripts/spec-staleness.sh check <n> # default: recompute + compare; nonzero on drift
|
|
13
|
+
# bash scripts/spec-staleness.sh <n> # alias for: check <n>
|
|
14
|
+
#
|
|
15
|
+
# set -euo pipefail; nonzero = loud fail; `stamp` is the only side effect.
|
|
16
|
+
set -euo pipefail
|
|
17
|
+
cd "${CLAUDE_PROJECT_DIR:-.}"
|
|
18
|
+
|
|
19
|
+
# ---- args ----
|
|
20
|
+
SUB="check"
|
|
21
|
+
case "${1:-}" in
|
|
22
|
+
stamp) SUB="stamp"; shift;;
|
|
23
|
+
check) SUB="check"; shift;;
|
|
24
|
+
esac
|
|
25
|
+
N="${1:-}"
|
|
26
|
+
[ -n "$N" ] || { echo "spec-staleness: usage: spec-staleness.sh [stamp|check] <phase-n>" >&2; exit 2; }
|
|
27
|
+
|
|
28
|
+
SPEC="docs/spec-phase-${N}.md"
|
|
29
|
+
PLAN="docs/PLAN.md"
|
|
30
|
+
DATAFLOW="docs/DATAFLOW.md"
|
|
31
|
+
[ -f "$SPEC" ] || { echo "spec-staleness: $SPEC not found." >&2; exit 2; }
|
|
32
|
+
[ -f "$PLAN" ] || { echo "spec-staleness: $PLAN not found." >&2; exit 2; }
|
|
33
|
+
|
|
34
|
+
# ---- sha256 of stdin (portable: sha256sum -> shasum -> node) ----
|
|
35
|
+
sha_stdin() {
|
|
36
|
+
if command -v sha256sum >/dev/null 2>&1; then sha256sum | cut -d' ' -f1
|
|
37
|
+
elif command -v shasum >/dev/null 2>&1; then shasum -a 256 | cut -d' ' -f1
|
|
38
|
+
else node -e "let d='';process.stdin.on('data',c=>d+=c).on('end',()=>console.log(require('crypto').createHash('sha256').update(d).digest('hex')))"
|
|
39
|
+
fi
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
# normalize: NFC-ish arrow unify (→ -> ->), collapse spaces, trim. Content-sensitive,
|
|
43
|
+
# whitespace-insensitive — so cosmetic reflow does not trip the guard, content does.
|
|
44
|
+
norm() { sed -e 's/→/->/g' -e 's/[[:space:]]\{1,\}/ /g' -e 's/^ //' -e 's/ $//'; }
|
|
45
|
+
|
|
46
|
+
# ---- extract this phase's block from PLAN.md (## Phase <n>: ... up to next ## Phase) ----
|
|
47
|
+
phase_block() {
|
|
48
|
+
awk -v n="$N" '
|
|
49
|
+
$0 ~ ("^## Phase " n ":") {inblk=1; print; next}
|
|
50
|
+
inblk && /^## Phase / {inblk=0}
|
|
51
|
+
inblk {print}
|
|
52
|
+
' "$PLAN"
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
BLOCK="$(phase_block || true)"
|
|
56
|
+
[ -n "$BLOCK" ] || { echo "spec-staleness: no '## Phase ${N}:' block in $PLAN." >&2; exit 2; }
|
|
57
|
+
|
|
58
|
+
# acceptance line(s) + dataflow line, normalized
|
|
59
|
+
ACC_LINE="$(printf '%s\n' "$BLOCK" | grep -E '^- acceptance:' | norm || true)"
|
|
60
|
+
DF_LINE="$(printf '%s\n' "$BLOCK" | grep -E '^- dataflow:' | norm || true)"
|
|
61
|
+
|
|
62
|
+
# in-scope transition tokens (from->to) named on the dataflow line
|
|
63
|
+
TOKENS="$(printf '%s\n' "$DF_LINE" | norm | grep -oE '[A-Za-z0-9_]+->[A-Za-z0-9_]+' | sort -u || true)"
|
|
64
|
+
|
|
65
|
+
# matching DATAFLOW.md data-rows (table rows naming an in-scope transition)
|
|
66
|
+
DF_ROWS=""
|
|
67
|
+
if [ -n "$TOKENS" ] && [ -f "$DATAFLOW" ]; then
|
|
68
|
+
while IFS= read -r tok; do
|
|
69
|
+
[ -n "$tok" ] || continue
|
|
70
|
+
rows="$(grep -E '^\|' "$DATAFLOW" | norm | grep -F "$tok" || true)"
|
|
71
|
+
DF_ROWS="${DF_ROWS}${rows}
|
|
72
|
+
"
|
|
73
|
+
done <<EOF
|
|
74
|
+
$TOKENS
|
|
75
|
+
EOF
|
|
76
|
+
fi
|
|
77
|
+
DF_ROWS="$(printf '%s\n' "$DF_ROWS" | grep -v '^$' | sort -u || true)"
|
|
78
|
+
|
|
79
|
+
# ---- the upstream signature + its hash ----
|
|
80
|
+
SIG="$(printf 'ACC:%s\nDF:%s\nROWS:\n%s\n' "$ACC_LINE" "$DF_LINE" "$DF_ROWS")"
|
|
81
|
+
WANT="$(printf '%s' "$SIG" | sha_stdin)"
|
|
82
|
+
|
|
83
|
+
HASH_RE='^<!-- spec-hash: .* -->$'
|
|
84
|
+
HAVE="$(grep -E "$HASH_RE" "$SPEC" | head -1 | sed -E 's/^<!-- spec-hash: (.*) -->$/\1/' || true)"
|
|
85
|
+
|
|
86
|
+
if [ "$SUB" = "stamp" ]; then
|
|
87
|
+
if grep -qE "$HASH_RE" "$SPEC"; then
|
|
88
|
+
tmp="$(mktemp)"
|
|
89
|
+
awk -v h="$WANT" '
|
|
90
|
+
/^<!-- spec-hash: .* -->$/ && !done { print "<!-- spec-hash: " h " -->"; done=1; next }
|
|
91
|
+
{ print }
|
|
92
|
+
' "$SPEC" > "$tmp" && mv "$tmp" "$SPEC"
|
|
93
|
+
else
|
|
94
|
+
echo "spec-staleness: $SPEC has no '<!-- spec-hash: ... -->' header line to stamp." >&2
|
|
95
|
+
exit 2
|
|
96
|
+
fi
|
|
97
|
+
echo "spec-staleness: stamped phase ${N} -> ${WANT}"
|
|
98
|
+
exit 0
|
|
99
|
+
fi
|
|
100
|
+
|
|
101
|
+
# ---- check ----
|
|
102
|
+
if [ -z "$HAVE" ] || [ "$HAVE" = "PENDING" ]; then
|
|
103
|
+
echo "spec-staleness: FAIL — phase ${N} spec hash is unstamped (${HAVE:-missing})." >&2
|
|
104
|
+
echo " Run: bash scripts/spec-staleness.sh stamp ${N}" >&2
|
|
105
|
+
exit 1
|
|
106
|
+
fi
|
|
107
|
+
if [ "$HAVE" != "$WANT" ]; then
|
|
108
|
+
echo "spec-staleness: FAIL — phase ${N} spec is STALE." >&2
|
|
109
|
+
echo " Upstream PLAN.md acceptance / DATAFLOW.md rows changed since the skeleton was stamped." >&2
|
|
110
|
+
echo " stored=${HAVE} current=${WANT}" >&2
|
|
111
|
+
echo " Regenerate the skeleton header from current PLAN/DATAFLOW, re-stamp, and re-fill." >&2
|
|
112
|
+
exit 1
|
|
113
|
+
fi
|
|
114
|
+
echo "spec-staleness: OK — phase ${N} spec header matches upstream (${WANT})."
|
|
115
|
+
exit 0
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""spec-assert.py — kit-versioned matcher-aware deep-equality comparator (v2.2).
|
|
2
|
+
|
|
3
|
+
The generated `data` boundary harness (test-author) asserts an actual response
|
|
4
|
+
against `fixtures/<case-id>-expected.json` via `spec_assert(actual, expected)`.
|
|
5
|
+
Deep equality, EXCEPT that volatile fields in the expected fixture carry a matcher
|
|
6
|
+
token instead of a literal (see §5.49). This is the ONLY comparator — no per-project
|
|
7
|
+
assertion logic. One file per supported test language; this is the Python one.
|
|
8
|
+
|
|
9
|
+
Matcher tokens (string values in the expected fixture):
|
|
10
|
+
|
|
11
|
+
"<UUID>" any UUID v4 string
|
|
12
|
+
"<ISO8601>" any ISO 8601 datetime string
|
|
13
|
+
"<ANY_STRING>" any non-null string
|
|
14
|
+
"<ANY_NUMBER>" any finite number (not bool)
|
|
15
|
+
"<UNORDERED>" any array (presence + shape only)
|
|
16
|
+
"<MATCHES:regex>" any string matching the pattern (re.search)
|
|
17
|
+
|
|
18
|
+
Order-insensitive array WITH item checking: wrap the expected array as
|
|
19
|
+
{"<UNORDERED>": [item, item, ...]}
|
|
20
|
+
and the actual must be a list that is an order-insensitive deep-equal multiset of
|
|
21
|
+
those items.
|
|
22
|
+
|
|
23
|
+
A matcher token asserts PRESENCE + SHAPE — never "ignore this field". A missing
|
|
24
|
+
volatile field still fails (strict key sets). Extra actual keys also fail.
|
|
25
|
+
|
|
26
|
+
Usage (pytest or any runner):
|
|
27
|
+
|
|
28
|
+
from importlib import import_module
|
|
29
|
+
spec_assert = import_module("tests.helpers.spec-assert").spec_assert # if importable
|
|
30
|
+
# or load directly:
|
|
31
|
+
# import importlib.util, pathlib
|
|
32
|
+
# spec = importlib.util.spec_from_file_location("spec_assert", ".../spec-assert.py")
|
|
33
|
+
...
|
|
34
|
+
spec_assert(actual, expected) # raises AssertionError with a JSON path on mismatch
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import json
|
|
40
|
+
import re
|
|
41
|
+
from numbers import Number
|
|
42
|
+
from pathlib import Path
|
|
43
|
+
from typing import Any
|
|
44
|
+
|
|
45
|
+
_UUID4 = re.compile(
|
|
46
|
+
r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"
|
|
47
|
+
)
|
|
48
|
+
_ISO8601 = re.compile(
|
|
49
|
+
r"^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:?\d{2})?$"
|
|
50
|
+
)
|
|
51
|
+
_MATCHES_PREFIX = "<MATCHES:"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class SpecMismatch(AssertionError):
|
|
55
|
+
"""Raised when actual does not satisfy the expected fixture (with a JSON path)."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def load_fixture(path: str | Path) -> Any:
|
|
59
|
+
"""Convenience loader for fixtures/<case-id>-*.json."""
|
|
60
|
+
return json.loads(Path(path).read_text(encoding="utf-8"))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _is_real_number(v: Any) -> bool:
|
|
64
|
+
# bool is a subclass of int in Python — exclude it explicitly.
|
|
65
|
+
return isinstance(v, Number) and not isinstance(v, bool)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _fail(path: str, msg: str) -> None:
|
|
69
|
+
raise SpecMismatch(f"spec-assert mismatch at {path}: {msg}")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _match_token(actual: Any, token: str, path: str) -> bool:
|
|
73
|
+
"""Return True if `token` is a known matcher and `actual` satisfies it.
|
|
74
|
+
Raises on a known token that is NOT satisfied. Returns False if not a token."""
|
|
75
|
+
if token == "<UUID>":
|
|
76
|
+
if not (isinstance(actual, str) and _UUID4.match(actual)):
|
|
77
|
+
_fail(path, f"expected a UUID v4 string, got {actual!r}")
|
|
78
|
+
return True
|
|
79
|
+
if token == "<ISO8601>":
|
|
80
|
+
if not (isinstance(actual, str) and _ISO8601.match(actual)):
|
|
81
|
+
_fail(path, f"expected an ISO 8601 datetime string, got {actual!r}")
|
|
82
|
+
return True
|
|
83
|
+
if token == "<ANY_STRING>":
|
|
84
|
+
if not isinstance(actual, str):
|
|
85
|
+
_fail(path, f"expected any string, got {type(actual).__name__}")
|
|
86
|
+
return True
|
|
87
|
+
if token == "<ANY_NUMBER>":
|
|
88
|
+
if not _is_real_number(actual):
|
|
89
|
+
_fail(path, f"expected any finite number, got {actual!r}")
|
|
90
|
+
return True
|
|
91
|
+
if token == "<UNORDERED>":
|
|
92
|
+
if not isinstance(actual, list):
|
|
93
|
+
_fail(path, f"expected any array, got {type(actual).__name__}")
|
|
94
|
+
return True
|
|
95
|
+
if token.startswith(_MATCHES_PREFIX) and token.endswith(">"):
|
|
96
|
+
pattern = token[len(_MATCHES_PREFIX):-1]
|
|
97
|
+
if not (isinstance(actual, str) and re.search(pattern, actual)):
|
|
98
|
+
_fail(path, f"expected a string matching /{pattern}/, got {actual!r}")
|
|
99
|
+
return True
|
|
100
|
+
return False
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _unordered_equal(actual: list, items: list, path: str) -> None:
|
|
104
|
+
if not isinstance(actual, list):
|
|
105
|
+
_fail(path, f"expected an array (unordered), got {type(actual).__name__}")
|
|
106
|
+
if len(actual) != len(items):
|
|
107
|
+
_fail(path, f"array length {len(actual)} != expected {len(items)} (unordered)")
|
|
108
|
+
remaining = list(actual)
|
|
109
|
+
for i, exp in enumerate(items):
|
|
110
|
+
found = -1
|
|
111
|
+
for j, act in enumerate(remaining):
|
|
112
|
+
try:
|
|
113
|
+
spec_assert(act, exp, f"{path}[unordered:{i}]")
|
|
114
|
+
found = j
|
|
115
|
+
break
|
|
116
|
+
except SpecMismatch:
|
|
117
|
+
continue
|
|
118
|
+
if found < 0:
|
|
119
|
+
_fail(path, f"no actual element matches expected item #{i}: {exp!r}")
|
|
120
|
+
remaining.pop(found)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def spec_assert(actual: Any, expected: Any, path: str = "$") -> None:
|
|
124
|
+
"""Assert `actual` deep-equals `expected`, honoring matcher tokens. Raises
|
|
125
|
+
SpecMismatch (an AssertionError) with a JSON path on the first divergence."""
|
|
126
|
+
# scalar matcher token
|
|
127
|
+
if isinstance(expected, str) and _match_token(actual, expected, path):
|
|
128
|
+
return
|
|
129
|
+
|
|
130
|
+
# {"<UNORDERED>": [...]} wrapper → order-insensitive item compare
|
|
131
|
+
if isinstance(expected, dict) and list(expected.keys()) == ["<UNORDERED>"]:
|
|
132
|
+
_unordered_equal(actual, expected["<UNORDERED>"], path)
|
|
133
|
+
return
|
|
134
|
+
|
|
135
|
+
if isinstance(expected, dict):
|
|
136
|
+
if not isinstance(actual, dict):
|
|
137
|
+
_fail(path, f"expected object, got {type(actual).__name__}")
|
|
138
|
+
exp_keys, act_keys = set(expected), set(actual)
|
|
139
|
+
if exp_keys != act_keys:
|
|
140
|
+
missing = exp_keys - act_keys
|
|
141
|
+
extra = act_keys - exp_keys
|
|
142
|
+
_fail(path, f"key mismatch (missing={sorted(missing)}, extra={sorted(extra)})")
|
|
143
|
+
for k in expected:
|
|
144
|
+
spec_assert(actual[k], expected[k], f"{path}.{k}")
|
|
145
|
+
return
|
|
146
|
+
|
|
147
|
+
if isinstance(expected, list):
|
|
148
|
+
if not isinstance(actual, list):
|
|
149
|
+
_fail(path, f"expected array, got {type(actual).__name__}")
|
|
150
|
+
if len(actual) != len(expected):
|
|
151
|
+
_fail(path, f"array length {len(actual)} != expected {len(expected)}")
|
|
152
|
+
for i, (a, e) in enumerate(zip(actual, expected)):
|
|
153
|
+
spec_assert(a, e, f"{path}[{i}]")
|
|
154
|
+
return
|
|
155
|
+
|
|
156
|
+
# scalar literal — strict equality (bool/int kept distinct)
|
|
157
|
+
if type(actual) is not type(expected) and not (
|
|
158
|
+
_is_real_number(actual) and _is_real_number(expected)
|
|
159
|
+
):
|
|
160
|
+
_fail(path, f"type {type(actual).__name__} != expected {type(expected).__name__}")
|
|
161
|
+
if actual != expected:
|
|
162
|
+
_fail(path, f"{actual!r} != expected {expected!r}")
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* spec-assert.ts — kit-versioned matcher-aware deep-equality comparator (v2.2).
|
|
3
|
+
*
|
|
4
|
+
* The generated `data`/`ui` boundary harness asserts an actual value against
|
|
5
|
+
* `fixtures/<case-id>-expected.json` via `specAssert(actual, expected)`. Deep
|
|
6
|
+
* equality, EXCEPT that volatile fields in the expected fixture carry a matcher
|
|
7
|
+
* token instead of a literal (§5.49). This is the ONLY comparator — no per-project
|
|
8
|
+
* assertion logic. One file per supported test language; this is the TS/JS one.
|
|
9
|
+
*
|
|
10
|
+
* Matcher tokens (string values in the expected fixture):
|
|
11
|
+
*
|
|
12
|
+
* "<UUID>" any UUID v4 string
|
|
13
|
+
* "<ISO8601>" any ISO 8601 datetime string
|
|
14
|
+
* "<ANY_STRING>" any string
|
|
15
|
+
* "<ANY_NUMBER>" any finite number
|
|
16
|
+
* "<UNORDERED>" any array (presence + shape only)
|
|
17
|
+
* "<MATCHES:regex>" any string matching the pattern (RegExp.test)
|
|
18
|
+
*
|
|
19
|
+
* Order-insensitive array WITH item checking: wrap the expected array as
|
|
20
|
+
* { "<UNORDERED>": [item, item, ...] }
|
|
21
|
+
* and the actual must be an array that is an order-insensitive deep-equal multiset.
|
|
22
|
+
*
|
|
23
|
+
* A token asserts PRESENCE + SHAPE — never "ignore this field". Missing volatile
|
|
24
|
+
* fields fail (strict key sets); extra actual keys also fail.
|
|
25
|
+
*
|
|
26
|
+
* import { specAssert, loadFixture } from "../helpers/spec-assert";
|
|
27
|
+
* specAssert(actual, loadFixture("fixtures/PH2-ORDER-01-expected.json"));
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { readFileSync } from "node:fs";
|
|
31
|
+
|
|
32
|
+
const UUID4 =
|
|
33
|
+
/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;
|
|
34
|
+
const ISO8601 =
|
|
35
|
+
/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:?\d{2})?$/;
|
|
36
|
+
const MATCHES_PREFIX = "<MATCHES:";
|
|
37
|
+
|
|
38
|
+
export class SpecMismatch extends Error {
|
|
39
|
+
constructor(message: string) {
|
|
40
|
+
super(message);
|
|
41
|
+
this.name = "SpecMismatch";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function loadFixture<T = unknown>(path: string): T {
|
|
46
|
+
return JSON.parse(readFileSync(path, "utf-8")) as T;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function fail(path: string, msg: string): never {
|
|
50
|
+
throw new SpecMismatch(`spec-assert mismatch at ${path}: ${msg}`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function isPlainObject(v: unknown): v is Record<string, unknown> {
|
|
54
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function typeName(v: unknown): string {
|
|
58
|
+
if (v === null) return "null";
|
|
59
|
+
if (Array.isArray(v)) return "array";
|
|
60
|
+
return typeof v;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Returns true if `token` is a known matcher and `actual` satisfies it.
|
|
64
|
+
* Throws on a known token that is NOT satisfied. Returns false if not a token. */
|
|
65
|
+
function matchToken(actual: unknown, token: string, path: string): boolean {
|
|
66
|
+
switch (token) {
|
|
67
|
+
case "<UUID>":
|
|
68
|
+
if (!(typeof actual === "string" && UUID4.test(actual)))
|
|
69
|
+
fail(path, `expected a UUID v4 string, got ${JSON.stringify(actual)}`);
|
|
70
|
+
return true;
|
|
71
|
+
case "<ISO8601>":
|
|
72
|
+
if (!(typeof actual === "string" && ISO8601.test(actual)))
|
|
73
|
+
fail(path, `expected an ISO 8601 datetime string, got ${JSON.stringify(actual)}`);
|
|
74
|
+
return true;
|
|
75
|
+
case "<ANY_STRING>":
|
|
76
|
+
if (typeof actual !== "string")
|
|
77
|
+
fail(path, `expected any string, got ${typeName(actual)}`);
|
|
78
|
+
return true;
|
|
79
|
+
case "<ANY_NUMBER>":
|
|
80
|
+
if (typeof actual !== "number" || !Number.isFinite(actual))
|
|
81
|
+
fail(path, `expected any finite number, got ${JSON.stringify(actual)}`);
|
|
82
|
+
return true;
|
|
83
|
+
case "<UNORDERED>":
|
|
84
|
+
if (!Array.isArray(actual))
|
|
85
|
+
fail(path, `expected any array, got ${typeName(actual)}`);
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
if (token.startsWith(MATCHES_PREFIX) && token.endsWith(">")) {
|
|
89
|
+
const pattern = token.slice(MATCHES_PREFIX.length, -1);
|
|
90
|
+
if (!(typeof actual === "string" && new RegExp(pattern).test(actual)))
|
|
91
|
+
fail(path, `expected a string matching /${pattern}/, got ${JSON.stringify(actual)}`);
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function unorderedEqual(actual: unknown, items: unknown[], path: string): void {
|
|
98
|
+
if (!Array.isArray(actual))
|
|
99
|
+
fail(path, `expected an array (unordered), got ${typeName(actual)}`);
|
|
100
|
+
if (actual.length !== items.length)
|
|
101
|
+
fail(path, `array length ${actual.length} != expected ${items.length} (unordered)`);
|
|
102
|
+
const remaining = [...actual];
|
|
103
|
+
items.forEach((exp, i) => {
|
|
104
|
+
let found = -1;
|
|
105
|
+
for (let j = 0; j < remaining.length; j++) {
|
|
106
|
+
try {
|
|
107
|
+
specAssert(remaining[j], exp, `${path}[unordered:${i}]`);
|
|
108
|
+
found = j;
|
|
109
|
+
break;
|
|
110
|
+
} catch (e) {
|
|
111
|
+
if (e instanceof SpecMismatch) continue;
|
|
112
|
+
throw e;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (found < 0) fail(path, `no actual element matches expected item #${i}: ${JSON.stringify(exp)}`);
|
|
116
|
+
remaining.splice(found, 1);
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Assert `actual` deep-equals `expected`, honoring matcher tokens. Throws
|
|
121
|
+
* SpecMismatch with a JSON path on the first divergence. */
|
|
122
|
+
export function specAssert(actual: unknown, expected: unknown, path = "$"): void {
|
|
123
|
+
// scalar matcher token
|
|
124
|
+
if (typeof expected === "string" && matchToken(actual, expected, path)) return;
|
|
125
|
+
|
|
126
|
+
// { "<UNORDERED>": [...] } wrapper → order-insensitive item compare
|
|
127
|
+
if (isPlainObject(expected)) {
|
|
128
|
+
const keys = Object.keys(expected);
|
|
129
|
+
if (keys.length === 1 && keys[0] === "<UNORDERED>") {
|
|
130
|
+
unorderedEqual(actual, expected["<UNORDERED>"] as unknown[], path);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (!isPlainObject(actual)) fail(path, `expected object, got ${typeName(actual)}`);
|
|
134
|
+
const expKeys = new Set(keys);
|
|
135
|
+
const actKeys = new Set(Object.keys(actual));
|
|
136
|
+
const missing = [...expKeys].filter((k) => !actKeys.has(k));
|
|
137
|
+
const extra = [...actKeys].filter((k) => !expKeys.has(k));
|
|
138
|
+
if (missing.length || extra.length)
|
|
139
|
+
fail(path, `key mismatch (missing=${JSON.stringify(missing)}, extra=${JSON.stringify(extra)})`);
|
|
140
|
+
for (const k of keys) specAssert(actual[k], expected[k], `${path}.${k}`);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (Array.isArray(expected)) {
|
|
145
|
+
if (!Array.isArray(actual)) fail(path, `expected array, got ${typeName(actual)}`);
|
|
146
|
+
if (actual.length !== expected.length)
|
|
147
|
+
fail(path, `array length ${actual.length} != expected ${expected.length}`);
|
|
148
|
+
for (let i = 0; i < expected.length; i++)
|
|
149
|
+
specAssert(actual[i], expected[i], `${path}[${i}]`);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// scalar literal — strict equality (typeof must agree; NaN-safe)
|
|
154
|
+
if (typeName(actual) !== typeName(expected))
|
|
155
|
+
fail(path, `type ${typeName(actual)} != expected ${typeName(expected)}`);
|
|
156
|
+
if (actual !== expected && !(Number.isNaN(actual) && Number.isNaN(expected)))
|
|
157
|
+
fail(path, `${JSON.stringify(actual)} != expected ${JSON.stringify(expected)}`);
|
|
158
|
+
}
|