@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:
@@ -27,34 +27,34 @@
27
27
  * `unsupported_scope` for the overlay branch — never silently empty.
28
28
  */
29
29
  import type { Affordance } from "../serving/protocol-envelope.js";
30
+ import { type SizeEstimate } from "../serving/response-shaping.js";
31
+ import { type AdjacencySignal } from "../serving/adjacency.js";
32
+ import { NOTES_HEADER, type NoteId } from "../serving/notes.js";
30
33
  export type CodegenMode = "codegen" | "review" | "test-plan";
31
34
  export type RiskLevel = "L1" | "L2" | "L3";
32
35
  /**
33
- * Response ENCODING level (v2 token diet, epic v2-token-diet slice s1).
36
+ * Nível da resposta — linha 0.21 (§5, ratificada pelo lead 2026-09-25).
34
37
  *
35
- * - `full` (default): classic payload, byte-identical to previous releases —
36
- * whether `detail` is omitted or explicitly "full".
37
- * - `standard` / `minimal`: same citable ID set, deduplicated encoding
38
- * (inverted `citations`, grouped `manual_grounding`, top-level
39
- * `provenance_legend` instead of per-item `source`). No information is
40
- * lost — only the serialization changes. Since s3b (revised ADENDA
41
- * 2026-07-05 — no top-N/subsetting) `minimal` differs from `standard`
42
- * ONLY in traceability serialization: evidence cap 10→5 and the minimal
43
- * `manual_grounding` form; the activated scope stays complete and
44
- * byte-identical to `standard`.
45
- * - `ultrathin` (s3c, reactivated by the operator 2026-07-05): one level below
46
- * `minimal`, same rules (COMPLETE activated set, no top-k, nothing id-only,
47
- * never silent) but requirements/controls WITHOUT the published
48
- * `description` (executable `descriptions_ref` → detail="minimal"),
49
- * evidence_patterns 0 inline (counts + rest-ref → detail="minimal"),
50
- * `manual_grounding` reduced to {total_entries, manual_commit_sha,
51
- * groups_ref} and `completeness_report` diagnostics trimmed to exact counts
52
- * (+ executable ref). Citable ID set unchanged (invariant 3).
38
+ * O eixo deixou de ser «quanto detalhe» e passou a «o que está INLINE e o que
39
+ * está POR REFERÊNCIA». Uma coisa saiu do eixo: a descrição publicada de cada
40
+ * requisito NUNCA sai, em nenhum nível (§1 — o requisito fundido).
53
41
  *
54
- * The default flips to `standard` only at graduation to the next stable
55
- * release (documented as breaking) — never on the beta line.
42
+ * - `lista` — todo o requisito activado vem completo e verbatim (id, nome,
43
+ * descrição, como se verifica, que prova se espera), com os ids
44
+ * citáveis e as instruções que proíbem inventar ids. O
45
+ * ancoramento no manual vem por referência.
46
+ * - `standard` — o que a `lista` promete (a adjacência detalhada inline chega
47
+ * na §2; até lá difere da `lista` só no eco do nível).
48
+ * - `full` — o que o `standard` promete, e mais: o ancoramento no manual
49
+ * verbatim inline, as relações do grafo inline e o traço de
50
+ * activação. É o nível da completude: não promete caber,
51
+ * promete não faltar — e declara o preço em `size_estimate`.
52
+ *
53
+ * `ultrathin` reformou-se (a sua razão documentada era cortar a descrição) e
54
+ * `minimal` passou a chamar-se `lista` (herda-lhe o envelope de 8.450 tk).
55
+ * O default continua a ser `full` (omissão ≡ "full").
56
56
  */
