@mmerterden/multi-agent-pipeline 20.40.0 → 20.41.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 (76) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +4 -1
  3. package/README.tr.md +4 -1
  4. package/docs/adr/0019-product-tree.md +143 -0
  5. package/docs/adr/README.md +1 -0
  6. package/docs/ecosystem.md +9 -9
  7. package/docs/facts.json +4 -4
  8. package/docs/features.md +6 -0
  9. package/install/claude.mjs +12 -3
  10. package/install/templates/claude-hooks.json +12 -1
  11. package/manifest.json +79 -60
  12. package/package.json +2 -2
  13. package/pipeline/commands/multi-agent/review-analysis/SKILL.md +1 -1
  14. package/pipeline/contract/types/index.d.ts +53 -49
  15. package/pipeline/lib/context-budget.mjs +5 -42
  16. package/pipeline/lib/hook-registration.mjs +5 -0
  17. package/pipeline/lib/md2confluence-v3.py +12 -4
  18. package/pipeline/lib/tiered-budget.mjs +87 -0
  19. package/pipeline/multi-agent-refs/analysis/review.md +23 -1
  20. package/pipeline/multi-agent-refs/features/code-graph.md +11 -1
  21. package/pipeline/multi-agent-refs/features/doctor.md +32 -1
  22. package/pipeline/multi-agent-refs/features/product-tree.md +68 -0
  23. package/pipeline/multi-agent-refs/features/unattended-security.md +88 -1
  24. package/pipeline/multi-agent-refs/features/usage-reporting.md +31 -0
  25. package/pipeline/multi-agent-refs/help/en.md +1 -0
  26. package/pipeline/multi-agent-refs/help/tr.md +1 -0
  27. package/pipeline/multi-agent-refs/knowledge.md +58 -0
  28. package/pipeline/multi-agent-refs/phases/phase-0-init.md +4 -0
  29. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -0
  30. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  31. package/pipeline/office/index.html +13 -7
  32. package/pipeline/office/toolkit.json +1 -1
  33. package/pipeline/preferences-template.json +1 -0
  34. package/pipeline/schemas/learnings-ledger.schema.json +35 -2
  35. package/pipeline/schemas/office-archive.schema.json +225 -128
  36. package/pipeline/schemas/prefs.schema.json +83 -0
  37. package/pipeline/schemas/product-tree-overlay.schema.json +57 -0
  38. package/pipeline/schemas/product-tree.schema.json +136 -0
  39. package/pipeline/schemas/toolkit-path-params.json +1 -1
  40. package/pipeline/scripts/_eval-stats.mjs +182 -0
  41. package/pipeline/scripts/_guard_rules.py +130 -1
  42. package/pipeline/scripts/_learnings-promotion.mjs +229 -0
  43. package/pipeline/scripts/_locate.mjs +539 -0
  44. package/pipeline/scripts/_memory-policy.mjs +213 -14
  45. package/pipeline/scripts/_product-tree-extract.mjs +761 -0
  46. package/pipeline/scripts/_product-tree.mjs +923 -0
  47. package/pipeline/scripts/_retrieval.mjs +13 -2
  48. package/pipeline/scripts/_stack-routing.mjs +1 -0
  49. package/pipeline/scripts/_user_guard_rules.py +744 -0
  50. package/pipeline/scripts/agent-guard.py +61 -5
  51. package/pipeline/scripts/agent-guard.sh +8 -1
  52. package/pipeline/scripts/doctor.mjs +157 -1
  53. package/pipeline/scripts/graph-query.mjs +257 -17
  54. package/pipeline/scripts/learnings-ledger.mjs +664 -43
  55. package/pipeline/scripts/note-mcp-failure.mjs +356 -0
  56. package/pipeline/scripts/note-mcp-failure.sh +19 -0
  57. package/pipeline/scripts/note-skill-use.mjs +93 -23
  58. package/pipeline/scripts/office-archive.mjs +23 -10
  59. package/pipeline/scripts/office-memory.mjs +4 -1
  60. package/pipeline/scripts/persona-walk-anchors.mjs +443 -0
  61. package/pipeline/scripts/product-tree-eval.mjs +685 -0
  62. package/pipeline/scripts/product-tree.mjs +544 -0
  63. package/pipeline/skills/.skill-manifest.json +11 -7
  64. package/pipeline/skills/.skills-index.json +12 -1
  65. package/pipeline/skills/shared/README.md +4 -3
  66. package/pipeline/skills/shared/core/google-play-compliance/references/examples.md +1 -1
  67. package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +1 -1
  68. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  69. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  70. package/pipeline/skills/shared/external/spec-persona-walk/SKILL.md +118 -0
  71. package/pipeline/skills/shared/external/spec-persona-walk/evals/evals.json +50 -0
  72. package/pipeline/skills/shared/external/spec-persona-walk/scripts/persona-walk-anchors.mjs +443 -0
  73. package/pipeline/skills/shared/external/storekit/SKILL.md +1 -1
  74. package/pipeline/skills/shared/external/swiftdata/SKILL.md +1 -1
  75. package/pipeline/skills/skill-copies.json +5 -1
  76. package/pipeline/skills/skills-index.md +2 -1
