@orkastery/cli 0.6.0 → 0.6.2

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 (118) hide show
  1. package/adapters/claude-code/agents/ork-check.md +1 -1
  2. package/adapters/claude-code/agents/ork-go.md +1 -1
  3. package/adapters/claude-code/agents/ork-goal.md +1 -1
  4. package/adapters/claude-code/agents/ork-master.md +1 -1
  5. package/adapters/claude-code/agents/ork-plan.md +1 -1
  6. package/adapters/claude-code/agents/ork-ship.md +1 -1
  7. package/adapters/claude-code/commands/ork.md +1 -1
  8. package/adapters/claude-code/mods/ork-torre/hooks/frases.ts +2 -0
  9. package/adapters/codex/skills/ork/SKILL.md +1 -1
  10. package/adapters/openclaw/openclaw.plugin.json +1 -1
  11. package/adapters/openclaw/package.json +1 -1
  12. package/assets/adapters-en/claude-code/agents/ork-check.md +1 -1
  13. package/assets/adapters-en/claude-code/agents/ork-go.md +1 -1
  14. package/assets/adapters-en/claude-code/agents/ork-goal.md +1 -1
  15. package/assets/adapters-en/claude-code/agents/ork-master.md +1 -1
  16. package/assets/adapters-en/claude-code/agents/ork-plan.md +1 -1
  17. package/assets/adapters-en/claude-code/agents/ork-ship.md +1 -1
  18. package/assets/adapters-en/claude-code/commands/ork.md +1 -1
  19. package/assets/adapters-en/codex/skills/ork/SKILL.md +1 -1
  20. package/assets/orkmind_fixture.py +4 -1
  21. package/assets/skills-en/core/orkastery-bootstrap/SKILL.md +1 -1
  22. package/assets/skills-en/phases/check-quality/SKILL.md +1 -1
  23. package/assets/skills-en/phases/go-implementation/SKILL.md +1 -1
  24. package/dist/adapters/claude-bg.js +9 -7
  25. package/dist/adapters/grok-events.js +227 -0
  26. package/dist/adapters/grok-mcp-servidor.js +622 -0
  27. package/dist/adapters/grok-mcp.js +178 -0
  28. package/dist/adapters/grok.js +686 -0
  29. package/dist/agendador-cpu.js +92 -0
  30. package/dist/branch-de-estado.js +7 -2
  31. package/dist/changelog-check.js +217 -0
  32. package/dist/check-agil.js +289 -25
  33. package/dist/check-paralelo.js +73 -18
  34. package/dist/ci.js +3 -2
  35. package/dist/claim-lint.js +29 -0
  36. package/dist/claims.js +4 -0
  37. package/dist/conducao.js +5 -0
  38. package/dist/docs.js +16 -16
  39. package/dist/doctor-forja.js +1 -3
  40. package/dist/doctor.js +1 -1
  41. package/dist/entrega-pr.js +10 -10
  42. package/dist/fabrica-estado.js +20 -11
  43. package/dist/fila-pesada.js +121 -11
  44. package/dist/hitl-classificacao.js +1 -0
  45. package/dist/horario.js +4 -1
  46. package/dist/index.js +63 -35
  47. package/dist/integracoes-locais.js +2 -0
  48. package/dist/intelligence-graph-cli.js +27 -9
  49. package/dist/locale-accounts.js +11 -3
  50. package/dist/locale-ajuda.js +10 -6
  51. package/dist/locale-claims.js +16 -2
  52. package/dist/locale-forja.js +2 -4
  53. package/dist/locale-grafo.js +56 -1
  54. package/dist/locale-maestro.js +38 -0
  55. package/dist/locale-network.js +8 -6
  56. package/dist/locale-onboarding.js +14 -0
  57. package/dist/locale-operacao-restante.js +2 -2
  58. package/dist/locale-preflight.js +80 -0
  59. package/dist/locale-projetos.js +6 -0
  60. package/dist/locale-prompts.js +8 -8
  61. package/dist/locale-pulse.js +4 -0
  62. package/dist/locale-retry.js +56 -2
  63. package/dist/locale-security-scan.js +35 -1
  64. package/dist/locale-ship.js +10 -2
  65. package/dist/locale-verify.js +15 -0
  66. package/dist/locale.js +24 -7
  67. package/dist/maestro-cli.js +12 -17
  68. package/dist/manifest.js +6 -1
  69. package/dist/mcp-install.js +24 -13
  70. package/dist/mcp-server.js +62 -33
  71. package/dist/mcp-verify-async.js +353 -0
  72. package/dist/mcp-verify-worker.js +17 -0
  73. package/dist/mcp-verify.js +10 -1
  74. package/dist/merge-da-entrega.js +85 -0
  75. package/dist/network-roadmap.js +18 -14
  76. package/dist/noctum-aceite.js +154 -14
  77. package/dist/noctum-cli.js +69 -12
  78. package/dist/noctum-entrega.js +55 -7
  79. package/dist/noctum-envelope.js +1 -1
  80. package/dist/noctum-execucao.js +5 -1
  81. package/dist/noctum-fechamento.js +18 -7
  82. package/dist/noctum-fila.js +6 -1
  83. package/dist/noctum-guarda.js +81 -4
  84. package/dist/noctum-maquinas.js +5 -1
  85. package/dist/noctum-modo.js +35 -7
  86. package/dist/noctum-reconciliacao.js +4 -1
  87. package/dist/noctum-rede.js +102 -0
  88. package/dist/noctum-relatorio.js +44 -10
  89. package/dist/noctum-retomada-rede.js +71 -0
  90. package/dist/noctum-vigia.js +49 -9
  91. package/dist/parado-no-condutor.js +14 -15
  92. package/dist/pedido-conducao.js +51 -0
  93. package/dist/phase.js +43 -15
  94. package/dist/postura-local.js +7 -3
  95. package/dist/preflight.js +27 -27
  96. package/dist/prompts.js +4 -2
  97. package/dist/pulse.js +4 -2
  98. package/dist/ratelimit.js +1 -0
  99. package/dist/rede.js +24 -12
  100. package/dist/retry.js +115 -10
  101. package/dist/runtime-context.js +165 -45
  102. package/dist/runtime-escada.js +7 -1
  103. package/dist/runtime-profiles.js +27 -17
  104. package/dist/runtimes.js +42 -5
  105. package/dist/security-scan/agil.js +18 -7
  106. package/dist/security-scan/cli.js +2 -2
  107. package/dist/security-scan/executor.js +8 -0
  108. package/dist/security-scan/report.js +1 -1
  109. package/dist/session-watcher-grok.js +425 -0
  110. package/dist/session-watcher.js +52 -11
  111. package/dist/sessoes-contas.js +33 -5
  112. package/dist/setup.js +11 -11
  113. package/dist/varredura-acoes.js +8 -15
  114. package/dist/verify.js +191 -43
  115. package/package.json +2 -2
  116. package/skills/core/orkastery-bootstrap/SKILL.md +1 -1
  117. package/skills/phases/check-quality/SKILL.md +1 -1
  118. package/skills/phases/go-implementation/SKILL.md +1 -1
