@semacode/cli 4.2.8 → 4.2.10

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.
@@ -217,6 +217,8 @@ export function renderizarDocumentoAgentesPorCapacidade(agentContextPack) {
217
217
  "points back to the applicable contract. The marker is not a substitute for",
218
218
  "validation, drift, impact, or finalization gates.",
219
219
  "",
220
+ "Historical migrations (including Prisma migrations/<timestamp>_<name>/migration.sql) retain their SQL bytes and contract links. Do not add headers, reformat SQL or remove a binding just to pass a gate. The path proves neither application nor checksum: check the project runbook and database migration history. Change behavior through a new migration and current schema/code bindings, preserving relevant historical references.",
221
+ "",
220
222
  "Generated Lua tests preserve the contract's failure shape. A case whose only",
221
223
  "expectation is `sucesso: falso` may terminate without an output, while a case",
222
224
  "that also declares observable output fields must return a structured failure",
@@ -260,451 +262,455 @@ export function renderizarDocumentoAgentesPorCapacidade(agentContextPack) {
260
262
  ].join("\n") + "\n";
261
263
  }
262
264
  function renderizarDocSintaxeSemaLocal(_agentContextPack) {
263
- return `# Sema Syntax for Codex
264
-
265
- Use this file as a compact reference before creating or fixing \`.sema\` contracts.
266
-
267
- ## Golden Rule
268
-
269
- Contract comes before code. Before writing \`.sema\`, read the local examples in \`exemplos/\`.
270
-
271
- ## Minimal Example
272
-
273
- \`\`\`sema
274
- module app.example {
275
- entity Item {
276
- fields {
277
- id: Id
278
- name: Texto
279
- active: Booleano
280
- }
281
- }
282
-
283
- task create_item {
284
- input {
285
- name: Texto required
286
- }
287
- output {
288
- item: Item
289
- }
290
- rules {
291
- name deve_ser preenchido
292
- }
293
- effects {
294
- persistencia Item
295
- auditoria item_created
296
- }
297
- guarantees {
298
- item existe
299
- }
300
- impl { js: app.createItem }
301
- vinculos {
302
- arquivo: "app.js"
303
- simbolo: app.createItem
304
- }
305
- tests {
306
- caso "creates valid item" {
307
- given { name: "Item" }
308
- expect { sucesso: verdadeiro }
309
- }
310
- }
311
- }
312
- }
313
- \`\`\`
314
-
315
- Plan the task-to-function and task-to-file mapping when creating the contract.
316
- These references are pending until implementation exists; confirm them with fresh drift.
317
- An implementation identifier is a symbol, not a filename. Put \`impl\` inside the
318
- task, never at module level. Link shared HTML/CSS with module-level
319
- \`vinculos { arquivo: "index.html" arquivo: "style.css" }\`; do not invent JavaScript
320
- implementations for assets. A \`SEMA-GOVERNED\` header identifies the owning contract
321
- but does not replace these mappings. Multiple tasks can reference the same file.
322
-
323
- ## Enums and Module Boundaries
324
-
325
- \`enum Filtro { todas, pendentes, concluidas }\` is valid. Do not wrap values in
326
- \`valores { ... }\`. Each file contains one module, with all declarations inside it.
327
- Malformed enums, trailing declarations, duplicate mapping blocks and arrow-style
328
- bindings are errors with a location and repair hint. Fix them before using counts
329
- from a recovered AST. An entity-only module may legitimately have no tasks.
330
-
331
- ## Test Values
332
-
333
- Lists and objects are field values inside \`given\`, \`when\`, \`expect\` or \`error\`.
334
- They may span lines and contain nested objects, lists, strings and booleans:
335
-
336
- \`\`\`sema
337
- tests {
338
- caso "filters pending tasks" {
339
- given {
340
- tarefas: [
341
- { id: "t1", concluida: falso },
342
- { id: "t2", concluida: verdadeiro }
343
- ]
344
- }
345
- expect { tarefas: [{ id: "t1", concluida: falso }] }
346
- }
347
- }
348
- \`\`\`
349
-
350
- Place this fragment inside a task. Keep closing delimiters balanced. \`PAR009\`
351
- points to a malformed literal; fix it before removing unrelated routes or tasks.
352
- Formatting preserves compound values and quoted text, including spaces.
353
-
354
- ## Common Blocks
355
-
356
- - \`docs\`: module summary and notes.
357
- - \`entity\`: domain model.
358
- - \`task\`: governed operation.
359
- - \`input\` and \`output\`: input and output contracts.
360
- - \`rules\`: validations and business rules.
361
- - \`effects\`: persistence, reads, events, audit, and external calls.
362
- - \`guarantees\`: what the task must provide after success.
363
- - \`error\`: named errors and messages.
364
- - \`tests\`: minimal behavior examples.
365
- - \`route\`: public surface linked to a task.
366
- - \`impl\` and \`vinculos\`: links between the contract and real code.
367
-
368
- ## Canonical \`use\` and \`impl\` Origins
369
-
370
- Use these origins before inventing a new one (aliases after \`ou\`):
371
-
372
- - \`ts\` ou \`typescript\`
373
- - \`js\` ou \`javascript\`
374
- - \`py\` ou \`python\`
375
- - \`dart\`
376
- - \`lua\`
377
- - \`cs\`, \`csharp\` ou \`dotnet\`
378
- - \`java\`
379
- - \`go\` ou \`golang\`
380
- - \`rust\` ou \`rs\`
381
- - \`cpp\`, \`cxx\`, \`cc\` ou \`c++\`
382
- - \`php\`
383
-
384
- Examples:
385
-
386
- \`\`\`sema
387
- use javascript app.web.expenses
388
-
389
- impl {
390
- js: src.app.saveExpense
391
- }
392
- \`\`\`
393
-
394
- \`\`\`sema
395
- use php app.legacy.pedidos
396
-
397
- impl {
398
- php: pedidos.criarPedido
399
- }
400
- \`\`\`
401
-
402
- \`sema compilar --alvo javascript\` defines a generation target. \`impl { js: ... }\` defines the live-code origin linked to the contract. They are different layers and both are valid.
403
-
404
- ## Layered \`impl\` Roles
405
-
406
- Layered code (route + service + persistence in the same language) can declare one \`impl\` per role. Append a supported role to any origin: \`rota\`, \`servico\`, \`persistencia\` or \`repositorio\`.
407
-
408
- \`\`\`sema
409
- impl {
410
- ts_rota: server.routes.monitores.criarMonitor
411
- ts_servico: server.services.monitores.criarMonitor
412
- ts_persistencia: server.repositories.monitores.criar
413
- }
414
- \`\`\`
415
-
416
- The role suffix combines with every origin, not only TypeScript:
417
-
418
- \`\`\`sema
419
- impl {
420
- php_rota: pedidos.rota.criarPedido
421
- php_servico: pedidos.servico.criarPedido
422
- php_persistencia: pedidos.repositorio.criar
423
- }
424
- \`\`\`
425
-
426
- Each origin-plus-role pair must appear at most once; the bare origin (for example \`ts\`) stays valid for single-layer tasks, and drift resolves every role independently.
427
-
428
- ## Small Canonical Lists
429
-
430
- - \`effects\`: \`persistencia\`, \`consulta\`, \`evento\`, \`auditoria\`, \`db.write\`, \`queue.publish\`, \`fs.write\`, \`network.egress\`, \`secret.read\`, \`shell.exec\`.
431
- - \`audit.motivo\`: \`obrigatorio\`, \`opcional\`, \`dispensado\`.
432
-
433
- ## Contract Size
434
-
435
- - up to ${LIMITE_AVISO_LINHAS_CONTRATO_SEMA} lines: healthy
436
- - ${LIMITE_AVISO_LINHAS_CONTRATO_SEMA + 1}-${LIMITE_BLOQUEIO_LINHAS_CONTRATO_SEMA} lines: diagnostic warning, plan a split
437
- - above ${LIMITE_BLOQUEIO_LINHAS_CONTRATO_SEMA}: blocks creation, edits, drift, finalization, generation, and snapshots
438
- - split by real domain/capability, such as \`expenses_entry.sema\`, \`expenses_totals.sema\`, \`expenses_persistence.sema\`
439
- - never use \`parte_1\`, \`parte_2\`, \`part_3\`, or equivalent names
440
- - do not remove \`guarantees\`, \`tests\`, \`authz\`, \`dados\`, or \`vinculos\` just to fit under the limit
441
- - multiple \`.sema\` contracts may govern the same code file through \`vinculos\`; this is expected
442
-
443
- ## JavaScript Is Supported
444
-
445
- The CLI supports JavaScript generation:
446
-
447
- \`\`\`bash
448
- sema compilar contratos/orders.sema --alvo javascript --saida ./generated/javascript
449
- \`\`\`
450
-
451
- The project can also generate TypeScript, Python, PHP, Dart, Lua, HTML, CSS, C#/.NET (\`dotnet\`), and C++ (\`cpp\`) when those targets are enabled in \`sema.config.json\`.
452
-
453
- ## Support Files
454
-
455
- - \`AGENTS.md\`: official Codex repository rules, loaded automatically.
456
- - \`${ARQUIVO_SEMA_BOOT}\`: first Sema read for Codex.
457
- - Profile-selected summary: the CLI materializes only the matching file within the configured budget. Skip it if the session already supplied the needed context.
458
- - \`${ARQUIVO_AGENT_CONTEXT_PACK}\`: internal CLI policy database, not an initial read.
459
- - \`SEMA_INDEX.json\`: internal CLI project index, not an initial read.
460
- - \`docs/commands.md\`: command catalog, gates, and \`--saida\` rule.
461
- - \`exemplos/\`: official DSL examples.
462
-
463
- If Codex does not know which shape to use, it must open \`exemplos/calculadora.sema\`, \`exemplos/crud_simples.sema\`, \`exemplos/pagamento.sema\`, or \`exemplos/tratamento_erro.sema\` before inventing syntax.
464
-
465
- Platform policy: Sema governs project contracts, scope, drift, evidence, and quality. It never bypasses platform policies, permissions, security controls, terms, or laws.
265
+ return `# Sema Syntax for Codex
266
+
267
+ Use this file as a compact reference before creating or fixing \`.sema\` contracts.
268
+
269
+ ## Golden Rule
270
+
271
+ Contract comes before code. Before writing \`.sema\`, read the local examples in \`exemplos/\`.
272
+
273
+ ## Minimal Example
274
+
275
+ \`\`\`sema
276
+ module app.example {
277
+ entity Item {
278
+ fields {
279
+ id: Id
280
+ name: Texto
281
+ active: Booleano
282
+ }
283
+ }
284
+
285
+ task create_item {
286
+ input {
287
+ name: Texto required
288
+ }
289
+ output {
290
+ item: Item
291
+ }
292
+ rules {
293
+ name deve_ser preenchido
294
+ }
295
+ effects {
296
+ persistencia Item
297
+ auditoria item_created
298
+ }
299
+ guarantees {
300
+ item existe
301
+ }
302
+ impl { js: app.createItem }
303
+ vinculos {
304
+ arquivo: "app.js"
305
+ simbolo: app.createItem
306
+ }
307
+ tests {
308
+ caso "creates valid item" {
309
+ given { name: "Item" }
310
+ expect { sucesso: verdadeiro }
311
+ }
312
+ }
313
+ }
314
+ }
315
+ \`\`\`
316
+
317
+ Plan the task-to-function and task-to-file mapping when creating the contract.
318
+ These references are pending until implementation exists; confirm them with fresh drift.
319
+ An implementation identifier is a symbol, not a filename. Put \`impl\` inside the
320
+ task, never at module level. Link shared HTML/CSS with module-level
321
+ \`vinculos { arquivo: "index.html" arquivo: "style.css" }\`; do not invent JavaScript
322
+ implementations for assets. A \`SEMA-GOVERNED\` header identifies the owning contract
323
+ but does not replace these mappings. Multiple tasks can reference the same file.
324
+
325
+ ## Enums and Module Boundaries
326
+
327
+ \`enum Filtro { todas, pendentes, concluidas }\` is valid. Do not wrap values in
328
+ \`valores { ... }\`. Each file contains one module, with all declarations inside it.
329
+ Malformed enums, trailing declarations, duplicate mapping blocks and arrow-style
330
+ bindings are errors with a location and repair hint. Fix them before using counts
331
+ from a recovered AST. An entity-only module may legitimately have no tasks.
332
+
333
+ ## Test Values
334
+
335
+ Lists and objects are field values inside \`given\`, \`when\`, \`expect\` or \`error\`.
336
+ They may span lines and contain nested objects, lists, strings and booleans:
337
+
338
+ \`\`\`sema
339
+ tests {
340
+ caso "filters pending tasks" {
341
+ given {
342
+ tarefas: [
343
+ { id: "t1", concluida: falso },
344
+ { id: "t2", concluida: verdadeiro }
345
+ ]
346
+ }
347
+ expect { tarefas: [{ id: "t1", concluida: falso }] }
348
+ }
349
+ }
350
+ \`\`\`
351
+
352
+ Place this fragment inside a task. Keep closing delimiters balanced. \`PAR009\`
353
+ points to a malformed literal; fix it before removing unrelated routes or tasks.
354
+ Formatting preserves compound values and quoted text, including spaces.
355
+
356
+ ## Common Blocks
357
+
358
+ - \`docs\`: module summary and notes.
359
+ - \`entity\`: domain model.
360
+ - \`task\`: governed operation.
361
+ - \`input\` and \`output\`: input and output contracts.
362
+ - \`rules\`: validations and business rules.
363
+ - \`effects\`: persistence, reads, events, audit, and external calls.
364
+ - \`guarantees\`: what the task must provide after success.
365
+ - \`error\`: named errors and messages.
366
+ - \`tests\`: minimal behavior examples.
367
+ - \`route\`: public surface linked to a task.
368
+ - \`impl\` and \`vinculos\`: links between the contract and real code.
369
+
370
+ ## Canonical \`use\` and \`impl\` Origins
371
+
372
+ Use these origins before inventing a new one (aliases after \`ou\`):
373
+
374
+ - \`ts\` ou \`typescript\`
375
+ - \`js\` ou \`javascript\`
376
+ - \`py\` ou \`python\`
377
+ - \`dart\`
378
+ - \`lua\`
379
+ - \`cs\`, \`csharp\` ou \`dotnet\`
380
+ - \`java\`
381
+ - \`go\` ou \`golang\`
382
+ - \`rust\` ou \`rs\`
383
+ - \`cpp\`, \`cxx\`, \`cc\` ou \`c++\`
384
+ - \`php\`
385
+
386
+ Examples:
387
+
388
+ \`\`\`sema
389
+ use javascript app.web.expenses
390
+
391
+ impl {
392
+ js: src.app.saveExpense
393
+ }
394
+ \`\`\`
395
+
396
+ \`\`\`sema
397
+ use php app.legacy.pedidos
398
+
399
+ impl {
400
+ php: pedidos.criarPedido
401
+ }
402
+ \`\`\`
403
+
404
+ \`sema compilar --alvo javascript\` defines a generation target. \`impl { js: ... }\` defines the live-code origin linked to the contract. They are different layers and both are valid.
405
+
406
+ ## Layered \`impl\` Roles
407
+
408
+ Layered code (route + service + persistence in the same language) can declare one \`impl\` per role. Append a supported role to any origin: \`rota\`, \`servico\`, \`persistencia\` or \`repositorio\`.
409
+
410
+ \`\`\`sema
411
+ impl {
412
+ ts_rota: server.routes.monitores.criarMonitor
413
+ ts_servico: server.services.monitores.criarMonitor
414
+ ts_persistencia: server.repositories.monitores.criar
415
+ }
416
+ \`\`\`
417
+
418
+ The role suffix combines with every origin, not only TypeScript:
419
+
420
+ \`\`\`sema
421
+ impl {
422
+ php_rota: pedidos.rota.criarPedido
423
+ php_servico: pedidos.servico.criarPedido
424
+ php_persistencia: pedidos.repositorio.criar
425
+ }
426
+ \`\`\`
427
+
428
+ Each origin-plus-role pair must appear at most once; the bare origin (for example \`ts\`) stays valid for single-layer tasks, and drift resolves every role independently.
429
+
430
+ ## Small Canonical Lists
431
+
432
+ - \`effects\`: \`persistencia\`, \`consulta\`, \`evento\`, \`auditoria\`, \`db.write\`, \`queue.publish\`, \`fs.write\`, \`network.egress\`, \`secret.read\`, \`shell.exec\`.
433
+ - \`audit.motivo\`: \`obrigatorio\`, \`opcional\`, \`dispensado\`.
434
+
435
+ ## Contract Size
436
+
437
+ - up to ${LIMITE_AVISO_LINHAS_CONTRATO_SEMA} lines: healthy
438
+ - ${LIMITE_AVISO_LINHAS_CONTRATO_SEMA + 1}-${LIMITE_BLOQUEIO_LINHAS_CONTRATO_SEMA} lines: diagnostic warning, plan a split
439
+ - above ${LIMITE_BLOQUEIO_LINHAS_CONTRATO_SEMA}: blocks creation, edits, drift, finalization, generation, and snapshots
440
+ - split by real domain/capability, such as \`expenses_entry.sema\`, \`expenses_totals.sema\`, \`expenses_persistence.sema\`
441
+ - never use \`parte_1\`, \`parte_2\`, \`part_3\`, or equivalent names
442
+ - do not remove \`guarantees\`, \`tests\`, \`authz\`, \`dados\`, or \`vinculos\` just to fit under the limit
443
+ - multiple \`.sema\` contracts may govern the same code file through \`vinculos\`; this is expected
444
+
445
+ ## JavaScript Is Supported
446
+
447
+ The CLI supports JavaScript generation:
448
+
449
+ \`\`\`bash
450
+ sema compilar contratos/orders.sema --alvo javascript --saida ./generated/javascript
451
+ \`\`\`
452
+
453
+ The project can also generate TypeScript, Python, PHP, Dart, Lua, HTML, CSS, C#/.NET (\`dotnet\`), and C++ (\`cpp\`) when those targets are enabled in \`sema.config.json\`.
454
+
455
+ ## Support Files
456
+
457
+ - \`AGENTS.md\`: official Codex repository rules, loaded automatically.
458
+ - \`${ARQUIVO_SEMA_BOOT}\`: first Sema read for Codex.
459
+ - Profile-selected summary: the CLI materializes only the matching file within the configured budget. Skip it if the session already supplied the needed context.
460
+ - \`${ARQUIVO_AGENT_CONTEXT_PACK}\`: internal CLI policy database, not an initial read.
461
+ - \`SEMA_INDEX.json\`: internal CLI project index, not an initial read.
462
+ - \`docs/commands.md\`: command catalog, gates, and \`--saida\` rule.
463
+ - \`exemplos/\`: official DSL examples.
464
+
465
+ If Codex does not know which shape to use, it must open \`exemplos/calculadora.sema\`, \`exemplos/crud_simples.sema\`, \`exemplos/pagamento.sema\`, or \`exemplos/tratamento_erro.sema\` before inventing syntax.
466
+
467
+ Platform policy: Sema governs project contracts, scope, drift, evidence, and quality. It never bypasses platform policies, permissions, security controls, terms, or laws.
466
468
  `;
467
469
  }
