@shiftleftpt/sbd-toe-mcp 0.20.0 → 0.21.1

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 (53) hide show
  1. package/README.md +2 -2
  2. package/dist/index.js +107 -266
  3. package/dist/index.js.map +1 -1
  4. package/dist/resources/sbd-toe-resources.js +1 -1
  5. package/dist/resources/sbd-toe-resources.js.map +1 -1
  6. package/dist/serving/adjacency.d.ts +68 -0
  7. package/dist/serving/adjacency.js +127 -0
  8. package/dist/serving/adjacency.js.map +1 -0
  9. package/dist/serving/affordances.js +4 -5
  10. package/dist/serving/affordances.js.map +1 -1
  11. package/dist/serving/agent-guide.js +5 -3
  12. package/dist/serving/agent-guide.js.map +1 -1
  13. package/dist/serving/behaviour-notes.d.ts +2 -2
  14. package/dist/serving/behaviour-notes.js +2 -8
  15. package/dist/serving/behaviour-notes.js.map +1 -1
  16. package/dist/serving/notes.d.ts +42 -0
  17. package/dist/serving/notes.js +44 -0
  18. package/dist/serving/notes.js.map +1 -0
  19. package/dist/serving/payload-ceilings.d.ts +73 -11
  20. package/dist/serving/payload-ceilings.js +85 -24
  21. package/dist/serving/payload-ceilings.js.map +1 -1
  22. package/dist/serving/response-shaping.d.ts +10 -0
  23. package/dist/serving/response-shaping.js +26 -0
  24. package/dist/serving/response-shaping.js.map +1 -1
  25. package/dist/serving/server-surface.d.ts +10 -0
  26. package/dist/serving/server-surface.js +14 -2
  27. package/dist/serving/server-surface.js.map +1 -1
  28. package/dist/serving/surface-history.d.ts +118 -0
  29. package/dist/serving/surface-history.js +119 -0
  30. package/dist/serving/surface-history.js.map +1 -0
  31. package/dist/tools/assess-implementation.d.ts +9 -0
  32. package/dist/tools/assess-implementation.js +7 -1
  33. package/dist/tools/assess-implementation.js.map +1 -1
  34. package/dist/tools/get-guide-by-role.d.ts +40 -0
  35. package/dist/tools/get-guide-by-role.js +158 -4
  36. package/dist/tools/get-guide-by-role.js.map +1 -1
  37. package/dist/tools/get-macro-processes.js +18 -8
  38. package/dist/tools/get-macro-processes.js.map +1 -1
  39. package/dist/tools/get-threat-landscape.js +11 -5
  40. package/dist/tools/get-threat-landscape.js.map +1 -1
  41. package/dist/tools/ontology-loader.d.ts +7 -0
  42. package/dist/tools/ontology-loader.js +2 -0
  43. package/dist/tools/ontology-loader.js.map +1 -1
  44. package/dist/tools/prepare-codegen-context.d.ts +373 -276
  45. package/dist/tools/prepare-codegen-context.js +523 -532
  46. package/dist/tools/prepare-codegen-context.js.map +1 -1
  47. package/dist/tools/resolve-entities.js +8 -4
  48. package/dist/tools/resolve-entities.js.map +1 -1
  49. package/dist/tools/select-requirements.d.ts +2 -1
  50. package/dist/tools/select-requirements.js +23 -8
  51. package/dist/tools/select-requirements.js.map +1 -1
  52. package/package.json +1 -1
  53. package/prompts/sbd-toe-grounded-codegen.md +11 -11
@@ -13,7 +13,7 @@
13
13
  * 3. Resolution: pull deterministic data from the three published sources
14
14
  * (runtime v0, runtime v1, overlay).
15
15
  * 4. Output: produce `activated_scope`, `g2_context`, `manual_grounding`,
16
- * `regulatory_overlay`, `citation_map`, `completeness_report`,
16
+ * `regulatory_overlay`, `citations` (0.21 §3: invertido em todos os níveis), `completeness_report`,
17
17
  * `llm_codegen_instructions` and `security_rationale_template`.
18
18
  *
19
19
  * Strict rules:
@@ -33,39 +33,13 @@ import { servedKgReleaseTag, servingServerVersion } from "../version-info.js";
33
33
  import { expandQueryWithAliases } from "../backend/semantic-index-gateway.js";
34
34
  import { requirementCategoryOf } from "../serving/requirement-id.js";
35
35
  import { prepareCodegenAffordances } from "../serving/affordances.js";
36
+ import { estimateSize } from "../serving/response-shaping.js";
37
+ import { PAYLOAD_PROMISE_TK as LEVEL_ENVELOPE_TK } from "../serving/payload-ceilings.js";
38
+ import { buildDeclaredAdjacency, declaredAdjacencyDetail } from "../serving/adjacency.js";
39
+ import { NOTES, NOTES_HEADER } from "../serving/notes.js";
40
+ import { buildActivationVocabulary } from "../serving/activation-vocabulary.js";
36
41
  import { runSelectionWithActivation, normalizeDeclaredTechnologies, stackTokensFromVocabulary } from "../serving/selection.js";
37
42
  import { REQUIREMENT_CEILING_BY_DETAIL, COST_PER_REQ_TK, BASE_TK, PAYLOAD_PROMISE_TK, projectedCostTk } from "../serving/payload-ceilings.js";
38
- const EVIDENCE_PATTERN_CAP = 25;
39
- /**
40
- * v2 token diet, s3 — evidence-pattern cap applied at `detail: "standard" |
41
- * "minimal"` ON TOP of the classic cap: the dieted list is the deterministic
42
- * PREFIX (relevance_score desc, id asc — the exact order the core already
43
- * emits) of the classic top-{@link EVIDENCE_PATTERN_CAP} list. Never silent:
44
- * `completeness_report` reports total/returned/capped and, when anything was
45
- * cut, `evidence_patterns_rest` says how to retrieve the rest (same tool,
46
- * `detail: "full"`).
47
- */
48
- const STANDARD_EVIDENCE_PATTERN_CAP = 10;
49
- /**
50
- * v2 token diet, s3b (revised per the 2026-07-05 operator ADENDA in
51
- * agentic/planeado/v2-token-diet/EPIC.md — no top-N, no subsetting of the
52
- * activated set): at `detail: "minimal"` the evidence cap tightens 10→5 with
53
- * the SAME s3 mechanism (deterministic prefix, never-silent counts +
54
- * executable rest-reference). This cap — together with the minimal
55
- * `manual_grounding` form — is the ONLY divergence from `standard`; the
56
- * activated scope (requirements/controls/slices/entities, with the verbatim
57
- * published descriptions) stays COMPLETE and byte-identical to `standard`.
58
- */
59
- const MINIMAL_EVIDENCE_PATTERN_CAP = 5;
60
- /**
61
- * v2 token diet, s3c (operator ADENDA 2026-07-05, reactivated same day): at
62
- * `detail: "ultrathin"` NO evidence pattern goes inline (cap 0) — the SAME s3
63
- * never-silent mechanism still applies in full: `completeness_report` reports
64
- * total/returned(=0)/capped(=total) and `evidence_patterns_rest` is the
65
- * executable reference to the CHEAPEST level that returns them inline
66
- * (detail="minimal" ⇒ top-5; "standard" ⇒ 10; "full" ⇒ classic 25).
67
- */
68
- const ULTRATHIN_EVIDENCE_PATTERN_CAP = 0;
69
43
  /**
70
44
  * Section → source map for the dieted encoding: each list is
71
45
  * source-homogeneous BY CONSTRUCTION (the projection types hardcode a single
@@ -85,7 +59,6 @@ const PROVENANCE_SOURCES = {
85
59
  "g2_context.practices": "runtime_v1",
86
60
  "g2_context.artifacts": "runtime_v1",
87
61
  "g2_context.relations": "runtime_v1",
88
- "g2_context.evidence_patterns": "runtime_v0",
89
62
  "manual_grounding.groups": "runtime_v1",
90
63
  "regulatory_overlay.frameworks": "overlay",
91
64
  "regulatory_overlay.obligations": "overlay",
@@ -93,51 +66,21 @@ const PROVENANCE_SOURCES = {
93
66
  "regulatory_overlay.playbooks": "overlay"
94
67
  };
95
68
  /**
96
- * Inline legend for `standard`/`minimal` (s3: slim pointer — the full legend,
97
- * including the section→source table and every derivation rule of the dieted
98
- * encoding, lives in the `sbd://toe/codegen-instructions/{mode}` resource,
99
- * section `detail_encoding`).
100
- */
101
- const PROVENANCE_LEGEND = {
102
- note: "Deduplicated encoding (detail=standard/minimal): per-item `source` fields " +
103
- "are elided (every list is source-homogeneous), requirement `category` = " +
104
- "requirement_id category segment (the one before the number: AUT-003→AUT, " +
105
- "REQ-AGN-001→AGN), g2_context entity lists are grouped as " +
106
- "{slice_id: {entity_id: name|null}}, and citations ids are referenced via " +
107
- "ids_from payload paths. Full legend: read_sbd_toe_resource(" +
108
- "sbd://toe/codegen-instructions/{mode}), section detail_encoding."
109
- };
110
- /**
111
- * Inline legend for `ultrathin` (s3c) — the standard/minimal legend text is
112
- * frozen within a bundle pin (snapshots are byte-frozen; the only edit so far is
113
- * the v1.10 category-segment wording, beta.3, bundle re-pin); ultrathin carries
114
- * its own note with the extra cut rules. Full legend: same MCP resource, section
115
- * `detail_encoding` (incl. the `ultrathin` entry).
69
+ * Inline legend for `lista`/`standard` (0.21): slim pointer — the full legend
70
+ * (section→source table + every derivation rule of the dieted encoding) lives
71
+ * in the `sbd://toe/codegen-instructions/{mode}` resource, `detail_encoding`.
116
72
  */
117
- const PROVENANCE_LEGEND_ULTRATHIN = {
118
- note: "Deduplicated encoding (detail=ultrathin): same rules as detail=standard/" +
119
- "minimal — per-item `source` elided, requirement `category` = " +
120
- "requirement_id category segment (before the number), g2_context entity lists grouped as " +
121
- "{slice_id: {entity_id: name|null}}, citations ids via ids_from payload " +
122
- "paths — PLUS: published `description` fields elided (executable " +
123
- "activated_scope.descriptions_ref, detail='minimal'), evidence_patterns 0 " +
124
- "inline (counts + rest-ref in completeness_report), manual_grounding " +
125
- "aggregate-only (total + sha + groups_ref) and completeness diagnostics " +
126
- "as exact counts (+ ref). Nothing silently dropped. Full legend: MCP " +
127
- "read_sbd_toe_resource(sbd://toe/codegen-instructions/{mode}), detail_encoding."
128
- };
73
+ const PROVENANCE_LEGEND = { note_id: "prepare.provenance_legend" }; // 0.21 §6-c: texto em sbd://toe/notes
129
74
  /**
130
- * v2 token diet, s4 — cheap turns, not fewer turns: short note (≈50 tokens)
131
- * appended to every `standard`/`minimal` ready payload. The production
132
- * write-test-edit loop is legitimate; what must not repeat is the cost of
133
- * re-requesting THIS payload — an identical call returns a byte-identical
134
- * result (deterministic, tested), so the context already in the session is
135
- * the source for the loop. Follow-ups that genuinely need more go through
136
- * `detail: "minimal"` or a targeted `consult_security_requirements` call —
137
- * never a repeat of the full payload. `full` carries NO hint (byte-identical
138
- * to the classic payload, EPIC invariant 1).
75
+ * v2 token diet, s4 — cheap turns, not fewer turns: short note appended to
76
+ * every `lista`/`standard` ready payload. An identical call returns a
77
+ * byte-identical result (deterministic, tested), so the context already in the
78
+ * session is the source for the write-test-edit loop. Follow-ups that need the
79
+ * inline grounding/relations/trace go through `detail: "full"` (declared
80
+ * price in size_estimate) or a targeted `consult_security_requirements` call.
139
81
  */
140
- export const REPEAT_CALL_HINT = "Identical input returns this exact payload (deterministic) — reuse the context already received; deepen via detail:'minimal' or a targeted consult_security_requirements.";
82
+ export const REPEAT_CALL_HINT = NOTES["prepare.repeat_call_hint"]; // 0.21 §6-c: servido por referência (note_id)
83
+ const REPEAT_CALL_HINT_ID = "prepare.repeat_call_hint";
141
84
  // ---------------------------------------------------------------------------
142
85
  // Activation lexicon (small, auditable; WP6 layers semantic scoring on top)
143
86
  // ---------------------------------------------------------------------------
@@ -1104,6 +1047,62 @@ function estimateV0RequirementCount(riskLevel, concerns) {
1104
1047
  }
1105
1048
  return filtered.length;
1106
1049
  }