@@ -27,7 +27,7 @@ ork phase list <thread> # o que ja aconteceu, com evidencia
27
27
 
28
28
  - O modo de conducao afrouxa a PAUSA, nunca a VERIFICACAO.
29
29
  - Nada de self-report: toda alegacao vem com o comando que a comprova e a saida real.
30
- - Esperas: nunca dispare verify, build ou suite com `&` dentro do comando, porque o processo se perde e a sessao espera um aviso que nunca vem; rode o `ork verify` em primeiro plano, com `timeout` (ele espera a vez na fila de recursos pesados), ou use a execucao em segundo plano do host, que avisa quando termina; nunca espere com `pgrep -f` cujo padrao aparece no proprio comando, porque o laco acha a si mesmo e nao termina: espere pelo arquivo de saida com prazo, ou pelo PID guardado.
30
+ - Esperas: nunca dispare verify, build ou suite com `&` dentro do comando, porque o processo se perde e a sessao espera um aviso que nunca vem; prefira `ork_verify` assíncrono e consulte `ork_verify_status` a cada 30–60 s; sem essa ferramenta, rode o `ork verify` em primeiro plano, com `timeout` (ele espera a vez na fila de recursos pesados), ou use a execucao em segundo plano do host, que avisa quando termina; nunca espere com `pgrep -f` cujo padrao aparece no proprio comando, porque o laco acha a si mesmo e nao termina: espere pelo arquivo de saida com prazo, ou pelo PID guardado.
31
31
  - Passo irreversivel (push, merge, delecao) so acontece quando o modo autoriza, e a autorizacao
32
32
  fica registrada no ledger.
33
33
  - Termine dizendo, em uma linha, em que ponto a thread esta e o que acontece agora.
@@ -27,7 +27,7 @@ ork phase list <thread> # o que ja aconteceu, com evidencia
27
27
 
28
28
  - O modo de conducao afrouxa a PAUSA, nunca a VERIFICACAO.
29
29
  - Nada de self-report: toda alegacao vem com o comando que a comprova e a saida real.
30
- - Esperas: nunca dispare verify, build ou suite com `&` dentro do comando, porque o processo se perde e a sessao espera um aviso que nunca vem; rode o `ork verify` em primeiro plano, com `timeout` (ele espera a vez na fila de recursos pesados), ou use a execucao em segundo plano do host, que avisa quando termina; nunca espere com `pgrep -f` cujo padrao aparece no proprio comando, porque o laco acha a si mesmo e nao termina: espere pelo arquivo de saida com prazo, ou pelo PID guardado.
30
+ - Esperas: nunca dispare verify, build ou suite com `&` dentro do comando, porque o processo se perde e a sessao espera um aviso que nunca vem; prefira `ork_verify` assíncrono e consulte `ork_verify_status` a cada 30–60 s; sem essa ferramenta, rode o `ork verify` em primeiro plano, com `timeout` (ele espera a vez na fila de recursos pesados), ou use a execucao em segundo plano do host, que avisa quando termina; nunca espere com `pgrep -f` cujo padrao aparece no proprio comando, porque o laco acha a si mesmo e nao termina: espere pelo arquivo de saida com prazo, ou pelo PID guardado.
31
31
  - Passo irreversivel (push, merge, delecao) so acontece quando o modo autoriza, e a autorizacao
32
32
  fica registrada no ledger.
33
33
  - Termine dizendo, em uma linha, em que ponto a thread esta e o que acontece agora.
@@ -28,7 +28,7 @@ ork phase list <thread> # o que ja aconteceu, com evidencia
28
28
 
29
29
  - O modo de conducao afrouxa a PAUSA, nunca a VERIFICACAO.
30
30
  - Nada de self-report: toda alegacao vem com o comando que a comprova e a saida real.
31
- - Esperas: nunca dispare verify, build ou suite com `&` dentro do comando, porque o processo se perde e a sessao espera um aviso que nunca vem; rode o `ork verify` em primeiro plano, com `timeout` (ele espera a vez na fila de recursos pesados), ou use a execucao em segundo plano do host, que avisa quando termina; nunca espere com `pgrep -f` cujo padrao aparece no proprio comando, porque o laco acha a si mesmo e nao termina: espere pelo arquivo de saida com prazo, ou pelo PID guardado.
31
+ - Esperas: nunca dispare verify, build ou suite com `&` dentro do comando, porque o processo se perde e a sessao espera um aviso que nunca vem; prefira `ork_verify` assíncrono e consulte `ork_verify_status` a cada 30–60 s; sem essa ferramenta, rode o `ork verify` em primeiro plano, com `timeout` (ele espera a vez na fila de recursos pesados), ou use a execucao em segundo plano do host, que avisa quando termina; nunca espere com `pgrep -f` cujo padrao aparece no proprio comando, porque o laco acha a si mesmo e nao termina: espere pelo arquivo de saida com prazo, ou pelo PID guardado.
32
32
  - Passo irreversivel (push, merge, delecao) so acontece quando o modo autoriza, e a autorizacao