468
470
  function renderizarDocFluxoPraticoSemaLocal(_agentContextPack) {
469
- return `# Practical Codex + Sema Workflow
470
-
471
- This is the minimum workflow for Codex in a local workspace.
472
-
473
- 1. Read \`${ARQUIVO_SEMA_BOOT}\`.
474
- 2. Run \`sema --version\`. If the shell cannot find it, use \`$HOME/.sema/bin/sema\` on macOS/Linux. On Windows, PowerShell resolves \`sema.ps1\` from PATH and cmd.exe resolves \`sema.cmd\`; use \`& "$env:SystemRoot\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$HOME\\.sema\\bin\\sema-managed.ps1" --version\` as the absolute fallback. Only then declare the CLI unavailable.
475
- 3. Run \`sema sessao "<intenção>" --json\`; then \`sema resumo <contrato> --micro --drift none --json\` only for the selected contract.
476
- 4. Run \`sema docs-impacto --intencao "<change>" --arquivo <contract> --json\` and retain mudancaId. After compaction, resume \`sema sessao --mudanca-id <id> --json\`: use recompiled \`estadoAtual\` and returned gates instead of old conclusions in the conversation summary. If the protocol is stale, synchronize it, reread SEMA_BOOT.md and resume the same id.
477
- 5. Read every required document returned by the command.
478
- 6. Consult command help or the relevant section of \`docs/commands.md\` when syntax, a gate or \`--saida\` is unclear.
479
- 7. If the right capability is unclear, run \`sema descobrir recomendar --intencao "<goal>" --json\`; do not auto-run ambiguous recommendations.
480
- 8. Use \`exemplos/\` and \`docs/syntax.md\` before creating or editing a contract.
481
- 9. Run \`sema drift <contract> --cache fresh --pacote --json\` and \`sema impacto\` before editing existing code.
482
- 10. For a new module, plan each task's \`impl\` and \`vinculos\` before code. Validate, scaffold with \`sema compilar <contract> --alvo <default target>\`, then implement those symbols and files. Pending references become verified only after fresh drift; a \`SEMA-GOVERNED\` header alone does not link a task. Test the application and run \`sema verificar\`.
483
- 11. Run \`sema formatar\` and \`sema validar\` after changing a \`.sema\` contract.
484
- 12. Run \`sema finalizar-mudanca --mudanca-id <id> --doc-lida <doc> --json\`, repeating --doc-lida for actual readings. The id preserves intention and files; declarations expire when hashes change. This checks documentation, not comprehension or behavior; validation, drift and tests remain separate.
485
-
486
- Contract edit rule: \`.sema\` has its own size budget. Above ${LIMITE_AVISO_LINHAS_CONTRATO_SEMA} lines, plan a split by domain/capability; above ${LIMITE_BLOQUEIO_LINHAS_CONTRATO_SEMA}, do not create or edit before splitting. Do not use parte_1/parte_2 and do not force a 1:1 contract-to-file relationship; several contracts can govern the same file through \`vinculos\`.
487
-
488
- Closing rule: the \`payload\` of \`sema drift --cache fresh --json\` must return \`sucesso:true\`. If it reports \`sucesso:false\`, \`vinculos_quebrados\`, \`rotas_divergentes\`, or \`impls_quebrados\`, the task is still blocked. Passing unit tests or a cache hit do not replace fresh green drift. \`vinculos_fora_do_escopo\` is informational: the file exists in the workspace outside the configured \`diretoriosCodigo\`, and each entry carries a \`diretorioSugerido\` to add to \`sema.config.json\`; it does not block closure. In 3.0.0, \`ok\` describes the CLI result path and never replaces a command-specific domain verdict.
489
-
490
- Focused drift rule: file and module scopes plan their physical file set before cataloging. They never fall back to a whole-project walk when no safe anchor exists. All indexers and semantic-budget checks reuse the same in-memory source read; a global walk is reserved for explicit \`--escopo projeto\`. Code discovery is deferred until that plan exists, homonymous candidates fail as ambiguous, and configured contract origins or code roots resolving outside the workspace are rejected before enumeration. \`inspecionar\`, \`impacto\`, and \`renomear-semantico\` preserve the same directed boundary. Missing unambiguous local dependencies make coverage partial and block success. In Python, an unresolved \`name\` from \`from module import name\` is not itself a missing file after \`module\` resolves: it may be an exported symbol, while a real child module is still included whenever its file exists.
491
-
492
- Cache rule: a closure gate should use \`sema drift <contrato> --escopo modulo --cache fresh --json\`. \`--cache none\` executes the same analysis without persistent-cache I/O, while \`--cache cache\` may reuse only extraction data whose schema, workspace identity, Git HEAD, plan, configuration, contracts, member paths, and strong content digests all match. Cache objects are stored in the operating system's user-cache directory, never below the workspace. A hit is acceleration, not evidence: final links, diagnostics, score, and success are always recalculated. Corruption or an unavailable cache degrades to an in-memory calculation.
493
-
494
- Query honesty rule: \`resumo\` and \`inspecionar\` default to \`--drift none\`. When analysis is skipped, score, confidence, implementation, routes, and other unobserved code claims inside the command payload must be \`null\` or explicitly marked not evaluated; zero is not a substitute for absent evidence.
495
-
496
- UI rule: if the task involves an interface, minimum evidence includes desktop and mobile. On a narrow viewport such as 390px, \`document.documentElement.scrollWidth <= document.documentElement.clientWidth\` must pass; horizontal scroll blocks closure.
497
-
498
- ## Codex Context Capacity
499
-
500
- All capacities use AGENTS.md -> SEMA_BOOT.md -> the contract returned by \`sema sessao\`.
501
- The first session asks for the configured token window; declare \`--janela-contexto <tokens> --salvar-perfil\`.
502
- Use \`--orcamento-contexto\` and \`--reserva-saida\` to allocate space. Counts use characters / 4, not the model tokenizer.
503
- The CLI reads SEMA_INDEX.json internally. Do not load the full index, global pack, or unrelated modules.
504
- An explicit \`--arquivo\` selects its contract and declared dependencies. Word matches are optional references.
505
-
506
- ## When to Generate Code
507
-
508
- If the delivery includes code derived from a contract, run \`sema compilar\`.
509
-
510
- \`\`\`bash
511
- sema compilar contratos/orders.sema --alvo javascript --saida ./generated/javascript
512
- \`\`\`
513
-
514
- Replace \`javascript\` with \`typescript\`, \`python\`, \`php\`, \`dart\`, \`lua\`, \`html\`, \`css\`, \`dotnet\`, or \`cpp\` when appropriate.
515
-
516
- ## Fail Closed
517
-
518
- - If the local CLI is unavailable, stop before editing governed code or contracts and ask for \`@semacode/cli\` installation.
519
- - If the applicable contract or semantic link is missing, create or repair it before code.
520
- - If validation or drift reports failure, broken links, divergent routes, or broken implementations, fix the evidence and run the gate again.
521
- - A local timeout is not authorization to skip Sema; retry with a larger timeout or a narrower scope.
471
+ return `# Practical Codex + Sema Workflow
472
+
473
+ This is the minimum workflow for Codex in a local workspace.
474
+
475
+ 1. Read \`${ARQUIVO_SEMA_BOOT}\`.
476
+ 2. Run \`sema --version\`. If the shell cannot find it, use \`$HOME/.sema/bin/sema\` on macOS/Linux. On Windows, PowerShell resolves \`sema.ps1\` from PATH and cmd.exe resolves \`sema.cmd\`; use \`& "$env:SystemRoot\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$HOME\\.sema\\bin\\sema-managed.ps1" --version\` as the absolute fallback. Only then declare the CLI unavailable.
477
+ 3. Run \`sema sessao "<intenção>" --json\`; then \`sema resumo <contrato> --micro --drift none --json\` only for the selected contract.
478
+ 4. Run \`sema docs-impacto --intencao "<change>" --arquivo <contract> --json\` and retain mudancaId. After compaction, resume \`sema sessao --mudanca-id <id> --json\`: use recompiled \`estadoAtual\` and returned gates instead of old conclusions in the conversation summary. If the protocol is stale, synchronize it, reread SEMA_BOOT.md and resume the same id.
479
+ 5. Read every required document returned by the command.
480
+ 6. Consult command help or the relevant section of \`docs/commands.md\` when syntax, a gate or \`--saida\` is unclear.
481
+ 7. If the right capability is unclear, run \`sema descobrir recomendar --intencao "<goal>" --json\`; do not auto-run ambiguous recommendations.
482
+ 8. Use \`exemplos/\` and \`docs/syntax.md\` before creating or editing a contract.
483
+ 9. Run \`sema drift <contract> --cache fresh --pacote --json\` and \`sema impacto\` before editing existing code.
484
+ 10. For a new module, plan each task's \`impl\` and \`vinculos\` before code. Validate, scaffold with \`sema compilar <contract> --alvo <default target>\`, then implement those symbols and files. Pending references become verified only after fresh drift; a \`SEMA-GOVERNED\` header alone does not link a task. Test the application and run \`sema verificar\`.
485
+ 11. Run \`sema formatar\` and \`sema validar\` after changing a \`.sema\` contract.
486
+ 12. Run \`sema finalizar-mudanca --mudanca-id <id> --doc-lida <doc> --json\`, repeating --doc-lida for actual readings. The id preserves intention and files; declarations expire when hashes change. This checks documentation, not comprehension or behavior; validation, drift and tests remain separate.
487
+
488
+ Contract edit rule: \`.sema\` has its own size budget. Above ${LIMITE_AVISO_LINHAS_CONTRATO_SEMA} lines, plan a split by domain/capability; above ${LIMITE_BLOQUEIO_LINHAS_CONTRATO_SEMA}, do not create or edit before splitting. Do not use parte_1/parte_2 and do not force a 1:1 contract-to-file relationship; several contracts can govern the same file through \`vinculos\`.
489
+
490
+ Closing rule: the \`payload\` of \`sema drift --cache fresh --json\` must return \`sucesso:true\`. If it reports \`sucesso:false\`, \`vinculos_quebrados\`, \`rotas_divergentes\`, or \`impls_quebrados\`, the task is still blocked. Passing unit tests or a cache hit do not replace fresh green drift. \`vinculos_fora_do_escopo\` is informational: the file exists in the workspace outside the configured \`diretoriosCodigo\`, and each entry carries a \`diretorioSugerido\` to add to \`sema.config.json\`; it does not block closure. In 3.0.0, \`ok\` describes the CLI result path and never replaces a command-specific domain verdict.
491
+
492
+ Historical migration rule: Historical migrations (including Prisma migrations/<timestamp>_<name>/migration.sql) retain their SQL bytes and contract links. Do not add headers, reformat SQL or remove a binding just to pass a gate. The path proves neither application nor checksum: check the project runbook and database migration history. Change behavior through a new migration and current schema/code bindings, preserving relevant historical references.
493
+
494
+ Focused drift rule: file and module scopes plan their physical file set before cataloging. They never fall back to a whole-project walk when no safe anchor exists. All indexers and semantic-budget checks reuse the same in-memory source read; a global walk is reserved for explicit \`--escopo projeto\`. Code discovery is deferred until that plan exists, homonymous candidates fail as ambiguous, and configured contract origins or code roots resolving outside the workspace are rejected before enumeration. \`inspecionar\`, \`impacto\`, and \`renomear-semantico\` preserve the same directed boundary. Missing unambiguous local dependencies make coverage partial and block success. In Python, an unresolved \`name\` from \`from module import name\` is not itself a missing file after \`module\` resolves: it may be an exported symbol, while a real child module is still included whenever its file exists.
495
+
496
+ Cache rule: a closure gate should use \`sema drift <contrato> --escopo modulo --cache fresh --json\`. \`--cache none\` executes the same analysis without persistent-cache I/O, while \`--cache cache\` may reuse only extraction data whose schema, workspace identity, Git HEAD, plan, configuration, contracts, member paths, and strong content digests all match. Cache objects are stored in the operating system's user-cache directory, never below the workspace. A hit is acceleration, not evidence: final links, diagnostics, score, and success are always recalculated. Corruption or an unavailable cache degrades to an in-memory calculation.
497
+
498
+ Query honesty rule: \`resumo\` and \`inspecionar\` default to \`--drift none\`. When analysis is skipped, score, confidence, implementation, routes, and other unobserved code claims inside the command payload must be \`null\` or explicitly marked not evaluated; zero is not a substitute for absent evidence.
499
+
500
+ UI rule: if the task involves an interface, minimum evidence includes desktop and mobile. On a narrow viewport such as 390px, \`document.documentElement.scrollWidth <= document.documentElement.clientWidth\` must pass; horizontal scroll blocks closure.
501
+
502
+ ## Codex Context Capacity
503
+
504
+ All capacities use AGENTS.md -> SEMA_BOOT.md -> the contract returned by \`sema sessao\`.
505
+ The first session asks for the configured token window; declare \`--janela-contexto <tokens> --salvar-perfil\`.
506
+ Use \`--orcamento-contexto\` and \`--reserva-saida\` to allocate space. Counts use characters / 4, not the model tokenizer.
507
+ The CLI reads SEMA_INDEX.json internally. Do not load the full index, global pack, or unrelated modules.
508
+ An explicit \`--arquivo\` selects its contract and declared dependencies. Word matches are optional references.
509
+
510
+ ## When to Generate Code
511
+
512
+ If the delivery includes code derived from a contract, run \`sema compilar\`.
513
+
514
+ \`\`\`bash
515
+ sema compilar contratos/orders.sema --alvo javascript --saida ./generated/javascript
516
+ \`\`\`
517
+
518
+ Replace \`javascript\` with \`typescript\`, \`python\`, \`php\`, \`dart\`, \`lua\`, \`html\`, \`css\`, \`dotnet\`, or \`cpp\` when appropriate.
519
+
520
+ ## Fail Closed
521
+
522
+ - If the local CLI is unavailable, stop before editing governed code or contracts and ask for \`@semacode/cli\` installation.
523
+ - If the applicable contract or semantic link is missing, create or repair it before code.
524
+ - If validation or drift reports failure, broken links, divergent routes, or broken implementations, fix the evidence and run the gate again.
525
+ - A local timeout is not authorization to skip Sema; retry with a larger timeout or a narrower scope.
522
526
  `;
523
527
  }
