@tduyng/pi-devos 0.0.0-stage → 0.14.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.
Files changed (109) hide show
  1. package/CHANGELOG.md +1421 -0
  2. package/LICENSE +201 -0
  3. package/README.md +206 -2
  4. package/package.json +44 -4
  5. package/plugins/devos/agents/reader.md +27 -0
  6. package/plugins/devos/agents/verifier.md +155 -0
  7. package/plugins/devos/pi/extension/devos.ts +605 -0
  8. package/plugins/devos/scripts/check-evidence-router.sh +140 -0
  9. package/plugins/devos/scripts/evidence-router.py +254 -0
  10. package/plugins/devos/scripts/gates/check-dod-core.sh +285 -0
  11. package/plugins/devos/scripts/gates/check-dod.sh +38 -0
  12. package/plugins/devos/scripts/gates/check-implementation-boundary.sh +99 -0
  13. package/plugins/devos/scripts/gates/check-port-source.sh +134 -0
  14. package/plugins/devos/scripts/gates/check-report-locations.sh +148 -0
  15. package/plugins/devos/scripts/gates/check-scenario-coverage.sh +104 -0
  16. package/plugins/devos/scripts/gates/gate-check.mjs +204 -0
  17. package/plugins/devos/scripts/gates/phase-gate.sh +208 -0
  18. package/plugins/devos/scripts/gates/plan-template-check.py +141 -0
  19. package/plugins/devos/scripts/gates/run-gate.sh +148 -0
  20. package/plugins/devos/scripts/gates/spec-contract.sh +19 -0
  21. package/plugins/devos/scripts/gates/spec-template-check.py +152 -0
  22. package/plugins/devos/scripts/gates/suite/01-dod.sh +485 -0
  23. package/plugins/devos/scripts/gates/suite/02-integrity.sh +310 -0
  24. package/plugins/devos/scripts/gates/suite/03-archetype.sh +255 -0
  25. package/plugins/devos/scripts/gates/suite/04-spec-validator.sh +183 -0
  26. package/plugins/devos/scripts/gates/suite/05-requires.sh +360 -0
  27. package/plugins/devos/scripts/gates/suite/06-clarify-adapters.sh +435 -0
  28. package/plugins/devos/scripts/gates/suite/07-lint-evals.sh +350 -0
  29. package/plugins/devos/scripts/gates/suite/08-converge.sh +591 -0
  30. package/plugins/devos/scripts/gates/suite/09-quality.sh +516 -0
  31. package/plugins/devos/scripts/gates/suite/10-eval-harness.sh +679 -0
  32. package/plugins/devos/scripts/gates/test-gates.sh +76 -0
  33. package/plugins/devos/scripts/gates/test-integrity-rubric.sh +152 -0
  34. package/plugins/devos/scripts/gates/test-phase-gate.sh +116 -0
  35. package/plugins/devos/skills/absorb/SKILL.md +75 -0
  36. package/plugins/devos/skills/absorb/references/distill.md +67 -0
  37. package/plugins/devos/skills/absorb/scripts/check-refs.sh +108 -0
  38. package/plugins/devos/skills/absorb/scripts/knowledge.py +258 -0
  39. package/plugins/devos/skills/build/SKILL.md +71 -0
  40. package/plugins/devos/skills/build/references/advanced-routing.md +19 -0
  41. package/plugins/devos/skills/build/references/defect.md +17 -0
  42. package/plugins/devos/skills/build/references/exposure.md +28 -0
  43. package/plugins/devos/skills/build/references/hard.md +39 -0
  44. package/plugins/devos/skills/build/references/refactor.md +66 -0
  45. package/plugins/devos/skills/build/references/routes.md +56 -0
  46. package/plugins/devos/skills/build/references/scale.md +84 -0
  47. package/plugins/devos/skills/build/references/spike.md +19 -0
  48. package/plugins/devos/skills/build/scripts/construct-census.py +204 -0
  49. package/plugins/devos/skills/build/scripts/dep-order.py +297 -0
  50. package/plugins/devos/skills/build/scripts/ledger.sh +228 -0
  51. package/plugins/devos/skills/build/scripts/route.sh +5 -0
  52. package/plugins/devos/skills/build/scripts/secret-scan.sh +121 -0
  53. package/plugins/devos/skills/build/scripts/toolchain-preflight.py +302 -0
  54. package/plugins/devos/skills/frame/SKILL.md +54 -0
  55. package/plugins/devos/skills/frame/references/template.md +115 -0
  56. package/plugins/devos/skills/frame/scripts/survey.sh +44 -0
  57. package/plugins/devos/skills/implement/SKILL.md +36 -0
  58. package/plugins/devos/skills/implement/references/conditional-plan.md +17 -0
  59. package/plugins/devos/skills/implement/references/debug-loop.md +7 -0
  60. package/plugins/devos/skills/implement/references/dod.md +37 -0
  61. package/plugins/devos/skills/implement/references/implement.md +54 -0
  62. package/plugins/devos/skills/implement/references/manual-gates.md +16 -0
  63. package/plugins/devos/skills/implement/references/plan.md +142 -0
  64. package/plugins/devos/skills/implement/references/resume.md +9 -0
  65. package/plugins/devos/skills/implement/references/scale.md +86 -0
  66. package/plugins/devos/skills/implement/references/verify-close.md +62 -0
  67. package/plugins/devos/skills/implement/references/visual-verification.md +7 -0
  68. package/plugins/devos/skills/implement/scripts/check-converge.sh +147 -0
  69. package/plugins/devos/skills/implement/scripts/equivalence-check.sh +140 -0
  70. package/plugins/devos/skills/implement/scripts/manifest-queue.sh +185 -0
  71. package/plugins/devos/skills/implement/scripts/ops-log.sh +58 -0
  72. package/plugins/devos/skills/implement/scripts/pilot-consistency.py +173 -0
  73. package/plugins/devos/skills/implement/scripts/validate-spec.sh +220 -0
  74. package/plugins/devos/skills/init/SKILL.md +100 -0
  75. package/plugins/devos/skills/init/references/archetype-sections.md +15 -0
  76. package/plugins/devos/skills/init/references/context.md +42 -0
  77. package/plugins/devos/skills/init/references/conventions-template.md +153 -0
  78. package/plugins/devos/skills/init/references/reverse-engineer.md +3 -0
  79. package/plugins/devos/skills/init/references/rule-format.md +58 -0
  80. package/plugins/devos/skills/init/references/shape-model.md +29 -0
  81. package/plugins/devos/skills/init/scripts/detect-archetype.py +461 -0
  82. package/plugins/devos/skills/init/scripts/render-rule.py +114 -0
  83. package/plugins/devos/skills/init/scripts/reverse-engineer.sh +162 -0
  84. package/plugins/devos/skills/learn/SKILL.md +29 -0
  85. package/plugins/devos/skills/learn/references/destinations.md +43 -0
  86. package/plugins/devos/skills/learn/references/scoring.md +26 -0
  87. package/plugins/devos/skills/review/SKILL.md +54 -0
  88. package/plugins/devos/skills/review/references/comments.md +13 -0
  89. package/plugins/devos/skills/review/references/gaps.md +26 -0
  90. package/plugins/devos/skills/review/references/reviewer.md +124 -0
  91. package/plugins/devos/skills/review/references/routing.md +35 -0
  92. package/plugins/devos/skills/review/scripts/__pycache__/prepare.cpython-313.pyc +0 -0
  93. package/plugins/devos/skills/review/scripts/prepare.py +763 -0
  94. package/plugins/devos/skills/spec/SKILL.md +57 -0
  95. package/plugins/devos/skills/spec/references/prototype.md +21 -0
  96. package/plugins/devos/skills/spec/references/question-craft.md +47 -0
  97. package/plugins/devos/skills/spec/references/roadmap-link.md +5 -0
  98. package/plugins/devos/skills/spec/references/write-spec.md +128 -0
  99. package/plugins/devos/skills/spec/scripts/clarify.sh +173 -0
  100. package/plugins/devos/skills/status/SKILL.md +67 -0
  101. package/plugins/devos/skills/status/references/cost.md +38 -0
  102. package/plugins/devos/skills/status/scripts/artifact-budgets.sh +88 -0
  103. package/plugins/devos/skills/status/scripts/check-requires.py +556 -0
  104. package/plugins/devos/skills/status/scripts/context-cost.sh +89 -0
  105. package/plugins/devos/skills/status/scripts/convention-usage.sh +184 -0
  106. package/plugins/devos/skills/status/scripts/findings-summary.sh +112 -0
  107. package/plugins/devos/skills/status/scripts/quality-correlation.sh +259 -0
  108. package/plugins/devos/skills/status/scripts/sizing-calibration.sh +71 -0
  109. package/plugins/devos/skills/status/scripts/spec-diff.sh +137 -0