33
33
  fica registrada no ledger.
34
34
  - Termine dizendo, em uma linha, em que ponto a thread esta e o que acontece agora.
@@ -29,7 +29,7 @@ ork phase list <thread> # o que ja aconteceu, com evidencia
29
29
 
30
30
  - O modo de conducao afrouxa a PAUSA, nunca a VERIFICACAO.
31
31
  - Nada de self-report: toda alegacao vem com o comando que a comprova e a saida real.
32
- - Esperas: nunca dispare verify, build ou suite com `&` dentro do comando, porque o processo se perde e a sessao espera um aviso que nunca vem; rode o `ork verify` em primeiro plano, com `timeout` (ele espera a vez na fila de recursos pesados), ou use a execucao em segundo plano do host, que avisa quando termina; nunca espere com `pgrep -f` cujo padrao aparece no proprio comando, porque o laco acha a si mesmo e nao termina: espere pelo arquivo de saida com prazo, ou pelo PID guardado.
32
+ - Esperas: nunca dispare verify, build ou suite com `&` dentro do comando, porque o processo se perde e a sessao espera um aviso que nunca vem; prefira `ork_verify` assíncrono e consulte `ork_verify_status` a cada 30–60 s; sem essa ferramenta, rode o `ork verify` em primeiro plano, com `timeout` (ele espera a vez na fila de recursos pesados), ou use a execucao em segundo plano do host, que avisa quando termina; nunca espere com `pgrep -f` cujo padrao aparece no proprio comando, porque o laco acha a si mesmo e nao termina: espere pelo arquivo de saida com prazo, ou pelo PID guardado.
33
33
  - Passo irreversivel (push, merge, delecao) so acontece quando o modo autoriza, e a autorizacao
34
34
  fica registrada no ledger.
35
35
  - Termine dizendo, em uma linha, em que ponto a thread esta e o que acontece agora.
@@ -27,7 +27,7 @@ ork phase list <thread> # o que ja aconteceu, com evidencia
27
27
 
28
28
  - O modo de conducao afrouxa a PAUSA, nunca a VERIFICACAO.
29
29
  - Nada de self-report: toda alegacao vem com o comando que a comprova e a saida real.
30
- - Esperas: nunca dispare verify, build ou suite com `&` dentro do comando, porque o processo se perde e a sessao espera um aviso que nunca vem; rode o `ork verify` em primeiro plano, com `timeout` (ele espera a vez na fila de recursos pesados), ou use a execucao em segundo plano do host, que avisa quando termina; nunca espere com `pgrep -f` cujo padrao aparece no proprio comando, porque o laco acha a si mesmo e nao termina: espere pelo arquivo de saida com prazo, ou pelo PID guardado.
30
+ - Esperas: nunca dispare verify, build ou suite com `&` dentro do comando, porque o processo se perde e a sessao espera um aviso que nunca vem; prefira `ork_verify` assíncrono e consulte `ork_verify_status` a cada 30–60 s; sem essa ferramenta, rode o `ork verify` em primeiro plano, com `timeout` (ele espera a vez na fila de recursos pesados), ou use a execucao em segundo plano do host, que avisa quando termina; nunca espere com `pgrep -f` cujo padrao aparece no proprio comando, porque o laco acha a si mesmo e nao termina: espere pelo arquivo de saida com prazo, ou pelo PID guardado.
31
31
  - Passo irreversivel (push, merge, delecao) so acontece quando o modo autoriza, e a autorizacao
32
32
  fica registrada no ledger.
33
33
  - Termine dizendo, em uma linha, em que ponto a thread esta e o que acontece agora.
@@ -27,7 +27,7 @@ ork phase list <thread> # o que ja aconteceu, com evidencia
27
27
 
28
28
  - O modo de conducao afrouxa a PAUSA, nunca a VERIFICACAO.
29
29
  - Nada de self-report: toda alegacao vem com o comando que a comprova e a saida real.
30
- - Esperas: nunca dispare verify, build ou suite com `&` dentro do comando, porque o processo se perde e a sessao espera um aviso que nunca vem; rode o `ork verify` em primeiro plano, com `timeout` (ele espera a vez na fila de recursos pesados), ou use a execucao em segundo plano do host, que avisa quando termina; nunca espere com `pgrep -f` cujo padrao aparece no proprio comando, porque o laco acha a si mesmo e nao termina: espere pelo arquivo de saida com prazo, ou pelo PID guardado.
30
+ - Esperas: nunca dispare verify, build ou suite com `&` dentro do comando, porque o processo se perde e a sessao espera um aviso que nunca vem; prefira `ork_verify` assíncrono e consulte `ork_verify_status` a cada 30–60 s; sem essa ferramenta, rode o `ork verify` em primeiro plano, com `timeout` (ele espera a vez na fila de recursos pesados), ou use a execucao em segundo plano do host, que avisa quando termina; nunca espere com `pgrep -f` cujo padrao aparece no proprio comando, porque o laco acha a si mesmo e nao termina: espere pelo arquivo de saida com prazo, ou pelo PID guardado.
31
31
  - Passo irreversivel (push, merge, delecao) so acontece quando o modo autoriza, e a autorizacao
32
32
  fica registrada no ledger.
33
33
  - Termine dizendo, em uma linha, em que ponto a thread esta e o que acontece agora.
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  description: Reconhece orkastery maestro e conduz pedidos, retomadas e status na conversa com o Maestro/Builder.
3
3
  argument-hint: "[pedido em linguagem natural|thread|status|board|plan|doctor|modos]"