@@ -25,7 +25,7 @@ Read `$HOME/.claude/multi-agent-refs/analysis/review.md` and execute it:
25
25
  1. **Resolve** from a local path, a Confluence URL or `pageId`, or a Jira key. No argument -> pick from recent analyses in `~/Desktop/multiAgentAnalysis/` and each repo's `analysis/`.
26
26
  2. **Deterministic gates first**, output reported verbatim before any model reads the document:
27
27
  `validate-analysis-doc.mjs <doc>`, and `build-references.mjs <state> --check <doc>` when a state JSON is available.
28
- 3. **Parallel model review** against the rubric: buildability, evidence, spine, altitude, admitted gaps, contradiction.
28
+ 3. **Parallel model review** against the rubric: buildability, evidence, spine, altitude, admitted gaps, contradiction. With `review.personaWalk.enabled` (off by default), a persona walk runs beside them; `persona-walk-anchors.mjs` drops findings whose anchor is not in the document.
29
29
  4. **Triage** into Blocker / Important / Suggestion.
30
30
  5. **Report** the profile it judged against and, explicitly, what was NOT checked.
31
31
  6. **Output** on request: chat (default), Confluence comment, Jira comment, or a `-review.md` beside the document.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: backlog
3
- description: "Registry and routine for approved but postponed engineering work: each item keeps its full spec, origin and unblock condition, and moves through deferred, ready, in-progress and done. Use when the user postpones work ('later', 'not now', 'put it on the list', 'backlog this'), asks what is on the backlog or still owed, works the backlog, picks up an item by id or the next one, finishes an item, or when a rename, a deleted subject or a doubted claim calls for a re-audit. Not for Jira or GitHub tickets, and never for summarising or rewriting a deferred spec."
3
+ description: "Registry and routine for approved but postponed engineering work: each item keeps its full spec, origin and unblock condition, and moves through deferred, ready, in-progress and done. Use when the user postpones work ('later', 'not now', 'put it on the list', 'backlog this'), asks what is on the backlog or still owed, works the backlog, picks up an item by id or the next one, finishes an item, or re-audits entries whose subject may be gone. Not for Jira or GitHub tickets, and never for summarising or rewriting a deferred spec."
4
4
  user-invocable: true
5
5
  argument-hint: [list | add | pick <id> | done <id> | re-audit]
6
6
  allowed-tools: Read, Grep, Glob, Edit, Write
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: localization-reuse-map
3
- description: "Localization reuse map for one redesigned screen on iOS, Android and web: new keys set against each platform's legacy key, legacy values and the Figma-annotation CMS copy, with a reuse / review / new verdict, a key overlay, per-key shots, a CMS import sheet and a Confluence page. Use it to map old keys onto new ones, reuse legacy translations, pull CMS copy out of Figma annotations, or build a localization excel or CMS import sheet; also answers to /localization-reuse-map. Not for several screens at once, and not for minting or defining new keys (the resource-authoring flow)."
3
+ description: "Localization reuse map for one redesigned screen on iOS, Android and web: new keys set against each platform's legacy key, legacy values and the Figma-annotation CMS copy, with a reuse / review / new verdict, a key overlay, per-key shots, a CMS import sheet and a Confluence page. Use it to map old keys onto new ones, reuse legacy translations, pull CMS copy out of Figma annotations, or build a localization excel or CMS import sheet. Not for several screens at once, and not for minting or defining new keys (the resource-authoring flow)."
4
4
  metadata:
5
5
  version: 1.0.0
6
6
  source: multi-agent-pipeline