@@ -0,0 +1,58 @@
1
+ #!/bin/bash
2
+ # ops-log.sh SPEC_DIR event [detail]: append one line to SPEC_DIR/ops.jsonl.
3
+ #
4
+ # The pipeline's own timeline. Filesystem-derived state says which artifacts
5
+ # exist; it cannot say when each phase happened or in what order a resumed run
6
+ # actually went. ops.jsonl is that record, and implement's resume detection
7
+ # and /devos:status read it instead of reconstructing.
8
+ #
9
+ # Fixed event vocabulary so readers match on names:
10
+ # started | plan-approved | implemented | verified | closed | note
11
+ #
12
+ # Appends are serialized with a mkdir lock (portable: darwin ships no flock(1)).
13
+ # Each line is one small write under that lock, so two sessions logging at the
14
+ # same moment cannot interleave into torn JSON.
15
+ set -u
16
+
17
+ usage="Usage: $0 SPEC_DIR <started|plan-approved|implemented|verified|closed|note> [detail]"
18
+
19
+ [[ $# -ge 2 ]] || { echo "$usage" >&2; exit 2; }
20
+ dir="$1"; event="$2"; detail="${3:-}"
21
+
22
+ case "$event" in
23
+ started|plan-approved|implemented|verified|closed|note) ;;
24
+ *) echo "$usage" >&2; exit 2 ;;
25
+ esac
26
+ case "$detail" in
27
+ *$'\n'*|*$'\r'*) echo "detail must be a single line" >&2; exit 2 ;;
28
+ esac
29
+
30
+ # JSON strings cannot contain raw control characters. Newline and carriage
31
+ # return are rejected above because they would also break the one-record-per-line
32
+ # format. Escape the other C0 controls before writing the JSON value.
33
+ detail=${detail//\\/\\\\}
34
+ detail=${detail//\"/\\\"}
35
+ printf -v backspace_escape '\\b'
36
+ printf -v formfeed_escape '\\f'
37
+ printf -v tab_escape '\\t'
38
+ detail=${detail//$'\b'/"$backspace_escape"}
39
+ detail=${detail//$'\f'/"$formfeed_escape"}
40
+ detail=${detail//$'\t'/"$tab_escape"}
41
+ for control_code in {1..31}; do
42
+ case "$control_code" in
43
+ 8|9|10|12|13) continue ;;
44
+ esac
45
+ printf -v control_char '\\%03o' "$control_code"
46
+ printf -v json_escape '\\u%04x' "$control_code"
47
+ detail=${detail//"$control_char"/"$json_escape"}
48
+ done
49
+
50
+ mkdir -p "$dir" || exit 1
51
+ file="$dir/ops.jsonl"
52
+ lock="$dir/.ops.lock"
53
+
54
+ while ! mkdir "$lock" 2>/dev/null; do sleep 0.05; done
55
+ trap 'rmdir "$lock" 2>/dev/null' EXIT
56
+
57
+ at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
58
+ printf '{"at":"%s","event":"%s","detail":"%s"}\n' "$at" "$event" "$detail" >> "$file"
@@ -0,0 +1,173 @@
1
+ #!/usr/bin/env python3
2
+ """pilot-consistency: did the same rulebook produce the same port three times?
3
+
4
+ A port's rulebook decides every unit after the first three, so the first three
5
+ are the pilot. Two of them coming out the same way is not evidence that the
6
+ rulebook is right, it is evidence that one rule was applied the same way twice.
7
+ The question the pilot has to answer is the other one: where the units
8
+ disagree, the rulebook is missing a rule or has a vague one, and the fan-out
9
+ to the remaining units would spread that defect.
10
+
11
+ The disagreement is found without a second translator. Every unit's source and
12
+ target are reduced to the same handful of structural roles, and the roles are
13
+ compared across the units. Only the units whose source holds the role are
14
+ compared, because a unit with no exception site decides nothing about
15
+ exceptions, and comparing it against a unit that has one says nothing.
16
+
17
+ One disagreement is a finding: a site the source had is gone in one unit and
18
+ there in another. The same kind of site came out two ways, so the rule that
19
+ decides it is not written down, or is written down badly. A softer difference,
20
+ the same kind of site kept in both units but in different numbers, is printed
21
+ as a note, because a language can legitimately need a different number of
22
+ branches for the same source branch.
23
+
24
+ The comparison is over structure, not over names, so it works across
25
+ languages: a port from Python to Rust keeps its branches and drops its
26
+ exceptions, and the tool says so instead of guessing which is right.
27
+
28
+ Deterministic, no model calls, no dependency beyond the standard library.
29
+
30
+ Usage:
31
+ pilot-consistency.py --manifest FILE [--units N] [--root DIR]
32
+
33
+ --manifest the manifest whose source and target columns name the units
34
+ --units how many units to compare, in manifest order (0 = all, default 3)
35
+ --root the directory the manifest's paths are relative to (default .)
36
+
37
+ Diagnostic envelope (shared by DevOS check scripts):
38
+ FAIL <check>: <message>
39
+ fix: <one actionable line>
40
+
41
+ Exit 0 = the pilot agrees, 1 = the pilot disagrees somewhere, 2 = usage.
42
+ """
43
+ from __future__ import annotations
44
+
45
+ import argparse
46
+ import re
47
+ import sys
48
+ from pathlib import Path
49
+
50
+ # The roles a port has to preserve. Each is a shape a site can have, and the
51
+ # count of a role is what a rule decides: a branch becomes a branch, an
52
+ # exception site becomes an error path or a returned error.
53
+ ROLES = {
54
+ "branch": r"\b(?:if|elif|else|switch|case|match|when)\b",
55
+ "loop": r"\b(?:for|while|foreach|do|loop)\b",
56
+ "error": r"\b(?:try|catch|except|finally|rescue|throw|raise|panic)\b",
57
+ "definition": r"\b(?:def|function|fn|func|class|struct|enum|interface|trait|impl)\b",
58
+ "return": r"\breturn\b",
59
+ }
60
+
61
+ BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.S)
62
+ LINE_COMMENT = re.compile(r"//[^\n]*|#[^\n]*")
63
+ STRING = re.compile(
64
+ r"\"\"\".*?\"\"\"|'''.*?'''|\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`", re.S
65
+ )
66
+
67
+ PATTERNS = {name: re.compile(pattern) for name, pattern in ROLES.items()}
68
+
69
+ KEPT, DROPPED = "kept", "dropped"
70
+
71
+
72
+ def strip_noise(text: str) -> str:
73
+ """Comments and string literals are not structure, and their words read as structure."""
74
+ text = BLOCK_COMMENT.sub(" ", text)
75
+ text = STRING.sub(" ", text)
76
+ text = LINE_COMMENT.sub(" ", text)
77
+ return text
78
+
79
+
80
+ def roles_of(path: Path) -> dict[str, int]:
81
+ try:
82
+ text = path.read_text(encoding="utf-8", errors="replace")
83
+ except OSError:
84
+ return {}
85
+ text = strip_noise(text)
86
+ return {name: len(pattern.findall(text)) for name, pattern in PATTERNS.items()}
87
+
88
+
89
+ def read_manifest(path: Path) -> list[tuple[str, str]]:
90
+ rows = []
91
+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
92
+ if not line.strip():
93
+ continue
94
+ parts = line.split("\t")
95
+ if len(parts) < 2 or parts[0] == "source":
96
+ continue
97
+ rows.append((parts[0].strip(), parts[1].strip()))
98
+ return rows
99
+
100
+
101
+ def main() -> int:
102
+ ap = argparse.ArgumentParser(description="did the same rulebook produce the same port three times")
103
+ ap.add_argument("--manifest", required=True, help="the manifest of the pilot units")
104
+ ap.add_argument("--units", type=int, default=3, help="how many units to compare (0 = all)")
105
+ ap.add_argument("--root", default=".", help="the directory the manifest's paths are relative to")
106
+ args = ap.parse_args()
107
+
108
+ manifest = Path(args.manifest)
109
+ if not manifest.is_file():
110
+ print(f"FAIL pilot-consistency: no manifest at {args.manifest}", file=sys.stderr)
111
+ print(" fix: point --manifest at the manifest of the phase you are piloting", file=sys.stderr)
112
+ return 2
113
+ root = Path(args.root).resolve()
114
+
115
+ units = []
116
+ for source, target in read_manifest(manifest):
117
+ src = root / source
118
+ tgt = root / target
119
+ if not src.is_file() or not tgt.is_file():
120
+ continue
121
+ units.append((source, target, roles_of(src), roles_of(tgt)))
122
+ if args.units and len(units) >= args.units:
123
+ break
124
+
125
+ if len(units) < 2:
126
+ print("pilot-consistency: fewer than two ported units to compare, so there is nothing to disagree about")
127
+ return 0
128
+
129
+ print("| Unit | Role | Source | Target | |")
130
+ print("|---|---|---|---|---|")
131
+ findings = []
132
+ notes = []
133
+ for role in ROLES:
134
+ answers = {}
135
+ for source, target, src_roles, tgt_roles in units:
136
+ source_count = src_roles.get(role, 0)
137
+ if source_count == 0:
138
+ continue
139
+ target_count = tgt_roles.get(role, 0)
140
+ outcome = KEPT if target_count else DROPPED
141
+ answers.setdefault(outcome, []).append((source, target, source_count, target_count))
142
+ print(f"| {target} | {role} | {source_count} | {target_count} | {outcome} |")
143
+ if len(answers) < 2:
144
+ continue
145
+ kept = answers[KEPT]
146
+ dropped = answers[DROPPED]
147
+ first = (kept or dropped)[0]
148
+ second = (dropped or kept)[0]
149
+ if kept and dropped:
150
+ findings.append((role, first, second, "kept in one unit, gone in another"))
151
+ else:
152
+ counts = {count for _, _, _, count in kept}
153
+ if len(counts) > 1:
154
+ notes.append((role, first, second, "kept in both units, in different numbers"))
155
+
156
+ for role, first, second, what in notes:
157
+ print(f"note {role}: {what}; read {first[1]} and {second[1]} side by side")
158
+
159
+ if not findings:
160
+ print()
161
+ print("pilot-consistency: the pilot units agree on every role, so the rulebook covers them")
162
+ return 0
163
+
164
+ print()
165
+ print("FAIL pilot-consistency: the pilot units translated the same kind of site two ways")
166
+ for role, first, second, what in findings:
167
+ print(f" fix: read {first[1]} and {second[1]} side by side and write the rule for {role}: {what}")
168
+ print(" a role the units disagree on is a rule that is missing or vague, and the fan-out spreads it")
169
+ return 1
170
+
171
+
172
+ if __name__ == "__main__":
173
+ sys.exit(main())
@@ -0,0 +1,220 @@
1
+ #!/bin/bash
2
+ # validate-spec.sh <spec-dir>: deterministic format check of a spec folder.
3
+ # Zero model calls. Run by implement before planning and by the
4
+ # verifier as its first completeness check.
5
+ #
6
+ # Diagnostic envelope (shared by DevOS check scripts):
7
+ # FAIL <check>: <message>
8
+ # fix: <one actionable line>
9
+ # Exit 0 = valid, 1 = findings, 2 = usage/missing folder.
10
+ set -u
11
+ dir="${1:-}"
12
+ if [[ -z "$dir" || ! -d "$dir" ]]; then
13
+ echo "FAIL validate-spec: spec directory not found: '${dir}'" >&2
14
+ echo " fix: pass a devos/specs/<name> folder" >&2
15
+ exit 2
16
+ fi
17
+ # Archived capsules are historical records. New plan gates apply to active
18
+ # work, not to specs that were completed before those gates existed. Detect
19
+ # the canonical layout rather than trusting a caller-provided exemption.
20
+ historical=0
21
+ if [[ "$(basename "$(dirname "$dir")")" == "archive" \
22
+ && "$(basename "$(dirname "$(dirname "$dir")")")" == "specs" ]]; then
23
+ historical=1
24
+ fi
25
+ fail=0
26
+ finding() { echo "FAIL validate-spec: $1"; echo " fix: $2"; fail=1; }
27
+
28
+ contract="$(dirname "$0")/../../../scripts/gates/spec-contract.sh"
29
+ sf=$(mktemp)
30
+ trap 'rm -f "$sf"' EXIT
31
+ cname="spec.md"
32
+ if ! bash "$contract" "$dir" >"$sf"; then
33
+ finding "spec.md missing in $dir" "write it (M route inline, or run /devos:spec)"
34
+ else
35
+ grep -qiE '^#+ .*goal' "$sf" || \
36
+ finding "$cname has no Goal section" "add a Goal section: 1-2 sentences of business purpose"
37
+ grep -qiE '^#+ .*out of scope|^\*\*out of scope' "$sf" || \
38
+ finding "$cname has no Out of Scope section" "state explicitly what this spec does not do"
39
+ # C route (behavior-preserving change): an `## Invariant` section stands in
40
+ # for user stories, scenarios and the Behavior delta. The contract is what
41
+ # must NOT change, so there is no scenario to write and no SC-n to trace, and
42
+ # requiring them produces a fabricated spec the verifier then checks against
43
+ # two empty sets. Section body extracted once, reused by both checks below.
44
+ # Heading matched exactly, never as a substring: a feature spec is free to
45
+ # have a "Business invariants" section, and reading that as the C route would
46
+ # silently switch off every scenario check it still needs.
47
+ inv_body=$(awk '/^#+ /{
48
+ h = tolower($0); sub(/^#+[ \t]*/, "", h); sub(/^[0-9]+[.)]?[ \t]*/, "", h)
49
+ sub(/[ \t]+$/, "", h); inv = (h == "invariant"); next
50
+ } inv' "$sf")
51
+ delta_body=$(awk '/^#+ /{ d = (tolower($0) ~ /behavior delta/); next } d' "$sf")
52
+
53
+ if [[ -n "$inv_body" ]]; then
54
+ # The whole route is a before/after comparison, so a named command is the
55
+ # one thing the section cannot omit. Backticks are how the template writes
56
+ # one, and how every other DevOS check recognizes a command.
57
+ grep -q '`' <<<"$inv_body" || \
58
+ finding "Invariant section names no command" "list at least one command that must still pass: \`command\` -> baseline: exit N, M passed"
59
+ grep -qiE 'surface|none, internal' <<<"$inv_body" || \
60
+ finding "Invariant section does not state the public surface" "add the exported names/routes/flags that must not move, or state 'none, internal only'"
61
+ # Both sections present means the spec is claiming to change behavior and
62
+ # preserve it. One of the two is wrong, and guessing which is not this
63
+ # script's job.
64
+ real_delta=$(grep -E '^[[:space:]]*[-*][[:space:]]+' <<<"$delta_body" | grep -ivE '\(none\)|^[[:space:]]*[-*][[:space:]]*none' || true)
65
+ if [[ -n "$real_delta" ]]; then
66
+ finding "spec has both an Invariant and a Behavior delta with entries" \
67
+ "a spec that changes behavior is not a C route: drop the Invariant and write scenarios, or move the delta entries to their own spec"
68
+ fi
69
+ elif ! grep -qE 'Scenario( SC-[0-9]+)?:' "$sf"; then
70
+ finding "$cname has no WHEN/THEN scenarios" "each behavior and business rule needs at least one 'Scenario SC-n: name / WHEN condition / THEN outcome' line, or an ## Invariant section if this is a behavior-preserving change"
71
+ else
72
+ while IFS=: read -r n line; do
73
+ if ! grep -qE 'WHEN .+ THEN' <<<"$line"; then
74
+ finding "malformed scenario at $cname:$n (needs WHEN ... THEN ... on the line)" "rewrite as: Scenario SC-n: name / WHEN condition / THEN observable outcome"
75
+ fi
76
+ # The SC-n ID is the stable index shared by the functional spec, plan,
77
+ # and verification report. It stays in devos/ artifacts. Implementation
78
+ # tests use behavior-facing names, and the output-boundary gate keeps the
79
+ # ID out of source.
80
+ if ! grep -qE 'Scenario SC-[0-9]+:' <<<"$line"; then
81
+ finding "scenario at $cname:$n has no SC-n ID" "number it: 'Scenario SC-1: name / WHEN ... THEN ...', sequential across the spec"
82
+ fi
83
+ done < <(grep -nE 'Scenario( SC-[0-9]+)?:' "$sf")
84
+ dupes=$(grep -oE 'Scenario SC-[0-9]+:' "$sf" | sort | uniq -d)
85
+ if [[ -n "$dupes" ]]; then
86
+ finding "duplicate scenario IDs in $cname: $(tr '\n' ' ' <<<"$dupes")" "IDs are unique within a spec; renumber the later duplicate to the next free number"
87
+ fi
88
+ fi
89
+ # Normative wording, made mechanical: a requirement nobody can falsify is not
90
+ # yet a requirement, and asking the writer to police its own hedges is prose
91
+ # a gate can replace. Section-aware, because Out of Scope and Behavior delta
92
+ # hedge legitimately (a deferred item, a quoted current behavior).
93
+ # Boundaries are POSIX bracket classes, never gawk's \y: that extension
94
+ # matches nothing on darwin's awk, so the check would pass silently forever.
95
+ while IFS= read -r h; do
96
+ finding "hedge word in a requirement at $cname:${h%%:*}:${h#*:}" \
97
+ "promote the hedge to MUST/SHALL, or move the item to Out of Scope"
98
+ done < <(awk '
99
+ /^#+ / { sect = tolower($0); next }
100
+ sect ~ /out of scope|behavior delta|appendix|known volatility/ { next }
101
+ /^[[:space:]]*[-*][[:space:]]/ || /Scenario( SC-[0-9]+)?:/ {
102
+ if (tolower($0) ~ /(^|[^[:alnum:]])(should|may|probably|ideally|might|possibly)([^[:alnum:]]|$)/)
103
+ printf "%d:%s\n", FNR, $0
104
+ }' "$sf")
105
+
106
+ # A functional spec describes behavior, not implementation. Tested on
107
+ # emptiness rather than grep's status: piping through head would report the
108
+ # pipeline's last exit code, which is head's, which is always 0.
109
+ fence=$(grep -nE '^[[:space:]]*```' "$sf" | head -1)
110
+ if [[ -n "$fence" ]]; then
111
+ finding "$cname has a code block at line ${fence%%:*}" \
112
+ "describe the behavior instead; a sample belongs in a table, and implementation belongs in spec.md"
113
+ fi
114
+
115
+ # Behavior delta (present from v0.4.0 specs onward; validated only if present)
116
+ if grep -qiE '^#+ .*behavior delta' "$sf"; then
117
+ removed=$(grep -iE '^#+ *Removed|^\*\*Removed' "$sf" | grep -ivE '\(none\)|: *$' || true)
118
+ if [[ -n "$removed" ]]; then
119
+ grep -qiE 'Reason' "$sf" || \
120
+ finding "Behavior delta removes behavior without a Reason" "each Removed entry states Reason and what replaces it"
121
+ fi
122
+ fi
123
+ fi
124
+
125
+ plan="$dir/spec.md"
126
+ if bash "$contract" --has-plan "$dir" && [[ "$historical" -eq 0 ]]; then
127
+
128
+ lines=$(awk 'END { print NR }' "$plan")
129
+ if (( lines > 300 )); then
130
+ finding "spec.md capsule is $lines lines (budget 300)" "split the spec: two small specs implement more reliably than one huge one"
131
+ fi
132
+
133
+ # A task group with no Files list is invisible to check-converge.sh, which
134
+ # skips any group it cannot resolve a file list for. The group then closes
135
+ # without ever proving its work landed, so the omission disables an existing
136
+ # gate rather than merely under-documenting the plan. The heading accepts the
137
+ # colon separator as well as the numbered one, the two forms check-converge
138
+ # reads: with the numbered form alone, `### Task Group: Lexer` was not a group
139
+ # here and its missing file list was never reported.
140
+ while IFS= read -r g; do
141
+ finding "task group at spec.md:${g%%:*} has no **Files:** line" \
142
+ "list the files this group touches; check-converge skips a group with none, so it closes unverified"
143
+ done < <(awk '
144
+ /^###[[:space:]]+Task[[:space:]]+Group([[:space:]]+|:)/ {
145
+ if (open) printf "%d:%s\n", start, head
146
+ open = 1; start = FNR; head = $0; next
147
+ }
148
+ open && /^\*\*Files:\*\*/ { open = 0 }
149
+ /^##[[:space:]]/ && !/^###/ { if (open) { printf "%d:%s\n", start, head; open = 0 } }
150
+ END { if (open) printf "%d:%s\n", start, head }' "$plan")
151
+
152
+ # Local Craft is the plan's project-specific evidence. Without this gate, a
153
+ # plan can omit the section that distinguishes local reuse and syntax from
154
+ # generic advice, while still passing every other structural check.
155
+ if ! grep -qiE '^#+[[:space:]]*Local Craft' "$plan"; then
156
+ finding "spec.md has no Local Craft section" \
157
+ "record project-specific syntax, reuse, package, or algorithm evidence, or state None"
158
+ else
159
+ local_craft=$(awk '
160
+ /^#+[[:space:]]*Local Craft/ { in_craft = 1; next }
161
+ in_craft && /^#+[[:space:]]/ { exit }
162
+ in_craft { print }
163
+ ' "$plan")
164
+ if ! grep -qiE '^[[:space:]]*(-[[:space:]]*)?(none|n/a)([[:space:]]*:.*)?$' <<<"$local_craft" \
165
+ && ! grep -qE '`[^`]+:[0-9]+(-[0-9]+)?`|https?://' <<<"$local_craft"; then
166
+ finding "spec.md Local Craft has no file:line or URL evidence" \
167
+ "name the project evidence, or state None when the task is conventional"
168
+ fi
169
+ fi
170
+
171
+ # Design Convergence (step 4b) is the plan's own anti-over-engineering pass:
172
+ # the smallest design that delivers the Goal, what it fails, and what was
173
+ # added only because something failed. Unenforced, it is the section a plan
174
+ # skips exactly when it is adding the most.
175
+ if ! grep -qiE '^#+[[:space:]]*Design Convergence' "$plan"; then
176
+ finding "spec.md has no Design Convergence section" \
177
+ "add it with Direct MVP, Failed Items, Adopted Additions, Rejected Additions; 'None' is a valid answer for the last three"
178
+ else
179
+ # Presence alone proves nothing: the section passes with four labels and no
180
+ # thought behind them. This is the one line of it a script can falsify.
181
+ # Every Adopted Addition answers a Failed Item, so additions listed against
182
+ # `Failed Items: None` is the section contradicting itself, and it is the
183
+ # exact shape an unjustified abstraction takes on the way into a plan.
184
+ dcval() { awk -v k="$1" '
185
+ tolower($0) ~ "^[-*][[:space:]]*\\*\\*" k "\\*\\*" {
186
+ sub(/^[^:]*:[[:space:]]*/, ""); print; exit }' "$plan"; }
187
+ empty() { [[ -z "$1" ]] || grep -qiE '^(none|n/?a)[[:punct:]]*$' <<<"$1"; }
188
+ if ! empty "$(dcval 'adopted additions')" && empty "$(dcval 'failed items')"; then
189
+ finding "Design Convergence adopts additions while Failed Items is None" \
190
+ "every addition answers a Failed Item: name what the Direct MVP fails and the evidence it fails, or drop the addition"
191
+ fi
192
+ fi
193
+
194
+ # Scenario traceability across artifacts (spec-kit's analyze pass, made a
195
+ # gate): every SC-n the functional spec declares must surface somewhere in
196
+ # the capsule, and every SC-n the capsule cites must exist. C routes are
197
+ # exempt (an Invariant declares no scenarios by design). Both directions are
198
+ # set differences over IDs, so prose cannot blur them and the check stays mechanical.
199
+ if [[ -f "$sf" && -z "$inv_body" ]] && grep -qE 'Scenario SC-[0-9]+:' "$sf"; then
200
+ declared=$(mktemp); cited=$(mktemp)
201
+ grep -oE 'SC-[0-9]+' <<<"$(grep -E 'Scenario SC-[0-9]+:' "$sf")" | sort -u > "$declared"
202
+ grep -vE 'Scenario SC-[0-9]+:' "$plan" | grep -oE 'SC-[0-9]+' | sort -u > "$cited" || true
203
+ while IFS= read -r sc; do
204
+ grep -qx "$sc" "$cited" || \
205
+ finding "scenario $sc is declared but covered nowhere in spec.md" \
206
+ "list it under one task group's Scenarios covered (or acceptance criteria / [human-check]) before approval"
207
+ done < "$declared"
208
+ while IFS= read -r sc; do
209
+ grep -qx "$sc" "$declared" || \
210
+ finding "spec.md cites $sc which $cname does not declare" \
211
+ "fix the ID or declare the scenario; a coverage claim pointing at nothing verifies nothing"
212
+ done < "$cited"
213
+ rm -f "$declared" "$cited"
214
+ fi
215
+ fi
216
+
217
+ if (( fail == 0 )); then
218
+ echo "PASS validate-spec: $dir well-formed"
219
+ fi
220
+ exit $fail
@@ -0,0 +1,100 @@
1
+ ---
2
+ name: init
3
+ description: "DevOS: Map an existing codebase into DevOS knowledge artifacts and wire AGENTS.md. Not for product planning."
4
+ argument-hint: "[--full] [--reverse-engineer]"
5
+ disable-model-invocation: true
6
+ ---
7
+
8
+ # /devos:init
9
+
10
+ **Scan now, starting at Step 1.** No arguments is the normal invocation, not a missing input: the repository is the input. Answering with a question about what to onboard is the one failure this command has, and it looks exactly like the command not running at all.
11
+
12
+ **Goal:** produce the three knowledge artifacts, plus the product-knowledge skeletons. Nothing else.
13
+
14
+ - `devos/product/codebase-map.md`: where things live
15
+ - `devos/product/domain-model.md`: shared vocabulary (one page max)
16
+ - `devos/standards/conventions.md`: skeleton of project choices, if it doesn't exist yet
17
+ - `devos/product/knowledge/sources.md` plus the four product artifacts: where the product's own promises are written down (Step 3b)
18
+
19
+ `--full` forces a complete re-scan. Full product-suite onboarding (mission, backlog, roadmap) is the separate `product` command, not this one.
20
+
21
+ `--reverse-engineer` (brownfield only, and only when asked): read `${CLAUDE_SKILL_DIR}/references/reverse-engineer.md` now and follow it.
22
+
23
+ ## Step 1: Incremental check
24
+
25
+ If `codebase-map.md` exists, read its `commit:` header and diff against HEAD. Nothing significant changed → say the map is current and stop. Some areas changed → refresh only those sections and the commit hash. `--full` forces a complete re-scan.
26
+
27
+ ## Step 2: Explore
28
+
29
+ **Greenfield repo:** `git ls-files` lists no source files (fresh project) → skip `codebase-map.md` entirely. There is nothing to map, and a map of intentions misdirects every future plan. Interview briefly instead: intended stack, how the project will prove it works; write only `conventions.md` (and `domain-model.md` when the user names entities). Say what you skipped and why.
30
+
31
+ **First, detect the archetypes.** Run `python3 ${CLAUDE_SKILL_DIR}/scripts/detect-archetype.py --facts` (if `${CLAUDE_SKILL_DIR}` was not expanded, it is this skill's directory) from the repo root. It prints the archetype tags, the resolved version of every framework it detects, and the project's declared check scripts, in well under a second and with no model calls. The version table fills Key dependencies below, the check table fills Verification commands in `conventions.md`, and both come from disk rather than recall. (Plain `detect-archetype.py` with no flag still prints only the JSON tag list, for callers that want just detection.) The tags decide which optional sections Step 3 emits and which areas the fan-out below covers, since a `design:*` or `style:*` hit is worth a component-inventory branch a Go CLI never pays for. Detection is reported, never enforced: an archetype it misses produces an empty section the human fills in, which beats a wrong guess stated with authority.
32
+
33
+ Understand the repo well enough to write the three artifacts: structure, entry points, domains, key dependencies, recurring patterns. On a full scan (the first run, or `--full`) of a large or multi-domain repo, read one top-level subsystem at a time and keep only a short summary of each, so exploration noise stays out of this conversation. An incremental re-scan stays single-pass, because a small delta never pays for a split. You decide the subsystem split, and there is no prescribed scan procedure.
34
+
35
+ ## Step 3: Write the artifacts
36
+
37
+ `codebase-map.md` (commit-worthy, future sessions read this instead of re-scanning):
38
+
39
+ ```markdown
40
+ # Codebase Map
41
+ <!-- Map budget: ≤120 lines. A map says where things live; an inventory of every endpoint goes stale and bloats every future plan. Overflow means you're documenting content, not location — cut detail, not domains. -->
42
+ > commit: [git rev-parse HEAD] | generated: [date]
43
+
44
+ ## Structure
45
+ [top-level dirs and their roles, entry points]
46
+
47
+ ## Domains
48
+ | Domain | Paths | Notes |
49
+
50
+ ## Key dependencies
51
+ [the `--facts` version table verbatim, then DB and external services from config. A framework named without its version is the input that makes a future plan guess.]
52
+
53
+ ## Archetype sections (emit only when detected by detect-archetype.py)
54
+ [Optional sections, each included only when the corresponding archetype is detected. Empty sections cost zero tokens on projects they don't apply to. Read `${CLAUDE_SKILL_DIR}/references/archetype-sections.md` for the section list whenever any ui:*, design:*, style:*, state:*, data:*, infra:*, or monorepo:* tag fires.]
55
+ ```
56
+
57
+ `domain-model.md`: read `${CLAUDE_SKILL_DIR}/references/shape-model.md` and follow it in this conversation (the vocabulary questions need the main agent). Entity names become the official vocabulary, one page max.
58
+
59
+ `conventions.md` (**skeleton only if missing, mandatory sections always**), following these rules.
60
+
61
+ **When the file exists**, do not re-copy the template over it and do not leave it as-is either. Append any mandatory section it lacks, and refresh Verification commands from the current `--facts` table, since a check the project gained since the last run is a check nothing is running.
62
+
63
+ **When it is missing**, copy `${CLAUDE_SKILL_DIR}/references/conventions-template.md` (if `${CLAUDE_SKILL_DIR}` was not expanded by your harness, it is this skill's own directory, the folder containing this SKILL.md) and fill in what you can infer, each marked `[inferred, confirm]`: the test runner, the architecture pattern, hard rules found in configs, the Branching & workspace pattern from existing branch names via `git branch -r`, and the `Workspace setup:` line from the lockfile present (pnpm-lock.yaml → `pnpm install --prefer-offline`, package-lock.json → `npm ci`, uv.lock → `uv sync`, Gemfile.lock → `bundle install`, Cargo and Go need none). Delete sections that do not apply.
64
+
65
+ **Verification commands**, always filled. Every row of the `--facts` **Declared checks** table goes in, verbatim and without triage, because that table is mechanical and a judgement call about which of a project's own checks matter most is how a type-check or an accessibility suite ends up never running. Then add what no manifest declares: a Terraform validate, a headless editor load, a linter with no script entry, a functional suite that only runs inside docker-compose, a CI job invoking a script directly. The table reads package.json, justfile and Makefile, so read the CI config too for commands that appear there and in no manifest. With no detectable checks at all, ask the user in one question what command proves the project works, and accept "none".
66
+
67
+ **Preview command**, filled the same way from the `--facts` preview candidates: the script that serves the app plus its URL. A UI that nothing can start is a UI nothing can check. Accept "none" for a project with no UI.
68
+
69
+ **CI & deploy topology** is mandatory when a `ci:*` tag fires, filled from the pipeline file itself: stage order, the branch/tag → environment matrix, and the per-brand or per-tenant deploy variants. That matrix is the first thing a plan needs when it touches CI and the last thing it can infer, and a project deploying four environments off three branch rules reads as a single `main` pipeline to anyone who only saw the scripts.
70
+
71
+ **Design sections are filled or explicitly emptied.** When `--facts` reports a `design:*` or `style:*` tag, `Design system / tokens`, `Component conventions` and `Styling` must not ship as template comments. Record the token source and its location if you found one, or one line saying no design system is declared and UI is improvised per feature. A detected archetype with an undeclared convention is the same gap as an undeclared check, and it is the one that makes each new screen match neither of the last two.
72
+
73
+ **Scoped rules**: where an inferred convention has a real file-glob to attach to (a language's strict-mode setting, a per-directory architecture boundary you actually found enforced), draft it as `devos/standards/rules/<NN>-<category>/<slug>.md` (format in `references/rule-format.md`) instead of a `conventions.md` line, `[inferred, confirm]` like every other inference, and never one the codebase doesn't actually exhibit, because that is a guess wearing a rule's authority.
74
+
75
+ ## Step 3b: Record where the product is documented
76
+
77
+ The three artifacts above describe what the code does. Nothing in them says what the product promises its users, which is the gap that makes a ticket written in product language unreadable to a new engineer.
78
+
79
+ Ask one question, with the candidates you found as options: where is this product documented for its users? A help centre, a published policy, a partner contract, a Notion space, a PDF. Accept "nothing published".
80
+
81
+ Then write the links, never the content. The manifest is the absorb script's file, so create it with the script and let it keep the columns:
82
+
83
+ ```bash
84
+ python3 ${CLAUDE_SKILL_DIR}/../absorb/scripts/knowledge.py --dir devos/product/knowledge init
85
+ python3 ${CLAUDE_SKILL_DIR}/../absorb/scripts/knowledge.py --dir devos/product/knowledge import --collection <slug> --listing <file> --version <label>
86
+ ```
87
+
88
+ `sources.tsv` holds one row per article: id, collection, url, source date, and the state an absorb run left it in. `devos/product/knowledge/cache/` is what a fetch writes, and the repository ignores it.
89
+
90
+ Pasting article prose into the repository is the failure mode here: it goes stale with no way to tell, and it costs every future session the tokens. `/devos:absorb` reads this file, fetches what the engineer confirms is in scope, and commits distilled rules with a source and a read date per claim.
91
+
92
+ Emit `devos/product/glossary.md`, `capabilities.md`, `personas.md` and `constraints.md` as skeletons, each one page, each with its column header and a line saying absorbing a source fills it. A term the code names differently from the product is a glossary row you can often fill from the domain model and the code alone, so fill what you can now. An empty skeleton is correct: every stage that reads these treats them as optional.
93
+
94
+ ## Step 4: Validate
95
+
96
+ Show the three artifacts (or their diffs), and any drafted rule files, to the user. Ask which inferred conventions or rules are wrong. Once confirmed, run `python3 ${CLAUDE_SKILL_DIR}/scripts/render-rule.py` on each new rule file so it reaches every installed tool's native rules surface immediately, not just Claude's.
97
+
98
+ ## Step 5: Wire the project context
99
+
100
+ Read `${CLAUDE_SKILL_DIR}/references/context.md` and follow it to put the DevOS section into `AGENTS.md`, so every session reads the artifacts, not just `/devos` commands. Requires user approval before writing.
@@ -0,0 +1,15 @@
1
+ # Codebase-map archetype sections
2
+
3
+ Emit each section only when detect-archetype.py reports the matching tag. Empty sections cost zero tokens on projects they don't apply to.
4
+
5
+ - `## UI Framework`: framework, routing, rendering mode (when ui:* detected)
6
+ - `## Component Library`: library name, version, customization approach (when design:* detected)
7
+ - `## Design System`: token location, theme structure, extension process (when design:* detected)
8
+ - `## Styling`: methodology, breakpoints, dark mode, motion (when style:* detected)
9
+ - `## State Management`: library, store shape, persistence (when state:* detected)
10
+ - `## Testing Strategy`: unit / integration / e2e / visual, tools, coverage targets (always include if detectable)
11
+ - `## Data Pipeline`: orchestrator, transformations, warehouse (when data:* detected)
12
+ - `## Infrastructure`: IaC tools, environment topology, deploy gate (when infra:* detected)
13
+ - `## CI & deploy topology`: pipeline file, stage order, which branch or tag rule selects which environment, per-brand or per-tenant deploy variants (when ci:* detected)
14
+ - `## Workspace Layout`: monorepo package graph, shared configs, which tool drives the graph and how a single package is built or tested through it (when monorepo:* detected)
15
+ - `## Runtime Environment`: how the app and its dependencies are brought up locally, the compose services or cluster context, and which checks run inside one rather than on the host (when container:* detected)
@@ -0,0 +1,42 @@
1
+ # Wire the project context
2
+
3
+ Run this in the **main agent**: the change needs user approval before writing.
4
+
5
+ ## Sources
6
+
7
+ Read from `devos/` (each may not exist, include only what does): `product/mission.md` (first paragraph of the pitch), `product/tech-stack.md`, `product/domain-model.md`, `product/codebase-map.md`, `standards/conventions.md`, `standards/rules/**/*.md`. Fallback: git remote, directory name, filesystem scan.
8
+
9
+ ## Snippet format
10
+
11
+ ```markdown
12
+ # [Project Name]
13
+
14
+ [One sentence from mission.md]
15
+
16
+ ## Project Context
17
+
18
+ Read when relevant (they're short):
19
+ - Conventions & test style: devos/standards/conventions.md
20
+ - Scoped rules: devos/standards/rules/[list each file, skipping any marked `superseded-by:` - audit trail, not guidance]
21
+ - Vocabulary: devos/product/domain-model.md
22
+ - Codebase map: devos/product/codebase-map.md
23
+ - Tech stack: devos/product/tech-stack.md
24
+
25
+ These apply to ALL work in this project, direct requests included, not just /devos:* commands. Match existing test and code style; entity names come from the domain model. **Scoped rules matter even on tools with no native glob-attach mechanism** (Codex CLI, OpenCode, Pi): this section is the fallback that makes them visible at all, since `AGENTS.md` is read natively there but `devos/standards/rules/` isn't auto-attached per file the way Copilot's own rules surface is.
26
+
27
+ ## Spec Progress
28
+
29
+ Progress is derived from the filesystem: which artifact files exist in a spec folder
30
+ (planning/notes.md, spec.md, verifications/). There is no state
31
+ file, and none should be created: it would drift from the filesystem the moment either changes.
32
+ ```
33
+
34
+ List only the files that actually exist. A reference to a missing file is worse than no reference.
35
+
36
+ ## Insertion
37
+
38
+ Write the snippet into `AGENTS.md`, the canonical project context file. Touch only the sections this skill owns (`# [Project Name]`, `## Project Context`, `## Spec Progress`). If the file has the section, replace it and show the diff for confirmation. If the file exists without the section, prepend it. If the file does not exist, create it. If an old `## Project Structure` section from a previous DevOS version exists, offer to replace it with `## Project Context`. Leave every other existing section untouched, `## Language` and any other project-specific section included, they are not this skill's concern.
39
+
40
+ `AGENTS.md` is the only context file to create or update.
41
+
42
+ **User approval required before modification.**