4
- allowed-tools: Bash(ork:*), Read, mcp__orkastery__ork_thread_status, mcp__orkastery__ork_phase_list, mcp__orkastery__ork_hitl_pending, mcp__orkastery__ork_observe, mcp__orkastery__ork_artifact_read, mcp__orkastery__ork_claims_list, mcp__orkastery__ork_git_status, mcp__orkastery__ork_thread_new, mcp__orkastery__ork_phase_run, mcp__orkastery__ork_preflight
4
+ allowed-tools: Bash(ork:*), Read, mcp__orkastery__ork_thread_status, mcp__orkastery__ork_phase_list, mcp__orkastery__ork_hitl_pending, mcp__orkastery__ork_observe, mcp__orkastery__ork_artifact_read, mcp__orkastery__ork_claims_list, mcp__orkastery__ork_verify_status, mcp__orkastery__ork_git_status, mcp__orkastery__ork_thread_new, mcp__orkastery__ork_phase_run, mcp__orkastery__ork_preflight
5
5
  ---
6
6
 
7
7
  # /orkastery:ork
@@ -7,6 +7,8 @@ export const FRASE_DO_MOTIVO: Readonly<Record<string, string>> = {
7
7
  'artifact.missing': 'falta um artefato que a fase exige',
8
8
  'claims.failed': 'uma claim reprovou no HEAD',
9
9
  'claims.unverifiable': 'há claim sem comando de verificação',
10
+ 'concurrency.lease-indeterminado': 'não foi possível provar se a vaga está livre',
11
+ 'conducao.acao-necessaria': 'a condução precisa executar uma ação',
10
12
  'policy.violation': 'uma policy de bloqueio foi violada',
11
13
  'runtime.autoconferencia': 'o CHECK caiu no mesmo runtime do GO',
12
14
  'verify.regression': 'um teste que passava na baseline caiu',
@@ -44,7 +44,7 @@ O dono conversa sobre o objetivo; voce opera o nucleo `ork` e apresenta o result
44
44
  passo. Preserve o modo e as autorizacoes da thread. Se ja recebeu uma fase do Orkastery,
45
45
  execute essa fase no escopo recebido, sem redespachar a si mesmo.
46
46
 
47
- - Esperas: nunca dispare verify, build ou suite com `&` dentro do comando, porque o processo se perde e a sessao espera um aviso que nunca vem; rode o `ork verify` em primeiro plano, com `timeout` (ele espera a vez na fila de recursos pesados), ou use a execucao em segundo plano do host, que avisa quando termina; nunca espere com `pgrep -f` cujo padrao aparece no proprio comando, porque o laco acha a si mesmo e nao termina: espere pelo arquivo de saida com prazo, ou pelo PID guardado.
47
+ - Esperas: nunca dispare verify, build ou suite com `&` dentro do comando, porque o processo se perde e a sessao espera um aviso que nunca vem; prefira `ork_verify` assíncrono e consulte `ork_verify_status` a cada 30–60 s; sem essa ferramenta, rode o `ork verify` em primeiro plano, com `timeout` (ele espera a vez na fila de recursos pesados), ou use a execucao em segundo plano do host, que avisa quando termina; nunca espere com `pgrep -f` cujo padrao aparece no proprio comando, porque o laco acha a si mesmo e nao termina: espere pelo arquivo de saida com prazo, ou pelo PID guardado.
48
48
 
49
49
  Quando descobertas, prefira as ferramentas MCP vinculadas ao projeto pelo servidor:
50
50
  `ork_thread_status`, `ork_phase_list`, `ork_hitl_pending`, `ork_thread_new(nome, modo)`,
@@ -2,7 +2,7 @@
2
2
  "id": "orkastery",
3
3
  "name": "Orkastery",
4
4
  "description": "Conducao de looping threads em 6 fases pelo nucleo `ork`, exposta ao OpenClaw como tools `ork_*`. Zero regra de negocio no host: cada tool e uma chamada de CLI. Toda tool de projeto aceita projeto (nome do projeto pedido); o cwd do gateway nunca escolhe o projeto. O status do roadmap vem de ork_network_roadmap; as maquinas da pessoa, de ork_network_status (sem projeto).",
5
- "version": "0.6.0",
5
+ "version": "0.6.2",
6
6
  "configSchema": {
7
7
  "type": "object",
8
8
  "properties": {},
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orkastery/openclaw-plugin",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "Plugin Orkastery para OpenClaw: 32 tools ork_* que traduzem intencao em chamada de CLI do nucleo `ork`. Zero regra de negocio no host.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -27,7 +27,7 @@ ork phase list <thread> # o que ja aconteceu, com evidencia
27
27
 
28
28
  - The conduction mode loosens the PAUSE, never the VERIFICATION.
29
29
  - No self-report: every statement comes with the command that proves it and the real output.
30
- - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
30
+ - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; prefer asynchronous `ork_verify` and query `ork_verify_status` every 30–60 s; without it, run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
31
31
  - An irreversible step (push, merge, deletion) only happens when the mode authorizes it, and the authorization
32
32
  is recorded in the ledger.
33
33
  - End by saying, in one line, where the thread stands and what happens now.
@@ -27,7 +27,7 @@ ork phase list <thread> # o que ja aconteceu, com evidencia
27
27
 
28
28
  - The conduction mode loosens the PAUSE, never the VERIFICATION.
29
29
  - No self-report: every statement comes with the command that proves it and the real output.
30
- - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
30
+ - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; prefer asynchronous `ork_verify` and query `ork_verify_status` every 30–60 s; without it, run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
31
31
  - An irreversible step (push, merge, deletion) only happens when the mode authorizes it, and the authorization
32
32
  is recorded in the ledger.
33
33
  - End by saying, in one line, where the thread stands and what happens now.
@@ -28,7 +28,7 @@ ork phase list <thread> # o que ja aconteceu, com evidencia
28
28
 
29
29
  - The conduction mode loosens the PAUSE, never the VERIFICATION.
30
30
  - No self-report: every statement comes with the command that proves it and the real output.
31
- - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
31
+ - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; prefer asynchronous `ork_verify` and query `ork_verify_status` every 30–60 s; without it, run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
32
32
  - An irreversible step (push, merge, deletion) only happens when the mode authorizes it, and the authorization
33
33
  is recorded in the ledger.
34
34
  - End by saying, in one line, where the thread stands and what happens now.
@@ -29,7 +29,7 @@ ork phase list <thread> # o que ja aconteceu, com evidencia
29
29
 
30
30
  - The conduction mode loosens the PAUSE, never the VERIFICATION.
31
31
  - No self-report: every statement comes with the command that proves it and the real output.
32
- - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
32
+ - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; prefer asynchronous `ork_verify` and query `ork_verify_status` every 30–60 s; without it, run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
33
33
  - An irreversible step (push, merge, deletion) only happens when the mode authorizes it, and the authorization
34
34
  is recorded in the ledger.
35
35
  - End by saying, in one line, where the thread stands and what happens now.
@@ -27,7 +27,7 @@ ork phase list <thread> # o que ja aconteceu, com evidencia
27
27
 
28
28
  - The conduction mode loosens the PAUSE, never the VERIFICATION.
29
29
  - No self-report: every statement comes with the command that proves it and the real output.
30
- - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
30
+ - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; prefer asynchronous `ork_verify` and query `ork_verify_status` every 30–60 s; without it, run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
31
31
  - An irreversible step (push, merge, deletion) only happens when the mode authorizes it, and the authorization
32
32
  is recorded in the ledger.
33
33
  - End by saying, in one line, where the thread stands and what happens now.
@@ -27,7 +27,7 @@ ork phase list <thread> # o que ja aconteceu, com evidencia
27
27
 
28
28
  - The conduction mode loosens the PAUSE, never the VERIFICATION.
29
29
  - No self-report: every statement comes with the command that proves it and the real output.
30
- - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
30
+ - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; prefer asynchronous `ork_verify` and query `ork_verify_status` every 30–60 s; without it, run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
31
31
  - An irreversible step (push, merge, deletion) only happens when the mode authorizes it, and the authorization
32
32
  is recorded in the ledger.
33
33
  - End by saying, in one line, where the thread stands and what happens now.
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  description: Recognizes orkastery maestro and conducts requests, resumptions and status in the conversation with the Maestro/Builder.
3
3
  argument-hint: "[natural-language request|thread|status|board|plan|doctor|modos]"
4
- allowed-tools: Bash(ork:*), Read, mcp__orkastery__ork_thread_status, mcp__orkastery__ork_phase_list, mcp__orkastery__ork_hitl_pending, mcp__orkastery__ork_observe, mcp__orkastery__ork_artifact_read, mcp__orkastery__ork_claims_list, mcp__orkastery__ork_git_status, mcp__orkastery__ork_thread_new, mcp__orkastery__ork_phase_run, mcp__orkastery__ork_preflight
4
+ allowed-tools: Bash(ork:*), Read, mcp__orkastery__ork_thread_status, mcp__orkastery__ork_phase_list, mcp__orkastery__ork_hitl_pending, mcp__orkastery__ork_observe, mcp__orkastery__ork_artifact_read, mcp__orkastery__ork_claims_list, mcp__orkastery__ork_verify_status, mcp__orkastery__ork_git_status, mcp__orkastery__ork_thread_new, mcp__orkastery__ork_phase_run, mcp__orkastery__ork_preflight
5
5
  ---
6
6
 
7
7
  # /orkastery:ork
@@ -44,7 +44,7 @@ The owner talks about the goal; you operate the `ork` core and present the resul
44
44
  step. Preserve the thread's mode and authorizations. If you already received an Orkastery phase,
45
45
  run that phase within the received scope, without redispatching yourself.
46
46
 
47
- - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
47
+ - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; prefer asynchronous `ork_verify` and query `ork_verify_status` every 30–60 s; without it, run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
48
48
 
49
49
  When discovered, prefer the MCP tools bound to the project by the server:
50
50
  `ork_thread_status`, `ork_phase_list`, `ork_hitl_pending`, `ork_thread_new(nome, modo)`,
@@ -4,6 +4,7 @@ import os
4
4
  from pathlib import Path
5
5
  import re
6
6
  import stat
7
+ import tempfile
7
8
  import time
8
9
 
9
10
 
@@ -11,8 +12,10 @@ def receipt_file(filename):
11
12
  try:
12
13
  path = Path(filename)
13
14
  root = path.parent
15
+ temp_root = Path(tempfile.gettempdir()).resolve()
14
16
  if (not path.is_absolute() or not re.fullmatch(r'receipt(?:-[a-f0-9]+)?\.json', path.name)
15
- or not re.fullmatch(r'/tmp/ork-prospective-fixture-[a-zA-Z0-9-]+', str(root))
17
+ or root.parent != temp_root
18
+ or not re.fullmatch(r'ork-prospective-fixture-[a-zA-Z0-9-]+', root.name)
16
19
  or root.resolve() != root or root.is_symlink()):
17
20
  raise ValueError()
18
21
  st = root.stat()
@@ -21,7 +21,7 @@ Distinguish the context before acting:
21
21
  - **Conductor session:** receives the owner's request, identifies or opens the thread, dispatches through `ork` and tracks the result; never writes product code in place of the dispatched session.
22
22
  - **Already dispatched phase session:** has received the thread, phase, prompt and worktree from `ork`.
23
23
  Work within that scope through the phase skill. Do not open another thread or redispatch your own phase to do the work already assigned to you.
24
- - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
24
+ - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; prefer asynchronous `ork_verify` and query `ork_verify_status` every 30–60 s; without it, run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
25
25
 
26
26
  ## Start or resume
27
27
 
@@ -23,7 +23,7 @@ ork worktree audit <thread> # a worktree confere no proprio git
23
23
  ork gate request <thread> # o pedido da pausa; o humano responde pelo canal autenticado
24
24
  ```
25
25
 
26
- - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
26
+ - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; prefer asynchronous `ork_verify` and query `ork_verify_status` every 30–60 s; without it, run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
27
27
 
28
28
  When the verdict is PRECISA DE MUDANCA, the GO-FIX / CHECK-REVERIFY sub-loop of block B3 is
29
29
  what conducts the way back, and it does not depend on a human until the final verdict:
@@ -24,7 +24,7 @@ ork claims add <thread> <arquivo> --claim "<...>" --verificar "<comando>" --fase
24
24
  ork verify <thread> # reexecuta no HEAD real
25
25
  ```
26
26
 
27
- - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
27
+ - Waits: never start verify, build or the suite with `&` inside the command, because the process gets lost and the session waits for a notice that never comes; prefer asynchronous `ork_verify` and query `ork_verify_status` every 30–60 s; without it, run `ork verify` in the foreground, with `timeout` (it waits its turn in the heavy-resource queue), or use the host's background execution, which tells you when it finishes; never wait with `pgrep -f` whose pattern shows up in the command itself, because the loop finds itself and never ends: wait for the output file with a deadline, or for the saved PID.
28
28
 
29
29
  ## What GO delivers
30
30
 
@@ -42,7 +42,7 @@ var __importStar = (this && this.__importStar) || (function () {
42
42
  };
43
43
  })();
44
44
  Object.defineProperty(exports, "__esModule", { value: true });
45
- exports.DAEMON_DO_CLAUDE = exports.PRAZO_DO_DAEMON_MS = exports.JANELA_CURTA_MAX_MS = exports.MOD_DA_ENTREGA = exports.MOD_DOS_TETOS = exports.MINIMO_DA_API_DE_MODS = exports.NOME_ADAPTER = void 0;
45
+ exports.DAEMON_DO_CLAUDE = exports.PRAZO_DO_DAEMON_MS = exports.JANELA_CURTA_MAX_MS = exports.MOD_DA_ENTREGA = exports.MOD_DOS_TETOS = exports.MINIMO_DA_API_DE_MODS = exports.MUTACOES_WORKTREE = exports.CONSULTAS_MCP = exports.NOME_ADAPTER = void 0;
46
46
  exports.ambienteDoPerfil = ambienteDoPerfil;
47
47
  exports.semContextoDeDespacho = semContextoDeDespacho;
48
48
  exports.disponivel = disponivel;
@@ -103,19 +103,21 @@ function semContextoDeDespacho(base, contexto) {
103
103
  delete env[chave];
104
104
  return env;
105
105
  }
106
- /** Consultas do perfil interactive; gates e respostas humanas nunca recebem grant. */
107
- const CONSULTAS_MCP = [
106
+ /** Consultas do perfil interactive; gates e respostas humanas nunca recebem grant. RM-067 (F4b): o grok usa as mesmas. */
107
+ exports.CONSULTAS_MCP = [
108
108
  'mcp__orkastery__ork_thread_status',
109
109
  'mcp__orkastery__ork_phase_list',
110
110
  'mcp__orkastery__ork_hitl_pending',
111
111
  'mcp__orkastery__ork_observe',
112
112
  'mcp__orkastery__ork_artifact_read',
113
113
  'mcp__orkastery__ork_claims_list',
114
+ 'mcp__orkastery__ork_verify_status',
114
115
  ];
115
116
  // RM-037 (defeito 1): a decisao autonoma pelo MCP tem o mesmo grant nos dois runtimes.
116
- const MUTACOES_WORKTREE = [
117
+ exports.MUTACOES_WORKTREE = [
117
118
  'mcp__orkastery__ork_artifact_write', 'mcp__orkastery__ork_claim_add', 'mcp__orkastery__ork_decision_record',
118
- 'mcp__orkastery__ork_git_commit', 'mcp__orkastery__ork_verify', 'mcp__orkastery__ork_ship',
119
+ 'mcp__orkastery__ork_request_conduction', 'mcp__orkastery__ork_git_commit', 'mcp__orkastery__ork_verify',
120
+ 'mcp__orkastery__ork_ship',
119
121
  ];
120
122
  /**
121
123
  * RM-031 KG5 (D7): as consultas do grafo, de leitura, so com a flag do manifesto da raiz; sem ela, nada muda.
@@ -133,7 +135,7 @@ function permissoesDaWorktree(cwd, permiteEditarProduto, consultas) {
133
135
  for (const prefixo of [`${absoluto}/${nome}`, `${absoluto}/**/${nome}`])
134
136
  deny.push(`Edit(${prefixo})`, `Edit(${prefixo}/**)`);
135
137
  }
136
- return { allow: [...consultas, 'mcp__orkastery__ork_git_status', ...MUTACOES_WORKTREE, ...(permiteEditarProduto ? [`Edit(${absoluto}/**)`] : [])], deny };
138
+ return { allow: [...consultas, 'mcp__orkastery__ork_git_status', ...exports.MUTACOES_WORKTREE, ...(permiteEditarProduto ? [`Edit(${absoluto}/**)`] : [])], deny };
137
139
  }
138
140
  /** O runtime esta disponivel nesta maquina? */
139
141
  function disponivel() {
@@ -246,7 +248,7 @@ function montarComando(pedido) {
246
248
  args.push('--settings', JSON.stringify({ env: doDespacho, ...(teams ? { teammateMode: teams.teammateMode } : {}), ...(entrada ?? {}) }));
247
249
  }
248
250
  if (contexto) {
249
- const consultas = [...CONSULTAS_MCP, ...(contexto.grafoMcp ? consultasDoGrafoMcp() : [])];
251
+ const consultas = [...exports.CONSULTAS_MCP, ...(contexto.grafoMcp ? consultasDoGrafoMcp() : [])];
250
252
  // Somente o servidor gerado: nao mesclar MCP de outros escopos nesta sessao filha.
251
253
  const permissoes = contexto.permissoesFilho === 'worktree'
252
254
  ? permissoesDaWorktree(pedido.cwd, contexto.permiteEditarProduto && !plano, consultas) : null;
@@ -0,0 +1,227 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ParserGrok = exports.LIMITE_ERRO_GROK = exports.LIMITE_LINHA_GROK = exports.STOP_CANCELADO = exports.STOP_FIM_NORMAL = void 0;
37
+ exports.redigirTextoGrok = redigirTextoGrok;
38
+ exports.redigirErroGrok = redigirErroGrok;
39
+ exports.tokensDoFim = tokensDoFim;
40
+ exports.falhaDeContaDoTextoGrok = falhaDeContaDoTextoGrok;
41
+ exports.falhaDoErroGrok = falhaDoErroGrok;
42
+ exports.lerStreamGrok = lerStreamGrok;
43
+ /**
44
+ * RM-067 (F2 da ork-grokbuild, D7): o stream `streaming-json` do Grok Build (`grok -p ... --output-format
45
+ * streaming-json`), lido por linha.
46
+ *
47
+ * Formato do guia `14-headless-mode` do repositório `xai-org/grok-build`, lido em 25/10/2026: NDJSON com `type`. O `end`
48
+ * é sempre o último evento e traz `stopReason` em snake_case (`end_turn`, `max_tokens`, `max_turn_requests`, `refusal`,
49
+ * `cancelled`), `sessionId`, `requestId`, `usage`, `num_turns`, `modelUsage` e, só quando o servidor informa o custo
50
+ * inteiro, `total_cost_usd`; o `error` traz `message`. A lista de tipos não é exaustiva (`max_turns_reached`,
51
+ * `auto_compact_*`): tipo desconhecido é ignorado. O texto do agente (`text`, `thought`) nunca classifica nada; só o
52
+ * `end` e o `error`, que o próprio runtime grava, entram no resultado.
53
+ */
54
+ const fs = __importStar(require("node:fs"));
55
+ const hitl_1 = require("../hitl");
56
+ const claude_bg_1 = require("./claude-bg");
57
+ /** O `stopReason` do fim normal do turno. */
58
+ exports.STOP_FIM_NORMAL = 'end_turn';
59
+ /** O `stopReason` do turno cancelado: interrupção, como a saída 130 e a 143. */
60
+ exports.STOP_CANCELADO = 'cancelled';
61
+ /** Linha maior que isto não é evento: invalida o stream sem reter a memória. */
62
+ exports.LIMITE_LINHA_GROK = 1024 * 1024;
63
+ /** Teto da mensagem de erro do runtime que vai ao ledger. */
64
+ exports.LIMITE_ERRO_GROK = 300;
65
+ const STOP = /^[a-z][a-z0-9_]{0,39}$/;
66
+ const ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
67
+ /**
68
+ * D7: um texto do runtime pronto para o ledger, sem corte: os segredos que o núcleo já conhece, a chave da xAI
69
+ * (`xai-...`) e sem controle. GO-FIX 1 (A4): quem corta, corta depois de redigir, para nenhum segredo perder o prefixo.
70
+ */
71
+ function redigirTextoGrok(texto) {
72
+ if (typeof texto !== 'string')
73
+ return '';
74
+ return (0, hitl_1.redigirSegredos)(texto)
75
+ .replace(/\bxai-[A-Za-z0-9_-]{16,}/g, '[redigido]')
76
+ .replace(/\p{Cc}/gu, ' ').replace(/\s+/g, ' ').trim();
77
+ }
78
+ /** D7: a mensagem de erro do runtime, redigida e até `LIMITE_ERRO_GROK` caracteres, sem partir par substituto. */
79
+ function redigirErroGrok(texto) {
80
+ return Array.from(redigirTextoGrok(texto)).slice(0, exports.LIMITE_ERRO_GROK).join('');
81
+ }
82
+ const tokensIndisponiveis = () => ({ disponivel: false, input: null, cachedInput: null, output: null,
83
+ total: null, unidade: 'tokens', escopo: 'sessao', fonte: 'unavailable' });
84
+ /** O `usage` do `end`, só com inteiros não negativos e total que cobre entrada e saída; fora disso, indisponível. */
85
+ function tokensDoFim(v) {
86
+ if (!v || typeof v !== 'object' || Array.isArray(v))
87
+ return tokensIndisponiveis();
88
+ const u = v;
89
+ const inteiro = (n) => Number.isSafeInteger(n) && n >= 0;
90
+ const input = u.input_tokens, output = u.output_tokens, cache = u.cache_read_input_tokens;
91
+ if (!inteiro(input) || !inteiro(output) || (cache !== undefined && !inteiro(cache)))
92
+ return tokensIndisponiveis();
93
+ const total = u.total_tokens === undefined ? input + output : u.total_tokens;
94
+ if (!inteiro(total) || total < input + output)
95
+ return tokensIndisponiveis();
96
+ return { disponivel: true, input, cachedInput: cache === undefined ? null : cache, output, total, unidade: 'tokens',
97
+ escopo: 'sessao', fonte: 'grok.end.usage' };
98
+ }
99
+ class ParserGrok {
100
+ pendente = Buffer.alloc(0);
101
+ descartando = false;
102
+ estado;
103
+ /** Eventos válidos lidos por esta instância: o progresso de uma leitura. */
104
+ eventosValidos = 0;
105
+ constructor(sessaoEsperada, estado) {
106
+ if (estado && estado.sessaoEsperada !== sessaoEsperada)
107
+ throw new Error('estado do parser do grok de outra sessão');
108
+ this.estado = estado ? structuredClone(estado)
109
+ : { sessaoEsperada, fim: null, erro: null, invalido: false, sessaoDivergente: false, eventos: 0 };
110
+ }
111
+ /** Lê as linhas completas do bloco; o resto fica pendente para o próximo. */
112
+ push(chunk) {
113
+ const dados = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
114
+ let inicio = 0;
115
+ for (let i = 0; i < dados.length; i++) {
116
+ if (dados[i] !== 10)
117
+ continue;
118
+ const linha = Buffer.concat([this.pendente, dados.subarray(inicio, i)]);
119
+ if (!this.descartando && linha.length <= exports.LIMITE_LINHA_GROK) {
120
+ if (linha.length) {
121
+ try {
122
+ this.evento(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(linha)));
123
+ }
124
+ catch {
125
+ this.estado.invalido = true;
126
+ }
127
+ }
128
+ }
129
+ else
130
+ this.estado.invalido = true;
131
+ this.pendente = Buffer.alloc(0);
132
+ this.descartando = false;
133
+ inicio = i + 1;
134
+ }
135
+ const resto = dados.subarray(inicio);
136
+ if (this.pendente.length + resto.length > exports.LIMITE_LINHA_GROK) {
137
+ this.descartando = true;
138
+ this.estado.invalido = true;
139
+ this.pendente = Buffer.alloc(0);
140
+ }
141
+ else if (!this.descartando)
142
+ this.pendente = Buffer.concat([this.pendente, resto]);
143
+ }
144
+ evento(bruto) {
145
+ if (!bruto || typeof bruto !== 'object' || Array.isArray(bruto)) {
146
+ this.estado.invalido = true;
147
+ return;
148
+ }
149
+ const e = bruto;
150
+ if (typeof e.type !== 'string' || e.type === '') {
151
+ this.estado.invalido = true;
152
+ return;
153
+ }
154
+ // O guia diz que o `end` é sempre o último: outro `end` ou um `error` depois dele é contrato quebrado.
155
+ if (this.estado.fim && (e.type === 'end' || e.type === 'error')) {
156
+ this.estado.invalido = true;
157
+ return;
158
+ }
159
+ this.eventosValidos++;
160
+ this.estado.eventos++;
161
+ if (e.type === 'error') {
162
+ this.estado.erro = { mensagem: redigirErroGrok(e.message) || 'erro do grok sem mensagem' };
163
+ return;
164
+ }
165
+ if (e.type !== 'end')
166
+ return;
167
+ const sessionId = typeof e.sessionId === 'string' && ID.test(e.sessionId) ? e.sessionId : null;
168
+ if (sessionId !== this.estado.sessaoEsperada)
169
+ this.estado.sessaoDivergente = true;
170
+ this.estado.fim = {
171
+ stopReason: typeof e.stopReason === 'string' && STOP.test(e.stopReason) ? e.stopReason : 'desconhecido',
172
+ sessionId,
173
+ requestId: typeof e.requestId === 'string' && ID.test(e.requestId) ? e.requestId : null,
174
+ numTurnos: Number.isSafeInteger(e.num_turns) && e.num_turns >= 0 ? e.num_turns : null,
175
+ tokens: tokensDoFim(e.usage),
176
+ custoUsd: typeof e.total_cost_usd === 'number' && Number.isFinite(e.total_cost_usd) && e.total_cost_usd >= 0
177
+ ? e.total_cost_usd : null,
178
+ };
179
+ }
180
+ }
181
+ exports.ParserGrok = ParserGrok;
182
+ /**
183
+ * D7 e RM-067 (F3): a falha da CONTA dita por um texto do `grok` (a mensagem do `error` ou o stderr), pelo critério único
184
+ * da D16 (`parseFalhaDeConta`), sem a cota. O formato do erro de cota esgotada do `grok` não está confirmado (E5 da página
185
+ * da RM-067): a fonte não diz o campo nem a mensagem. O sinal tipado de cota só pode vir de erro estruturado do runtime, e
186
+ * uma frase parecida marcaria o perfil e tiraria a conta do rodízio por suposição; até o ensaio real (F5) ler o formato,
187
+ * nenhum texto do `grok` vira `runtime.quota-exhausted`, e o `grok` fica fora da escada automática e do fallback por
188
+ * cota. O login e o modelo seguem pela frase, como na F2.
189
+ */
190
+ function falhaDeContaDoTextoGrok(texto, agoraMs = Date.now()) {
191
+ const falha = (0, claude_bg_1.parseFalhaDeConta)(texto, agoraMs);
192
+ return falha?.motivo === 'runtime.quota-exhausted' ? null : falha;
193
+ }
194
+ /**
195
+ * D7: a falha da CONTA dita pelo próprio runtime no objeto `error` do stream (login, modelo), sem a cota
196
+ * (`falhaDeContaDoTextoGrok`): o que a frase não tipa fica `null`, e a parada segue tipada como `runtime.unavailable`.
197
+ */
198
+ function falhaDoErroGrok(erro, agoraMs = Date.now()) {
199
+ return erro ? falhaDeContaDoTextoGrok(erro.mensagem, agoraMs) : null;
200
+ }
201
+ /**
202
+ * O stream inteiro de um despacho curto (a falha antes da sessão), lido sem seguir link e até `limiteBytes`; `null`
203
+ * quando o arquivo não existe, não é arquivo comum ou passa do limite.
204
+ */
205
+ function lerStreamGrok(arquivo, sessaoEsperada, limiteBytes = 8 * 1024 * 1024) {
206
+ let fd;
207
+ try {
208
+ fd = fs.openSync(arquivo, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
209
+ }
210
+ catch {
211
+ return null;
212
+ }
213
+ try {
214
+ const st = fs.fstatSync(fd);
215
+ if (!st.isFile() || st.size > limiteBytes)
216
+ return null;
217
+ const bytes = Buffer.alloc(st.size);
218
+ fs.readSync(fd, bytes, 0, st.size, 0);
219
+ const parser = new ParserGrok(sessaoEsperada);
220
+ // A última linha sem quebra também é evento: o processo terminou e não vai completá-la.
221
+ parser.push(bytes.length && bytes[bytes.length - 1] !== 10 ? Buffer.concat([bytes, Buffer.from('\n')]) : bytes);
222
+ return parser.estado;
223
+ }
224
+ finally {
225
+ fs.closeSync(fd);
226
+ }
227
+ }