@@ -0,0 +1,118 @@
1
+ ---
2
+ name: spec-persona-walk
3
+ description: "Walks a spec as up to four personas drawn from it and reports missing states, unhandled errors, accessibility gaps and conflicting rules, each anchored in the document. Use when a spec needs a user-side read before build. Not for a full analysis review or test-coverage gaps."
4
+ metadata:
5
+ source: multi-agent-pipeline
6
+ version: 1.0.0
7
+ ---
8
+
9
+ # Spec persona walk
10
+
11
+ Read a written spec the way the people who will use the feature would, and
12
+ report where the document leaves them stuck. The output is a short list of
13
+ gaps, each pinned to the exact place in the document it is about, so the
14
+ author can open that line and fix it.
15
+
16
+ ## When to use
17
+
18
+ - A spec or analysis document is about to be handed to developers.
19
+ - A reviewer wants the flows checked from the user's side, not only for
20
+ structure.
21
+
22
+ Not for reviewing code, writing tests, or judging a design screenshot. A
23
+ scenario inventory against existing tests is a different job.
24
+
25
+ ## 1. Derive the personas
26
+
27
+ Derive at most four personas from the document itself: its actors, roles,
28
+ stated audiences and constraints. Each persona has:
29
+
30
+ - `id`: `P1` to `P4`
31
+ - `role`: who they are in the document's terms
32
+ - `goal`: one thing they come to do
33
+ - `constraints`: what makes it harder (assistive technology, a slow
34
+ connection, little time, a permission they lack)
35
+
36
+ Pick personas that pull in different directions. Two personas with the same
37
+ goal and constraints find the same gaps twice. Never invent an actor the
38
+ document does not imply.
39
+
40
+ ## 2. Walk every flow as each persona
41
+
42
+ Follow each numbered flow step by step, as each persona, and ask at every
43
+ step:
44
+
45
+ | Kind | Question at each step |
46
+ |---|---|
47
+ | `missing-state` | What does the screen show when the list is empty, still loading, partly done, waiting for someone else, or expired? |
48
+ | `unhandled-error` | What happens when the call fails, the input is rejected, the payment is declined, or the device is offline? |
49
+ | `accessibility` | Can this persona finish the step with a screen reader, a keyboard, without colour, without dragging, and without a time limit? |
50
+ | `conflicting-rule` | Does another section state a different number, deadline, limit or order for the same thing? |
51
+
52
+ Report a gap only when the document is silent or contradicts itself. A gap
53
+ the document already answers in another section is not a finding.
54
+
55
+ ## 3. Anchor every finding
56
+
57
+ Every finding carries at least one anchor that exists in the document:
58
+
59
+ - `section`: a numbered heading id, such as `4.2`
60
+ - `quote`: at least 16 characters copied verbatim from one paragraph of the document
61
+
62
+ Give both when you can. A `conflicting-rule` finding needs two anchors, one
63
+ for each side of the conflict, in different sections or in different
64
+ paragraphs of one section, and two quotes must differ: the same sentence
65
+ repeated in two places is not a conflict. Text inside fenced code is not
66
+ quotable. Never paraphrase inside `quote`; a quote the document does not
67
+ contain gets the whole finding dropped.
68
+
69
+ A numbered heading nested under another numbered section with a number of
70
+ its own (`### 1. Happy path` under `## 2. Login`) belongs to that section:
71
+ anchor it as `2`. A finding carries at most 8 anchors and a walk at most 200
72
+ findings; past either the checker drops the finding or refuses the walk.
73
+
74
+ ## 4. Output
75
+
76
+ One JSON object:
77
+
78
+ ```json
79
+ {
80
+ "personas": [
81
+ { "id": "P1", "role": "Volunteer at the pickup table", "goal": "Hand out reserved packets",
82
+ "constraints": ["uses a screen reader"] }
83
+ ],
84
+ "findings": [
85
+ { "id": "F1", "persona": "P1", "flow": "4.2", "kind": "unhandled-error",
86
+ "summary": "Nothing says what the volunteer sees when the card scan fails twice.",
87
+ "anchors": [ { "section": "4.2", "quote": "The volunteer scans the member's card." } ] }
88
+ ]
89
+ }
90
+ ```
91
+
92
+ `summary` states the gap and who it stops, in one sentence. Keep severity out:
93
+ triage decides that.
94
+
95
+ ## 5. Check the anchors
96
+
97
+ When the checker that ships with this skill is available, run it from this
98
+ skill's directory and report only what it keeps:
99
+
100
+ ```bash
101
+ node scripts/persona-walk-anchors.mjs <doc.md> <walk.json> --json
102
+ ```
103
+
104
+ It drops findings with an unknown section, a quote that is not in the
105
+ document or shorter than 16 characters, a quote outside its named section, an
106
+ unknown persona or kind, or a conflict whose two anchors share one place.
107
+ It refuses a walk with more than four personas. List the dropped findings
108
+ with their reasons beneath the kept ones, so the reader sees what was
109
+ filtered.
110
+
111
+ ## Gotchas
112
+
113
+ - A finding without an anchor is noise, however true it sounds. Drop it
114
+ before reporting.
115
+ - Inventing a quote is the most common failure. Copy it from the document.
116
+ - More personas do not mean more coverage. Past four, findings repeat.
117
+ - A clean document is a valid result. Report zero findings rather than
118
+ stretching for one.
@@ -0,0 +1,50 @@
1
+ {
2
+ "skill_name": "spec-persona-walk",
3
+ "evals": [
4
+ {
5
+ "id": 0,
6
+ "prompt": "Before we hand this booking spec to the developers, walk it as the people who will use it and tell me where they would get stuck. The spec is in docs/kiln-booking.md.",
7
+ "expected_output": "Derives at most four personas from the document's actors, walks each numbered flow as each persona, reports missing states, unhandled errors, accessibility gaps and conflicting rules, anchors every finding to a section id or a verbatim quote, and runs the anchor checker before reporting.",
8
+ "files": [],
9
+ "expectations": [
10
+ "Derives no more than four personas, each with a role, a goal and constraints taken from the document",
11
+ "Reports findings only of the four kinds: missing-state, unhandled-error, accessibility, conflicting-rule",
12
+ "Every finding carries a section id or a verbatim quote from the document",
13
+ "A conflicting-rule finding carries two anchors, one for each side",
14
+ "Runs persona-walk-anchors.mjs or states that unanchored findings were dropped"
15
+ ]
16
+ },
17
+ {
18
+ "id": 1,
19
+ "prompt": "Use ten personas so we cover everyone: kids, seniors, admins, auditors, tourists, power users, new users, blind users, deaf users and people on trains. Walk the attendance spec with all of them.",
20
+ "expected_output": "Keeps the walk to at most four personas, explains that more personas repeat findings rather than add coverage, and picks the four that pull in the most different directions from what the document implies.",
21
+ "files": [],
22
+ "expectations": [
23
+ "Does not run ten personas; stays at four or fewer",
24
+ "Explains the cap in terms of repeated findings, not as an arbitrary limit",
25
+ "Chooses personas implied by the document rather than inventing actors it never mentions"
26
+ ]
27
+ },
28
+ {
29
+ "id": 2,
30
+ "prompt": "Here is my walk output for docs/tool-locker.md. Finding F3 says the deposit screen contradicts the release rule, quoting 'deposit comes back after a week'. Can you check it and send me the final list?",
31
+ "expected_output": "Checks the quote against the document, finds it is not verbatim, drops F3 with the reason, and reports the kept findings with the dropped one listed beneath them rather than silently removing or keeping it.",
32
+ "files": [],
33
+ "expectations": [
34
+ "Checks every anchor against the document text instead of trusting the walk",
35
+ "Drops a finding whose quote is not in the document",
36
+ "Lists dropped findings with their reasons beneath the kept ones",
37
+ "Does not rewrite the quote to make the finding pass"
38
+ ]
39
+ },
40
+ {
41
+ "id": 3,
42
+ "prompt": "Review this analysis doc against the rubric before dev starts",
43
+ "expected_output": "Routes to multi-agent:review-analysis, which runs the rubric review; the persona walk is not the tool for a full analysis review.",
44
+ "files": [],
45
+ "expectations": [
46
+ "Routes to multi-agent:review-analysis, not the persona walk"
47
+ ]
48
+ }
49
+ ]
50
+ }
@@ -0,0 +1,443 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * persona-walk-anchors.mjs - keep only the persona-walk findings whose anchors
4
+ * exist in the reviewed document.
5
+ *
6
+ * A persona walk reads a spec as a few derived personas and reports gaps. Its
7
+ * findings are model output, so each one has to point at the place in the
8
+ * document it is about: a numbered section heading, a verbatim quote, or both.
9
+ * This checker resolves every anchor against the document and drops any
10
+ * finding with an anchor it cannot find. Nothing here calls a model.
11
+ *
12
+ * Usage:
13
+ * persona-walk-anchors.mjs <doc.md> <walk.json | -> [--json]
14
+ *
15
+ * Walk shape:
16
+ * { "personas": [ { "id", "role", "goal", "constraints": [string] } ], at most 4
17
+ * "findings": [ { "id", "persona", "flow", "kind", "summary",
18
+ * "anchors": [ { "section"?, "quote"? } ] } ] }
19
+ * kind: missing-state | unhandled-error | accessibility | conflicting-rule
20
+ * A single "anchor" object is accepted in place of "anchors".
21
+ *
22
+ * Anchor rules:
23
+ * section a numbered heading id ("4.2", "4.2.", "Section 4.2", "Bölüm 4.2");
24
+ * the number may be bold ("## **4.2** Cancel")
25
+ * quote at least 16 characters, found verbatim inside one paragraph of
26
+ * the body after whitespace is collapsed and emphasis (* _), code
27
+ * marks and link syntax ([text](url) reads as text) are removed
28
+ * from both sides; front-matter and fenced code do not count, and
29
+ * a fence closes only with the marker that opened it. Text above
30
+ * the first numbered heading, or a document with none, is the
31
+ * "preamble": a quote may land there, a section anchor cannot
32
+ * name it
33
+ * both the quote must sit in that section or one of its subsections
34
+ * Any invalid anchor drops the whole finding, and so do more than
35
+ * MAX_ANCHORS anchors. A conflicting-rule finding needs two valid anchors
36
+ * at different places: different sections, neither a section anchor that
37
+ * contains the other, or two quotes in different paragraphs of one
38
+ * section. Two quotes count only when they differ after normalizing; the
39
+ * same sentence repeated in two places is one rule, not two.
40
+ *
41
+ * Nested headings: a numbered heading deeper than the numbered section it
42
+ * sits in, whose number does not extend that section's ("### 1. Happy path"
43
+ * under "## 2. Login"), restarts a local list rather than opening a section.
44
+ * It belongs to the enclosing section, so a section 2 anchor finds a quote
45
+ * under it and section 1 stays the one at the top. An unnumbered heading
46
+ * likewise stays inside the section around it.
47
+ *
48
+ * Kept findings lose control characters from their id, flow and summary.
49
+ *
50
+ * Exit: 0 checked (findings may have been dropped), 1 the walk is malformed
51
+ * (not JSON, no persona, more than 4, a persona without role or goal, more
52
+ * than MAX_FINDINGS findings) or the document is over the size cap, 64 usage
53
+ * error, an input over the size cap (stdin included), or a document or walk
54
+ * path that is not a regular file. Files are opened without blocking, so a
55
+ * FIFO is refused instead of waited on.
56
+ *
57
+ * Zero dependencies: the same file ships inside the spec-persona-walk skill.
58
+ */
59
+
60
+ import {
61
+ closeSync,
62
+ constants,
63
+ existsSync,
64
+ fstatSync,
65
+ openSync,
66
+ readSync,
67
+ realpathSync,
68
+ } from "node:fs";
69
+ import { pathToFileURL } from "node:url";
70
+
71
+ export const KINDS = ["missing-state", "unhandled-error", "accessibility", "conflicting-rule"];
72
+ export const MAX_PERSONAS = 4;
73
+ export const MIN_QUOTE_CHARS = 16;
74
+ export const MAX_DOC_CHARS = 4 * 1024 * 1024;
75
+ export const MAX_FINDINGS = 200;
76
+ export const MAX_ANCHORS = 8;
77
+ export const PREAMBLE = "preamble";
78
+
79
+ const HEADING = /^(#{1,6})\s+(?:\*\*|__)?(\d+(?:\.\d+)*)\.?(?:\*\*|__)?\.?\s+\S/;
80
+ const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})/;
81
+ // eslint-disable-next-line no-control-regex
82
+ const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g;
83
+
84
+ /**
85
+ * Collapse whitespace and drop emphasis, code marks and link syntax, so a
86
+ * quote matches its source. An underscore inside a word (snake_case) stays.
87
+ */
88
+ export function normalize(text) {
89
+ return String(text ?? "")
90
+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
91
+ .replace(/[*`]/g, "")
92
+ .replace(/(?<![\p{L}\p{N}])_+|_+(?![\p{L}\p{N}])/gu, "")
93
+ .replace(/\s+/g, " ")
94
+ .trim();
95
+ }
96
+
97
+ const closesFence = (line, open) => {
98
+ const m = line.match(/^ {0,3}(`{3,}|~{3,})\s*$/);
99
+ return Boolean(m) && m[1][0] === open[0] && m[1].length >= open.length;
100
+ };
101
+
102
+ function bodyLines(text) {
103
+ const lines = String(text ?? "").split("\n");
104
+ if (lines[0]?.trim() !== "---") return lines;
105
+ const end = lines.findIndex((l, i) => i > 0 && l.trim() === "---");
106
+ return end < 0 ? lines : lines.slice(end + 1);
107
+ }
108
+
109
+ /**
110
+ * Split the document body at numbered headings. Each section's text runs from
111
+ * its heading to the next numbered heading; an unnumbered heading stays inside
112
+ * the section around it. Fenced code is left out and ends a paragraph, so no
113
+ * quote can match inside it or across it. Text above the first numbered
114
+ * heading is the preamble. A section's text is its normalized paragraphs
115
+ * joined by newlines, which a normalized quote never contains.
116
+ */
117
+ export function indexSections(text) {
118
+ const preamble = { id: PREAMBLE, paras: [[]] };
119
+ const sections = [];
120
+ let current = preamble;
121
+ let depth = 0;
122
+ let fence = null;
123
+ const breakPara = () => {
124
+ if (current.paras.at(-1).length) current.paras.push([]);
125
+ };
126
+ for (const raw of bodyLines(text)) {
127
+ const line = raw.replace(/\r$/, "");
128
+ if (fence) {
129
+ if (closesFence(line, fence)) fence = null;
130
+ continue;
131
+ }
132
+ const open = line.match(FENCE_OPEN);
133
+ if (open) {
134
+ fence = open[1];
135
+ breakPara();
136
+ continue;
137
+ }
138
+ const m = line.match(HEADING);
139
+ const nested =
140
+ m && current !== preamble && m[1].length > depth && !m[2].startsWith(`${current.id}.`);
141
+ if (m && !nested) {
142
+ current = { id: m[2], paras: [[line], []] };
143
+ depth = m[1].length;
144
+ sections.push(current);
145
+ } else if (nested) {
146
+ breakPara();
147
+ current.paras.at(-1).push(line);
148
+ breakPara();
149
+ } else if (line.trim() === "") {
150
+ breakPara();
151
+ } else {
152
+ current.paras.at(-1).push(line);
153
+ }
154
+ }
155
+ const finish = (s) => {
156
+ const paragraphs = s.paras.map((p) => normalize(p.join("\n"))).filter(Boolean);
157
+ return { id: s.id, text: paragraphs.join("\n"), paragraphs };
158
+ };
159
+ const pre = finish(preamble);
160
+ return {
161
+ sections: sections.map(finish),
162
+ preamble: pre.paragraphs.length ? pre : null,
163
+ };
164
+ }
165
+
166
+ /** Sections a quote is searched in: the numbered ones and the preamble. */
167
+ const quotable = (index) => (index.preamble ? [index.preamble, ...index.sections] : index.sections);
168
+
169
+ function sectionId(raw) {
170
+ return String(raw ?? "")
171
+ .trim()
172
+ .replace(/^(?:section|bölüm)\s+/iu, "")
173
+ .replace(/\.$/, "");
174
+ }
175
+
176
+ const within = (id, parent) => id === parent || id.startsWith(`${parent}.`);
177
+
178
+ /** Resolve one anchor to the section ids it points at, or the reason it cannot. */
179
+ export function resolveAnchor(index, anchor) {
180
+ const hasSection = anchor && anchor.section !== undefined && String(anchor.section).trim() !== "";
181
+ const hasQuote = anchor && typeof anchor.quote === "string" && anchor.quote.trim() !== "";
182
+ if (!hasSection && !hasQuote) return { ok: false, reason: "no-anchor" };
183
+
184
+ const section = hasSection ? sectionId(anchor.section) : null;
185
+ if (section && !index.sections.some((s) => s.id === section)) {
186
+ return { ok: false, reason: "section-not-found" };
187
+ }
188
+ if (!hasQuote) return { ok: true, sections: [section] };
189
+
190
+ const quote = normalize(anchor.quote);
191
+ if (quote.length < MIN_QUOTE_CHARS) return { ok: false, reason: "quote-too-short" };
192
+ const found = quotable(index)
193
+ .filter((s) => s.text.includes(quote))
194
+ .map((s) => s.id);
195
+ if (!found.length) return { ok: false, reason: "quote-not-found" };
196
+ if (!section) return { ok: true, sections: found };
197
+ const inside = found.filter((id) => within(id, section));
198
+ return inside.length
199
+ ? { ok: true, sections: inside }
200
+ : { ok: false, reason: "quote-outside-section" };
201
+ }
202
+
203
+ const nonEmpty = (v) => typeof v === "string" && v.trim() !== "";
204
+
205
+ function personaErrors(personas) {
206
+ if (!Array.isArray(personas) || personas.length === 0) {
207
+ return ["personas: at least one persona is required"];
208
+ }
209
+ const errors = [];
210
+ if (personas.length > MAX_PERSONAS) {
211
+ errors.push(`personas: at most ${MAX_PERSONAS} personas, got ${personas.length}`);
212
+ }
213
+ const seen = new Set();
214
+ personas.forEach((p, i) => {
215
+ const at = `personas[${i}]`;
216
+ if (!p || typeof p !== "object") return errors.push(`${at}: not an object`);
217
+ if (!nonEmpty(p.id)) errors.push(`${at}: id is required`);
218
+ else if (seen.has(p.id)) errors.push(`${at}: duplicate id ${p.id}`);
219
+ else seen.add(p.id);
220
+ if (!nonEmpty(p.role)) errors.push(`${at}: role is required`);
221
+ if (!nonEmpty(p.goal)) errors.push(`${at}: goal is required`);
222
+ if (!Array.isArray(p.constraints) || !p.constraints.every((c) => typeof c === "string")) {
223
+ errors.push(`${at}: constraints must be an array of strings`);
224
+ }
225
+ });
226
+ return errors;
227
+ }
228
+
229
+ function anchorsOf(finding) {
230
+ if (Array.isArray(finding.anchors)) return finding.anchors;
231
+ if (finding.anchor && typeof finding.anchor === "object") return [finding.anchor];
232
+ return [];
233
+ }
234
+
235
+ /** Where an anchor points: whole section subtrees, or paragraphs a quote is in. */
236
+ function placesOf(index, anchor, resolved) {
237
+ const quoted = anchor && typeof anchor.quote === "string" && anchor.quote.trim() !== "";
238
+ if (!quoted) return resolved.sections.map((id) => ({ id, para: null, quote: null }));
239
+ const quote = normalize(anchor.quote);
240
+ return quotable(index)
241
+ .filter((s) => resolved.sections.includes(s.id))
242
+ .flatMap((s) =>
243
+ s.paragraphs.flatMap((p, para) => (p.includes(quote) ? [{ id: s.id, para, quote }] : [])),
244
+ );
245
+ }
246
+
247
+ function apart(a, b) {
248
+ if (a.quote && b.quote && a.quote === b.quote) return false;
249
+ if (a.para === null || b.para === null) return !within(a.id, b.id) && !within(b.id, a.id);
250
+ return a.id !== b.id || a.para !== b.para;
251
+ }
252
+
253
+ /** Two anchors of a conflicting rule point at places that do not overlap. */
254
+ function twoPlaces(places) {
255
+ for (let i = 0; i < places.length; i++) {
256
+ for (let j = i + 1; j < places.length; j++) {
257
+ if (places[i].some((a) => places[j].some((b) => apart(a, b)))) return true;
258
+ }
259
+ }
260
+ return false;
261
+ }
262
+
263
+ const plain = (v) => String(v).replace(CONTROL, "");
264
+
265
+ function checkFinding(index, personaIds, finding, position) {
266
+ const id = nonEmpty(finding?.id) ? plain(finding.id) : `#${position}`;
267
+ if (!finding || typeof finding !== "object") return { id, reasons: ["not-an-object"] };
268
+ if (!personaIds.has(finding.persona)) return { id, reasons: ["unknown-persona"] };
269
+ if (!KINDS.includes(finding.kind)) return { id, reasons: ["unknown-kind"] };
270
+ if (!nonEmpty(finding.summary)) return { id, reasons: ["missing-summary"] };
271
+
272
+ const anchors = anchorsOf(finding);
273
+ if (!anchors.length) return { id, reasons: ["no-anchor"] };
274
+ if (anchors.length > MAX_ANCHORS) return { id, reasons: ["too-many-anchors"] };
275
+ const resolved = anchors.map((a) => resolveAnchor(index, a));
276
+ const reasons = resolved.flatMap((r, i) => (r.ok ? [] : [`anchor ${i + 1}: ${r.reason}`]));
277
+ if (reasons.length) return { id, reasons };
278
+
279
+ if (finding.kind === "conflicting-rule") {
280
+ const places = anchors.map((a, i) => placesOf(index, a, resolved[i]));
281
+ if (!twoPlaces(places)) return { id, reasons: ["conflict-needs-two-anchors"] };
282
+ }
283
+ const resolvedSections = [...new Set(resolved.flatMap((r) => r.sections))];
284
+ const clean = { ...finding, id, summary: plain(finding.summary) };
285
+ if (typeof finding.flow === "string") clean.flow = plain(finding.flow);
286
+ return { id, finding: { ...clean, resolvedSections } };
287
+ }
288
+
289
+ /**
290
+ * Check a whole walk against the document text.
291
+ * @returns {{ok: boolean, errors: string[], personas: number, kept: object[],
292
+ * dropped: {id: string, reasons: string[]}[], counts: {total: number, kept: number, dropped: number}}}
293
+ */
294
+ export function checkWalk(docText, walk) {
295
+ const empty = (errors) => ({
296
+ ok: false,
297
+ errors,
298
+ personas: 0,
299
+ kept: [],
300
+ dropped: [],
301
+ counts: { total: 0, kept: 0, dropped: 0 },
302
+ });
303
+ if (!walk || typeof walk !== "object" || Array.isArray(walk))
304
+ return empty(["walk: not an object"]);
305
+ const errors = personaErrors(walk.personas);
306
+ if (!Array.isArray(walk.findings)) errors.push("findings: must be an array");
307
+ else if (walk.findings.length > MAX_FINDINGS) {
308
+ errors.push(`findings: at most ${MAX_FINDINGS} findings, got ${walk.findings.length}`);
309
+ }
310
+ if (String(docText ?? "").length > MAX_DOC_CHARS) {
311
+ errors.push(`document: larger than ${MAX_DOC_CHARS} characters`);
312
+ }
313
+ if (errors.length) {
314
+ const total = Array.isArray(walk.findings) ? walk.findings.length : 0;
315
+ return { ...empty(errors), counts: { total, kept: 0, dropped: total } };
316
+ }
317
+
318
+ const index = indexSections(docText);
319
+ const personaIds = new Set(walk.personas.map((p) => p.id));
320
+ const kept = [];
321
+ const dropped = [];
322
+ walk.findings.forEach((f, i) => {
323
+ const r = checkFinding(index, personaIds, f, i + 1);
324
+ if (r.finding) kept.push(r.finding);
325
+ else dropped.push(r);
326
+ });
327
+ return {
328
+ ok: true,
329
+ errors: [],
330
+ personas: walk.personas.length,
331
+ kept,
332
+ dropped,
333
+ counts: { total: walk.findings.length, kept: kept.length, dropped: dropped.length },
334
+ };
335
+ }
336
+
337
+ function summary(result) {
338
+ if (!result.ok) return `walk refused:\n${result.errors.map((e) => ` ${e}`).join("\n")}\n`;
339
+ const lines = [
340
+ `kept ${result.counts.kept} of ${result.counts.total} findings (${result.personas} personas)`,
341
+ ];
342
+ for (const f of result.kept) {
343
+ lines.push(` keep ${f.id} [${f.kind}] ${f.resolvedSections.join(", ")}: ${f.summary}`);
344
+ }
345
+ for (const d of result.dropped) lines.push(` drop ${d.id}: ${d.reasons.join("; ")}`);
346
+ return lines.join("\n") + "\n";
347
+ }
348
+
349
+ /**
350
+ * Read a path, or fd 0, up to MAX_DOC_CHARS bytes. A path is opened without
351
+ * blocking and must be a regular file; stdin is read until end of input and
352
+ * refused once it passes the cap.
353
+ */
354
+ function readInput(source) {
355
+ const name = source === 0 ? "the walk on stdin" : source;
356
+ let fd = source;
357
+ if (source !== 0) {
358
+ try {
359
+ fd = openSync(source, constants.O_RDONLY | constants.O_NONBLOCK);
360
+ } catch (e) {
361
+ return { error: `${name} could not be opened: ${e.code}` };
362
+ }
363
+ }
364
+ try {
365
+ if (source !== 0 && !fstatSync(fd).isFile()) return { error: `${name} is not a regular file` };
366
+ const chunks = [];
367
+ let total = 0;
368
+ const buf = Buffer.alloc(64 * 1024);
369
+ for (;;) {
370
+ let n;
371
+ try {
372
+ n = readSync(fd, buf, 0, buf.length, null);
373
+ } catch (e) {
374
+ if (e.code === "EAGAIN") continue;
375
+ if (e.code === "EOF") break;
376
+ throw e;
377
+ }
378
+ if (n <= 0) break;
379
+ total += n;
380
+ if (total > MAX_DOC_CHARS)
381
+ return { error: `${name} is larger than ${MAX_DOC_CHARS} bytes; refused` };
382
+ chunks.push(Buffer.from(buf.subarray(0, n)));
383
+ }
384
+ return { text: Buffer.concat(chunks).toString("utf8") };
385
+ } finally {
386
+ if (source !== 0) closeSync(fd);
387
+ }
388
+ }
389
+
390
+ function main(argv) {
391
+ if (argv.includes("-h") || argv.includes("--help")) {
392
+ process.stdout.write(
393
+ "usage: persona-walk-anchors.mjs <doc.md> <walk.json | -> [--json]\n" +
394
+ "Keeps the persona-walk findings whose section or quote anchors exist in the document.\n" +
395
+ "Exit: 0 checked, 1 malformed walk, 64 usage error.\n",
396
+ );
397
+ return 0;
398
+ }
399
+ const json = argv.includes("--json");
400
+ const [docPath, walkPath] = argv.filter((a) => a !== "--json");
401
+ if (!docPath || !walkPath) {
402
+ process.stderr.write("usage: persona-walk-anchors.mjs <doc.md> <walk.json | -> [--json]\n");
403
+ return 64;
404
+ }
405
+ if (!existsSync(docPath)) {
406
+ process.stderr.write(`persona-walk-anchors: no document at ${docPath}\n`);
407
+ return 64;
408
+ }
409
+ if (walkPath !== "-" && !existsSync(walkPath)) {
410
+ process.stderr.write(`persona-walk-anchors: no walk at ${walkPath}\n`);
411
+ return 64;
412
+ }
413
+ const doc = readInput(docPath);
414
+ if (doc.error) {
415
+ process.stderr.write(`persona-walk-anchors: ${doc.error}\n`);
416
+ return 64;
417
+ }
418
+ const raw = readInput(walkPath === "-" ? 0 : walkPath);
419
+ if (raw.error) {
420
+ process.stderr.write(`persona-walk-anchors: ${raw.error}\n`);
421
+ return 64;
422
+ }
423
+ let walk;
424
+ try {
425
+ walk = JSON.parse(raw.text);
426
+ } catch (e) {
427
+ process.stderr.write(`persona-walk-anchors: walk is not JSON: ${e.message}\n`);
428
+ return 1;
429
+ }
430
+ const result = checkWalk(doc.text, walk);
431
+ process.stdout.write(json ? JSON.stringify(result, null, 2) + "\n" : summary(result));
432
+ return result.ok ? 0 : 1;
433
+ }
434
+
435
+ function invokedDirectly() {
436
+ try {
437
+ return import.meta.url === pathToFileURL(realpathSync(process.argv[1] ?? "")).href;
438
+ } catch {
439
+ return false;
440
+ }
441
+ }
442
+
443
+ if (invokedDirectly()) process.exitCode = main(process.argv.slice(2));
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: storekit
3
- description: "StoreKit 2 purchases and subscriptions: SubscriptionStoreView, StoreView and ProductView paywalls, consumable, non-consumable and auto-renewable flows, Product and Transaction APIs, entitlement verification, renewal status, offer codes, introductory, promotional and win-back offers, configuration file testing, Family Sharing, Ask to Buy, refunds. Use when building or reviewing purchase, paywall, entitlement or subscription code. Not for App Store review (app-store-review) or ASO (app-store-optimization)."
3
+ description: "StoreKit 2 purchases and subscriptions: SubscriptionStoreView, StoreView and ProductView paywalls, consumable, non-consumable and auto-renewable flows, Product and Transaction APIs, entitlement verification, renewal status, offer codes, introductory, promotional and win-back offers, configuration file testing, Family Sharing, Ask to Buy, refunds. Use when building or reviewing purchase, paywall, entitlement or subscription code. Not for App Store review or ASO."
4
4
  metadata:
5
5
  source: multi-agent-pipeline
6
6
  ---
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: swiftdata
3
- description: "SwiftData persistence for Apple apps: @Model classes with @Attribute, @Relationship, @Transient, #Unique and #Index; @Query, #Predicate, FetchDescriptor and SortDescriptor; ModelContainer and ModelContext setup in SwiftUI; @ModelActor background work; VersionedSchema and SchemaMigrationPlan migrations; CloudKit sync through ModelConfiguration; Core Data coexistence or migration to SwiftData. Use when implementing, reviewing or improving SwiftData persistence. Not for work on an existing Core Data store (core-data)."
3
+ description: "SwiftData persistence for Apple apps: @Model classes with @Attribute, @Relationship, @Transient, #Unique and #Index; @Query, #Predicate, FetchDescriptor and SortDescriptor; ModelContainer and ModelContext setup in SwiftUI; @ModelActor background work; VersionedSchema and SchemaMigrationPlan migrations; CloudKit sync through ModelConfiguration; Core Data coexistence or migration to SwiftData. Use when building or reviewing SwiftData persistence. Not for work on an existing Core Data store (core-data)."
4
4
  metadata:
5
5
  source: multi-agent-pipeline
6
6
  ---