524
528
  function renderizarDocComandosSemaLocal(agentContextPack) {
525
- return `# Sema Command Catalog
526
-
527
- Use this file when Codex does not know which command to run. A Sema command is an operational gate; do not replace it with a Markdown report.
528
-
529
- ## Minimum Local Flow
530
-
531
- \`\`\`bash
532
- sema --version
533
- sema sessao "<intencao>" --json
534
- sema resumo --drift none
535
- sema docs-impacto --intencao "<acao>" --arquivo <contract> --json
536
- \`\`\`
537
-
538
- If \`sema\` is absent from \`PATH\`, use \`$HOME/.sema/bin/sema\` on macOS/Linux. On Windows, PowerShell resolves \`sema.ps1\` from PATH, cmd.exe resolves \`sema.cmd\`, and the absolute fallback is \`& "$env:SystemRoot\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$HOME\\.sema\\bin\\sema-managed.ps1" --version\`. \`sema skill sync --json\` repairs launcher and skill without touching the workspace or plugin caches.
539
-
540
- Then read every required doc returned by \`docs-impacto\`.
541
-
542
- ## Session Opening
543
-
544
- - \`sema sessao "<intencao>" [--arquivo <contrato-ou-codigo>] [--janela-contexto <tokens>] [--orcamento-contexto <tokens>] [--reserva-saida <tokens>] [--salvar-perfil] --json\`: asks for the effective window when absent and stores the profile only on explicit request. The compact response contains workspace identity, artifact freshness, matching contracts and linked files, mandatory document paths, scoped gates and next steps. The index stays inside the CLI. The budget estimates local entry instructions plus the current delivery using characters/4; it does not measure the conversation or the model's exact tokenizer. Omitted candidates are counted and require scope refinement; mandatory readings are never silently waived. Treat \`frescor.fresco:false\` as a pre-action blocker and run the suggested \`sema sync-codex --json\`. Navigation never authorizes execution.
545
-
546
- ## Public JSON output
547
-
548
- \`sema --version\` stays plain exact SemVer text. With \`--json\`, help and command-control failures use exactly one six-field \`sema.cli.control/v1\` document on stdout with empty stderr. Every syntactically valid command uses exactly one eight-field \`sema.cli.result/v1\` document containing only \`schemaVersion\`, \`ok\`, \`kind\`, \`command\`, \`code\`, \`message\`, \`exitCode\`, and \`payload\`. The command-specific result is nested under \`payload\`, never \`data\`; envelope \`ok\` does not replace domain fields inside that payload. Valid structured domain failures use \`DOMAIN_ERROR\`, while uncaught runtime exceptions remain redacted \`FATAL_ERROR\` control failures.
549
-
550
- ## Global Distribution
551
-
552
- - \`sema skill status --json\`: diagnoses the managed launcher and bundled skill without writing.
553
- - \`sema skill sync --json\`: repairs only Sema-managed launcher and skill destinations; it never writes into the workspace or plugin caches.
554
-
555
- ## Contract and Discovery
556
-
557
- - \`sema iniciar --template <base|nestjs|fastapi|nextjs-api|nextjs-consumer|react-vite-consumer|angular-consumer|flutter-consumer|node-firebase-worker|aspnet-api|springboot-api|go-http-api|rust-axum-api|cpp-service-bridge> [--force]\`: creates a new Sema project and preserves existing files by default; \`--force\` is the only explicit overwrite path. Inside a subfolder of an already governed workspace, the subfolder is registered under \`diretoriosCodigo\` of the ancestral \`sema.config.json\` (safe write, deduplicated) instead of creating a local config; if the parent config cannot be written, the scaffold proceeds and prints the exact line to add.
558
- - \`sema validar <arquivo-ou-pasta> --json\`: validates \`.sema\` contracts.
559
- - \`sema diagnosticos <arquivo.sema> --json\`: details errors and warnings.
560
- - \`sema formatar <arquivo-ou-pasta>\`: formats contracts.
561
- - \`sema inspecionar <arquivo-ou-pasta> [--drift <none|cache|fresh>] --json\`: shows the contract surface; drift is skipped by default.
562
- - \`sema ast <arquivo.sema> --json\`: shows AST for syntax debugging.
563
- - \`sema ir <arquivo.sema> --json\`: shows the IR used by gates and generators.
564
- - \`sema descobrir catalogo --json\`: lists governance flows, profiles, specialized workflows, pipelines, generators, capability tokens, and adapters from their canonical registries.
565
- - \`sema descobrir recomendar --intencao "<goal>" --json\`: ranks compatible capabilities deterministically without executing the selected command.
566
- - \`sema descobrir explicar <id> --json\`: explains inputs, boundaries, reasons, and the command template for one capability.
567
- - \`sema pipeline listar|descrever <id> --json\` and \`sema capabilities --json\`: compact projections of the same discovery catalog.
568
-
569
- ## Change and Closure
570
-
571
- - \`sema docs-impacto --intencao "<acao>" --arquivo <contract> --json\`: discovers required docs and returns mudancaId with next argument arrays.
572
- - \`sema drift <arquivo-ou-pasta> --escopo modulo [--cache <none|cache|fresh>] --json\`: plans a safe physical scope, then compares contract and implementation without a global fallback.
573
- - \`sema impacto <arquivo-ou-pasta> --alvo <token> --mudanca "<descricao>" --json\`: maps impact before changing behavior.
574
- - \`sema verificar <arquivo-ou-pasta> --json\`: runs aggregated final verification.
575
- - \`sema finalizar-mudanca --mudanca-id <id> --doc-lida <arquivo> --json\`: checks scoped reading declarations and file hashes, not comprehension or application behavior. Repeat --doc-lida for actual readings. Explicit --intencao and --arquivo remain supported.
576
-
577
- Honest closure: unwrap drift JSON and treat its command payload as the source of truth. \`payload.sucesso:false\`, non-empty \`payload.vinculos_quebrados\`, non-empty \`payload.rotas_divergentes\`, or non-empty \`payload.impls_quebrados\` mean the change is not complete yet. Do not report "clean drift" without a green payload. \`payload.vinculos_fora_do_escopo\` is informational: the file exists in the workspace outside \`diretoriosCodigo\`, and each entry carries a \`diretorioSugerido\` for \`sema.config.json\`.
578
-
579
- Focused drift exposes its planned, declared, inferred, and missing files plus catalog visit/read metrics in \`escopo_aplicado\`. A missing declared file or a missing unambiguous code-referenced dependency is a blocker reported as \`vinculo_quebrado\`; a missing inferred candidate derived from an \`impl\` symbol is informational under \`arquivosAusentesInferidos\` and never blocks an implementation that resolved. For Python \`from module import name\`, Sema still includes \`name\` when it resolves as a real submodule, but never reports the absent submodule candidate as a broken link after the parent module resolved because \`name\` may be a function, class, or variable. File and module scopes fail closed without a safe anchor, with homonymous implementation candidates, or with missing local dependencies; only \`--escopo projeto\` may walk every configured code root. Logical roots such as \`src\` are probed deterministically without a discovery walk. Configured contract origins and code roots are confined before enumeration, and \`inspecionar\`, \`impacto\`, and \`renomear-semantico\` reuse the same directed boundary without reopening arbitrary external paths.
580
-
581
- Drift analysis and cache modes are explicit:
582
-
583
- - \`sema drift\` defaults to \`--cache fresh\`. \`none\` still executes drift but performs zero persistent-cache I/O; \`cache\` reuses a fully validated extraction hit and publishes misses; \`fresh\` ignores hits, recalculates, and publishes the new extraction.
584
- - \`sema resumo\` and \`sema inspecionar\` default to \`--drift none\`. In that mode their payload does not execute drift and returns \`null\` for score, confidence, implementation, routes, or other code evidence that was not observed. Use \`--drift cache\` or \`--drift fresh\` when that evidence is required. \`--com-drift\` remains a temporary alias for \`--drift fresh\`.
585
- - When a query explicitly runs drift, \`payload.analiseDrift.sucesso\` exposes the result and a failed requested analysis returns a nonzero exit code.
586
- - The value aliases \`off\`, \`auto\`, and \`refresh\` normalize to \`none\`, \`cache\`, and \`fresh\` for one compatibility release and emit a structured deprecation warning. Wrong flags, repeated flags, conflicts, and invalid values fail instead of falling back silently.
587
- - Persistent cache objects live outside the workspace under the operating system's user-cache directory. Workspace identity is hashed; public JSON and events expose only an opaque key and \`$SEMA_CACHE/...\` paths. Corruption or cache unavailability becomes a miss and never changes the drift result. Only validated extraction data is reused; links, diagnostics, scores, and the final success decision are recalculated.
588
-
589
- A cache hit is acceleration, not final evidence; closure still requires fresh drift.
590
-
591
- ## Sema Code
592
-
593
- - \`sema compilar <arquivo-ou-pasta> --alvo <typescript|python|php|dart|lua|javascript|html|css|dotnet|cpp> --saida <diretorio> [--estrutura <flat|modulos|backend>] [--framework <base|nestjs|fastapi>]\`: generates starter/support artifacts from the contract.
594
- - \`sema testar <arquivo.sema> --alvo <alvo> --saida <diretorio-temporario>\`: generates and runs local tests when the target supports it.
595
- - \`sema importar <nestjs|express|fastify|koa|fastapi|flask|nextjs|nextjs-consumer|react-vite-consumer|angular-consumer|flutter-consumer|sveltekit-consumer|nuxt-consumer|firebase|typescript|python|dart|dotnet|java|go|rust|cpp|php> <diretorio> --saida <diretorio> --json\`: imports a legacy project into initial contracts; only these sources have a real importer.
596
- - \`sema renomear-semantico <arquivo-ou-pasta> --de <nome> --para <nome> --json\`: helps rename symbols semantically.
597
-
598
- Rule for \`--saida\`: the folder passed to \`sema compilar --saida\` is generated output. It is not the final delivery by itself. The final delivery is the target files/links declared by the contract. If the contract asks for \`index.html\`, \`css/styles.css\`, and \`js/app.js\`, creating only \`saida/expense_control.ts\` does not complete the task.
599
-
600
- Sema Code traceability rule: generated artifacts must point back to the source module/contract and preserve that the same final file may be governed by several \`.sema\` contracts through \`vinculos\`. Do not force a 1:1 contract-file relationship and do not treat \`saida/\` as the final project.
601
-
602
- Ready UI rule: if the task generates an app, site, dashboard, form, or static HTML, run desktop/mobile visual validation when the surface allows it. On narrow mobile (for example 390px), \`scrollWidth <= clientWidth\` must pass; a layout that stacks but overflows horizontally is not responsive.
603
-
604
- ## Canonical Syntax Lists
605
-
606
- - Origins for \`use\` and \`impl\` (11, aliases after \`/\`): \`ts/typescript\`, \`js/javascript\`, \`py/python\`, \`dart\`, \`lua\`, \`cs/csharp/dotnet\`, \`java\`, \`go/golang\`, \`rust/rs\`, \`cpp/cxx/cc/c++\`, \`php\`.
607
- - Layered \`impl\` roles: append \`_rota\`, \`_servico\`, \`_persistencia\` or \`_repositorio\` to any origin (\`ts_rota\`, \`php_servico\`, \`cs_persistencia\`, \`py_repositorio\`).
608
- - Generation targets (10): \`typescript\`, \`javascript/js\`, \`python\`, \`php\`, \`dart\`, \`lua\`, \`html\`, \`css\`, \`dotnet/cs/csharp\`, \`cpp/c++/cxx/cc\`.
609
- - \`sema iniciar --template\` (14): \`base\`, \`nestjs\`, \`fastapi\`, \`nextjs-api\`, \`nextjs-consumer\`, \`react-vite-consumer\`, \`angular-consumer\`, \`flutter-consumer\`, \`node-firebase-worker\`, \`aspnet-api\`, \`springboot-api\`, \`go-http-api\`, \`rust-axum-api\`, \`cpp-service-bridge\`.
610
- - Frequent \`effects\` categories: \`persistencia\`, \`consulta\`, \`evento\`, \`auditoria\`, \`db.write\`, \`queue.publish\`, \`fs.write\`, \`network.egress\`, \`secret.read\`, \`shell.exec\`.
611
- - Accepted \`audit.motivo\` values: \`obrigatorio\`, \`opcional\`, \`dispensado\`.
612
-
613
- \`sema compilar --alvo javascript\` is a generation target. \`impl { js: ... }\` is the live-code origin. Do not swap one for the other.
614
-
615
- ## Codex and Context
616
-
617
- Project initialization creates configuration and agent rules without inventing a business contract.
618
- Demonstrations stay under exemplos/; active contracts are authored in contratos/ for the actual request.
619
- An adopted workspace with no contracts returns contrato_necessario and does not validate an application.
620
-
621
- The CLI selects context files before generation: micro up to 32,768 tokens,
622
- short up to 131,072, expanded above that. The budget may lower the selected
623
- level further. Only the matching summary is materialized; other variants
624
- are removed from active entry files, with existing edits preserved in
625
- .sema/contexto-legado/. Internal indexes are not required readings.
626
- A session already supplying the needed task context does not require another summary.
627
-
628
- Freshness checks managed instructions, contract hashes and changes to the
629
- materialized context profile. Synchronization preserves manual AGENTS rules.
630
- The budget counts AGENTS.md, SEMA_BOOT.md and the current delivery, using
631
- characters / 4. It does not measure chat history, host instructions or
632
- cumulative future file reads and tool results. Oversized requests must refine
633
- the scope; no blocking rule is silently waived.
634
-
635
- validar and formatar require selected .sema contracts. Empty scope returns
636
- SEM_CLI_SEM_CONTRATOS and does not validate an application or adopt a project.
637
- First-time adoption requires consent and the configured context window.
638
-
639
- - \`sema ajuda-ia\`: short guidance for Codex.
640
- - \`sema starter-ia\`: operational starter.
641
- - \`sema contexto-ia <arquivo.sema> --saida <dir> --json\`: profile-selected context files; raw AST/IR/drift are consulted separately only when needed.
642
- - \`sema resumo <arquivo-ou-pasta> [--drift <none|cache|fresh>] --json\`: compact context; drift is not executed unless requested.
643
- - \`sema prompt-curto <arquivo-ou-pasta> --json\`: compact prompt.
644
- - \`sema sync-codex --json\`: synchronizes the official Codex entrypoint and local support docs.
645
- - \`sema instalar-exemplos --json\`: installs official examples in the workspace.
646
- - \`sema exemplos-prompt-ia\`: shows prompt examples, not \`.sema\` examples.
647
-
648
- ## Profiles and Author
649
-
650
- - \`sema author iniciar|validar|briefing|revisar-cliches|validar-narrativa|validar-proibicoes\`: governs authorial writing.
651
- - \`sema profile validar <software|workflow|ops|game|simulation|legal|research|redacao|propostas|conversas> <arquivo> --json\`: validates an artifact by profile.
652
- - \`sema profile capabilities --json\`: lists profiles/capabilities.
653
- - \`sema rule-packs --profile <profile> --json\`: lists rule packs.
654
-
655
- \`author\` is a specialized \`sema author\` workflow, not a \`profile validar\` alias. Discovery exposes that distinction explicitly.
656
-
657
- ## AI-native Content Pipeline
658
-
659
- - \`sema conteudo capabilities --json\`: lists generic producer, evaluator, and adapter capabilities without fixing a platform.
660
- - \`sema conteudo validar <definition.json> --json\`: validates the content DAG, gates, and open adapters.
661
- - \`sema conteudo planejar <definition.json> --alvos-arquivo <targets.json> --json\`: creates a declarative multi-target plan for an external runner.
662
- - \`sema conteudo validar-envelope --envelope-arquivo <envelope.json> --confianca-arquivo <trust.json> --trust-root-digest <sha256:...> --revocation-digest <sha256:...> --payload-type <type> --json\`: verifies Ed25519 identity, authorization, freshness, scope, and the separately pinned trust root and current revocation overlay.
663
- - \`sema conteudo registrar <ledger.ndjson> --envelope-arquivo <envelope.json> --politica-arquivo <policy-envelope.json> --confianca-arquivo <trust.json> --trust-root-digest <sha256:...> --revocation-digest <sha256:...> --ledger-id <id> --expected-head <sha256:...> --json\`: appends a verified envelope under the signed run policy to the local replay ledger at an externally retained head.
664
- - \`sema conteudo status <definition.json> --politica-arquivo <policy-envelope.json> --confianca-arquivo <trust.json> --trust-root-digest <sha256:...> --revocation-digest <sha256:...> --ledger-arquivo <ledger.ndjson> --expected-head <sha256:...> --json\`: verifies the signed policy and its \`targetSetDigest\`, then derives verdicts, operational conditions, completion, and next actions from canonical events.
665
- - \`sema conteudo projetar <definition.json> --politica-arquivo <policy-envelope.json> --confianca-arquivo <trust.json> --trust-root-digest <sha256:...> --revocation-digest <sha256:...> --ledger-arquivo <ledger.ndjson> --expected-head <sha256:...> --saida <manifest.json> --json\`: regenerates a non-authoritative manifest bound to the ledger head.
666
-
667
- The content command is an AI-native, multi-channel, multi-format control plane. It never runs producers, evaluators, creative tools, or publication adapters; those belong to an external runner. It has no native human-review transition. A signed policy binds \`runId\`, definition, ledger, trust root, gates, complete target set, and the full \`issuedAt\`/\`expiresAt\` authorization window; no event may be recorded outside it. Stages select \`adapterPolicy\` as \`NONE\`, \`CONSTRAINTS\`, or \`CONFIRMATION\`; definition v1 accepts one output per stage. Constraint results must come from independent signed observations, including independently observed media type, not artifact metadata or executor claims. Target metadata is an exact scalar allowlist from \`requiredMetadata + optionalMetadata\`; \`accountScope\` is a credential-free \`account:<alias>\` reference, and artifact metadata is prohibited in v1. Deterministic evidence and AI opinions have separate quorum fields. Evidence requires an exact \`content.evidence.attest:<evidenceType>\` capability; adapter evidence requires \`content.adapter.attest:<adapterId>@<version>:<evidenceType>\` plus signed adapter binding.
668
-
669
- Verdicts such as \`APROVADO\`, \`REPROVADO\`, and \`INCONCLUSIVO\` remain separate from operational conditions such as \`AGUARDANDO_EVENTO_EXTERNO\` and \`FERRAMENTA_INDISPONIVEL\`. A generated manifest is only a projection and cannot alter canonical state.
670
-
671
- Local NDJSON plus a hash chain is portable evidence for replay, not a strong append-only trust boundary. Retain \`expectedHead\`, the canonical trust-root digest, and the current revocation digest externally, or use protected storage for high assurance. The trust-root pin identifies the authority snapshot independently from the revocation overlay. A workspace-local trust file additionally requires \`--development-local-trust\`; the flag does not disable digest pinning. Append freshness uses the platform clock rather than caller-provided \`recordedAt\`, and an authority in the current revocation overlay cannot sign an accepted policy.
672
-
673
- ## AI-native Interactive Systems
674
-
675
- - \`sema interativo capabilities --json\`: lists the canonical interactive capability vocabulary.
676
- - \`sema interativo schema --json\`: exposes the stable read-only definition schema, enum matrix, constraints, extension-command and data-schema shapes, plus canonical example paths for AI clients.
677
- - \`sema interativo pipelines --json\`: lists reusable game, simulation, and hybrid pipelines.
678
- - \`sema interativo adapters [--spatial-model <NON_SPATIAL|TWO_D|TWO_POINT_FIVE_D|THREE_D>] [--render-mode <HEADLESS|TEXT|VISUAL|XR>] --json\`: lists compatible external adapter descriptors.
679
- - \`sema interativo validar <definition.json> --json\`: validates independent kind, spatial model, render mode, visual profile, fidelity, control, time, world, budget, pipeline, and acceptance axes.
680
- - \`sema interativo planejar <definition.json> --json\`: expands compatible stages and required evidence without running an engine.
681
- - \`sema interativo validar-evidencias|status <definition.json> [--plano-arquivo <plan.json>] --bundle-arquivo <bundle.json> --json\`: validates a portable evidence bundle or derives non-authoritative status; \`--evidencias-arquivo\` is an alias and an omitted plan is recomputed deterministically.
682
- - \`sema interativo validar-protocolo <adapter-run.json> --json\`: checks DETECT/PROBE/SNAPSHOT/PLAN/APPLY/VALIDATE/EVIDENCE/ROLLBACK ordering and stable target binding.
683
- - Experience IR: \`validar-ir\`, \`indexar-ir\`, \`consultar-ir --semantic-id <id>\`, \`chunk-ir --semantic-id <id> [--raso]\`, and \`descrever-ir\`.
684
- - Operational state: \`validar-engine-snapshot\`, \`diff-engine-snapshots\`, \`validar-asset-provenance\`, \`validar-editor-state\`, \`planejar-jobs\`, \`validar-acceptance\`, \`operar-acceptance --operation <VALIDATE|EVALUATE|INVALIDATE> --context-file <file>\`, and \`validar-multimodal\`.
685
- - Temporal, autonomy, and testing: \`validar-temporal\`, \`validar-evidencia-temporal --bundle-arquivo <file>\`, \`validar-autonomia\`, \`validar-playtest-fuzz\`, and \`validar-multiplayer\`.
686
- - Portability and workers: \`analisar-portabilidade\` and \`validar-workers\`.
687
- - \`sema interativo validar-control-run <control-run.json> --definition-arquivo <definition.json> --plano-arquivo <plan.json> --contrato-arquivo <validation-contract.json> --entrada-arquivo <input.json> [--entrada-auxiliar-arquivo <supporting-input.json>] --evidencia-arquivo <evidence.json> --resultado-arquivo <result.json> --json\`: binds one advanced validation to its complete local digest chain instead of trusting a standalone result.
688
-
689
- The control-run command recomputes the canonical plan and selected pure validator, then verifies the definition, pipeline descriptor, validation contract, schema-declared inputs, evidence, and result digests. Prefix advanced items with \`sema interativo\` and pass the documented JSON file as the positional argument; an agent does not have to infer the validator or payload shape from a filename or visual style. The machine-readable schema publishes command maps, input/output schema links, required top-level fields, \`outputTargets\` path segments from the payload root, at least one real output shape per command, and official fixtures for all 20 advanced commands. Validation-result shapes describe \`payload.resultado\`; projected IR values use \`indice\`, \`entry\`, \`chunk\`, or \`descriptor\`; operation projections such as \`engineDiff\` and \`jobOrchestrationPlan\` live under \`payload.resultado.value\`; the job plan's ordered \`queue\` is the assignment list and exposes kind, priority, adapter, dependencies, locks, budgets, heartbeat, checkpoint, and recovery data.
690
-
691
- Spatial model and render mode are orthogonal: \`THREE_D + HEADLESS\` is valid, while XR requires \`THREE_D\`. \`PIXEL_8_BIT\` and \`PIXEL_16_BIT\` are independent visual profiles available to games and simulations. Every command above rejects unknown, duplicate, missing-value, or invalid-enum arguments, remains local, read-only, and non-authoritative, and leaves engine/editor execution, authorization, mutation, rollback, migration, rendering, playtest, and worker scheduling to external runners. Full local coverage is \`STRUCTURALLY_COMPLETE\`, never authoritative completion, and a local evidence bundle is never presented as authoritative trust.
692
-
693
- ## Operational
694
-
695
- - \`sema doctor\`: diagnoses local installation.
696
-
697
- ## Forbidden
698
-
699
- - Do not use an external workspace source to inspect a local workspace when \`sema --version\` or the managed launcher works.
700
- - Do not search the entire disk for \`.sema\` syntax; use \`exemplos/\`, \`docs/syntax.md\`, and this catalog.
701
- - Do not stop after \`sema compilar\` if the contract target files still do not exist.
702
- - Do not replace \`sema compilar\` with \`sema testar\` when the contract requires generated code.
703
- - Do not create a Markdown report to pretend a gate ran.
704
- - Do not say drift passed when the unwrapped \`sema drift --cache fresh --json\` payload returned \`sucesso:false\`, a non-empty \`vinculos_quebrados\`, \`rotas_divergentes\`, or \`impls_quebrados\` list. \`vinculos_fora_do_escopo\` entries are informational scope hints, not broken links.
705
- - Do not declare a UI responsive without mobile/desktop proof; horizontal scroll at 390px blocks closure.
706
-
707
- Governed code policy: keep the \`SEMA-GOVERNED\` marker, split large code by real responsibility, preserve contract links, and never treat a generated output directory as the final delivery.
529
+ return `# Sema Command Catalog
530
+
531
+ Use this file when Codex does not know which command to run. A Sema command is an operational gate; do not replace it with a Markdown report.
532
+
533
+ ## Minimum Local Flow
534
+
535
+ \`\`\`bash
536
+ sema --version
537
+ sema sessao "<intencao>" --json
538
+ sema resumo --drift none
539
+ sema docs-impacto --intencao "<acao>" --arquivo <contract> --json
540
+ \`\`\`
541
+
542
+ If \`sema\` is absent from \`PATH\`, use \`$HOME/.sema/bin/sema\` on macOS/Linux. On Windows, PowerShell resolves \`sema.ps1\` from PATH, cmd.exe resolves \`sema.cmd\`, and the absolute fallback is \`& "$env:SystemRoot\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$HOME\\.sema\\bin\\sema-managed.ps1" --version\`. \`sema skill sync --json\` repairs launcher and skill without touching the workspace or plugin caches.
543
+
544
+ Then read every required doc returned by \`docs-impacto\`.
545
+
546
+ ## Session Opening
547
+
548
+ - \`sema sessao "<intencao>" [--arquivo <contrato-ou-codigo>] [--janela-contexto <tokens>] [--orcamento-contexto <tokens>] [--reserva-saida <tokens>] [--salvar-perfil] --json\`: asks for the effective window when absent and stores the profile only on explicit request. The compact response contains workspace identity, artifact freshness, matching contracts and linked files, mandatory document paths, scoped gates and next steps. The index stays inside the CLI. The budget estimates local entry instructions plus the current delivery using characters/4; it does not measure the conversation or the model's exact tokenizer. Omitted candidates are counted and require scope refinement; mandatory readings are never silently waived. Treat \`frescor.fresco:false\` as a pre-action blocker and run the suggested \`sema sync-codex --json\`. Navigation never authorizes execution.
549
+
550
+ ## Public JSON output
551
+
552
+ \`sema --version\` stays plain exact SemVer text. With \`--json\`, help and command-control failures use exactly one six-field \`sema.cli.control/v1\` document on stdout with empty stderr. Every syntactically valid command uses exactly one eight-field \`sema.cli.result/v1\` document containing only \`schemaVersion\`, \`ok\`, \`kind\`, \`command\`, \`code\`, \`message\`, \`exitCode\`, and \`payload\`. The command-specific result is nested under \`payload\`, never \`data\`; envelope \`ok\` does not replace domain fields inside that payload. Valid structured domain failures use \`DOMAIN_ERROR\`, while uncaught runtime exceptions remain redacted \`FATAL_ERROR\` control failures.
553
+
554
+ ## Global Distribution
555
+
556
+ - \`sema skill status --json\`: diagnoses the managed launcher and bundled skill without writing.
557
+ - \`sema skill sync --json\`: repairs only Sema-managed launcher and skill destinations; it never writes into the workspace or plugin caches.
558
+
559
+ ## Contract and Discovery
560
+
561
+ - \`sema iniciar --template <base|nestjs|fastapi|nextjs-api|nextjs-consumer|react-vite-consumer|angular-consumer|flutter-consumer|node-firebase-worker|aspnet-api|springboot-api|go-http-api|rust-axum-api|cpp-service-bridge> [--force]\`: creates a new Sema project and preserves existing files by default; \`--force\` is the only explicit overwrite path. Inside a subfolder of an already governed workspace, the subfolder is registered under \`diretoriosCodigo\` of the ancestral \`sema.config.json\` (safe write, deduplicated) instead of creating a local config; if the parent config cannot be written, the scaffold proceeds and prints the exact line to add.
562
+ - \`sema validar <arquivo-ou-pasta> --json\`: validates \`.sema\` contracts.
563
+ - \`sema diagnosticos <arquivo.sema> --json\`: details errors and warnings.
564
+ - \`sema formatar <arquivo-ou-pasta>\`: formats contracts.
565
+ - \`sema inspecionar <arquivo-ou-pasta> [--drift <none|cache|fresh>] --json\`: shows the contract surface; drift is skipped by default.
566
+ - \`sema ast <arquivo.sema> --json\`: shows AST for syntax debugging.
567
+ - \`sema ir <arquivo.sema> --json\`: shows the IR used by gates and generators.
568
+ - \`sema descobrir catalogo --json\`: lists governance flows, profiles, specialized workflows, pipelines, generators, capability tokens, and adapters from their canonical registries.
569
+ - \`sema descobrir recomendar --intencao "<goal>" --json\`: ranks compatible capabilities deterministically without executing the selected command.
570
+ - \`sema descobrir explicar <id> --json\`: explains inputs, boundaries, reasons, and the command template for one capability.
571
+ - \`sema pipeline listar|descrever <id> --json\` and \`sema capabilities --json\`: compact projections of the same discovery catalog.
572
+
573
+ ## Change and Closure
574
+
575
+ - \`sema docs-impacto --intencao "<acao>" --arquivo <contract> --json\`: discovers required docs and returns mudancaId with next argument arrays.
576
+ - \`sema drift <arquivo-ou-pasta> --escopo modulo [--cache <none|cache|fresh>] [--pacote] --json\`: plans a safe physical scope, then compares contract and implementation without a global fallback. Both JSON forms expose \`payload.status.success\`, \`payload.status.score\` and \`payload.counts\`; full output preserves legacy fields. Session context values are in \`payload.perfil\`, not directly in \`payload\`.
577
+ - \`sema impacto <arquivo-ou-pasta> --alvo <token> --mudanca "<descricao>" --json\`: maps impact before changing behavior.
578
+ - \`sema verificar <arquivo-ou-pasta> --json\`: runs aggregated final verification.
579
+ - \`sema finalizar-mudanca --mudanca-id <id> --doc-lida <arquivo> --json\`: checks scoped reading declarations and file hashes, not comprehension or application behavior. Repeat --doc-lida for actual readings. Explicit --intencao and --arquivo remain supported.
580
+
581
+ Honest closure: unwrap drift JSON and treat its command payload as the source of truth. \`payload.sucesso:false\`, non-empty \`payload.vinculos_quebrados\`, non-empty \`payload.rotas_divergentes\`, or non-empty \`payload.impls_quebrados\` mean the change is not complete yet. Do not report "clean drift" without a green payload. \`payload.vinculos_fora_do_escopo\` is informational: the file exists in the workspace outside \`diretoriosCodigo\`, and each entry carries a \`diretorioSugerido\` for \`sema.config.json\`.
582
+
583
+ Focused drift exposes its planned, declared, inferred, and missing files plus catalog visit/read metrics in \`escopo_aplicado\`. A missing declared file or a missing unambiguous code-referenced dependency is a blocker reported as \`vinculo_quebrado\`; a missing inferred candidate derived from an \`impl\` symbol is informational under \`arquivosAusentesInferidos\` and never blocks an implementation that resolved. For Python \`from module import name\`, Sema still includes \`name\` when it resolves as a real submodule, but never reports the absent submodule candidate as a broken link after the parent module resolved because \`name\` may be a function, class, or variable. File and module scopes fail closed without a safe anchor, with homonymous implementation candidates, or with missing local dependencies; only \`--escopo projeto\` may walk every configured code root. Logical roots such as \`src\` are probed deterministically without a discovery walk. Configured contract origins and code roots are confined before enumeration, and \`inspecionar\`, \`impacto\`, and \`renomear-semantico\` reuse the same directed boundary without reopening arbitrary external paths.
584
+
585
+ Drift analysis and cache modes are explicit:
586
+
587
+ - \`sema drift\` defaults to \`--cache fresh\`. \`none\` still executes drift but performs zero persistent-cache I/O; \`cache\` reuses a fully validated extraction hit and publishes misses; \`fresh\` ignores hits, recalculates, and publishes the new extraction.
588
+ - \`sema resumo\` and \`sema inspecionar\` default to \`--drift none\`. In that mode their payload does not execute drift and returns \`null\` for score, confidence, implementation, routes, or other code evidence that was not observed. Use \`--drift cache\` or \`--drift fresh\` when that evidence is required. \`--com-drift\` remains a temporary alias for \`--drift fresh\`.
589
+ - When a query explicitly runs drift, \`payload.analiseDrift.sucesso\` exposes the result and a failed requested analysis returns a nonzero exit code.
590
+ - The value aliases \`off\`, \`auto\`, and \`refresh\` normalize to \`none\`, \`cache\`, and \`fresh\` for one compatibility release and emit a structured deprecation warning. Wrong flags, repeated flags, conflicts, and invalid values fail instead of falling back silently.
591
+ - Persistent cache objects live outside the workspace under the operating system's user-cache directory. Workspace identity is hashed; public JSON and events expose only an opaque key and \`$SEMA_CACHE/...\` paths. Corruption or cache unavailability becomes a miss and never changes the drift result. Only validated extraction data is reused; links, diagnostics, scores, and the final success decision are recalculated.
592
+
593
+ A cache hit is acceleration, not final evidence; closure still requires fresh drift.
594
+
595
+ ## Sema Code
596
+
597
+ - \`sema compilar <arquivo-ou-pasta> --alvo <typescript|python|php|dart|lua|javascript|html|css|dotnet|cpp> --saida <diretorio> [--estrutura <flat|modulos|backend>] [--framework <base|nestjs|fastapi>]\`: generates starter/support artifacts from the contract.
598
+ - \`sema testar <arquivo.sema> --alvo <alvo> --saida <diretorio-temporario>\`: generates and runs local tests when the target supports it.
599
+ - \`sema importar <nestjs|express|fastify|koa|fastapi|flask|nextjs|nextjs-consumer|react-vite-consumer|angular-consumer|flutter-consumer|sveltekit-consumer|nuxt-consumer|firebase|typescript|python|dart|dotnet|java|go|rust|cpp|php> <diretorio> --saida <diretorio> --json\`: imports a legacy project into initial contracts; only these sources have a real importer.
600
+ - \`sema renomear-semantico <arquivo-ou-pasta> --de <nome> --para <nome> --json\`: helps rename symbols semantically.
601
+
602
+ Rule for \`--saida\`: the folder passed to \`sema compilar --saida\` is generated output. It is not the final delivery by itself. The final delivery is the target files/links declared by the contract. If the contract asks for \`index.html\`, \`css/styles.css\`, and \`js/app.js\`, creating only \`saida/expense_control.ts\` does not complete the task.
603
+
604
+ Sema Code traceability rule: generated artifacts must point back to the source module/contract and preserve that the same final file may be governed by several \`.sema\` contracts through \`vinculos\`. Do not force a 1:1 contract-file relationship and do not treat \`saida/\` as the final project.
605
+
606
+ Ready UI rule: if the task generates an app, site, dashboard, form, or static HTML, run desktop/mobile visual validation when the surface allows it. On narrow mobile (for example 390px), \`scrollWidth <= clientWidth\` must pass; a layout that stacks but overflows horizontally is not responsive.
607
+
608
+ ## Canonical Syntax Lists
609
+
610
+ - Origins for \`use\` and \`impl\` (11, aliases after \`/\`): \`ts/typescript\`, \`js/javascript\`, \`py/python\`, \`dart\`, \`lua\`, \`cs/csharp/dotnet\`, \`java\`, \`go/golang\`, \`rust/rs\`, \`cpp/cxx/cc/c++\`, \`php\`.
611
+ - Layered \`impl\` roles: append \`_rota\`, \`_servico\`, \`_persistencia\` or \`_repositorio\` to any origin (\`ts_rota\`, \`php_servico\`, \`cs_persistencia\`, \`py_repositorio\`).
612
+ - Generation targets (10): \`typescript\`, \`javascript/js\`, \`python\`, \`php\`, \`dart\`, \`lua\`, \`html\`, \`css\`, \`dotnet/cs/csharp\`, \`cpp/c++/cxx/cc\`.
613
+ - \`sema iniciar --template\` (14): \`base\`, \`nestjs\`, \`fastapi\`, \`nextjs-api\`, \`nextjs-consumer\`, \`react-vite-consumer\`, \`angular-consumer\`, \`flutter-consumer\`, \`node-firebase-worker\`, \`aspnet-api\`, \`springboot-api\`, \`go-http-api\`, \`rust-axum-api\`, \`cpp-service-bridge\`.
614
+ - Frequent \`effects\` categories: \`persistencia\`, \`consulta\`, \`evento\`, \`auditoria\`, \`db.write\`, \`queue.publish\`, \`fs.write\`, \`network.egress\`, \`secret.read\`, \`shell.exec\`.
615
+ - Accepted \`audit.motivo\` values: \`obrigatorio\`, \`opcional\`, \`dispensado\`.
616
+
617
+ \`sema compilar --alvo javascript\` is a generation target. \`impl { js: ... }\` is the live-code origin. Do not swap one for the other.
618
+
619
+ ## Codex and Context
620
+
621
+ Project initialization creates configuration and agent rules without inventing a business contract.
622
+ Demonstrations stay under exemplos/; active contracts are authored in contratos/ for the actual request.
623
+ An adopted workspace with no contracts returns contrato_necessario and does not validate an application.
624
+
625
+ The CLI selects context files before generation: micro up to 32,768 tokens,
626
+ short up to 131,072, expanded above that. The budget may lower the selected
627
+ level further. Only the matching summary is materialized; other variants
628
+ are removed from active entry files, with existing edits preserved in
629
+ .sema/contexto-legado/. Internal indexes are not required readings.
630
+ A session already supplying the needed task context does not require another summary.
631
+
632
+ Freshness checks managed instructions, contract hashes and changes to the
633
+ materialized context profile. Synchronization preserves manual AGENTS rules.
634
+ The budget counts AGENTS.md, SEMA_BOOT.md and the current delivery, using
635
+ characters / 4. It does not measure chat history, host instructions or
636
+ cumulative future file reads and tool results. Oversized requests must refine
637
+ the scope; no blocking rule is silently waived.
638
+
639
+ validar and formatar require selected .sema contracts. Empty scope returns
640
+ SEM_CLI_SEM_CONTRATOS and does not validate an application or adopt a project.
641
+ First-time adoption requires consent and the configured context window.
642
+
643
+ - \`sema ajuda-ia\`: short guidance for Codex.
644
+ - \`sema starter-ia\`: operational starter.
645
+ - \`sema contexto-ia <arquivo.sema> --saida <dir> --json\`: profile-selected context files; raw AST/IR/drift are consulted separately only when needed.
646
+ - \`sema resumo <arquivo-ou-pasta> [--drift <none|cache|fresh>] --json\`: compact context; drift is not executed unless requested.
647
+ - \`sema prompt-curto <arquivo-ou-pasta> --json\`: compact prompt.
648
+ - \`sema sync-codex --json\`: synchronizes the official Codex entrypoint and local support docs.
649
+ - \`sema instalar-exemplos --json\`: installs official examples in the workspace.
650
+ - \`sema exemplos-prompt-ia\`: shows prompt examples, not \`.sema\` examples.
651
+
652
+ ## Profiles and Author
653
+
654
+ - \`sema author iniciar|validar|briefing|revisar-cliches|validar-narrativa|validar-proibicoes\`: governs authorial writing.
655
+ - \`sema profile validar <software|workflow|ops|game|simulation|legal|research|redacao|propostas|conversas> <arquivo> --json\`: validates an artifact by profile.
656
+ - \`sema profile capabilities --json\`: lists profiles/capabilities.
657
+ - \`sema rule-packs --profile <profile> --json\`: lists rule packs.
658
+
659
+ \`author\` is a specialized \`sema author\` workflow, not a \`profile validar\` alias. Discovery exposes that distinction explicitly.
660
+
661
+ ## AI-native Content Pipeline
662
+
663
+ - \`sema conteudo capabilities --json\`: lists generic producer, evaluator, and adapter capabilities without fixing a platform.
664
+ - \`sema conteudo validar <definition.json> --json\`: validates the content DAG, gates, and open adapters.
665
+ - \`sema conteudo planejar <definition.json> --alvos-arquivo <targets.json> --json\`: creates a declarative multi-target plan for an external runner.
666
+ - \`sema conteudo validar-envelope --envelope-arquivo <envelope.json> --confianca-arquivo <trust.json> --trust-root-digest <sha256:...> --revocation-digest <sha256:...> --payload-type <type> --json\`: verifies Ed25519 identity, authorization, freshness, scope, and the separately pinned trust root and current revocation overlay.
667
+ - \`sema conteudo registrar <ledger.ndjson> --envelope-arquivo <envelope.json> --politica-arquivo <policy-envelope.json> --confianca-arquivo <trust.json> --trust-root-digest <sha256:...> --revocation-digest <sha256:...> --ledger-id <id> --expected-head <sha256:...> --json\`: appends a verified envelope under the signed run policy to the local replay ledger at an externally retained head.
668
+ - \`sema conteudo status <definition.json> --politica-arquivo <policy-envelope.json> --confianca-arquivo <trust.json> --trust-root-digest <sha256:...> --revocation-digest <sha256:...> --ledger-arquivo <ledger.ndjson> --expected-head <sha256:...> --json\`: verifies the signed policy and its \`targetSetDigest\`, then derives verdicts, operational conditions, completion, and next actions from canonical events.
669
+ - \`sema conteudo projetar <definition.json> --politica-arquivo <policy-envelope.json> --confianca-arquivo <trust.json> --trust-root-digest <sha256:...> --revocation-digest <sha256:...> --ledger-arquivo <ledger.ndjson> --expected-head <sha256:...> --saida <manifest.json> --json\`: regenerates a non-authoritative manifest bound to the ledger head.
670
+
671
+ The content command is an AI-native, multi-channel, multi-format control plane. It never runs producers, evaluators, creative tools, or publication adapters; those belong to an external runner. It has no native human-review transition. A signed policy binds \`runId\`, definition, ledger, trust root, gates, complete target set, and the full \`issuedAt\`/\`expiresAt\` authorization window; no event may be recorded outside it. Stages select \`adapterPolicy\` as \`NONE\`, \`CONSTRAINTS\`, or \`CONFIRMATION\`; definition v1 accepts one output per stage. Constraint results must come from independent signed observations, including independently observed media type, not artifact metadata or executor claims. Target metadata is an exact scalar allowlist from \`requiredMetadata + optionalMetadata\`; \`accountScope\` is a credential-free \`account:<alias>\` reference, and artifact metadata is prohibited in v1. Deterministic evidence and AI opinions have separate quorum fields. Evidence requires an exact \`content.evidence.attest:<evidenceType>\` capability; adapter evidence requires \`content.adapter.attest:<adapterId>@<version>:<evidenceType>\` plus signed adapter binding.
672
+
673
+ Verdicts such as \`APROVADO\`, \`REPROVADO\`, and \`INCONCLUSIVO\` remain separate from operational conditions such as \`AGUARDANDO_EVENTO_EXTERNO\` and \`FERRAMENTA_INDISPONIVEL\`. A generated manifest is only a projection and cannot alter canonical state.
674
+
675
+ Local NDJSON plus a hash chain is portable evidence for replay, not a strong append-only trust boundary. Retain \`expectedHead\`, the canonical trust-root digest, and the current revocation digest externally, or use protected storage for high assurance. The trust-root pin identifies the authority snapshot independently from the revocation overlay. A workspace-local trust file additionally requires \`--development-local-trust\`; the flag does not disable digest pinning. Append freshness uses the platform clock rather than caller-provided \`recordedAt\`, and an authority in the current revocation overlay cannot sign an accepted policy.
676
+
677
+ ## AI-native Interactive Systems
678
+
679
+ - \`sema interativo capabilities --json\`: lists the canonical interactive capability vocabulary.
680
+ - \`sema interativo schema --json\`: exposes the stable read-only definition schema, enum matrix, constraints, extension-command and data-schema shapes, plus canonical example paths for AI clients.
681
+ - \`sema interativo pipelines --json\`: lists reusable game, simulation, and hybrid pipelines.
682
+ - \`sema interativo adapters [--spatial-model <NON_SPATIAL|TWO_D|TWO_POINT_FIVE_D|THREE_D>] [--render-mode <HEADLESS|TEXT|VISUAL|XR>] --json\`: lists compatible external adapter descriptors.
683
+ - \`sema interativo validar <definition.json> --json\`: validates independent kind, spatial model, render mode, visual profile, fidelity, control, time, world, budget, pipeline, and acceptance axes.
684
+ - \`sema interativo planejar <definition.json> --json\`: expands compatible stages and required evidence without running an engine.
685
+ - \`sema interativo validar-evidencias|status <definition.json> [--plano-arquivo <plan.json>] --bundle-arquivo <bundle.json> --json\`: validates a portable evidence bundle or derives non-authoritative status; \`--evidencias-arquivo\` is an alias and an omitted plan is recomputed deterministically.
686
+ - \`sema interativo validar-protocolo <adapter-run.json> --json\`: checks DETECT/PROBE/SNAPSHOT/PLAN/APPLY/VALIDATE/EVIDENCE/ROLLBACK ordering and stable target binding.
687
+ - Experience IR: \`validar-ir\`, \`indexar-ir\`, \`consultar-ir --semantic-id <id>\`, \`chunk-ir --semantic-id <id> [--raso]\`, and \`descrever-ir\`.
688
+ - Operational state: \`validar-engine-snapshot\`, \`diff-engine-snapshots\`, \`validar-asset-provenance\`, \`validar-editor-state\`, \`planejar-jobs\`, \`validar-acceptance\`, \`operar-acceptance --operation <VALIDATE|EVALUATE|INVALIDATE> --context-file <file>\`, and \`validar-multimodal\`.
689
+ - Temporal, autonomy, and testing: \`validar-temporal\`, \`validar-evidencia-temporal --bundle-arquivo <file>\`, \`validar-autonomia\`, \`validar-playtest-fuzz\`, and \`validar-multiplayer\`.
690
+ - Portability and workers: \`analisar-portabilidade\` and \`validar-workers\`.
691
+ - \`sema interativo validar-control-run <control-run.json> --definition-arquivo <definition.json> --plano-arquivo <plan.json> --contrato-arquivo <validation-contract.json> --entrada-arquivo <input.json> [--entrada-auxiliar-arquivo <supporting-input.json>] --evidencia-arquivo <evidence.json> --resultado-arquivo <result.json> --json\`: binds one advanced validation to its complete local digest chain instead of trusting a standalone result.
692
+
693
+ The control-run command recomputes the canonical plan and selected pure validator, then verifies the definition, pipeline descriptor, validation contract, schema-declared inputs, evidence, and result digests. Prefix advanced items with \`sema interativo\` and pass the documented JSON file as the positional argument; an agent does not have to infer the validator or payload shape from a filename or visual style. The machine-readable schema publishes command maps, input/output schema links, required top-level fields, \`outputTargets\` path segments from the payload root, at least one real output shape per command, and official fixtures for all 20 advanced commands. Validation-result shapes describe \`payload.resultado\`; projected IR values use \`indice\`, \`entry\`, \`chunk\`, or \`descriptor\`; operation projections such as \`engineDiff\` and \`jobOrchestrationPlan\` live under \`payload.resultado.value\`; the job plan's ordered \`queue\` is the assignment list and exposes kind, priority, adapter, dependencies, locks, budgets, heartbeat, checkpoint, and recovery data.
694
+
695
+ Spatial model and render mode are orthogonal: \`THREE_D + HEADLESS\` is valid, while XR requires \`THREE_D\`. \`PIXEL_8_BIT\` and \`PIXEL_16_BIT\` are independent visual profiles available to games and simulations. Every command above rejects unknown, duplicate, missing-value, or invalid-enum arguments, remains local, read-only, and non-authoritative, and leaves engine/editor execution, authorization, mutation, rollback, migration, rendering, playtest, and worker scheduling to external runners. Full local coverage is \`STRUCTURALLY_COMPLETE\`, never authoritative completion, and a local evidence bundle is never presented as authoritative trust.
696
+
697
+ ## Operational
698
+
699
+ - \`sema doctor\`: diagnoses local installation.
700
+
701
+ ## Forbidden
702
+
703
+ - Do not use an external workspace source to inspect a local workspace when \`sema --version\` or the managed launcher works.
704
+ - Do not search the entire disk for \`.sema\` syntax; use \`exemplos/\`, \`docs/syntax.md\`, and this catalog.
705
+ - Do not stop after \`sema compilar\` if the contract target files still do not exist.
706
+ - Do not replace \`sema compilar\` with \`sema testar\` when the contract requires generated code.
707
+ - Do not create a Markdown report to pretend a gate ran.
708
+ - Do not say drift passed when the unwrapped \`sema drift --cache fresh --json\` payload returned \`sucesso:false\`, a non-empty \`vinculos_quebrados\`, \`rotas_divergentes\`, or \`impls_quebrados\` list. \`vinculos_fora_do_escopo\` entries are informational scope hints, not broken links.
709
+ - Do not declare a UI responsive without mobile/desktop proof; horizontal scroll at 390px blocks closure.
710
+
711
+ Historical migration rule: Historical migrations (including Prisma migrations/<timestamp>_<name>/migration.sql) retain their SQL bytes and contract links. Do not add headers, reformat SQL or remove a binding just to pass a gate. The path proves neither application nor checksum: check the project runbook and database migration history. Change behavior through a new migration and current schema/code bindings, preserving relevant historical references.
712
+
713
+ Governed code policy: keep the \`SEMA-GOVERNED\` marker, split large code by real responsibility, preserve contract links, and never treat a generated output directory as the final delivery.
708
714
  `;
709
715
  }
710
716
  export async function sincronizarEntrypointCodex(baseProjeto, agentContextPack) {