57
- export type CodegenDetailLevel = "ultrathin" | "minimal" | "standard" | "full";
57
+ export type CodegenDetailLevel = "lista" | "standard" | "full";
58
58
  export interface PrepareCodegenContextInput {
59
59
  task: string;
60
60
  risk_level?: RiskLevel;
@@ -77,15 +77,22 @@ export interface PrepareCodegenContextInput {
77
77
  * Substituem o casamento de substring sobre o texto livre de `stack`.
78
78
  */
79
79
  technologies?: string[];
80
+ /**
81
+ * 0.21 §6 — FORMA B no prepare (como no select): declarações ESTRUTURAIS, verdadeiras e
82
+ * verificáveis contra o catálogo. É o que torna um lote de decomposição EXECUTÁVEL: cada
83
+ * lote é a partição das categorias que a tua declaração activou, e a união dos lotes é o
84
+ * conjunto inteiro (m_recall = 1, testado). Só no caminho declarativo.
85
+ */
86
+ chapters?: string[];
87
+ categories?: string[];
80
88
  regulatory_frameworks?: string[];
81
89
  include_regulatory_overlay?: boolean;
82
90
  detail?: CodegenDetailLevel;
83
91
  /**
84
92
  * v2 token diet, s2 — escape hatch for clients that cannot make a second
85
- * call: when true, `detail: "standard" | "minimal"` keeps `g2_context.relations`
93
+ * call: when true, `detail: "lista" | "standard"` keeps `g2_context.relations`
86
94
  * inline (dieted: no per-item `source`) instead of `relations_ref`.
87
- * Ignored at `detail: "full"` (full is always byte-identical to the classic
88
- * payload, relations inline).
95
+ * Ignored at `detail: "full"` (relations always inline there).
89
96
  */
90
97
  include_relations?: boolean;
91
98
  debug?: boolean;
@@ -120,13 +127,70 @@ export interface ActivationTraceEntry {
120
127
  /** Auditable reason explaining why the activation fired. */
121
128
  reason: string;
122
129
  }
130
+ /**
131
+ * 0.21 §1 — O REQUISITO FUNDIDO: um objecto por requisito, inline em TODOS os
132
+ * níveis. Antes, `activated_scope.requirements` trazia {requirement_id, name,
133
+ * category, type} e o «como verifico» vivia num bloco à parte
134
+ * (`g2_context.evidence_patterns`, chaveado por `maps_to_requirement_id`,
135
+ * capado a 25/10/5/0 por nível) — o modelo tinha de fazer o join, e um modelo
136
+ * apressado pegava no nome de três palavras e preenchia o resto de cabeça.
137
+ * Agora o requisito é UMA coisa: id, nome, descrição publicada (nunca sai),
138
+ * verificação e prova esperada — verbatim do bundle (requirements.json +
139
+ * evidence_patterns.json, 1:1 por requisito no KG v1.12.0). Os campos do
140
+ * padrão que NÃO vêm inline (evidence_pattern_id, control_id,
141
+ * expected_artifact_type_ids) mudam de sítio e passam a referenciados —
142
+ * `completeness_report.verification.by_ref` é a chamada executável.
143
+ */
144
+ export interface FusedRequirement {
145
+ id: string;
146
+ name: string;
147
+ /** Published `type` (base | domain-specific) — not derivable, kept inline. */
148
+ type?: string;
149
+ /** Lossless guard: present ONLY when not derivable from the id's category segment (expected never). */
150
+ category?: string;
151
+ /** Verbatim published description — NEVER elided, at any level (0.21 §1). */
152
+ description?: string;
153
+ /** Verbatim `verification_logic` of the requirement's published evidence pattern. */
154
+ verify?: string;
155
+ /** Verbatim `evidence_expectation` of the same pattern. */
156
+ evidence?: string;
157
+ /** Present at detail="full" only (the dieted levels carry it once, in `provenance_legend`). */
158
+ source?: "runtime_v0";
159
+ }
160
+ /**
161
+ * 0.21 §2 — A ADJACÊNCIA DECLARADA, ligada ao prepare. EM TODOS OS NÍVEIS, o mais magro
162
+ * incluído: não é nível de detalhe, é correcção — quem pede o modo barato é quem mais
163
+ * provavelmente sub-declarou, e um modo barato que cale «faltou-te privacidade» é pior do
164
+ * que não existir. Aritmética sobre o vocabulário fechado (src/serving/adjacency.ts): para
165
+ * cada valor NÃO declarado, a mesma selecção determinística com esse valor acrescentado,
166
+ * contando os ids que entrariam. Nunca leitura da tarefa. O resumo (top-N por impacto +
167
+ * denominadores) vai inline sempre; o detalhe (todos os sinais) vai inline em
168
+ * standard/full e por referência executável em lista — é o separador dos dois níveis.
169
+ * Em `selection_mode: "discover"` a adjacência é relativa à DECLARAÇÃO feita (a aritmética
170
+ * não lê o conjunto inferido): com declaração vazia, todo o vocabulário é adjacente.
171
+ */
172
+ export interface PrepareAdjacency {
173
+ /** Top-N por would_add (desempate estável: kind, depois nome). O nome do campo é a frase. */
174
+ undeclared_that_would_change_the_set: AdjacencySignal[];
175
+ /** Valores do vocabulário sondados (todos os não declarados). */
176
+ scanned: number;
177
+ /** Quantos mudariam o conjunto — o DENOMINADOR do resumo. */
178
+ would_change_the_set: number;
179
+ /** Quantos vão nomeados no resumo. */
180
+ shown: number;
181
+ /** standard/full: a lista COMPLETA (o resumo é o seu prefixo). */
182
+ detail?: AdjacencySignal[];
183
+ /** lista: onde está a lista completa — executável verbatim. */
184
+ detail_ref?: {
185
+ tool: "prepare_sbd_toe_codegen_context";
186
+ with: {
187
+ detail: "standard";
188
+ };
189
+ note_id: NoteId;
190
+ };
191
+ }
123
192
  export interface ActivatedScope {
124
- requirements: Array<{
125
- requirement_id: string;
126
- name: string;
127
- category: string;
128
- source: "runtime_v0";
129
- }>;
193
+ requirements: FusedRequirement[];
130
194
  controls: Array<{
131
195
  control_id: string;
132
196
  name: string;
@@ -134,6 +198,8 @@ export interface ActivatedScope {
134
198
  control_type: string;
135
199
  source: "runtime_v0";
136
200
  confidence: "direct" | "derived";
201
+ /** 0.21 §1: verbatim published description, `direct` controls only, at every level. */
202
+ description?: string;
137
203
  }>;
138
204
  slices: Array<{
139
205
  slice_id: string;
@@ -166,24 +232,21 @@ export interface G2ContextRelation {
166
232
  object_type: string | null;
167
233
  source: "runtime_v1";
168
234
  }
169
- export interface G2ContextEvidencePattern {
170
- id: string;
171
- maps_to_requirement_id?: string;
172
- maps_to_control_id?: string;
173
- evidence_expectation?: string;
174
- verification_logic?: string;
175
- expected_artifact_type_ids?: string[];
176
- /** Score in [0,1] driving cap order. 1.0 = direct control match, 0.7 = active requirement, 0.5 = derived control match. */
177
- relevance_score: number;
178
- source: "runtime_v0";
179
- }
235
+ /**
236
+ * 0.21 §1 — `g2_context.evidence_patterns` DEIXOU DE SER BLOCO. O «como
237
+ * verifico» de cada requisito activado vai inline no próprio requisito
238
+ * ({@link FusedRequirement}.verify/.evidence); os caps 25/10/5/0 por nível
239
+ * morreram com ele. Os padrões que só tocavam o âmbito por um CONTROLO
240
+ * activado (requisito fora do conjunto) não são inlinados — pertencem a
241
+ * outros requisitos — e ficam contados + referenciados em
242
+ * `completeness_report.verification` (nunca silencioso).
243
+ */
180
244
  export interface G2Context {
181
245
  control_objectives: G2ContextEntity[];
182
246
  mechanisms: G2ContextEntity[];
183
247
  practices: G2ContextEntity[];
184
248
  artifacts: G2ContextEntity[];
185
249
  relations: G2ContextRelation[];
186
- evidence_patterns: G2ContextEvidencePattern[];
187
250
  }
188
251
  export interface ManualGroundingEntry {
189
252
  rastreabilidade_role: string;
@@ -229,6 +292,39 @@ export interface RegulatoryOverlayContext {
229
292
  title: string;
230
293
  source: "overlay";
231
294
  }>;
295
+ /** 0.21.1 — present when obligations were activated: mappings are scoped to the activated context (see {@link OverlayMappingsScope}). */
296
+ mappings_scope?: OverlayMappingsScope;
297
+ }
298
+ /**
299
+ * 0.21.1 — O OVERLAY RESTRINGE-SE AO QUE A CHAMADA ACTIVOU.
300
+ *
301
+ * Defeito (desde pelo menos a 0.19.4): com `include_regulatory_overlay`, o prepare devolvia TODOS os
302
+ * mapeamentos das obrigações do framework para todo o Manual — 1 693 no RGPD, ≈117k tokens — quando
303
+ * só ~5% apontavam para o que a tarefa activou. As obrigações continuam completas (são ids citáveis:
304
+ * invariante 3); os mapeamentos servem-se só quando o alvo está no âmbito, e o resto conta-se aqui,
305
+ * por tipo, com a chamada executável que o devolve. Nunca silencioso.
306
+ */
307
+ export interface OverlayMappingsScope {
308
+ /** All mappings of the activated obligations (what 0.21.0 served inline). */
309
+ total: number;
310
+ /** Mappings served inline in `mappings` (target in the activated scope, not derivable). */
311
+ served: number;
312
+ /** Evidence-pattern mappings elided because they mirror a served requirement mapping. */
313
+ derivable_elided: number;
314
+ /** Mappings whose target is outside the activated scope — reachable via rest_ref. */
315
+ out_of_scope: number;
316
+ /** Per target type: total vs served (exact; the sum closes). */
317
+ by_target_type: Record<string, {
318
+ total: number;
319
+ served: number;
320
+ derivable_elided: number;
321
+ out_of_scope: number;
322
+ }>;
323
+ rest_ref: {
324
+ tool: "resolve_entities";
325
+ with: string;
326
+ note_id: NoteId;
327
+ };
232
328
  }
233
329
  export interface CitationMapEntry {
234
330
  source: "runtime_v0" | "runtime_v1" | "overlay" | "manual" | "manual_rastreabilidade";
@@ -248,14 +344,8 @@ export interface CompletenessReport {
248
344
  unnamed_v1_entities: number;
249
345
  v1_consistency_mismatches: string[];
250
346
  v1_manifest_warnings: string[];
251
- /** Total evidence patterns matched before the relevance cap was applied. */
252
- evidence_patterns_total: number;
253
- /** Patterns retained in `g2_context.evidence_patterns` after the cap. */
254
- evidence_patterns_returned: number;
255
- /** Patterns dropped because of the cap (visible in debug.rejected_candidates). */
256
- evidence_patterns_capped: number;
257
- /** Cap value applied during this resolution. */
258
- evidence_pattern_cap: number;
347
+ /** 0.21 §1 — never-silent summary of the fused verification (see {@link VerificationSummary}). */
348
+ verification: VerificationSummary;
259
349
  /**
260
350
  * MP1 selection summary (G-mp1a O2, 2026-08-31): the requirement set comes from
261
351
  * the selection engine (baseline ∪ context-activated chapters, narrowed by the
@@ -268,7 +358,7 @@ export interface CompletenessReport {
268
358
  narrowed_out_categories: number;
269
359
  narrowed_out_requirements: number;
270
360
  /** Opcionais no perfil ultrathin (dieta s3c): a banda continua declarada no
271
- * select e nos perfis standard/minimal/full; recuperação via narrowed_out_ref. */
361
+ * select e em todos os níveis (0.21: lista/standard/full); recuperação via narrowed_out_ref. */
272
362
  excluded_by_level_categories?: number;
273
363
  excluded_by_level_requirements?: number;
274
364
  /** 0.19.0 (dieta por forma — tectos vigiam): fracção só-lexical da selecção; o
@@ -276,7 +366,49 @@ export interface CompletenessReport {
276
366
  lexical_share?: number;
277
367
  narrowed_out_ref: {
278
368
  tool: "select_sbd_toe_requirements";
279
- note: string;
369
+ note_id: NoteId;
370
+ };
371
+ };
372
+ }
373
+ /**
374
+ * 0.21 §1 — sumário NUNCA-SILENCIOSO da verificação fundida. Substitui os
375
+ * contadores do cap (total/returned/capped/cap) que morreram com o bloco.
376
+ * Cada número tem denominador nomeado; cada coisa que não vem inline tem a
377
+ * chamada executável que a devolve.
378
+ */
379
+ export interface VerificationSummary {
380
+ /** Denominator: activated requirements (= activated_scope.requirements.length). */
381
+ requirements: number;
382
+ /** Requirements carrying BOTH `verify` and `evidence` inline. */
383
+ with_verify_and_evidence: number;
384
+ /** Requirements whose published pattern lacks `verify` and/or `evidence` (expected 0 on KG v1.12.0). */
385
+ partial: number;
386
+ /** Requirements with NO published evidence pattern at all (expected 0 on KG v1.12.0). */
387
+ without_pattern: number;
388
+ /**
389
+ * Pattern fields NOT inlined in the fused requirement (evidence_pattern_id,
390
+ * control_id, expected_artifact_type_ids) — moved by reference: the
391
+ * verification matrix serves the full row per requirement (≤50 ids/call).
392
+ */
393
+ by_ref: {
394
+ tool: "get_sbd_toe_verification_matrix";
395
+ with: string;
396
+ /** Number of calls needed to cover every activated requirement (⌈requirements/50⌉). */
397
+ calls: number;
398
+ fields: ["evidence_pattern_id", "control_id", "expected_artifact_type_ids"];
399
+ note_id: NoteId;
400
+ };
401
+ /**
402
+ * Published patterns linked to an ACTIVATED control whose requirement is NOT
403
+ * in the activated set. Never inlined (they belong to other requirements);
404
+ * counted here and reachable by the executable ref.
405
+ */
406
+ related_by_control_outside_scope: {
407
+ count: number;
408
+ ref: {
409
+ tool: "resolve_entities";
410
+ with: string;
411
+ note_id: NoteId;
280
412
  };
281
413
  };
282
414
  }
@@ -284,7 +416,7 @@ export interface SecurityRationaleTemplate {
284
416
  task: string;
285
417
  decisions: Array<{
286
418
  decision: "<fill: what design choice was made>";
287
- rationale: "<fill: why, citing IDs from citation_map>";
419
+ rationale: "<fill: why, citing IDs from citations>";
288
420
  cited_ids: ["<requirement_id|control_id|slice_id|obligation_id>"];
289
421
  }>;
290
422
  validations: Array<{
@@ -301,6 +433,8 @@ export interface SecurityRationaleTemplate {
301
433
  }
302
434
  export interface PrepareCodegenContextResultReady {
303
435
  status: "ready_for_codegen";
436
+ /** 0.21 §6-c — como resolver qualquer `note_id` deste payload (um cabeçalho, não N notas). */
437
+ notes: typeof NOTES_HEADER;
304
438
  /** RF-H advisory band — adjacent tools the caller likely needs next. */
305
439
  next?: Affordance[];
306
440
  mode: CodegenMode;
@@ -309,6 +443,8 @@ export interface PrepareCodegenContextResultReady {
309
443
  };
310
444
  activation_trace: ActivationTraceEntry[];
311
445
  activated_scope: ActivatedScope;
446
+ /** 0.21 §2 — resumo + detalhe inline (full). */
447
+ adjacency: PrepareAdjacency;
312
448
  g2_context: G2Context;
313
449
  manual_grounding: ManualGroundingEntry[];
314
450
  regulatory_overlay: RegulatoryOverlayContext;
@@ -325,11 +461,46 @@ export interface PrepareCodegenContextResultReady {
325
461
  runtime_v1: string;
326
462
  overlay: string | "absent";
327
463
  };
464
+ /**
465
+ * 0.21 §5 — o preço DECLARADO desta resposta (chars e ≈tokens = chars/4, a
466
+ * mesma régua da medição). `full` não tem tecto: não promete caber, promete
467
+ * não faltar — e diz quanto custou. Presente em todos os níveis.
468
+ */
469
+ size_estimate?: DeclaredSize;
328
470
  debug?: {
329
471
  rejected_candidates: ActivationTraceEntry[];
330
472
  notes: string[];
331
473
  };
332
474
  }
475
+ /**
476
+ * 0.21 §5 — o preço declarado, e o envelope contra o qual se lê. `full` não
477
+ * tem envelope (promessa = completude). Nos níveis com envelope herdado
478
+ * (lista 8.450, standard 9.200) o payload diz se coube: `within_envelope`.
479
+ * Quando não coube, DIZ-O — nunca em silêncio (é a regra da casa desde a
480
+ * 0.19.4): o tecto por-id é o ratificado, mas o custo por requisito da forma
481
+ * fundida é o medido, e quando os dois não fecham o consumidor lê-o aqui.
482
+ */
483
+ export type DeclaredSize = SizeEstimate & {
484
+ envelope_tk?: number;
485
+ within_envelope?: boolean;
486
+ note_id?: NoteId;
487
+ };
488
+ export interface DecompositionBatch {
489
+ /** A receita EXECUTÁVEL: re-chama o prepare com estes campos (mais task, risk_level e detail). */
490
+ with: {
491
+ categories: string[];
492
+ technologies?: string[];
493
+ changed_files?: string[];
494
+ };
495
+ /** Contagem REAL do lote (selecção corrida), ≤ tecto por construção. */
496
+ requirements: number;
497
+ /** De onde vieram estas categorias na tua declaração: concerns e activadores largos (efeito preservado). */
498
+ derived_from: {
499
+ concerns: string[];
500
+ exposure?: string;
501
+ data_sensitivity?: string;
502
+ };
503
+ }
333
504
  export interface PrepareCodegenContextResultBlocked {
334
505
  status: "needs_clarification" | "needs_decomposition" | "unsupported_scope" | "needs_input";
335
506
  /**
@@ -352,13 +523,33 @@ export interface PrepareCodegenContextResultBlocked {
352
523
  cost_per_req_tk: number;
353
524
  projected_tk: number;
354
525
  promise_tk: number;
355
- batches: Array<{
356
- concerns: string[];
357
- estimated_requirements: number;
358
- }>;
526
+ /**
527
+ * 0.21 §6 (condição da decisão (a), lead 2026-09-25): os lotes SOMAM O TODO. Cada lote é
528
+ * uma declaração ESTRUTURAL (`categories` — a partição exacta das categorias que a tua
529
+ * declaração activou), com `technologies` e `changed_files` preservados literalmente;
530
+ * `exposure`/`data_sensitivity` estão preservados pelo seu EFEITO (as categorias que
531
+ * produziram entram na partição) e não re-declarados — re-declará-los somaria as suas
532
+ * categorias a todos os lotes e nenhum caberia. `requirements` é a contagem REAL do lote
533
+ * (a selecção corre-se), não uma estimativa; a união dos lotes ⊇ a selecção inteira.
534
+ */
535
+ batches: DecompositionBatch[];
536
+ /** Denominador da prova: união dos lotes vs selecção inteira (m_recall = 1 por construção; verificado nos testes). */
537
+ union: {
538
+ requirements: number;
539
+ recall: number;
540
+ };
359
541
  };
360
542
  /** RF-H advisory band — adjacent tools the caller likely needs next. */
361
543
  next?: Affordance[];
544
+ /**
545
+ * 0.21 §6 — em `needs_input`, o objecto do motor (razão, recurso do vocabulário, exemplo,
546
+ * candidatos a confirmar, declarações inertes) mais `valid_values`: para cada eixo que ficou
547
+ * inerte (stack/technologies, exposure, data_sensitivity), a LISTA dos valores válidos — o
548
+ * erro nomeia o vocabulário, não só o aponta.
549
+ */
550
+ needs_input?: Record<string, unknown> & {
551
+ valid_values?: Record<string, string[]>;
552
+ };
362
553
  mode: CodegenMode;
363
554
  input_echo: Required<Pick<PrepareCodegenContextInput, "task">> & Omit<PrepareCodegenContextInput, "task"> & {
364
555
  task_role?: string;
@@ -375,7 +566,7 @@ export interface PrepareCodegenContextResultBlocked {
375
566
  * provenance is carried once, in `provenance_legend`). */
376
567
  export type WithoutSource<T> = Omit<T, "source">;
377
568
  /**
378
- * Inverted citation encoding (replaces `citation_map` in `standard`/`minimal`).
569
+ * Inverted citation encoding (replaces `citation_map` in `lista`/`standard`).
379
570
  * Grouped by source; `source_data` is an ORDERED run-length map
380
571
  * `file → count`: the first N₁ citable ids come from the first file, the
381
572
  * next N₂ from the second, and so on. This preserves the exact per-id
@@ -448,17 +639,17 @@ export interface ManualGroundingMinimalGroup {
448
639
  * (kept verbatim from the standard group; expected never). */
449
640
  v1_entity_names?: Record<string, string>;
450
641
  }
451
- /** Executable reference to the full per-group grounding ids (s3b). */
452
- export interface GroundingGroupsRef {
642
+ /** Executable reference to the flat, verbatim grounding entries (detail="full"). */
643
+ export interface GroundingEntriesRef {
453
644
  tool: "prepare_sbd_toe_codegen_context";
454
- /** Merge over this call's input_echo: same input, detail="standard". */
645
+ /** Merge over this call's input_echo: same input, detail="full". */
455
646
  with: {
456
- detail: "standard";
647
+ detail: "full";
457
648
  };
458
- note: string;
649
+ note_id: NoteId;
459
650
  }
460
651
  /**
461
- * `manual_grounding` at `detail: "minimal"` (s3b revised): aggregated
652
+ * `manual_grounding` at `detail: "lista" | "standard"` (0.21; born as the s3b minimal form): aggregated
462
653
  * provenance — total count, the manual_commit_sha shared by every group
463
654
  * (hoisted), and the (role, chapter, file) group list with per-group entry
464
655
  * COUNTS instead of per-group id lists — plus the executable `groups_ref`.
@@ -474,13 +665,13 @@ export interface ManualGroundingMinimal {
474
665
  * its own `manual_commit_sha` inline (lossless guard). */
475
666
  manual_commit_sha?: string;
476
667
  groups: ManualGroundingMinimalGroup[];
477
- /** How to obtain the full per-group v1_entity_ids (detail="standard"). */
478
- groups_ref: GroundingGroupsRef;
668
+ /** 0.21: how to obtain the verbatim flat entries (detail="full" — the only level that inlines the grounding). */
669
+ entries_ref: GroundingEntriesRef;
479
670
  /** Lossless guard: entries without a v1_entity_id (expected empty). */
480
671
  ungrouped?: Array<WithoutSource<ManualGroundingEntry>>;
481
672
  }
482
673
  /**
483
- * `manual_grounding` at `detail: "ultrathin"` (s3c): aggregate provenance ONLY
674
+ * RETIRADO na 0.21 (era `manual_grounding` at `detail: "ultrathin"`): aggregate provenance ONLY
484
675
  * — `{total_entries, manual_commit_sha, groups_ref}` — derived from the s3b
485
676
  * minimal form with the (role, chapter, file) group list elided too. Never
486
677
  * silent: `total_entries` is the exact flat detail="full" entry count and
@@ -493,74 +684,27 @@ export interface ManualGroundingMinimal {
493
684
  * `citations`/`ids_from`, and the grounding id SET stays reconstructible from
494
685
  * this same payload's g2_context entity maps without any extra call.
495
686
  */
496
- export interface ManualGroundingUltrathin {
497
- /** Number of flat detail="full" entries the elided groups encode. */
498
- total_entries: number;
499
- /** Hoisted provenance (expected always: one published manual commit). */
500
- manual_commit_sha?: string;
501
- /** Lossless guard: present ONLY when hoisting failed or a group carried
502
- * v1_entity_names (never expected) — the s3b minimal groups, verbatim. */
503
- groups?: ManualGroundingMinimalGroup[];
504
- /** How to obtain the full per-group v1_entity_ids (detail="standard"). */
505
- groups_ref: GroundingGroupsRef;
506
- /** Lossless guard: entries without a v1_entity_id (expected empty). */
507
- ungrouped?: Array<WithoutSource<ManualGroundingEntry>>;
508
- }
509
687
  /**
510
- * v2 token diet, s3 — dieted requirement projection. `category` is elided when
511
- * (and only when) it equals the category segment of the `requirement_id` —
512
- * the segment immediately before the number (`AUT-003` → `AUT`,
513
- * `REQ-AGN-001` → `AGN`; consumer contract v1.10 §1.18, single source
514
- * `src/serving/requirement-id.ts`). True for all 255 published requirements;
515
- * the field survives verbatim on any future mismatch — lossless guard. `description` is the PUBLISHED bundle
516
- * field (data/publish/runtime/requirements.json), verbatim, never paraphrased
517
- * — the "how" the full projection historically dropped.
688
+ * 0.21 §1 — dieted requirement = the fused requirement without the per-item
689
+ * `source` (carried once in `provenance_legend`). `category` is elided when
690
+ * (and only when) it equals the id's category segment (`AUT-003` → `AUT`,
691
+ * `REQ-AGN-001` → `AGN`; consumer contract v1.10 §1.18) — lossless guard.
518
692
  */
519
- export interface DietedRequirement {
520
- requirement_id: string;
521
- name: string;
522
- type?: string;
523
- /** Present only on the (never expected) category ≠ id-category-segment mismatch. */
524
- category?: string;
525
- /** Verbatim `description` from the published bundle. */
526
- description?: string;
527
- }
693
+ export type DietedRequirement = WithoutSource<FusedRequirement>;
528
694
  /**
529
695
  * v2 token diet, s3 — dieted control projection: classic fields minus `source`
530
696
  * plus, for `confidence: "direct"` controls only, the verbatim published
531
697
  * `description` (data/publish/runtime/controls.json).
532
698
  */
533
- export type DietedControl = WithoutSource<ActivatedScope["controls"][number]> & {
534
- description?: string;
535
- };
536
- /**
537
- * v2 token diet, s3c — executable reference left in `activated_scope` at
538
- * `detail: "ultrathin"`, where the verbatim published `description` fields
539
- * (the "how", s3) are elided from requirements and direct controls. Never
540
- * silent: the lists themselves stay COMPLETE (same ids, same order, name
541
- * always present — nothing id-only); only the description field moves behind
542
- * this reference. detail="minimal" is the cheapest level that returns the
543
- * same complete scope WITH the descriptions (verbatim, never paraphrased).
544
- */
545
- export interface ActivatedScopeDescriptionsRef {
546
- tool: "prepare_sbd_toe_codegen_context";
547
- /** Merge over this call's input_echo: same input, detail="minimal". */
548
- with: {
549
- detail: "minimal";
550
- };
551
- note: string;
552
- }
699
+ export type DietedControl = WithoutSource<ActivatedScope["controls"][number]>;
553
700
  export interface DietedActivatedScope {
554
701
  requirements: DietedRequirement[];
555
702
  controls: DietedControl[];
556
703
  slices: Array<WithoutSource<ActivatedScope["slices"][number]>>;
557
704
  regulatory_obligations: Array<WithoutSource<ActivatedScope["regulatory_obligations"][number]>>;
558
- /** Present ONLY at detail="ultrathin" (s3c): how to obtain the verbatim
559
- * published descriptions elided from requirements + direct controls. */
560
- descriptions_ref?: ActivatedScopeDescriptionsRef;
561
705
  }
562
706
  /**
563
- * v2 token diet, s2 — Relations on-demand. In `standard`/`minimal` the inline
707
+ * v2 token diet, s2 — Relations on-demand. In `lista`/`standard` the inline
564
708
  * `g2_context.relations` array (~4.3K tokens) is replaced by a REFERENCE to
565
709
  * executable calls of the `trace_sbd_toe_graph` tool whose union returns a
566
710
  * superset of the elided relations. Anchors are activated slice_ids/entity_ids
@@ -610,10 +754,10 @@ export interface RelationsRef {
610
754
  };
611
755
  /** Only present when a relation is neither lens-recoverable nor implicit. */
612
756
  residual_relations?: Array<WithoutSource<G2ContextRelation>>;
613
- note: string;
757
+ note_id: NoteId;
614
758
  }
615
759
  /**
616
- * v2 token diet, s3 — slice-grouped entity encoding for `standard`/`minimal`:
760
+ * v2 token diet, s3 — slice-grouped entity encoding for `lista`/`standard`:
617
761
  * `{ slice_id: { entity_id: name | null } }`. Lossless re-encoding of the
618
762
  * classic entity list: `entity_type` is the list the map lives in,
619
763
  * `slice_id` is the group key, `slice_family` is
@@ -622,13 +766,6 @@ export interface RelationsRef {
622
766
  * Group/key order preserves the classic list order (insertion order).
623
767
  */
624
768
  export type SliceGroupedEntityNames = Record<string, Record<string, string | null>>;
625
- /**
626
- * v2 token diet, s3 — dieted evidence pattern: classic projection minus
627
- * `source` (s1 legend) and minus the tool-computed `relevance_score` (the
628
- * DETERMINISTIC list order — relevance_score desc, then id asc — already
629
- * carries the ranking; documented in the codegen-instructions resource).
630
- */
631
- export type DietedEvidencePattern = Omit<G2ContextEvidencePattern, "source" | "relevance_score">;
632
769
  export interface DietedG2Context {
633
770
  control_objectives: SliceGroupedEntityNames;
634
771
  mechanisms: SliceGroupedEntityNames;
@@ -636,55 +773,68 @@ export interface DietedG2Context {
636
773
  artifacts: SliceGroupedEntityNames;
637
774
  /** Inline only with `include_relations: true` (s2); otherwise see relations_ref. */
638
775
  relations?: Array<WithoutSource<G2ContextRelation>>;
639
- /** Present when relations are elided (s2 default at standard/minimal). */
640
- relations_ref?: RelationsRef;
641
- /** s3: deterministic top-{@link STANDARD_EVIDENCE_PATTERN_CAP} prefix of the
642
- * classic list (see completeness_report for the never-silent counts). */
643
- evidence_patterns: DietedEvidencePattern[];
776
+ /** 0.21 §3: relations LEAVE the dieted levels — this never-silent summary replaces relations_ref
777
+ * (0 of the relations point outside what the payload already carries in the measured cases;
778
+ * any that cannot be recovered from the payload or a lens stays inline in residual_relations). */
779
+ relations_summary?: RelationsSummary;
780
+ /** Only present when a relation is neither lens-recoverable nor implicit (expected 0). */
781
+ residual_relations?: Array<WithoutSource<G2ContextRelation>>;
644
782
  }
783
+ /**
784
+ * 0.21 §3 — «relations saem» dos níveis dieted: medido, as relações activadas
785
+ * ligam nós que o payload JÁ recebeu (belongsToSlice ≡ slice_id da entidade;
786
+ * objective→mechanism/practice recuperável por trace_sbd_toe_graph). Fica a
787
+ * contabilidade exacta (a mesma do relations_ref do full) e o caminho de volta.
788
+ */
789
+ export interface RelationsSummary {
790
+ total_relations: number;
791
+ via_lenses: number;
792
+ implicit_in_entities: number;
793
+ residual_inline: number;
794
+ note_id: NoteId;
795
+ }
796
+ /**
797
+ * 0.21 §3 — o `full` SERVIDO: o classic com duas mudanças de forma, sem mudança
798
+ * de conjunto (invariante 3): `citations` invertido (legenda por fonte + ids
799
+ * referenciados por caminho do payload — a função de `citation_map` era «estes
800
+ * ids são legais», e a forma repetia {source, source_data} uma vez por id) e
801
+ * `relations_ref` em vez das relations inline (`include_relations: true`
802
+ * repõe-nas). O core continua a construir citation_map/relations internamente.
803
+ */
804
+ export type PrepareCodegenContextResultReadyFull = Omit<PrepareCodegenContextResultReady, "citation_map" | "g2_context"> & {
805
+ citations: CitationsBySource;
806
+ g2_context: Omit<G2Context, "relations"> & {
807
+ /** Inline only with `include_relations: true`. */
808
+ relations?: G2ContextRelation[];
809
+ /** Default at full: executable trace_sbd_toe_graph calls + exact coverage accounting. */
810
+ relations_ref?: RelationsRef;
811
+ };
812
+ };
645
813
  export interface DietedRegulatoryOverlayContext {
646
814
  frameworks: Array<WithoutSource<RegulatoryOverlayContext["frameworks"][number]>>;
647
815
  obligations: Array<WithoutSource<RegulatoryOverlayContext["obligations"][number]>>;
648
816
  mappings: Array<WithoutSource<RegulatoryOverlayContext["mappings"][number]>>;
649
817
  playbooks: Array<WithoutSource<RegulatoryOverlayContext["playbooks"][number]>>;
818
+ mappings_scope?: OverlayMappingsScope;
650
819
  }
651
820
  /**
652
- * Inline legend for `standard`/`minimal` (s3: slim pointer — the full legend,
653
- * including the section→source table and every derivation rule of the dieted
654
- * encoding, lives in the `sbd://toe/codegen-instructions/{mode}` resource,
655
- * section `detail_encoding`).
821
+ * Inline legend for `lista`/`standard` (0.21): slim pointer — the full legend
822
+ * (section→source table + every derivation rule of the dieted encoding) lives
823
+ * in the `sbd://toe/codegen-instructions/{mode}` resource, `detail_encoding`.
656
824
  */
657
825
  declare const PROVENANCE_LEGEND: {
658
- readonly note: string;
826
+ readonly note_id: NoteId;
659
827
  };
660
828
  export type ProvenanceLegend = typeof PROVENANCE_LEGEND;
661
829
  /**
662
- * v2 token diet, s4 — cheap turns, not fewer turns: short note (≈50 tokens)
663
- * appended to every `standard`/`minimal` ready payload. The production
664
- * write-test-edit loop is legitimate; what must not repeat is the cost of
665
- * re-requesting THIS payload — an identical call returns a byte-identical
666
- * result (deterministic, tested), so the context already in the session is
667
- * the source for the loop. Follow-ups that genuinely need more go through
668
- * `detail: "minimal"` or a targeted `consult_security_requirements` call —
669
- * never a repeat of the full payload. `full` carries NO hint (byte-identical
670
- * to the classic payload, EPIC invariant 1).
671
- */
672
- export declare const REPEAT_CALL_HINT = "Identical input returns this exact payload (deterministic) \u2014 reuse the context already received; deepen via detail:'minimal' or a targeted consult_security_requirements.";
673
- /**
674
- * v2 token diet, s3 — reference that replaces the inline
675
- * `llm_codegen_instructions` + `security_rationale_template` boilerplate at
676
- * `detail: "standard" | "minimal"` (both stay inline at `full`). The MCP
677
- * resource carries, per mode, the exact instruction slots and the template
678
- * skeleton; `active_conditions` lists which conditional slots apply to THIS
679
- * call, so the inline full content is reconstructible byte-identically.
830
+ * v2 token diet, s4 — cheap turns, not fewer turns: short note appended to
831
+ * every `lista`/`standard` ready payload. An identical call returns a
832
+ * byte-identical result (deterministic, tested), so the context already in the
833
+ * session is the source for the write-test-edit loop. Follow-ups that need the
834
+ * inline grounding/relations/trace go through `detail: "full"` (declared
835
+ * price in size_estimate) or a targeted `consult_security_requirements` call.
680
836
  */
681
- export interface CodegenInstructionsRef {
682
- resource: string;
683
- /** Conditional instruction slots active for this call (see the resource's
684
- * `llm_codegen_instructions.slots[].when`). */
685
- active_conditions: InstructionCondition[];
686
- note: string;
687
- }
837
+ export declare const REPEAT_CALL_HINT: string;
688
838
  /**
689
839
  * v2 token diet, s3 — never-silent counter left in place of the elided
690
840
  * `activation_trace` at `detail: "standard" | "minimal"` (the full trace is
@@ -692,107 +842,27 @@ export interface CodegenInstructionsRef {
692
842
  */
693
843
  export interface ActivationTraceRef {
694
844
  entries: number;
695
- note: string;
696
- }
697
- /**
698
- * v2 token diet, s3 — executable reference for retrieving the evidence
699
- * patterns omitted by the standard cap (boundList discipline: the counts live
700
- * in the same completeness_report; this says HOW to get the rest).
701
- */
702
- export interface EvidencePatternsRest {
703
- tool: "prepare_sbd_toe_codegen_context";
704
- /** Merge over this call's input_echo: same input, detail="full" (the
705
- * classic top-25) at standard/minimal; detail="minimal" (the CHEAPEST level
706
- * that returns patterns inline) at ultrathin (s3c). */
707
- with: {
708
- detail: "full";
709
- } | {
710
- detail: "minimal";
711
- };
712
- note: string;
713
- }
714
- /** Completeness report at `standard`/`minimal`: classic counters (with the
715
- * s3 cap values) plus, when patterns were cut, the executable rest-reference. */
716
- export type DietedCompletenessReport = CompletenessReport & {
717
- evidence_patterns_rest?: EvidencePatternsRest;
718
- };
719
- /**
720
- * v2 token diet, s3c — executable reference for the completeness diagnostics
721
- * elided at `detail: "ultrathin"` (never silent: exact counts stay inline;
722
- * detail="minimal" is the cheapest level whose completeness_report carries
723
- * the full text arrays inline).
724
- */
725
- export interface V1DiagnosticsRef {
726
- tool: "prepare_sbd_toe_codegen_context";
727
- /** Merge over this call's input_echo: same input, detail="minimal". */
728
- with: {
729
- detail: "minimal";
730
- };
731
- note: string;
845
+ note_id: NoteId;
732
846
  }
733
847
  /**
734
- * Completeness report at `detail: "ultrathin"` (s3c) — trimmed to the
735
- * essentials that support the never-silent discipline. KEPT verbatim: every
736
- * expected/returned count and m_recall (recall audit), named/unnamed entity
737
- * counts, and the evidence counts (total / returned=0 / capped=total / cap=0)
738
- * with the executable `evidence_patterns_rest`. CUT (serialization only, each
739
- * replaced by its exact count + the executable `v1_diagnostics_ref` when any
740
- * count > 0): the `v1_consistency_mismatches` and `v1_manifest_warnings` TEXT
741
- * arrays (the verbose per-slice contract-warning strings, ~100 tokens/call).
742
- */
743
- export type UltrathinCompletenessReport = Omit<DietedCompletenessReport, "v1_consistency_mismatches" | "v1_manifest_warnings"> & {
744
- /** Exact length of the elided v1_consistency_mismatches array (expected 0). */
745
- v1_consistency_mismatches_count: number;
746
- /** Exact length of the elided v1_manifest_warnings array. */
747
- v1_manifest_warnings_count: number;
748
- /** Present iff either count above is > 0: how to obtain the full texts. */
749
- v1_diagnostics_ref?: V1DiagnosticsRef;
750
- };
751
- /**
752
- * `ready_for_codegen` result at `detail: "standard" | "minimal"`. Same citable
753
- * ID set as the full result (invariant 3) — the encoding is deduplicated (s1),
754
- * relations are served on-demand (s2) and, since s3:
755
- * - `g2_context.evidence_patterns` is capped 25→10 (deterministic prefix;
756
- * never-silent counts + rest-reference in `completeness_report`);
757
- * - `llm_codegen_instructions` + `security_rationale_template` move to the
758
- * `sbd://toe/codegen-instructions/{mode}` MCP resource
759
- * (`codegen_instructions_ref` carries the URI + active conditions);
848
+ * `ready_for_codegen` result at `detail: "lista" | "standard"` (0.21). Same
849
+ * citable ID set as the full result (invariant 3) — the encoding is
850
+ * deduplicated (s1), relations are served on-demand (s2), and since 0.21 §1:
851
+ * - every requirement is the FUSED object (id, name, type, description,
852
+ * verify, evidence) — the description never leaves;
853
+ * - `llm_codegen_instructions` + `security_rationale_template` are INLINE
854
+ * (they are what stops id invention);
855
+ * - `manual_grounding` is the counts+sha form with an executable
856
+ * `entries_ref` → detail="full" (the only level that inlines it);
760
857
  * - `activation_trace` is included only with `debug: true`
761
- * (`activation_trace_ref` keeps the never-silent count otherwise);
762
- * - requirements and `direct` controls carry the verbatim published
763
- * `description` (the "how"), and derivable fields (`category`,
764
- * `entity_type`, `slice_family`, `relevance_score`, repeated citation ids)
765
- * are elided per the resource's `detail_encoding` legend.
766
- *
767
- * s3b (revised per the 2026-07-05 operator ADENDA — NO top-N/subsetting):
768
- * `minimal` diverges from `standard` ONLY in serialization of traceability,
769
- * never in execution context. The activated scope (requirements + controls
770
- * with descriptions, slices, obligations, g2 entities, citations,
771
- * relations_ref) is byte-identical to `standard`; `minimal` additionally
772
- * - caps `g2_context.evidence_patterns` 10→5 (same s3 mechanism: prefix,
773
- * counts, rest-ref);
774
- * - serves `manual_grounding` in the minimal form ({@link
775
- * ManualGroundingMinimal}: counts + hoisted sha + executable groups_ref).
776
- *
777
- * s3c (`detail: "ultrathin"`, operator ADENDA 2026-07-05): one level below
778
- * `minimal`, same rules (activated set COMPLETE, no top-k, nothing id-only,
779
- * never silent). Diverges from `minimal` ONLY in:
780
- * - requirements/controls WITHOUT the published `description` (fields kept:
781
- * requirement {requirement_id, name, type}; control {control_id, name,
782
- * domain, control_type, confidence}; the `category` lossless guard is
783
- * unchanged) + executable `activated_scope.descriptions_ref`;
784
- * - `g2_context.evidence_patterns` cap 5→0 (counts + rest-ref to the
785
- * cheapest level that returns them: detail="minimal");
786
- * - `manual_grounding` in the ultrathin form ({@link ManualGroundingUltrathin}:
787
- * total + hoisted sha + executable groups_ref, group list elided);
788
- * - `completeness_report` diagnostics trimmed ({@link
789
- * UltrathinCompletenessReport}: text arrays → exact counts + executable ref).
790
- * Everything else — g2 entity maps (id→name|null), relations_ref, citations,
791
- * codegen_instructions_ref, repeat_call_hint, provenance, next — is
792
- * byte-identical to the other dieted levels.
858
+ * (`activation_trace_ref` keeps the never-silent count otherwise).
859
+ * `lista` and `standard` differ only in the echoed level until the §2
860
+ * adjacency detail lands (declared, not decided: see decisions/0003 §6.2).
793
861
  */
794
862
  export interface PrepareCodegenContextResultReadyDieted {
795
863
  status: "ready_for_codegen";
864
+ /** 0.21 §6-c — como resolver qualquer `note_id` deste payload. */
865
+ notes: typeof NOTES_HEADER;
796
866
  /** RF-H advisory band — adjacent tools the caller likely needs next. */
797
867
  next?: Affordance[];
798
868
  mode: CodegenMode;
@@ -803,20 +873,27 @@ export interface PrepareCodegenContextResultReadyDieted {
803
873
  activation_trace_ref?: ActivationTraceRef;
804
874
  provenance_legend: ProvenanceLegend;
805
875
  activated_scope: DietedActivatedScope;
876
+ /** 0.21 §2 — resumo inline sempre; detalhe inline (standard) ou por referência (lista). */
877
+ adjacency: PrepareAdjacency;
806
878
  g2_context: DietedG2Context;
807
- /** Grouped (standard), minimal (s3b) or ultrathin form (s3c). */
808
- manual_grounding: ManualGroundingGrouped | ManualGroundingMinimal | ManualGroundingUltrathin;
879
+ /** Counts + hoisted sha + executable entries_ref (detail="full"). */
880
+ manual_grounding: ManualGroundingMinimal;
809
881
  regulatory_overlay: DietedRegulatoryOverlayContext;
810
882
  citations: CitationsBySource;
811
- completeness_report: DietedCompletenessReport | UltrathinCompletenessReport;
812
- codegen_instructions_ref: CodegenInstructionsRef;
813
- /** s4 — reuse note ({@link REPEAT_CALL_HINT}): identical re-call is
883
+ completeness_report: CompletenessReport;
884
+ llm_codegen_instructions: string[];
885
+ security_rationale_template: SecurityRationaleTemplate;
886
+ /** s4 — reuse note (texto em sbd://toe/notes/prepare.repeat_call_hint): identical re-call is
814
887
  * deterministic; the context already received is the loop's source. */
815
- repeat_call_hint: string;
888
+ repeat_call_hint: {
889
+ note_id: NoteId;
890
+ };
816
891
  provenance: PrepareCodegenContextResultReady["provenance"];
892
+ /** 0.21 §5 — declared price of this response (chars, ≈tokens, envelope). */
893
+ size_estimate?: DeclaredSize;
817
894
  debug?: PrepareCodegenContextResultReady["debug"];
818
895
  }
819
- export type PrepareCodegenContextResult = PrepareCodegenContextResultReady | PrepareCodegenContextResultReadyDieted | PrepareCodegenContextResultBlocked;
896
+ export type PrepareCodegenContextResult = PrepareCodegenContextResultReadyFull | PrepareCodegenContextResultReadyDieted | PrepareCodegenContextResultBlocked;
820
897
  export declare const VALID_CONCERNS: readonly ["auth", "logging", "validation", "api", "config", "integrity", "distribution", "ide", "requirements", "architecture", "iac", "encryption", "secrets", "build", "supply_chain", "testing", "threat_modeling", "monitoring", "release", "deployment", "integration", "files", "privacy", "agents"];
821
898
  export type Concern = (typeof VALID_CONCERNS)[number];
822
899
  /**
@@ -880,7 +957,7 @@ export declare function categoriesForConcerns(concerns: Concern[]): Set<string>;
880
957
  * lists the conditions active for a given call, so a client reading the
881
958
  * resource reconstructs the inline instruction list byte-identically.
882
959
  */
883
- export type InstructionCondition = "always" | "regulatory_overlay" | "risk_level:L1" | "risk_level:L2" | "risk_level:L3" | "citation_map_empty";
960
+ export type InstructionCondition = "always" | "regulatory_overlay" | "risk_level:L1" | "risk_level:L2" | "risk_level:L3" | "citations_empty";
884
961
  export interface InstructionSlot {
885
962
  when: InstructionCondition;
886
963
  text: string;
@@ -895,14 +972,16 @@ export declare const CODEGEN_INSTRUCTION_MODES: readonly CodegenMode[];
895
972
  export declare const CODEGEN_INSTRUCTIONS_RESOURCE_URI_PREFIX = "sbd://toe/codegen-instructions/";
896
973
  export declare function codegenInstructionsResourceUri(mode: CodegenMode): string;
897
974
  /**
898
- * Full legend of the dieted (`standard`/`minimal`) encoding, published in the
975
+ * Full legend of the dieted (`lista`/`standard`) encoding, published in the
899
976
  * codegen-instructions resource. Every rule here is a lossless, deterministic
900
977
  * derivation over the SAME payload (or an executable reference) — nothing is
901
978
  * silently dropped (EPIC invariant 2) and no data changes, only serialization
902
- * (EPIC invariant 4).
979
+ * (EPIC invariant 4). 0.21 §1: the requirement is fused (description never
980
+ * leaves) and the evidence_patterns block is gone at every level.
903
981
  */
904
982
  declare const DETAIL_ENCODING_LEGEND: {
905
983
  readonly note: string;
984
+ readonly levels: string;
906
985
  readonly sources: {
907
986
  readonly note: string;
908
987
  readonly map: {
@@ -915,7 +994,6 @@ declare const DETAIL_ENCODING_LEGEND: {
915
994
  readonly "g2_context.practices": "runtime_v1";
916
995
  readonly "g2_context.artifacts": "runtime_v1";
917
996
  readonly "g2_context.relations": "runtime_v1";
918
- readonly "g2_context.evidence_patterns": "runtime_v0";
919
997
  readonly "manual_grounding.groups": "runtime_v1";
920
998
  readonly "regulatory_overlay.frameworks": "overlay";
921
999
  readonly "regulatory_overlay.obligations": "overlay";
@@ -926,12 +1004,12 @@ declare const DETAIL_ENCODING_LEGEND: {
926
1004
  readonly citations: string;
927
1005
  readonly activated_scope_requirements: string;
928
1006
  readonly activated_scope_controls: string;
1007
+ readonly adjacency: string;
929
1008
  readonly g2_entities: string;
930
- readonly evidence_patterns: string;
931
- readonly manual_grounding_minimal: string;
1009
+ readonly verification: string;
1010
+ readonly manual_grounding: string;
932
1011
  readonly activation_trace: string;
933
1012
  readonly relations_ref: string;
934
- readonly ultrathin: string;
935
1013
  };
936
1014
  export interface CodegenInstructionsResourceContent {
937
1015
  resource: string;
@@ -961,6 +1039,25 @@ export interface CodegenInstructionsResourceContent {
961
1039
  * task string (input_echo.task.trim()).
962
1040
  */
963
1041
  export declare function buildCodegenInstructionsResourceContent(mode: CodegenMode): CodegenInstructionsResourceContent;
1042
+ /**
1043
+ * 0.21 §3 — resolve the ids of a `citations` block over the payload that carries it
1044
+ * (any level): `section.list[].field` iterates a list; `keys(g2_context.<list>[slice])`
1045
+ * iterates the slice groups then the entity-id keys. Explicit `ids` is the lossless
1046
+ * fallback. Exported so consumers and tests read ids by the SAME published rule.
1047
+ */
1048
+ export declare function citableIds(payload: unknown): string[];
1049
+ /**
1050
+ * 0.21 — a forma por nível é uma TABELA, não ramos: o que cada nível põe
1051
+ * inline e o que põe por referência. Parametrizável de propósito — a §4 do
1052
+ * despacho (o Mensor mede se o `manual_grounding` vai inline ou por
1053
+ * referência) e o «2 ou 3 níveis» ficam em aberto e decidem-se aqui, numa
1054
+ * linha, sem reescrever o servidor.
1055
+ */
1056
+ export declare const LEVEL_FORM: Readonly<Record<Exclude<CodegenDetailLevel, "full">, {
1057
+ manual_grounding: "ref";
1058
+ relations: "ref";
1059
+ adjacency_detail: "ref" | "inline";
1060
+ }>>;
964
1061
  export declare function handlePrepareCodegenContext(raw: PrepareCodegenContextInput): PrepareCodegenContextResult;
965
1062
  export declare const __wp5Lexicon: {
966
1063
  VALID_CONCERNS: readonly ["auth", "logging", "validation", "api", "config", "integrity", "distribution", "ide", "requirements", "architecture", "iac", "encryption", "secrets", "build", "supply_chain", "testing", "threat_modeling", "monitoring", "release", "deployment", "integration", "files", "privacy", "agents"];