1050
+ /**
1051
+ * 0.21.1 — serve só os mapeamentos cujo alvo está no âmbito activado; o resto conta-se e referencia-se.
1052
+ * Puro e determinístico: a ordem servida é a ordem publicada.
1053
+ */
1054
+ function scopeOverlayMappings(context, scope) {
1055
+ if (scope.obligationIds.length === 0 || context.mappings.length === 0)
1056
+ return context;
1057
+ const inScope = (m) => {
1058
+ switch (m.target_type) {
1059
+ case "Requirement": return scope.requirementIds.has(m.target_id);
1060
+ case "Control": return scope.controlIds.has(m.target_id);
1061
+ case "EvidencePattern": return scope.evidencePatternToRequirement.has(m.target_id);
1062
+ case "KnowledgeBundle": return scope.bundleIds.has(m.target_id);
1063
+ default: return false; // Practice (manual practices chapter:slug) and any future type: counted + ref
1064
+ }
1065
+ };
1066
+ const requirementPairs = new Set(context.mappings.filter((m) => m.target_type === "Requirement" && inScope(m)).map((m) => `${m.obligation_id}|${m.target_id}`));
1067
+ const served = [];
1068
+ const byType = {};
1069
+ let elided = 0;
1070
+ for (const m of context.mappings) {
1071
+ const bucket = (byType[m.target_type] ??= { total: 0, served: 0, derivable_elided: 0, out_of_scope: 0 });
1072
+ bucket.total += 1;
1073
+ if (!inScope(m)) {
1074
+ bucket.out_of_scope += 1;
1075
+ continue;
1076
+ }
1077
+ if (m.target_type === "EvidencePattern") {
1078
+ const req = scope.evidencePatternToRequirement.get(m.target_id);
1079
+ if (req !== undefined && requirementPairs.has(`${m.obligation_id}|${req}`)) {
1080
+ bucket.derivable_elided += 1;
1081
+ elided += 1;
1082
+ continue;
1083
+ }
1084
+ }
1085
+ bucket.served += 1;
1086
+ served.push(m);
1087
+ }
1088
+ const total = context.mappings.length;
1089
+ return {
1090
+ ...context,
1091
+ mappings: served,
1092
+ mappings_scope: {
1093
+ total,
1094
+ served: served.length,
1095
+ derivable_elided: elided,
1096
+ out_of_scope: total - served.length - elided,
1097
+ by_target_type: byType,
1098
+ rest_ref: {
1099
+ tool: "resolve_entities",
1100
+ with: `record_type="regulatory_mapping", filters={"obligation_id":{"in":${JSON.stringify(scope.obligationIds)}}}`,
1101
+ note_id: "prepare.overlay.mappings_scope"
1102
+ }
1103
+ }
1104
+ };
1105
+ }
1107
1106
  function resolveOverlay(input) {
1108
1107
  const wantsOverlay = input.include_regulatory_overlay || input.regulatory_frameworks.length > 0;
1109
1108
  const emptyContext = {
@@ -1263,11 +1262,11 @@ export function instructionSlotsForMode(mode) {
1263
1262
  const slots = [
1264
1263
  {
1265
1264
  when: "always",
1266
- text: "Generate code or review changes ONLY against the deterministic IDs provided in `citation_map`. Do NOT invent SbD-ToE requirement, control, slice, mechanism or obligation IDs."
1265
+ text: "Generate code or review changes ONLY against the deterministic IDs provided in `citations` (the closed world of legal ids for this task). Do NOT invent SbD-ToE requirement, control, slice, mechanism or obligation IDs."
1267
1266
  },
1268
1267
  {
1269
1268
  when: "always",
1270
- text: "For each non-trivial design decision, populate the `security_rationale_template.decisions[].cited_ids` with IDs from `citation_map`. If no ID applies, say so explicitly."
1269
+ text: "For each non-trivial design decision, populate the `security_rationale_template.decisions[].cited_ids` with IDs from `citations`. If no ID applies, say so explicitly."
1271
1270
  },
1272
1271
  {
1273
1272
  when: "always",
@@ -1289,13 +1288,13 @@ export function instructionSlotsForMode(mode) {
1289
1288
  if (mode === "review") {
1290
1289
  slots.push({
1291
1290
  when: "always",
1292
- text: "Review mode: enumerate findings per changed_file, mapped to the activated_scope. Each finding must reference at least one citation_map ID or say 'no normative ID covers this'."
1291
+ text: "Review mode: enumerate findings per changed_file, mapped to the activated_scope. Each finding must reference at least one id from `citations` or say 'no normative ID covers this'."
1293
1292
  });
1294
1293
  }
1295
1294
  if (mode === "test-plan") {
1296
1295
  slots.push({
1297
1296
  when: "always",
1298
- text: "Test-plan mode: produce a checklist of tests grouped by validated_id, with input/expectation, and reference evidence_patterns when available."
1297
+ text: "Test-plan mode: produce a checklist of tests grouped by validated_id, with input/expectation. Each activated requirement carries its own `verify` (validation method) and `evidence` (expected proof) inline — use them verbatim as the test's expectation; for evidence_pattern_id/control_id/expected_artifact_type_ids follow completeness_report.verification.by_ref."
1299
1298
  });
1300
1299
  }
1301
1300
  for (const level of ["L1", "L2", "L3"]) {
@@ -1305,8 +1304,8 @@ export function instructionSlotsForMode(mode) {
1305
1304
  });
1306
1305
  }
1307
1306
  slots.push({
1308
- when: "citation_map_empty",
1309
- text: "Citation_map is empty. This is a strong signal the activated scope did not yield deterministic anchors — request clarification before generating code."
1307
+ when: "citations_empty",
1308
+ text: "`citations` is empty. This is a strong signal the activated scope did not yield deterministic anchors — request clarification before generating code."
1310
1309
  });
1311
1310
  return slots;
1312
1311
  }
@@ -1318,7 +1317,7 @@ function activeInstructionConditions(args) {
1318
1317
  if (args.riskLevel)
1319
1318
  active.push(`risk_level:${args.riskLevel}`);
1320
1319
  if (args.citationMapEmpty)
1321
- active.push("citation_map_empty");
1320
+ active.push("citations_empty");
1322
1321
  return active;
1323
1322
  }
1324
1323
  function buildLlmInstructions(args) {
@@ -1336,7 +1335,7 @@ const SECURITY_RATIONALE_TEMPLATE_SKELETON = {
1336
1335
  decisions: [
1337
1336
  {
1338
1337
  decision: "<fill: what design choice was made>",
1339
- rationale: "<fill: why, citing IDs from citation_map>",
1338
+ rationale: "<fill: why, citing IDs from citations>",
1340
1339
  cited_ids: ["<requirement_id|control_id|slice_id|obligation_id>"]
1341
1340
  }
1342
1341
  ],
@@ -1372,16 +1371,28 @@ export function codegenInstructionsResourceUri(mode) {
1372
1371
  return `${CODEGEN_INSTRUCTIONS_RESOURCE_URI_PREFIX}${mode}`;
1373
1372
  }
1374
1373
  /**
1375
- * Full legend of the dieted (`standard`/`minimal`) encoding, published in the
1374
+ * Full legend of the dieted (`lista`/`standard`) encoding, published in the
1376
1375
  * codegen-instructions resource. Every rule here is a lossless, deterministic
1377
1376
  * derivation over the SAME payload (or an executable reference) — nothing is
1378
1377
  * silently dropped (EPIC invariant 2) and no data changes, only serialization
1379
- * (EPIC invariant 4).
1378
+ * (EPIC invariant 4). 0.21 §1: the requirement is fused (description never
1379
+ * leaves) and the evidence_patterns block is gone at every level.
1380
1380
  */
1381
1381
  const DETAIL_ENCODING_LEGEND = {
1382
- note: "How to read a detail=standard/minimal payload of prepare_sbd_toe_codegen_context. " +
1382
+ note: "How to read a detail=lista/standard payload of prepare_sbd_toe_codegen_context (0.21). " +
1383
1383
  "Every rule below is a deterministic re-encoding of the same published data: " +
1384
- "nothing is silently dropped, and detail=full always returns the classic inline payload.",
1384
+ "nothing is silently dropped. detail=full inlines everything (grounding, relations, trace) " +
1385
+ "and declares its price in size_estimate; the fused requirement is identical at every level.",
1386
+ levels: "lista — every activated requirement complete and verbatim (id, name, type, description, verify, " +
1387
+ "evidence) + citable ids + the instructions that forbid inventing ids; manual grounding by " +
1388
+ "reference (manual_grounding.entries_ref → detail='full'); relations OUT (g2_context.relations_summary " +
1389
+ "keeps the exact accounting; include_relations=true restores them); adjacency SUMMARY inline (top-N + " +
1390
+ "denominators), detail by reference. standard — what lista promises plus the adjacency DETAIL inline " +
1391
+ "(every undeclared signal that would change the set). full — what standard promises plus manual_grounding verbatim inline, " +
1392
+ "g2_context.relations_ref (executable trace calls; include_relations=true inlines them) and " +
1393
+ "activation_trace inline; no requirement ceiling. " +
1394
+ "'ultrathin' was retired in 0.21 (its documented purpose was to cut the description, which " +
1395
+ "is no longer negotiable); 'minimal' became 'lista' (same 8,450 tk envelope).",
1385
1396
  sources: {
1386
1397
  note: "Per-item `source` fields are elided. Every list below is source-homogeneous " +
1387
1398
  "(no exceptions): apply the listed source to each of its items. " +
@@ -1390,69 +1401,63 @@ const DETAIL_ENCODING_LEGEND = {
1390
1401
  "reference to trace_sbd_toe_graph calls, not a source list.",
1391
1402
  map: PROVENANCE_SOURCES
1392
1403
  },
1393
- citations: "citations.<source>.source_data is an ordered run-length map file -> count. " +
1404
+ citations: "0.21 §3: `citations` is the closed world of legal ids at EVERY level (citation_map is gone). " +
1405
+ "citations.<source>.source_data is an ordered run-length map file -> count. " +
1394
1406
  "The citable ids are NOT repeated: citations.<source>.ids_from is aligned 1:1 " +
1395
1407
  "with the source_data files, and names the payload path whose ids (in payload " +
1396
- "order) form that file's run. Paths of the form " +
1397
- "keys(g2_context.<list>[slice]) iterate the slice groups in order, then the " +
1398
- "entity-id keys in order. If a file ever has no path mapping, the group " +
1399
- "carries explicit `ids` instead (lossless fallback).",
1400
- activated_scope_requirements: "requirement `category` is elided because it equals the requirement_id " +
1401
- "category segment — the one immediately before the number (AUT-003→AUT, " +
1402
- "REQ-AGN-001→AGN; consumer contract v1.10 §1.18). Verbatim bundle invariant; " +
1403
- "the field survives inline on any future mismatch. `description` is the verbatim published field from " +
1404
- "data/publish/runtime/requirements.json — never paraphrased.",
1408
+ "order) form that file's run. Paths of the form section.list[].field iterate a list; " +
1409
+ "keys(g2_context.<list>[slice]) (lista/standard) iterate the slice groups in order, then the " +
1410
+ "entity-id keys in order; at full the g2 sections are lists (g2_context.<list>[].entity_id). " +
1411
+ "If a file ever has no path mapping, the group carries explicit `ids` instead (lossless fallback).",
1412
+ activated_scope_requirements: "ONE object per requirement (0.21 §1): {id, name, type, description, verify, evidence}. " +
1413
+ "`description` is the verbatim published field (data/publish/runtime/requirements.json) and " +
1414
+ "NEVER leaves, at any level. `verify` = verification_logic and `evidence` = " +
1415
+ "evidence_expectation of the requirement's published evidence pattern " +
1416
+ "(data/publish/runtime/evidence_patterns.json, 1:1 per requirement), verbatim. The pattern's " +
1417
+ "other fields (evidence_pattern_id, control_id, expected_artifact_type_ids) are served by " +
1418
+ "reference: completeness_report.verification.by_ref (get_sbd_toe_verification_matrix, ≤50 " +
1419
+ "ids per call). `category` is elided because it equals the id category segment (AUT-003→AUT, " +
1420
+ "REQ-AGN-001→AGN; consumer contract v1.10 §1.18) — the field survives inline on any mismatch.",
1405
1421
  activated_scope_controls: "controls with confidence='direct' carry the verbatim published `description` " +
1406
1422
  "from data/publish/runtime/controls.json.",
1423
+ adjacency: "0.21 §2 — `adjacency` at EVERY level: the closed-vocabulary signals you did NOT declare that would " +
1424
+ "change the requirement set, with what each would add (arithmetic over the declaration: the same " +
1425
+ "deterministic selection re-run with the signal added — never a reading of the task). " +
1426
+ "undeclared_that_would_change_the_set is the top-N by would_add; would_change_the_set is the " +
1427
+ "denominator (never truncated in silence); scanned is how many vocabulary values were probed. " +
1428
+ "`detail` (the full list; the summary is its prefix) is inline at standard/full and reachable via " +
1429
+ "detail_ref at lista. In selection_mode='discover' the adjacency is relative to the declaration made, " +
1430
+ "not to the inferred set.",
1407
1431
  g2_entities: "g2_context.control_objectives/mechanisms/practices/artifacts are grouped as " +
1408
1432
  "{slice_id: {entity_id: name|null}}. entity_type is the list the map lives in " +
1409
1433
  "(ControlObjective/Mechanism/Practice/Artifact), slice_id is the group key, " +
1410
1434
  "slice_family is activated_scope.slices[].objective_family for that slice_id, " +
1411
1435
  "and a null name means the entity is unnamed in the published rastreabilidade " +
1412
1436
  "(the full projection omits `name` for it).",
1413
- evidence_patterns: "g2_context.evidence_patterns is the deterministic prefix (relevance desc, " +
1414
- "then id asc; the tool-computed relevance_score is elided — the order carries " +
1415
- "the ranking) of the classic detail=full list, capped per " +
1416
- "completeness_report.evidence_pattern_cap. completeness_report reports " +
1417
- "total/returned/capped and, when anything was cut, evidence_patterns_rest " +
1418
- "says how to retrieve the rest (same input, detail='full'; with debug=true " +
1419
- "the ids beyond the classic cap are listed in debug.rejected_candidates).",
1420
- manual_grounding_minimal: "At detail=minimal, manual_grounding is the aggregated-provenance form " +
1421
- "(s3b): total_entries, the manual_commit_sha shared by every group " +
1422
- "(hoisted; a group keeps its own sha inline only if hoisting was not " +
1423
- "possible), and the (rastreabilidade_role, manual_chapter, manual_file) " +
1424
- "groups with the exact per-group `entries` COUNT instead of the " +
1425
- "v1_entity_ids list (counts sum to total_entries — never silent). The " +
1426
- "grounding id set is already in the same payload (g2_context entity-map " +
1427
- "keys); manual_grounding.groups_ref is the executable reference (same " +
1428
- "input, detail='standard') for the per-group id lists — groups align " +
1429
- "1:1, same order. detail=standard keeps the full grouping inline.",
1430
- activation_trace: "activation_trace is elided at detail=standard/minimal; " +
1437
+ verification: "There is no g2_context.evidence_patterns block any more (0.21 §1). " +
1438
+ "completeness_report.verification declares the denominators: requirements, " +
1439
+ "with_verify_and_evidence, partial, without_pattern, and " +
1440
+ "related_by_control_outside_scope (patterns linked to an activated control whose " +
1441
+ "requirement is not in the activated set — never inlined, reachable via the ref).",
1442
+ manual_grounding: "At detail=lista/standard, manual_grounding is the counts form: total_entries, the " +
1443
+ "manual_commit_sha shared by every group (hoisted; a group keeps its own sha inline " +
1444
+ "only if hoisting was not possible), and the (rastreabilidade_role, manual_chapter, " +
1445
+ "manual_file) groups with the exact per-group `entries` COUNT (counts sum to " +
1446
+ "total_entries — never silent). The grounding id set is already in the same payload " +
1447
+ "(g2_context entity-map keys); manual_grounding.entries_ref is the executable " +
1448
+ "reference (same input, detail='full') for the verbatim flat entries.",
1449
+ activation_trace: "activation_trace is elided at detail=lista/standard; " +
1431
1450
  "activation_trace_ref.entries keeps the exact count. Re-call with debug=true " +
1432
1451
  "to include the full trace (it is always inline at detail=full).",
1433
- relations_ref: "Inline g2_context.relations are elided at detail=standard/minimal (re-call " +
1434
- "with include_relations=true to restore them). Recover the elided graph edges " +
1452
+ relations_ref: "0.21 §3: inline g2_context.relations are elided at EVERY level (re-call with " +
1453
+ "include_relations=true to restore them). At full, g2_context.relations_ref lists the " +
1454
+ "executable trace calls; at lista/standard only g2_context.relations_summary (the same exact " +
1455
+ "accounting) stays — the edges link nodes this payload already carries. Recover the elided graph edges " +
1435
1456
  "by executing trace_sbd_toe_graph with each {lens, anchor} pair listed " +
1436
1457
  "(anchors are activated slice/entity ids from the same payload); the " +
1437
1458
  "belongsToSlice edges counted as coverage.implicit_in_entities are already " +
1438
1459
  "encoded by the slice grouping key of every g2_context entity; any relation " +
1439
- "covered by neither stays inline in residual_relations (never silent).",
1440
- ultrathin: "detail=ultrathin (s3c) applies every rule above PLUS: (1) requirements " +
1441
- "{requirement_id, name, type} and controls {control_id, name, domain, " +
1442
- "control_type, confidence} keep the COMPLETE activated set (same ids, " +
1443
- "same order, name always present) but elide the published `description` " +
1444
- "— activated_scope.descriptions_ref is the executable reference (same " +
1445
- "input, detail='minimal') for the verbatim descriptions; (2) " +
1446
- "g2_context.evidence_patterns is empty (cap 0) — completeness_report " +
1447
- "keeps total/returned=0/capped=total and evidence_patterns_rest points " +
1448
- "to detail='minimal' (cheapest level returning patterns inline; " +
1449
- "'standard' returns 10, 'full' the classic 25); (3) manual_grounding is " +
1450
- "{total_entries, manual_commit_sha, groups_ref} — the group list is " +
1451
- "elided (detail='standard' returns the full 1:1 grouping); (4) " +
1452
- "v1_consistency_mismatches/v1_manifest_warnings text arrays are replaced " +
1453
- "by exact *_count fields (+ v1_diagnostics_ref when any count > 0, " +
1454
- "detail='minimal' returns the texts). The citable id set and the " +
1455
- "citations/ids_from encoding are IDENTICAL to the other dieted levels."
1460
+ "covered by neither stays inline in residual_relations (never silent)."
1456
1461
  };
1457
1462
  /**
1458
1463
  * Content of the `sbd://toe/codegen-instructions/{mode}` MCP resource — the
@@ -1468,17 +1473,18 @@ export function buildCodegenInstructionsResourceContent(mode) {
1468
1473
  return {
1469
1474
  resource: codegenInstructionsResourceUri(mode),
1470
1475
  mode,
1471
- note: "Static per-mode boilerplate for prepare_sbd_toe_codegen_context at " +
1472
- "detail=standard/minimal (kept inline at detail=full). Also carries the " +
1473
- "detail_encoding legend for the dieted payload.",
1476
+ note: "Static per-mode boilerplate of prepare_sbd_toe_codegen_context (0.21: the " +
1477
+ "instructions and the template are INLINE at every level; this resource is the " +
1478
+ "reference copy, slot by slot). Also carries the detail_encoding legend.",
1474
1479
  // 0.15.0 item 8, invertido para esta linha (0.20): aqui o trace EXISTE.
1475
1480
  line_note: "Nesta linha 0.20 o trace_sbd_toe_graph existe: execute os " +
1476
1481
  "relations_ref directamente ({lens, anchor}). include_relations=true no " +
1477
1482
  "prepare continua disponível como atalho para relações inline.",
1478
1483
  llm_codegen_instructions: {
1479
- assembly: "Include each slot whose `when` is 'always' or appears in this call's " +
1480
- "codegen_instructions_ref.active_conditions, in the listed order — the " +
1481
- "result is byte-identical to the detail=full inline llm_codegen_instructions.",
1484
+ assembly: "Include each slot whose `when` is 'always' or whose condition holds for the call " +
1485
+ "(regulatory_overlay: activated_scope.regulatory_obligations non-empty; " +
1486
+ "risk_level:<L>: input_echo.risk_level; citations_empty: no citable id), in the " +
1487
+ "listed order — the result is byte-identical to the inline llm_codegen_instructions.",
1482
1488
  slots: instructionSlotsForMode(mode)
1483
1489
  },
1484
1490
  security_rationale_template: {
@@ -1514,12 +1520,12 @@ function blocked(input, raw, status, reasons, suggestions, partial, debug) {
1514
1520
  }
1515
1521
  return result;
1516
1522
  }
1517
- const DETAIL_LEVELS = new Set([
1518
- "ultrathin",
1519
- "minimal",
1520
- "standard",
1521
- "full"
1522
- ]);
1523
+ const DETAIL_LEVELS = new Set(["lista", "standard", "full"]);
1524
+ /** 0.21: níveis retirados/renomeados — o erro diz para onde foram, nunca só «inválido». */
1525
+ const RETIRED_DETAIL_LEVELS = {
1526
+ ultrathin: "'ultrathin' retirou-se na 0.21: a sua razão de existir era cortar a descrição publicada, e a descrição deixou de ser negociável (nunca sai, em nenhum nível). Usa detail='lista'.",
1527
+ minimal: "'minimal' passou a chamar-se 'lista' na 0.21 (herda-lhe o envelope de 8.450 tk; traz a descrição, verify e evidence de cada requisito inline). Usa detail='lista'."
1528
+ };
1523
1529
  /**
1524
1530
  * Validate the `detail` input (v2 token diet, s1). Invalid values fail fast
1525
1531
  * with a JSON-RPC -32602 (same pattern as trace-graph's lens validation);
@@ -1534,12 +1540,11 @@ function parseDetail(raw) {
1534
1540
  if (typeof value === "string" && DETAIL_LEVELS.has(value)) {
1535
1541
  return value;
1536
1542
  }
1537
- throw Object.assign(new Error(`Invalid "detail": ${JSON.stringify(value)}. Use one of: ultrathin, minimal, standard, full.`), {
1538
- rpcError: {
1539
- code: -32602,
1540
- message: 'Invalid "detail". Use one of: ultrathin, minimal, standard, full.'
1541
- }
1542
- });
1543
+ const retired = typeof value === "string" ? RETIRED_DETAIL_LEVELS[value] : undefined;
1544
+ const message = retired
1545
+ ? `Invalid "detail": ${JSON.stringify(value)}. ${retired}`
1546
+ : `Invalid "detail": ${JSON.stringify(value)}. Use one of: lista, standard, full.`;
1547
+ throw Object.assign(new Error(message), { rpcError: { code: -32602, message } });
1543
1548
  }
1544
1549
  /**
1545
1550
  * Validate the `include_relations` input (v2 token diet, s2). Only booleans
@@ -1568,9 +1573,7 @@ const PRED_REALIZED_BY_PRACTICE = "objective_realized_by_practice";
1568
1573
  // s3: slimmed — the full explanation lives in the codegen-instructions MCP
1569
1574
  // resource (detail_encoding.relations_ref). Kept URI-free on purpose: the
1570
1575
  // no-leak gate scans relations_ref for any scheme://.
1571
- const RELATIONS_REF_NOTE = "Inline g2_context.relations elided; execute each listed trace_sbd_toe_graph " +
1572
- "{lens, anchor} call to recover them, or re-call with include_relations=true. " +
1573
- "Encoding details: MCP resource codegen-instructions, detail_encoding.relations_ref.";
1576
+ const RELATIONS_REF_NOTE_ID = "prepare.relations_ref"; // 0.21 §6-c: texto em src/serving/notes.ts → sbd://toe/notes/prepare.relations_ref
1574
1577
  /**
1575
1578
  * v2 token diet, s2 — build the `relations_ref` for `detail: "standard" |
1576
1579
  * "minimal"`. See the {@link RelationsRefLensCall} doc block for the full
@@ -1690,7 +1693,7 @@ function buildRelationsRef(result) {
1690
1693
  implicit_in_entities: implicitInEntities,
1691
1694
  residual_inline: residual.length
1692
1695
  },
1693
- note: RELATIONS_REF_NOTE
1696
+ note_id: RELATIONS_REF_NOTE_ID
1694
1697
  };
1695
1698
  if (residual.length > 0)
1696
1699
  relationsRef.residual_relations = residual;
@@ -1708,7 +1711,7 @@ function stripSource(items) {
1708
1711
  * if one ever appears, the group falls back to explicit `ids` (lossless).
1709
1712
  */
1710
1713
  const CITATION_FILE_TO_PAYLOAD_PATH = {
1711
- "data/publish/runtime/requirements.json": "activated_scope.requirements[].requirement_id",
1714
+ "data/publish/runtime/requirements.json": "activated_scope.requirements[].id",
1712
1715
  "data/publish/runtime/controls.json": "activated_scope.controls[].control_id",
1713
1716
  "data/publish/runtime/v1/slices.json": "activated_scope.slices[].slice_id",
1714
1717
  "data/publish/runtime/v1/control_objectives.json": "keys(g2_context.control_objectives[slice])",
@@ -1718,6 +1721,37 @@ const CITATION_FILE_TO_PAYLOAD_PATH = {
1718
1721
  "data/publish/overlay/external_frameworks.json": "regulatory_overlay.frameworks[].framework_id",
1719
1722
  "data/publish/overlay/external_obligations.json": "activated_scope.regulatory_obligations[].obligation_id"
1720
1723
  };
1724
+ /** 0.21 §3: at `full` the g2 entity sections are LISTS (classic), so the ids_from paths differ
1725
+ * only for those four files; every other path is shared with the dieted levels. */
1726
+ const CITATION_FILE_TO_PAYLOAD_PATH_FULL = {
1727
+ ...CITATION_FILE_TO_PAYLOAD_PATH,
1728
+ "data/publish/runtime/v1/control_objectives.json": "g2_context.control_objectives[].entity_id",
1729
+ "data/publish/runtime/v1/mechanisms.json": "g2_context.mechanisms[].entity_id",
1730
+ "data/publish/runtime/v1/practices.json": "g2_context.practices[].entity_id",
1731
+ "data/publish/runtime/v1/artifacts.json": "g2_context.artifacts[].entity_id"
1732
+ };
1733
+ /**
1734
+ * 0.21 §3 — resolve the ids of a `citations` block over the payload that carries it
1735
+ * (any level): `section.list[].field` iterates a list; `keys(g2_context.<list>[slice])`
1736
+ * iterates the slice groups then the entity-id keys. Explicit `ids` is the lossless
1737
+ * fallback. Exported so consumers and tests read ids by the SAME published rule.
1738
+ */
1739
+ export function citableIds(payload) {
1740
+ const root = payload;
1741
+ const at = (path) => {
1742
+ const keys = /^keys\(g2_context\.([a-z_]+)\[slice\]\)$/.exec(path);
1743
+ if (keys) {
1744
+ const grouped = (root["g2_context"]?.[keys[1]] ?? {});
1745
+ return Object.values(grouped).flatMap((entities) => Object.keys(entities));
1746
+ }
1747
+ const list = /^([a-z0-9_]+)\.([a-z0-9_]+)\[\]\.([a-z0-9_]+)$/.exec(path);
1748
+ if (!list)
1749
+ throw new Error(`ids_from path desconhecido: ${path}`);
1750
+ const items = (root[list[1]]?.[list[2]] ?? []);
1751
+ return items.map((item) => item[list[3]]);
1752
+ };
1753
+ return Object.values(root.citations ?? {}).flatMap((group) => group?.ids ?? (group?.ids_from ?? []).flatMap(at));
1754
+ }
1721
1755
  /**
1722
1756
  * Invert the classic `citation_map` (id → {source, source_data}) into
1723
1757
  * source-grouped `citations` (see {@link CitationsGroup}). Pure re-encoding:
@@ -1727,7 +1761,8 @@ const CITATION_FILE_TO_PAYLOAD_PATH = {
1727
1761
  * of repeated; a group keeps explicit `ids` only if one of its files has no
1728
1762
  * payload-path mapping (never expected for the published bundle).
1729
1763
  */
1730
- function invertCitationMap(citationMap) {
1764
+ function invertCitationMap(citationMap, layout = "grouped") {
1765
+ const pathTable = layout === "list" ? CITATION_FILE_TO_PAYLOAD_PATH_FULL : CITATION_FILE_TO_PAYLOAD_PATH;
1731
1766
  const bySource = new Map();
1732
1767
  for (const [id, entry] of Object.entries(citationMap)) {
1733
1768
  let files = bySource.get(entry.source);
@@ -1751,7 +1786,7 @@ function invertCitationMap(citationMap) {
1751
1786
  for (const [file, fileIds] of files) {
1752
1787
  source_data[file] = fileIds.length;
1753
1788
  ids.push(...fileIds);
1754
- const path = CITATION_FILE_TO_PAYLOAD_PATH[file];
1789
+ const path = pathTable[file];
1755
1790
  if (path === undefined)
1756
1791
  allFilesMapped = false;
1757
1792
  else
@@ -1830,11 +1865,7 @@ function groupManualGrounding(result) {
1830
1865
  return grouped;
1831
1866
  }
1832
1867
  // s3b: kept URI-free on purpose (no-leak discipline, same as RELATIONS_REF_NOTE).
1833
- const GROUNDING_GROUPS_REF_NOTE = "Per-group v1_entity_ids elided at detail=minimal (each group carries its " +
1834
- "exact `entries` count). The grounding id set is already in this payload — " +
1835
- "every grounding id is an entity-id key of the g2_context maps. Re-call " +
1836
- "with the same input at detail='standard' for the per-group id lists " +
1837
- "(groups align 1:1, same order).";
1868
+ const GROUNDING_ENTRIES_REF_NOTE_ID = "prepare.grounding.entries_ref"; // 0.21 §6-c: texto em src/serving/notes.ts → sbd://toe/notes/prepare.grounding.entries_ref
1838
1869
  /**
1839
1870
  * v2 token diet, s3b (revised ADENDA 2026-07-05) — minimal-form
1840
1871
  * `manual_grounding`, derived from the detail="standard" grouping (so the 1:1
@@ -1871,101 +1902,17 @@ function buildMinimalGrounding(grouped) {
1871
1902
  entries: group.v1_entity_ids.length,
1872
1903
  ...(group.v1_entity_names ? { v1_entity_names: group.v1_entity_names } : {})
1873
1904
  })),
1874
- groups_ref: {
1905
+ entries_ref: {
1875
1906
  tool: "prepare_sbd_toe_codegen_context",
1876
- with: { detail: "standard" },
1877
- note: GROUNDING_GROUPS_REF_NOTE
1907
+ with: { detail: "full" },
1908
+ note_id: GROUNDING_ENTRIES_REF_NOTE_ID
1878
1909
  }
1879
1910
  };
1880
1911
  if (grouped.ungrouped)
1881
1912
  minimal.ungrouped = grouped.ungrouped;
1882
1913
  return minimal;
1883
1914
  }
1884
- // s3c notes — all NEW constants (the s1–s4 note texts are byte-frozen by the
1885
- // standard/minimal golden snapshots and are never edited). Kept URI-free
1886
- // (no-leak discipline, same as RELATIONS_REF_NOTE).
1887
- const GROUNDING_GROUPS_REF_NOTE_ULTRATHIN = "Grounding group list elided at detail=ultrathin (total_entries is the " +
1888
- "exact flat entry count; manual_commit_sha is the shared published manual " +
1889
- "commit). The grounding id set is already in this payload — every " +
1890
- "grounding id is an entity-id key of the g2_context maps. Re-call with the " +
1891
- "same input at detail='standard' for the full (role, chapter, file) groups " +
1892
- "with per-group v1_entity_ids; detail='minimal' returns the groups with " +
1893
- "per-group counts.";
1894
- const DESCRIPTIONS_REF_NOTE = "Published `description` fields (the 'how') elided at detail=ultrathin — " +
1895
- "the requirement/control lists themselves are COMPLETE (same ids, same " +
1896
- "order, name always present). Re-call with the same input at " +
1897
- "detail='minimal' for the same complete scope WITH the verbatim published " +
1898
- "descriptions (requirements + direct controls).";
1899
- const EVIDENCE_PATTERNS_REST_NOTE_ULTRATHIN = "No evidence pattern goes inline at detail=ultrathin (returned=0; " +
1900
- "capped=total). Re-call with the same input at detail='minimal' for the " +
1901
- "deterministic top-5 (cheapest level that returns patterns inline); " +
1902
- "detail='standard' returns the top-10 and detail='full' the classic " +
1903
- "top-25 (each list is a deterministic prefix of the next).";
1904
- const ACTIVATION_TRACE_REF_NOTE_ULTRATHIN = "activation_trace elided at detail=ultrathin — re-call with debug=true to " +
1905
- "include it (always inline at detail=full).";
1906
- const V1_DIAGNOSTICS_REF_NOTE = "v1_consistency_mismatches/v1_manifest_warnings texts elided at " +
1907
- "detail=ultrathin (exact counts inline). Re-call with the same input at " +
1908
- "detail='minimal' for the full text arrays in completeness_report.";
1909
- /**
1910
- * v2 token diet, s3c — ultrathin-form `manual_grounding`, derived from the
1911
- * s3b minimal form (so `total_entries`, the hoisted sha and the ungrouped
1912
- * guard are byte-identical by construction). Serialization-only cut, never
1913
- * silent: the (role, chapter, file) group list with per-group counts is
1914
- * elided; `total_entries` keeps the exact flat count and `groups_ref` is the
1915
- * executable reference to the full grouping (same input, detail="standard").
1916
- * Lossless guards (expected never): if the sha was not hoistable or any group
1917
- * carries `v1_entity_names`, the minimal `groups` list survives inline.
1918
- */
1919
- function buildUltrathinGrounding(minimal) {
1920
- const mustKeepGroups = minimal.manual_commit_sha === undefined ||
1921
- minimal.groups.some((group) => group.v1_entity_names !== undefined || group.manual_commit_sha !== undefined);
1922
- const ultrathin = {
1923
- total_entries: minimal.total_entries,
1924
- ...(minimal.manual_commit_sha !== undefined
1925
- ? { manual_commit_sha: minimal.manual_commit_sha }
1926
- : {}),
1927
- ...(mustKeepGroups && minimal.groups.length > 0 ? { groups: minimal.groups } : {}),
1928
- groups_ref: {
1929
- tool: "prepare_sbd_toe_codegen_context",
1930
- with: { detail: "standard" },
1931
- note: GROUNDING_GROUPS_REF_NOTE_ULTRATHIN
1932
- }
1933
- };
1934
- if (minimal.ungrouped)
1935
- ultrathin.ungrouped = minimal.ungrouped;
1936
- return ultrathin;
1937
- }
1938
- /**
1939
- * v2 token diet, s3c — trim the completeness report for `detail: "ultrathin"`.
1940
- * Every COUNT survives verbatim (never-silent backbone: expected/returned per
1941
- * entity kind, m_recall, named/unnamed, evidence total/returned/capped/cap and
1942
- * the rest-ref); only the two diagnostic TEXT arrays are re-encoded as exact
1943
- * counts + the executable `v1_diagnostics_ref` (see
1944
- * {@link UltrathinCompletenessReport} for what is cut and why).
1945
- */
1946
- function trimCompletenessForUltrathin(report) {
1947
- const { v1_consistency_mismatches, v1_manifest_warnings, ...kept } = report;
1948
- // 0.15.0: ultrathin OMITE os counts excluded_by_level (dieta; tecto 4.840 vigia) —
1949
- // a banda fica declarada no select e nos perfis standard/minimal/full.
1950
- if (kept.selection) {
1951
- const { excluded_by_level_categories: _c, excluded_by_level_requirements: _r, lexical_share: _lx, ...selRest } = kept.selection;
1952
- kept.selection = selRest;
1953
- }
1954
- return {
1955
- ...kept,
1956
- v1_consistency_mismatches_count: v1_consistency_mismatches.length,
1957
- v1_manifest_warnings_count: v1_manifest_warnings.length,
1958
- ...(v1_consistency_mismatches.length + v1_manifest_warnings.length > 0
1959
- ? {
1960
- v1_diagnostics_ref: {
1961
- tool: "prepare_sbd_toe_codegen_context",
1962
- with: { detail: "minimal" },
1963
- note: V1_DIAGNOSTICS_REF_NOTE
1964
- }
1965
- }
1966
- : {})
1967
- };
1968
- }
1915
+ // (notas s3c removidas na 0.21 — o nível ultrathin reformou-se.)
1969
1916
  /** Slice-grouped, name-only entity encoding (see {@link SliceGroupedEntityNames}). */
1970
1917
  function groupEntitiesBySlice(entities) {
1971
1918
  const grouped = {};
@@ -1981,135 +1928,74 @@ function categoryIsDerivable(requirementId, category) {
1981
1928
  const derived = requirementCategoryOf(requirementId);
1982
1929
  return derived !== undefined && derived === category;
1983
1930
  }
1984
- /** Dieted requirements: `source`/derivable `category` elided, verbatim
1985
- * published `description` appended (s3 — the "how"). s3c: at
1986
- * `detail: "ultrathin"` (`includeDescriptions: false`) the description is
1987
- * elided too — each item is exactly {requirement_id, name, type} (plus the
1988
- * unchanged `category` lossless guard) with the executable
1989
- * `activated_scope.descriptions_ref` pointing at detail="minimal". */
1990
- function dietRequirements(requirements, includeDescriptions) {
1991
- const descriptionById = new Map();
1992
- if (includeDescriptions) {
1993
- for (const requirement of getOntologyData().requirements) {
1994
- if (requirement.description) {
1995
- descriptionById.set(requirement.requirement_id, requirement.description);
1996
- }
1997
- }
1998
- }
1931
+ /** Dieted requirements (0.21 §1): the fused object minus per-item `source`;
1932
+ * `category` elided iff derivable from the id (lossless guard otherwise). The
1933
+ * description/verify/evidence come from the core — they are the SAME at every
1934
+ * level; nothing is added or removed here. */
1935
+ function dietRequirements(requirements) {
1999
1936
  return requirements.map((item) => {
2000
1937
  const { source: _source, category, ...rest } = item;
2001
- const description = descriptionById.get(item.requirement_id);
2002
1938
  return {
2003
1939
  ...rest,
2004
- ...(categoryIsDerivable(item.requirement_id, category) ? {} : { category }),
2005
- ...(description ? { description } : {})
1940
+ ...(category !== undefined && !categoryIsDerivable(item.id, category) ? { category } : {})
2006
1941
  };
2007
1942
  });
2008
1943
  }
2009
- /** Dieted controls: `source` elided; `direct` controls carry the verbatim
2010
- * published `description` (s3 — the "how"). s3c: at `detail: "ultrathin"`
2011
- * (`includeDescriptions: false`) the description is elided — each item is
2012
- * exactly {control_id, name, domain, control_type, confidence} (every
2013
- * non-description published field: small, useful, and required to keep the
2014
- * item more than id-only). */
2015
- function dietControls(controls, includeDescriptions) {
2016
- const descriptionById = new Map();
2017
- if (includeDescriptions) {
2018
- for (const control of getOntologyData().controls) {
2019
- if (control.description)
2020
- descriptionById.set(control.control_id, control.description);
2021
- }
2022
- }
2023
- return controls.map((item) => {
2024
- const { source: _source, ...rest } = item;
2025
- const description = item.confidence === "direct" ? descriptionById.get(item.control_id) : undefined;
2026
- return { ...rest, ...(description ? { description } : {}) };
2027
- });
1944
+ /** Dieted controls: `source` elided; the `direct` controls' verbatim published
1945
+ * `description` comes from the core (0.21: at every level, full included). */
1946
+ function dietControls(controls) {
1947
+ return stripSource(controls);
2028
1948
  }
2029
1949
  /**
2030
- * v2 token diet, s1+s2+s3 — dieted encoding for `detail: "standard" |
2031
- * "minimal"`. Pure post-processing over the byte-identical full result. The
2032
- * citable ID set is EXACTLY the full one (invariant 3; the omitted evidence
2033
- * patterns carry no citation_map ids — verified by tests). Every cut is
2034
- * either a lossless derivable-field re-encoding documented in the
2035
- * codegen-instructions resource legend, or an explicit bound with
2036
- * total/returned/omitted counts plus an executable reference to the rest
2037
- * (invariant 2 — never silent):
2038
- * - s1: inverted citations, grouped grounding, per-item `source` legend;
1950
+ * 0.21 — a forma por nível é uma TABELA, não ramos: o que cada nível põe
1951
+ * inline e o que põe por referência. Parametrizável de propósito — a §4 do
1952
+ * despacho (o Mensor mede se o `manual_grounding` vai inline ou por
1953
+ * referência) e o «2 ou 3 níveis» ficam em aberto e decidem-se aqui, numa
1954
+ * linha, sem reescrever o servidor.
1955
+ */
1956
+ export const LEVEL_FORM = {
1957
+ lista: { manual_grounding: "ref", relations: "ref", adjacency_detail: "ref" }, // relations "ref" = 0.21 §3 summary (accounting + way back)
1958
+ standard: { manual_grounding: "ref", relations: "ref", adjacency_detail: "inline" } // 0.21 §2: o separador lista↔standard
1959
+ };
1960
+ const ADJACENCY_DETAIL_REF_NOTE_ID = "prepare.adjacency.detail_ref"; // 0.21 §6-c: texto em src/serving/notes.ts → sbd://toe/notes/prepare.adjacency.detail_ref
1961
+ /**
1962
+ * Dieted encoding for `detail: "lista" | "standard"` (0.21). Pure
1963
+ * post-processing over the full result. The citable ID set is EXACTLY the
1964
+ * full one (invariant 3). Every cut is either a lossless derivable-field
1965
+ * re-encoding documented in the codegen-instructions resource legend, or an
1966
+ * explicit bound with counts plus an executable reference (never silent):
1967
+ * - s1: inverted citations, per-item `source` legend;
2039
1968
  * - s2: relations on-demand via `relations_ref` (include_relations restores);
2040
- * - s3: evidence cap 25→10 (deterministic prefix; counts + rest-ref in
2041
- * completeness_report), instructions/template → MCP resource, trace only
2042
- * with debug, verbatim published `description` on requirements + direct
2043
- * controls, and derivable-field dedup (category, entity_type/slice_family
2044
- * via slice-grouped entity maps, relevance_score, citation id repeats);
2045
- * - s3b (revised ADENDA 2026-07-05 — no top-N): `minimal` keeps the
2046
- * activated scope byte-identical to `standard` and diverges ONLY on
2047
- * traceability serialization — evidence cap 10→5 (same mechanism) and
2048
- * `manual_grounding` in the minimal form (counts + hoisted sha +
2049
- * executable groups_ref);
2050
- * - s3c (`ultrathin`, operator reactivation 2026-07-05): same complete
2051
- * activated set, but descriptions elided (descriptions_ref →
2052
- * detail="minimal"), evidence cap 5→0 (rest-ref → detail="minimal"),
2053
- * grounding aggregate-only and completeness diagnostics as counts + ref.
1969
+ * - 0.21 §1: the fused requirement is byte-identical to full's minus
1970
+ * `source`; instructions + template INLINE; manual_grounding in the
1971
+ * counts form with `entries_ref` → detail="full"; trace only with debug.
2054
1972
  */
2055
- function applyStructuralDiet(result, detail, includeRelations) {
2056
- // s3/s3b/s3c evidence cap (standard 10, minimal 5, ultrathin 0):
2057
- // deterministic prefix of the classic (already sorted: relevance_score desc,
2058
- // id asc) list; each dieted list is by construction a prefix of the next
2059
- // level's. Never-silent counts below; the rest-ref points to detail="full"
2060
- // (classic top-25) at standard/minimal and to detail="minimal" (the
2061
- // CHEAPEST level that returns patterns inline) at ultrathin.
2062
- const ultrathin = detail === "ultrathin";
2063
- const evidenceCap = ultrathin
2064
- ? ULTRATHIN_EVIDENCE_PATTERN_CAP
2065
- : detail === "minimal"
2066
- ? MINIMAL_EVIDENCE_PATTERN_CAP
2067
- : STANDARD_EVIDENCE_PATTERN_CAP;
2068
- const evidenceKept = result.g2_context.evidence_patterns.slice(0, evidenceCap);
2069
- const evidenceTotal = result.completeness_report.evidence_patterns_total;
2070
- const evidenceCapped = evidenceTotal - evidenceKept.length;
2071
- const completeness = {
2072
- ...result.completeness_report,
2073
- evidence_patterns_returned: evidenceKept.length,
2074
- evidence_patterns_capped: evidenceCapped,
2075
- evidence_pattern_cap: evidenceCap,
2076
- ...(evidenceCapped > 0
2077
- ? {
2078
- evidence_patterns_rest: (ultrathin
2079
- ? {
2080
- tool: "prepare_sbd_toe_codegen_context",
2081
- with: { detail: "minimal" },
2082
- note: EVIDENCE_PATTERNS_REST_NOTE_ULTRATHIN
2083
- }
2084
- : {
2085
- tool: "prepare_sbd_toe_codegen_context",
2086
- with: { detail: "full" },
2087
- note: "Re-call with the same input at detail='full' for the classic inline " +
2088
- `top-${EVIDENCE_PATTERN_CAP} evidence_patterns (this list is its ` +
2089
- "deterministic prefix); with debug=true, ids beyond the classic cap " +
2090
- "are listed in debug.rejected_candidates."
2091
- })
2092
- }
2093
- : {})
2094
- };
2095
- // s3 instructions → resource: conditions computed from the SAME resolved
2096
- // inputs the core used, so resource + active_conditions reconstruct the
2097
- // inline full content byte-identically.
2098
- const echoedRisk = result.input_echo.risk_level;
2099
- const riskLevel = echoedRisk === "L1" || echoedRisk === "L2" || echoedRisk === "L3"
2100
- ? echoedRisk
2101
- : undefined;
2102
- const instructionsRef = {
2103
- resource: codegenInstructionsResourceUri(result.mode),
2104
- active_conditions: activeInstructionConditions({
2105
- hasOverlay: result.activated_scope.regulatory_obligations.length > 0,
2106
- riskLevel,
2107
- citationMapEmpty: Object.keys(result.citation_map).length === 0
2108
- }),
2109
- note: "Slots por índice: read_sbd_toe_resource(uri, slot=\"<n>\"); active_conditions filtram; byte-identical ao detail=full."
1973
+ const RELATIONS_SUMMARY_NOTE_ID = "prepare.relations_summary"; // 0.21 §6-c: texto em src/serving/notes.ts → sbd://toe/notes/prepare.relations_summary
1974
+ /**
1975
+ * 0.21 §3 — the SERVED full: classic content, two form changes, same citable set.
1976
+ * `citations` (inverted; ids via list paths) replaces `citation_map`; `relations_ref`
1977
+ * replaces the inline relations unless `include_relations: true`.
1978
+ */
1979
+ function shapeFull(result, includeRelations) {
1980
+ const { citation_map, g2_context, ...rest } = result;
1981
+ const { relations, ...g2 } = g2_context;
1982
+ return {
1983
+ ...rest,
1984
+ ...(includeRelations ? { input_echo: { ...result.input_echo, include_relations: true } } : {}),
1985
+ g2_context: {
1986
+ ...g2,
1987
+ ...(includeRelations ? { relations } : { relations_ref: buildRelationsRef(result) })
1988
+ },
1989
+ citations: invertCitationMap(citation_map, "list")
2110
1990
  };
1991
+ }
1992
+ function applyStructuralDiet(result, detail, includeRelations) {
1993
+ const form = LEVEL_FORM[detail];
1994
+ // 0.21 §3: the exact accounting comes from the same builder the full uses for relations_ref.
1995
+ const relationsRef = includeRelations || form.relations !== "ref" ? undefined : buildRelationsRef(result);
2111
1996
  const dieted = {
2112
1997
  status: result.status,
1998
+ notes: NOTES_HEADER,
2113
1999
  mode: result.mode,
2114
2000
  // Echo the requested detail (and the include_relations escape hatch, when
2115
2001
  // active) for audit; the FULL result never echoes either (explicit "full"
@@ -2119,102 +2005,125 @@ function applyStructuralDiet(result, detail, includeRelations) {
2119
2005
  detail,
2120
2006
  ...(includeRelations ? { include_relations: true } : {})
2121
2007
  },
2122
- // s3: activation_trace only with debug=true; never-silent counter otherwise
2123
- // (s3c: ultrathin carries its own note — the standard/minimal text is
2124
- // byte-frozen by the golden snapshots).
2125
2008
  ...(result.debug
2126
2009
  ? { activation_trace: result.activation_trace }
2127
2010
  : {
2128
2011
  activation_trace_ref: {
2129
2012
  entries: result.activation_trace.length,
2130
- note: ultrathin
2131
- ? ACTIVATION_TRACE_REF_NOTE_ULTRATHIN
2132
- : "activation_trace elided at detail=standard/minimal — re-call with " +
2133
- "debug=true to include it (always inline at detail=full)."
2013
+ note_id: "prepare.activation_trace_ref"
2134
2014
  }
2135
2015
  }),
2136
- provenance_legend: ultrathin ? PROVENANCE_LEGEND_ULTRATHIN : PROVENANCE_LEGEND,
2137
- // s3c: ultrathin elides the published descriptions (executable
2138
- // descriptions_ref → detail="minimal"); the lists stay COMPLETE.
2016
+ provenance_legend: PROVENANCE_LEGEND,
2139
2017
  activated_scope: {
2140
- requirements: dietRequirements(result.activated_scope.requirements, !ultrathin),
2141
- controls: dietControls(result.activated_scope.controls, !ultrathin),
2018
+ requirements: dietRequirements(result.activated_scope.requirements),
2019
+ controls: dietControls(result.activated_scope.controls),
2142
2020
  slices: stripSource(result.activated_scope.slices),
2143
- regulatory_obligations: stripSource(result.activated_scope.regulatory_obligations),
2144
- ...(ultrathin
2145
- ? {
2146
- descriptions_ref: {
2147
- tool: "prepare_sbd_toe_codegen_context",
2148
- with: { detail: "minimal" },
2149
- note: DESCRIPTIONS_REF_NOTE
2150
- }
2151
- }
2152
- : {})
2021
+ regulatory_obligations: stripSource(result.activated_scope.regulatory_obligations)
2153
2022
  },
2023
+ // 0.21 §2: resumo sempre; detalhe inline (standard) ou por referência executável (lista).
2024
+ adjacency: form.adjacency_detail === "inline"
2025
+ ? result.adjacency
2026
+ : {
2027
+ undeclared_that_would_change_the_set: result.adjacency.undeclared_that_would_change_the_set,
2028
+ scanned: result.adjacency.scanned,
2029
+ would_change_the_set: result.adjacency.would_change_the_set,
2030
+ shown: result.adjacency.shown,
2031
+ detail_ref: { tool: "prepare_sbd_toe_codegen_context", with: { detail: "standard" }, note_id: ADJACENCY_DETAIL_REF_NOTE_ID }
2032
+ },
2154
2033
  g2_context: {
2155
2034
  control_objectives: groupEntitiesBySlice(result.g2_context.control_objectives),
2156
2035
  mechanisms: groupEntitiesBySlice(result.g2_context.mechanisms),
2157
2036
  practices: groupEntitiesBySlice(result.g2_context.practices),
2158
2037
  artifacts: groupEntitiesBySlice(result.g2_context.artifacts),
2159
- ...(includeRelations
2038
+ ...(relationsRef === undefined
2160
2039
  ? { relations: stripSource(result.g2_context.relations) }
2161
- : { relations_ref: buildRelationsRef(result) }),
2162
- evidence_patterns: evidenceKept.map(({ source: _source, relevance_score: _score, ...rest }) => rest)
2040
+ : {
2041
+ relations_summary: {
2042
+ total_relations: relationsRef.total_relations,
2043
+ via_lenses: relationsRef.coverage.via_lenses,
2044
+ implicit_in_entities: relationsRef.coverage.implicit_in_entities,
2045
+ residual_inline: relationsRef.coverage.residual_inline,
2046
+ note_id: RELATIONS_SUMMARY_NOTE_ID
2047
+ },
2048
+ ...(relationsRef.residual_relations ? { residual_relations: relationsRef.residual_relations } : {})
2049
+ })
2163
2050
  },
2164
- // s3b: minimal serves the count+provenance form (executable groups_ref);
2165
- // standard keeps the full grouping; s3c: ultrathin serves the aggregate
2166
- // form only (total + hoisted sha + groups_ref, group list elided).
2167
- manual_grounding: ultrathin
2168
- ? buildUltrathinGrounding(buildMinimalGrounding(groupManualGrounding(result)))
2169
- : detail === "minimal"
2170
- ? buildMinimalGrounding(groupManualGrounding(result))
2171
- : groupManualGrounding(result),
2051
+ manual_grounding: buildMinimalGrounding(groupManualGrounding(result)),
2172
2052
  regulatory_overlay: {
2173
2053
  frameworks: stripSource(result.regulatory_overlay.frameworks),
2174
2054
  obligations: stripSource(result.regulatory_overlay.obligations),
2175
2055
  mappings: stripSource(result.regulatory_overlay.mappings),
2176
- playbooks: stripSource(result.regulatory_overlay.playbooks)
2056
+ playbooks: stripSource(result.regulatory_overlay.playbooks),
2057
+ ...(result.regulatory_overlay.mappings_scope ? { mappings_scope: result.regulatory_overlay.mappings_scope } : {})
2177
2058
  },
2178
2059
  citations: invertCitationMap(result.citation_map),
2179
- // s3c: ultrathin trims the diagnostic text arrays to exact counts + ref.
2180
- completeness_report: ultrathin
2181
- ? trimCompletenessForUltrathin(completeness)
2182
- : completeness,
2183
- codegen_instructions_ref: instructionsRef,
2060
+ completeness_report: result.completeness_report,
2061
+ llm_codegen_instructions: result.llm_codegen_instructions,
2062
+ security_rationale_template: result.security_rationale_template,
2184
2063
  // s4: identical re-call is deterministic — point the client back at the
2185
- // context it already holds (full stays byte-identical: no hint there).
2186
- repeat_call_hint: REPEAT_CALL_HINT,
2064
+ // context it already holds.
2065
+ repeat_call_hint: { note_id: REPEAT_CALL_HINT_ID },
2187
2066
  provenance: result.provenance
2188
2067
  };
2189
- if (result.debug) {
2190
- // 0.20.0-beta.26 (§17-A, menor): a nota contava o cap CLÁSSICO (returned=25) mesmo
2191
- // quando o nível dietado devolvia 5 — o número que o consumidor lia não era o que
2192
- // recebeu. Passa a contar o efectivo, dizendo qual é o cap deste `detail`.
2193
- dieted.debug = {
2194
- ...result.debug,
2195
- notes: result.debug.notes.map((note) => note.startsWith("evidence_patterns: total=")
2196
- ? `evidence_patterns: total=${evidenceTotal} returned=${evidenceKept.length} capped=${evidenceCapped} (cap efectivo do detail="${detail}": ${evidenceCap}; cap clássico: ${EVIDENCE_PATTERN_CAP})`
2197
- : note)
2198
- };
2199
- }
2068
+ if (result.debug)
2069
+ dieted.debug = result.debug;
2200
2070
  return dieted;
2201
2071
  }
2072
+ /**
2073
+ * 0.21 §5 — o preço declarado. Duas passagens: a primeira mede com o campo a
2074
+ * zero, a segunda re-mede com os dígitos reais lá dentro, para que o número
2075
+ * anunciado seja o do payload QUE O CONSUMIDOR RECEBE (±1 token de
2076
+ * arredondamento, nunca mais). Régua = chars/4, a mesma da medição do §5.
2077
+ */
2078
+ const ENVELOPE_EXCEEDED_NOTE_ID = "prepare.size_estimate.envelope_exceeded"; // 0.21 §6-c: texto em src/serving/notes.ts → sbd://toe/notes/prepare.size_estimate.envelope_exceeded
2079
+ function withSizeEstimate(payload, detail) {
2080
+ const envelope = LEVEL_ENVELOPE_TK[detail];
2081
+ const declare = (est) => envelope === undefined
2082
+ ? est
2083
+ : {
2084
+ ...est,
2085
+ envelope_tk: envelope,
2086
+ within_envelope: est.approx_tokens <= envelope,
2087
+ ...(est.approx_tokens <= envelope ? {} : { note_id: ENVELOPE_EXCEEDED_NOTE_ID })
2088
+ };
2089
+ const first = estimateSize({ ...payload, size_estimate: declare({ chars: 0, approx_tokens: 0 }) });
2090
+ const second = estimateSize({ ...payload, size_estimate: declare(first) });
2091
+ return { ...payload, size_estimate: declare(second) };
2092
+ }
2202
2093
  export function handlePrepareCodegenContext(raw) {
2203
- // v2 token diet (s1/s2): `detail` and `include_relations` select the
2204
- // response ENCODING only — they are validated up-front and never influence
2205
- // activation/resolution.
2094
+ // `detail` and `include_relations` select the response ENCODING only —
2095
+ // they are validated up-front and never influence activation/resolution.
2206
2096
  const detail = parseDetail(raw);
2207
2097
  const includeRelations = parseIncludeRelations(raw);
2208
2098
  const result = prepareCodegenContextCore(raw);
2209
- const shaped = detail !== "full" && result.status === "ready_for_codegen"
2210
- ? applyStructuralDiet(result, detail, includeRelations)
2211
- : result;
2099
+ const shaped = result.status !== "ready_for_codegen"
2100
+ ? result
2101
+ : detail === "full"
2102
+ ? shapeFull(result, includeRelations)
2103
+ : applyStructuralDiet(result, detail, includeRelations);
2212
2104
  // RF-H: append the advisory band (status-aware, pure) around the deterministic result.
2213
- return { ...shaped, next: prepareCodegenAffordances(result.status, "citation_map" in result ? Object.keys(result.citation_map).filter((id) => /^[A-Z]{3}-\d{3}$/.test(id)) : []) };
2105
+ const withNext = { ...shaped, next: prepareCodegenAffordances(result.status, "citation_map" in result ? Object.keys(result.citation_map).filter((id) => /^[A-Z]{3}-\d{3}$/.test(id)) : []) };
2106
+ // 0.21 §5: every ready payload declares its price (full has no ceiling — it declares instead).
2107
+ return withNext.status === "ready_for_codegen" ? withSizeEstimate(withNext, detail) : withNext;
2214
2108
  }
2215
2109
  function prepareCodegenContextCore(raw) {
2216
2110
  const input = normalizeInput(raw);
2217
- const preGate = gateBeforeActivation(input);
2111
+ // 0.21 §6 — o `task` vs o contrato: em modo DECLARATIVO com declaração, o task é contexto
2112
+ // REGISTADO (task_role: recorded_context) e NÃO influencia o resultado — logo não pode
2113
+ // barrar a resposta (contagem de palavras, padrões de vagueza, tecnologia fora do âmbito).
2114
+ // O gate mantém-se onde o task é MOTOR: em `discover`, e em declarativo sem declaração
2115
+ // (onde a selecção responde needs_input de qualquer forma).
2116
+ const selectionModeEarly = raw.selection_mode === "discover" ? "discover" : "declarative";
2117
+ const structuralEarly = {
2118
+ chapters: Array.isArray(raw.chapters) ? raw.chapters.filter((x) => typeof x === "string" && x.length > 0) : [],
2119
+ categories: Array.isArray(raw.categories) ? raw.categories.filter((x) => typeof x === "string" && x.length > 0) : []
2120
+ };
2121
+ // Em declarativo o gate NUNCA corre: sem declaração a selecção responde needs_input a nomear
2122
+ // o vocabulário (o contrato), e uma declaração inerte (stack fora do vocabulário) é declarada
2123
+ // com os valores válidos — nunca um needs_clarification sobre o task, que não é motor aqui.
2124
+ void structuralEarly;
2125
+ const taskIsRecordedContext = selectionModeEarly === "declarative";
2126
+ const preGate = taskIsRecordedContext ? null : gateBeforeActivation(input);
2218
2127
  if (preGate && preGate.status !== "ready_for_codegen") {
2219
2128
  return blocked(input, raw, preGate.status, preGate.reasons, preGate.suggestions, [], { rejected: [], notes: [] });
2220
2129
  }
@@ -2225,11 +2134,19 @@ function prepareCodegenContextCore(raw) {
2225
2134
  const selectionMode = raw.selection_mode === "discover" ? "discover" : "declarative";
2226
2135
  const declaredTechnologies = normalizeDeclaredTechnologies(Array.isArray(raw.technologies) ? raw.technologies.filter((t) => typeof t === "string") : [], input.stack);
2227
2136
  const declarativeSelection = selectionMode !== "discover";
2137
+ // 0.21 §6 — forma B no prepare: chapters/categories declarados passam ao motor tal e qual,
2138
+ // e CONTAM como declaração (o lote de decomposição é uma chamada só com `categories`).
2139
+ const structural = {
2140
+ chapters: Array.isArray(raw.chapters) ? raw.chapters.filter((x) => typeof x === "string" && x.length > 0) : [],
2141
+ categories: Array.isArray(raw.categories) ? raw.categories.filter((x) => typeof x === "string" && x.length > 0) : []
2142
+ };
2228
2143
  const hasDeclaredActivator = input.concerns.length > 0 ||
2229
2144
  input.exposure !== undefined ||
2230
2145
  input.data_sensitivity !== undefined ||
2231
2146
  input.changed_files.length > 0 ||
2232
- declaredTechnologies.length > 0;
2147
+ declaredTechnologies.length > 0 ||
2148
+ structural.chapters.length > 0 ||
2149
+ structural.categories.length > 0;
2233
2150
  // P1-A (0.20.0-beta.22): a decisão de needs_input é UMA e vive no motor — indexada
2234
2151
  // à activação produzida, não à presença de campos. O prepare reage ao veredicto
2235
2152
  // (abaixo, depois de correr a selecção), em vez de ter a sua própria regra.
@@ -2253,10 +2170,17 @@ function prepareCodegenContextCore(raw) {
2253
2170
  void focusConcerns; // kept for the debug notes below; the gate no longer counts requirements
2254
2171
  // MP1 selection (G-mp1a O2): the engine composes baseline ∪ context and narrows
2255
2172
  // by the task's declared signals — this is the requirement set served.
2256
- const selection = runSelectionWithActivation(input, activation, selectionMode === "discover" ? (raw.technologies ?? []) : declaredTechnologies, selectionMode);
2173
+ const selection = runSelectionWithActivation(input, activation, selectionMode === "discover" ? (raw.technologies ?? []) : declaredTechnologies, selectionMode, structural);
2257
2174
  if (selection.needs_input) {
2258
2175
  const ni = selection.needs_input;
2259
- return blocked(input, raw, "needs_input", [
2176
+ const inert = (ni.inert_declarations ?? []).join(" ");
2177
+ const vocab = buildActivationVocabulary();
2178
+ const validValues = {
2179
+ ...(/\bstack=|\btechnologies=/.test(inert) ? { technologies: vocab.technologies.values.map((t) => String(t.value)) } : {}),
2180
+ ...(/\bexposure=/.test(inert) ? { exposure: vocab.exposure.values.map((e) => String(e.value)) } : {}),
2181
+ ...(/\bdata_sensitivity=/.test(inert) ? { data_sensitivity: vocab.data_sensitivity.values.map((d) => String(d.value)) } : {})
2182
+ };
2183
+ const blockedNeedsInput = blocked(input, raw, "needs_input", [
2260
2184
  ni.reason,
2261
2185
  "Contrato v1.18-beta: o servidor responde ao declarado e NÃO interpreta o `task` — que fica registado para auditoria."
2262
2186
  ], [
@@ -2268,6 +2192,8 @@ function prepareCodegenContextCore(raw) {
2268
2192
  ...(ni.inert_declarations?.length ? [`Declarações inertes nesta chamada: ${ni.inert_declarations.join("; ")}.`] : []),
2269
2193
  `Queres o comportamento inferencial antigo? selection_mode="discover" (exploratório).`
2270
2194
  ], activation.trace);
2195
+ blockedNeedsInput.needs_input = { ...ni, ...(Object.keys(validValues).length > 0 ? { valid_values: validValues } : {}) };
2196
+ return blockedNeedsInput;
2271
2197
  }
2272
2198
  const estimatedRequirements = selection.selected.length;
2273
2199
  // 0.19.4 («a promessa do minimal», lead opção 2): tecto de requisitos por-id
@@ -2278,40 +2204,81 @@ function prepareCodegenContextCore(raw) {
2278
2204
  const ceilingDetail = parseDetail(raw);
2279
2205
  const requirementCeiling = REQUIREMENT_CEILING_BY_DETAIL[ceilingDetail];
2280
2206
  if (requirementCeiling !== undefined && selection.selected.length > requirementCeiling) {
2207
+ // 0.21 §6 (condição da decisão (a)): lotes que SOMAM O TODO. Partição das categorias
2208
+ // activadas em lotes ≤ tecto (guloso por tamanho decrescente), cada lote uma declaração
2209
+ // ESTRUTURAL executável; technologies/changed_files preservados literalmente; a contagem
2210
+ // de cada lote é REAL (a selecção corre-se para o lote).
2281
2211
  const byCategory = new Map();
2282
2212
  for (const r of selection.selected)
2283
2213
  byCategory.set(r.category, (byCategory.get(r.category) ?? 0) + 1);
2284
- const remaining = new Set(byCategory.keys());
2285
- const batches = [];
2286
- while (remaining.size > 0 && batches.length < 3) {
2287
- let best = null;
2288
- let bestCats = [];
2289
- let bestWeight = 0;
2290
- for (const concern of VALID_CONCERNS) {
2291
- const cats = [...categoriesForConcerns([concern])].filter((c) => remaining.has(c));
2292
- const weight = cats.reduce((n, c) => n + (byCategory.get(c) ?? 0), 0);
2293
- if (weight > bestWeight) {
2294
- best = concern;
2295
- bestCats = cats;
2296
- bestWeight = weight;
2214
+ const categoriesDesc = [...byCategory.entries()].sort((a, b2) => b2[1] - a[1] || a[0].localeCompare(b2[0]));
2215
+ // As tecnologias preservadas em cada lote podem acrescentar requisitos por regra NOMEADA
2216
+ // (ex.: SES-008 por `jwt`) fora das categorias do lote — reserva-se essa margem na
2217
+ // capacidade de cada lote, para que a contagem REAL (abaixo) nunca exceda o tecto.
2218
+ const technologyExtras = declaredTechnologies.length > 0
2219
+ ? runSelectionWithActivation({ ...input, concerns: [], exposure: undefined, data_sensitivity: undefined, changed_files: [] }, { ...activation, concerns: [], sliceFamilies: [], trace: [], rejected: [], notes: [] }, declaredTechnologies, "declarative", { chapters: [], categories: [] }).selected.length
2220
+ : 0;
2221
+ const capacity = Math.max(1, requirementCeiling - technologyExtras);
2222
+ const bins = [];
2223
+ const binLoad = [];
2224
+ for (const [category, count] of categoriesDesc) {
2225
+ let placed = false;
2226
+ for (let i = 0; i < bins.length; i += 1) {
2227
+ if (binLoad[i] + count <= capacity) {
2228
+ bins[i].push(category);
2229
+ binLoad[i] += count;
2230
+ placed = true;
2231
+ break;
2297
2232
  }
2298
2233
  }
2299
- if (!best)
2300
- break;
2301
- batches.push({ concerns: [best], estimated_requirements: bestWeight });
2302
- for (const c of bestCats)
2303
- remaining.delete(c);
2234
+ if (!placed) {
2235
+ bins.push([category]);
2236
+ binLoad.push(count);
2237
+ }
2304
2238
  }
2239
+ const activatorConcerns = new Set([
2240
+ ...(input.exposure ? EXPOSURE_CONCERNS[input.exposure] ?? [] : []),
2241
+ ...(input.data_sensitivity ? SENSITIVITY_CONCERNS[input.data_sensitivity] ?? [] : [])
2242
+ ]);
2243
+ const concernsForCategory = (category) => [...new Set([...input.concerns, ...activation.concerns])].filter((c) => categoriesForConcerns([c]).has(category)).sort();
2244
+ const batchWith = (categories) => ({
2245
+ categories,
2246
+ ...(declaredTechnologies.length > 0 ? { technologies: [...declaredTechnologies] } : {}),
2247
+ ...(input.changed_files.length > 0 ? { changed_files: [...input.changed_files] } : {})
2248
+ });
2249
+ const union = new Set();
2250
+ const batches = bins.map((categories) => {
2251
+ const w = batchWith(categories);
2252
+ const run = runSelectionWithActivation({ ...input, concerns: [] }, { ...activation, concerns: [], sliceFamilies: [], trace: [], rejected: [], notes: [] }, w.technologies ?? [], "declarative", { chapters: [], categories });
2253
+ for (const r of run.selected)
2254
+ union.add(r.requirement_id);
2255
+ const concerns = [...new Set(categories.flatMap(concernsForCategory))].filter((c) => !activatorConcerns.has(c) || input.concerns.includes(c)).sort();
2256
+ return {
2257
+ with: w,
2258
+ requirements: run.selected.length,
2259
+ derived_from: {
2260
+ concerns,
2261
+ ...(input.exposure && categories.some((cat) => [...activatorConcerns].some((c) => (EXPOSURE_CONCERNS[input.exposure] ?? []).includes(c) && categoriesForConcerns([c]).has(cat))) ? { exposure: input.exposure } : {}),
2262
+ ...(input.data_sensitivity && categories.some((cat) => [...activatorConcerns].some((c) => (SENSITIVITY_CONCERNS[input.data_sensitivity] ?? []).includes(c) && categoriesForConcerns([c]).has(cat))) ? { data_sensitivity: input.data_sensitivity } : {})
2263
+ }
2264
+ };
2265
+ });
2266
+ const selectedIds = selection.selected.map((r) => r.requirement_id);
2267
+ const covered = selectedIds.filter((id) => union.has(id)).length;
2268
+ const recall = selectedIds.length === 0 ? 1 : covered / selectedIds.length;
2305
2269
  const projected = projectedCostTk(ceilingDetail, selection.selected.length) ?? 0;
2306
2270
  const b = blocked(input, raw, "needs_decomposition", [
2307
2271
  `Selecção de ${selection.selected.length} requisitos excede o tecto de ${requirementCeiling} para detail="${ceilingDetail}" ` +
2308
2272
  `(medição: ~${COST_PER_REQ_TK[ceilingDetail] ?? 0} tk/req sobre base ~${BASE_TK[ceilingDetail] ?? 0} tk ⇒ ~${projected} tk, ` +
2309
- `acima da promessa de ${PAYLOAD_PROMISE_TK[ceilingDetail] ?? 0} tk deste nível).`
2273
+ `acima do envelope de ${PAYLOAD_PROMISE_TK[ceilingDetail] ?? 0} tk deste nível).`
2310
2274
  ], [
2311
- "Divide por área — repete SÓ com task + risk_level + concerns do lote; os activadores largos (exposure/data_sensitivity/stack) ficam FORA da chamada do lote, porque concerns SOMAM activação, não restringem. Lotes (estimativas por área do pedido original): " +
2312
- batches.map((bt, i) => `${i + 1}) concerns=[${bt.concerns.map((c) => `"${c}"`).join(", ")}] (~${bt.estimated_requirements} reqs)`).join("; ") +
2313
- ". Categorias sem lote entram na chamada mais próxima.",
2314
- `Em alternativa usa detail="full" (sem tecto — payload completo, custo alto) ou reduz o âmbito da task.`
2275
+ `Divide em ${batches.length} lotes que SOMAM O TODO (união = ${union.size} ids, m_recall ${recall.toFixed(2)} face à selecção inteira): ` +
2276
+ "repete com task + risk_level + detail + `categories` do lote" +
2277
+ (declaredTechnologies.length > 0 || input.changed_files.length > 0 ? " (technologies/changed_files preservados em cada lote)" : "") +
2278
+ ". Cada lote é a partição EXACTA das categorias que a tua declaração activou — exposure/data_sensitivity estão lá pelo seu efeito (re-declará-los somaria as suas categorias a todos os lotes). Lotes: " +
2279
+ batches.map((bt, i) => `${i + 1}) categories=[${bt.with.categories.map((c) => `"${c}"`).join(", ")}] (${bt.requirements} reqs; de ${bt.derived_from.concerns.map((c) => `"${c}"`).join(", ") || "activadores"}${bt.derived_from.exposure ? `, exposure=${bt.derived_from.exposure}` : ""}${bt.derived_from.data_sensitivity ? `, data_sensitivity=${bt.derived_from.data_sensitivity}` : ""})`).join("; ") +
2280
+ ".",
2281
+ `Em alternativa usa detail="full" (sem tecto — preço declarado em size_estimate) ou reduz o âmbito da task.`
2315
2282
  ], activation.trace, input.debug ? { rejected: activation.rejected, notes: activation.notes } : undefined);
2316
2283
  b.requirement_ceiling = {
2317
2284
  detail: ceilingDetail,
@@ -2320,7 +2287,8 @@ function prepareCodegenContextCore(raw) {
2320
2287
  cost_per_req_tk: COST_PER_REQ_TK[ceilingDetail] ?? 0,
2321
2288
  projected_tk: projected,
2322
2289
  promise_tk: PAYLOAD_PROMISE_TK[ceilingDetail] ?? 0,
2323
- batches
2290
+ batches,
2291
+ union: { requirements: union.size, recall: Number(recall.toFixed(4)) }
2324
2292
  };
2325
2293
  return b;
2326
2294
  }
@@ -2393,67 +2361,74 @@ function prepareCodegenContextCore(raw) {
2393
2361
  });
2394
2362
  const directControlIds = new Set(v0.controls.filter((control) => control.confidence === "direct").map((control) => control.control_id));
2395
2363
  const derivedControlIds = new Set(v0.controls.filter((control) => control.confidence === "derived").map((control) => control.control_id));
2396
- const activeRequirementIdsForEvidence = new Set(v0.requirements.map((requirement) => requirement.requirement_id));
2397
- function projectEvidencePattern(pattern, relevanceScore) {
2398
- const projection = {
2399
- id: pattern.id,
2400
- relevance_score: relevanceScore,
2364
+ // ----- 0.21 §1: the fused requirement ---------------------------------
2365
+ // One object per requirement: the published description NEVER leaves, and the
2366
+ // requirement's own evidence pattern (1:1 in the bundle) is inlined as
2367
+ // verify/evidence. No cap, no join left to the model. Patterns that touched
2368
+ // the scope only through an activated CONTROL (their requirement is outside
2369
+ // the activated set) are NOT inlined — they belong to other requirements —
2370
+ // and are counted + referenced below (never silent).
2371
+ const activeRequirementIds = new Set(v0.requirements.map((r) => r.requirement_id));
2372
+ const patternByRequirement = new Map();
2373
+ for (const pattern of ontologyForSelection.evidencePatterns ?? []) {
2374
+ if (pattern.maps_to_requirement_id && !patternByRequirement.has(pattern.maps_to_requirement_id)) {
2375
+ patternByRequirement.set(pattern.maps_to_requirement_id, pattern);
2376
+ }
2377
+ }
2378
+ let withVerifyAndEvidence = 0;
2379
+ let partialPatterns = 0;
2380
+ let withoutPattern = 0;
2381
+ const fusedRequirements = v0.requirements.map((requirement) => {
2382
+ const pattern = patternByRequirement.get(requirement.requirement_id);
2383
+ const verify = pattern?.verification_logic;
2384
+ const evidence = pattern?.evidence_expectation;
2385
+ if (!pattern)
2386
+ withoutPattern += 1;
2387
+ else if (verify && evidence)
2388
+ withVerifyAndEvidence += 1;
2389
+ else
2390
+ partialPatterns += 1;
2391
+ return {
2392
+ id: requirement.requirement_id,
2393
+ name: requirement.name,
2394
+ ...(requirement.type ? { type: requirement.type } : {}),
2395
+ ...(categoryIsDerivable(requirement.requirement_id, requirement.category) ? {} : { category: requirement.category }),
2396
+ ...(requirement.description ? { description: requirement.description } : {}),
2397
+ ...(verify ? { verify } : {}),
2398
+ ...(evidence ? { evidence } : {}),
2401
2399
  source: "runtime_v0"
2402
2400
  };
2403
- if (pattern.maps_to_requirement_id)
2404
- projection.maps_to_requirement_id = pattern.maps_to_requirement_id;
2405
- if (pattern.maps_to_control_id)
2406
- projection.maps_to_control_id = pattern.maps_to_control_id;
2407
- if (pattern.evidence_expectation)
2408
- projection.evidence_expectation = pattern.evidence_expectation;
2409
- if (pattern.verification_logic)
2410
- projection.verification_logic = pattern.verification_logic;
2411
- if (pattern.expected_artifact_type_ids && pattern.expected_artifact_type_ids.length > 0) {
2412
- projection.expected_artifact_type_ids = pattern.expected_artifact_type_ids;
2413
- }
2414
- return projection;
2415
- }
2416
- /**
2417
- * 0.20.0-beta.26 (§17-A) — ORDENAÇÃO POR PERTENÇA AO ÂMBITO.
2418
- *
2419
- * A ordenação anterior dava 1.0 a qualquer EP ligado a um CONTROLO directo e só 0.7 ao
2420
- * EP ligado a um REQUISITO do âmbito activado: a pertença ao controlo ganhava à pertença
2421
- * ao requisito, e o desempate por id fazia o resto. Efeito medido: numa tarefa de
2422
- * validação (âmbito ERR/VAL) vinham 5 em 5 EPs de fora — EP-API-002/003/007, EP-AUT-010,
2423
- * EP-CFG-005 — e nem um EP-VAL/EP-ERR; em `auth` funcionava por SORTE ALFABÉTICA
2424
- * (ACC < API < AUT < CFG < ERR < VAL). Pior: em «exigir reautenticação» o `minimal`
2425
- * omitia EP-AUT-009, o padrão do requisito que a tarefa NOMEIA.
2426
- *
2427
- * Isto não é um modelo de relevância — é uma comparação de PERTENÇA, e é por isso que
2428
- * pode ser uma invariante testável: o requisito do âmbito activado vem primeiro, depois
2429
- * o controlo directo, depois o derivado, e o id só desempata dentro do mesmo escalão.
2430
- */
2431
- const scoredEvidencePatterns = v0.evidencePatterns.map((pattern) => {
2432
- let score = 0;
2433
- if (pattern.maps_to_requirement_id &&
2434
- activeRequirementIdsForEvidence.has(pattern.maps_to_requirement_id)) {
2435
- score = Math.max(score, 1.0);
2436
- }
2437
- if (pattern.maps_to_control_id &&
2438
- directControlIds.has(pattern.maps_to_control_id)) {
2439
- score = Math.max(score, 0.7);
2440
- }
2441
- if (pattern.maps_to_control_id &&
2442
- derivedControlIds.has(pattern.maps_to_control_id)) {
2443
- score = Math.max(score, 0.5);
2444
- }
2445
- return { pattern, score };
2446
2401
  });
2447
- scoredEvidencePatterns.sort((a, b) => b.score - a.score || a.pattern.id.localeCompare(b.pattern.id));
2448
- const keptEvidencePatterns = scoredEvidencePatterns.slice(0, EVIDENCE_PATTERN_CAP);
2449
- const cappedEvidencePatterns = scoredEvidencePatterns.slice(EVIDENCE_PATTERN_CAP);
2402
+ const relatedByControlOutsideScope = v0.evidencePatterns.filter((pattern) => !(pattern.maps_to_requirement_id && activeRequirementIds.has(pattern.maps_to_requirement_id))).length;
2403
+ const verificationCalls = Math.ceil(v0.requirements.length / 50);
2404
+ const riskForRef = input.risk_level ? `"${input.risk_level}"` : "<declara o risk_level>";
2405
+ const verification = {
2406
+ requirements: v0.requirements.length,
2407
+ with_verify_and_evidence: withVerifyAndEvidence,
2408
+ partial: partialPatterns,
2409
+ without_pattern: withoutPattern,
2410
+ by_ref: {
2411
+ tool: "get_sbd_toe_verification_matrix",
2412
+ with: `risk_level=${riskForRef}, requirement_ids=[activated_scope.requirements[].id] (≤50 por chamada)`,
2413
+ calls: verificationCalls,
2414
+ fields: ["evidence_pattern_id", "control_id", "expected_artifact_type_ids"],
2415
+ note_id: "prepare.verification.by_ref"
2416
+ },
2417
+ related_by_control_outside_scope: {
2418
+ count: relatedByControlOutsideScope,
2419
+ ref: {
2420
+ tool: "resolve_entities",
2421
+ with: 'record_type="evidence_pattern", filters={"maps_to_control_id":{"in":[activated_scope.controls[].control_id]}}',
2422
+ note_id: "prepare.verification.related_by_control_outside_scope"
2423
+ }
2424
+ }
2425
+ };
2450
2426
  const g2Context = {
2451
2427
  control_objectives: activatedCOs.map((entity) => projectV1Entity(entity, g2Data)),
2452
2428
  mechanisms: activatedMechanisms.map((entity) => projectV1Entity(entity, g2Data)),
2453
2429
  practices: activatedPractices.map((entity) => projectV1Entity(entity, g2Data)),
2454
2430
  artifacts: activatedArtifacts.map((entity) => projectV1Entity(entity, g2Data)),
2455
- relations: activatedRelations.map(projectRelation),
2456
- evidence_patterns: keptEvidencePatterns.map(({ pattern, score }) => projectEvidencePattern(pattern, score))
2431
+ relations: activatedRelations.map(projectRelation)
2457
2432
  };
2458
2433
  // ----- Manual grounding ----------------------------------------------
2459
2434
  const manualGrounding = [];
@@ -2477,20 +2452,17 @@ function prepareCodegenContextCore(raw) {
2477
2452
  }
2478
2453
  // ----- Activated scope projection ------------------------------------
2479
2454
  const activatedScope = {
2480
- requirements: v0.requirements.map((requirement) => ({
2481
- requirement_id: requirement.requirement_id,
2482
- name: requirement.name,
2483
- category: requirement.category,
2484
- type: requirement.type,
2485
- source: "runtime_v0"
2486
- })),
2455
+ requirements: fusedRequirements,
2456
+ // 0.21 §1: a description publicada dos controlos DIRECTOS vai em todos os
2457
+ // níveis, o full incluído («não promete caber, promete não faltar»).
2487
2458
  controls: v0.controls.map((control) => ({
2488
2459
  control_id: control.control_id,
2489
2460
  name: control.name,
2490
2461
  domain: control.domain,
2491
2462
  control_type: control.control_type,
2492
2463
  source: "runtime_v0",
2493
- confidence: control.confidence
2464
+ confidence: control.confidence,
2465
+ ...(control.confidence === "direct" && control.description ? { description: control.description } : {})
2494
2466
  })),
2495
2467
  slices: activatedSlices.map((slice) => ({
2496
2468
  slice_id: slice.slice_id,
@@ -2598,16 +2570,12 @@ function prepareCodegenContextCore(raw) {
2598
2570
  lexical_share: selection.basis_summary.lexical_share,
2599
2571
  narrowed_out_ref: {
2600
2572
  tool: "select_sbd_toe_requirements",
2601
- note: "Categorias elegíveis sem sinal na tarefa foram excluídas pelo narrowing MP1 — " +
2602
- "a lista completa (por categoria, com razão) vem de select_sbd_toe_requirements com o mesmo contexto."
2573
+ note_id: "prepare.selection.narrowed_out_ref"
2603
2574
  }
2604
2575
  },
2605
2576
  v1_consistency_mismatches: g2Data.consistency.mismatches,
2606
2577
  v1_manifest_warnings: g2Data.consistency.warnings,
2607
- evidence_patterns_total: scoredEvidencePatterns.length,
2608
- evidence_patterns_returned: keptEvidencePatterns.length,
2609
- evidence_patterns_capped: cappedEvidencePatterns.length,
2610
- evidence_pattern_cap: EVIDENCE_PATTERN_CAP
2578
+ verification
2611
2579
  };
2612
2580
  // ----- Build LLM instructions + rationale template -------------------
2613
2581
  const citedIds = Object.keys(citationMap);
@@ -2618,15 +2586,46 @@ function prepareCodegenContextCore(raw) {
2618
2586
  riskLevel: input.risk_level
2619
2587
  });
2620
2588
  const security_rationale_template = buildSecurityRationaleTemplate(input.taskTrimmed);
2589
+ // ----- 0.21 §2: adjacência declarada -----------------------------------
2590
+ // Relativa à DECLARAÇÃO tal como o chamador a fez (aritmética sobre o vocabulário, nunca
2591
+ // leitura da tarefa); o módulo aplica risk_level L2 quando omitido.
2592
+ const adjacencyBase = {
2593
+ risk_level: input.risk_level ?? "L2",
2594
+ ...(input.concerns.length > 0 ? { concerns: [...input.concerns] } : {}),
2595
+ ...(input.exposure !== undefined ? { exposure: input.exposure } : {}),
2596
+ ...(input.data_sensitivity !== undefined ? { data_sensitivity: input.data_sensitivity } : {}),
2597
+ ...(declaredTechnologies.length > 0 ? { technologies: [...declaredTechnologies] } : {}),
2598
+ ...(input.changed_files.length > 0 ? { changed_files: [...input.changed_files] } : {})
2599
+ };
2600
+ const adjacencySummary = buildDeclaredAdjacency(adjacencyBase);
2601
+ const adjacency = {
2602
+ undeclared_that_would_change_the_set: adjacencySummary.undeclared_that_would_change_the_set,
2603
+ scanned: adjacencySummary.scanned,
2604
+ would_change_the_set: adjacencySummary.would_change_the_set,
2605
+ shown: adjacencySummary.shown,
2606
+ detail: declaredAdjacencyDetail(adjacencyBase)
2607
+ };
2608
+ // ----- 0.21.1: overlay restrito ao âmbito activado ---------------------
2609
+ const scopedOverlay = scopeOverlayMappings(overlayResolution.context, {
2610
+ requirementIds: new Set(v0.requirements.map((r) => r.requirement_id)),
2611
+ controlIds: new Set(v0.controls.map((c) => c.control_id)),
2612
+ evidencePatternToRequirement: new Map(v0.requirements
2613
+ .map((r) => [patternByRequirement.get(r.requirement_id)?.id, r.requirement_id])
2614
+ .filter((pair) => typeof pair[0] === "string")),
2615
+ bundleIds: new Set(v0.requirements.map((r) => r.source_bundle).filter((b) => typeof b === "string")),
2616
+ obligationIds: overlayResolution.activatedObligations.map((o) => o.obligation_id)
2617
+ });
2621
2618
  const result = {
2622
2619
  status: "ready_for_codegen",
2620
+ notes: NOTES_HEADER,
2623
2621
  mode: input.mode,
2624
2622
  input_echo: inputEcho(raw),
2625
2623
  activation_trace: activation.trace,
2626
2624
  activated_scope: activatedScope,
2625
+ adjacency,
2627
2626
  g2_context: g2Context,
2628
2627
  manual_grounding: manualGrounding,
2629
- regulatory_overlay: overlayResolution.context,
2628
+ regulatory_overlay: scopedOverlay,
2630
2629
  citation_map: citationMap,
2631
2630
  completeness_report: completeness,
2632
2631
  llm_codegen_instructions,
@@ -2642,23 +2641,15 @@ function prepareCodegenContextCore(raw) {
2642
2641
  }
2643
2642
  };
2644
2643
  if (input.debug) {
2645
- const cappedEntries = cappedEvidencePatterns.map(({ pattern, score }) => ({
2646
- source: "scope_gate",
2647
- produced: pattern.id,
2648
- trigger: pattern.maps_to_control_id ?? pattern.maps_to_requirement_id ?? "<no anchor>",
2649
- score,
2650
- confidence: "deterministic",
2651
- reason: `Evidence pattern dropped by the scope-membership cap (cap=${EVIDENCE_PATTERN_CAP}); within a membership tier the order is by id, not by relevance.`
2652
- }));
2653
2644
  result.debug = {
2654
- rejected_candidates: [...activation.rejected, ...cappedEntries],
2645
+ rejected_candidates: activation.rejected,
2655
2646
  notes: [
2656
2647
  ...activation.notes,
2657
2648
  `concerns: ${activation.concerns.join(", ") || "(none)"}`,
2658
2649
  `slice_families: ${activation.sliceFamilies.join(", ") || "(none)"}`,
2659
2650
  `overlay_status: ${overlayResolution.status}`,
2660
2651
  `estimated_v0_requirements: ${estimatedRequirements}`,
2661
- `evidence_patterns: total=${scoredEvidencePatterns.length} returned=${keptEvidencePatterns.length} capped=${cappedEvidencePatterns.length}`
2652
+ `verification: requirements=${verification.requirements} with_verify_and_evidence=${verification.with_verify_and_evidence} partial=${verification.partial} without_pattern=${verification.without_pattern} related_by_control_outside_scope=${verification.related_by_control_outside_scope.count}`
2662
2653
  ]
2663
2654
  };
2664
2655
  }