pantheon-opencode 2.0.0-beta.5 → 2.0.0-beta.6

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.
@@ -23,11 +23,22 @@
23
23
  * dispatch-panel layer must never win while this window is open; field
24
24
  * report beta.2: navigation "stopped working" was exactly that theft).
25
25
  */
26
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
26
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
27
27
  import { join } from 'node:path'
28
28
  import type { Context } from '@opencode/plugin/tui/context'
29
29
  import { createSignal, For, onCleanup, Show } from 'solid-js'
30
30
  import {
31
+ buildAutonomyTab,
32
+ DEFAULT_DECISION_BUDGETS,
33
+ DEFAULT_GOAL_LOOP_PREFS,
34
+ type DecisionBudgets,
35
+ type GoalLoopPrefs,
36
+ MONTHLY_USD_CYCLE,
37
+ PER_DECISION_USD_CYCLE,
38
+ parseUsd,
39
+ } from './autonomy-state.ts'
40
+ import {
41
+ applyDecisionRow,
31
42
  buildDecisionTab,
32
43
  type DecisionConfigRead,
33
44
  readDecisionRouterConfig,
@@ -79,12 +90,33 @@ import {
79
90
 
80
91
  export const ROUTE_NAME = 'pantheon-settings'
81
92
 
93
+ /** The input mode the page pushes while mounted (composer layers sleep). */
94
+ export const ROUTE_MODE = 'pantheon-settings'
95
+
82
96
  /** Loose local shape of a host route (the real Route lives in the host typings). */
83
97
  type WindowRoute =
84
98
  | { type: 'home' }
85
99
  | { type: 'session'; sessionID: string }
86
100
  | { type: 'plugin'; name: string; data?: Record<string, unknown> }
87
101
 
102
+ /**
103
+ * Strip a LIVE route object down to the plain shape the route store expects.
104
+ * `router.current()` returns the host's live data (reactive proxies, location
105
+ * objects with cycles) and the host's navigate deep-clones via JSON.stringify
106
+ * — passing the live object through throws "cyclic structures" and the
107
+ * window could never close (field report beta.5, root cause).
108
+ */
109
+ function plainRoute(route: WindowRoute | undefined): WindowRoute {
110
+ if (route === undefined) return { type: 'home' }
111
+ if (route.type === 'session' && 'sessionID' in route && typeof route.sessionID === 'string') {
112
+ return { type: 'session', sessionID: route.sessionID }
113
+ }
114
+ if (route.type === 'plugin' && typeof route.name === 'string') {
115
+ return { type: 'plugin', name: route.name }
116
+ }
117
+ return { type: 'home' }
118
+ }
119
+
88
120
  // ── Shared blocking state (the dispatch panel gates on this) ───────────
89
121
 
90
122
  const [blocking, setBlocking] = createSignal(false)
@@ -133,6 +165,110 @@ function writeOverridesToDisk(load: OverridesLoad): void {
133
165
  writeFileSync(globalOverridesPath(), serializeOverrides(load.global), 'utf8')
134
166
  }
135
167
 
168
+ function userOpenCodeConfigPath(): string {
169
+ const xdgConfig = process.env.XDG_CONFIG_HOME ?? join(process.env.HOME ?? '', '.config')
170
+ return join(xdgConfig, 'opencode', 'opencode.json')
171
+ }
172
+
173
+ /** Read options.goal_loop from the user's opencode.json (fail-open). */
174
+ function readGoalLoopPrefs(): GoalLoopPrefs {
175
+ const fallback = { ...DEFAULT_GOAL_LOOP_PREFS }
176
+ try {
177
+ const parsed = JSON.parse(readFileSync(userOpenCodeConfigPath(), 'utf8')) as {
178
+ options?: { goal_loop?: Partial<GoalLoopPrefs> }
179
+ }
180
+ const raw = parsed?.options?.goal_loop
181
+ if (raw && typeof raw === 'object') {
182
+ return {
183
+ enabled: typeof raw.enabled === 'boolean' ? raw.enabled : fallback.enabled,
184
+ cooldownMs:
185
+ typeof raw.cooldownMs === 'number' && raw.cooldownMs >= 1000
186
+ ? Math.floor(raw.cooldownMs)
187
+ : fallback.cooldownMs,
188
+ maxContinuations:
189
+ typeof raw.maxContinuations === 'number' && raw.maxContinuations >= 1
190
+ ? Math.min(200, Math.floor(raw.maxContinuations))
191
+ : fallback.maxContinuations,
192
+ }
193
+ }
194
+ } catch {
195
+ /* fail-open */
196
+ }
197
+ return fallback
198
+ }
199
+
200
+ /** Read the decision budgets from decision-router.json's `budget` envelope (fail-open). */
201
+ function readDecisionBudgets(): DecisionBudgets {
202
+ const fallback = { ...DEFAULT_DECISION_BUDGETS }
203
+ try {
204
+ const path = join(
205
+ process.env.XDG_CONFIG_HOME ?? join(process.env.HOME ?? '', '.config'),
206
+ 'pantheon',
207
+ 'decision-router.json',
208
+ )
209
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as { budget?: Partial<DecisionBudgets> }
210
+ const raw = parsed?.budget
211
+ if (raw && typeof raw === 'object') {
212
+ return {
213
+ monthlyUsd:
214
+ typeof raw.monthlyUsd === 'number' && raw.monthlyUsd > 0
215
+ ? raw.monthlyUsd
216
+ : fallback.monthlyUsd,
217
+ perDecisionUsd:
218
+ typeof raw.perDecisionUsd === 'number' && raw.perDecisionUsd > 0
219
+ ? raw.perDecisionUsd
220
+ : fallback.perDecisionUsd,
221
+ }
222
+ }
223
+ } catch {
224
+ /* fail-open */
225
+ }
226
+ return fallback
227
+ }
228
+
229
+ /**
230
+ * Surgically set one key under `options` in the user's opencode.json
231
+ * (preserving every other key). Startup-applied options live here — the
232
+ * runtime resolves them once at plugin setup.
233
+ */
234
+ function writeUserOption(key: string, value: unknown): void {
235
+ const path = userOpenCodeConfigPath()
236
+ let doc: Record<string, unknown> = {}
237
+ try {
238
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>
239
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) doc = parsed
240
+ } catch {
241
+ /* start a fresh object — nothing parseable to preserve */
242
+ }
243
+ const options =
244
+ typeof doc.options === 'object' && doc.options !== null && !Array.isArray(doc.options)
245
+ ? { ...(doc.options as Record<string, unknown>) }
246
+ : {}
247
+ options[key] = value
248
+ doc.options = options
249
+ writeFileSync(path, `${JSON.stringify(doc, null, 2)}\n`)
250
+ }
251
+
252
+ /** Merge the `budget` envelope into decision-router.json (0600 preserved). */
253
+ function writeDecisionBudget(budgets: { monthlyUsd: number; perDecisionUsd: number }): void {
254
+ const path = join(
255
+ process.env.XDG_CONFIG_HOME ?? join(process.env.HOME ?? '', '.config'),
256
+ 'pantheon',
257
+ 'decision-router.json',
258
+ )
259
+ let doc: Record<string, unknown> = {}
260
+ try {
261
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>
262
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) doc = parsed
263
+ } catch {
264
+ throw new Error('decision-router.json unreadable — repair via `decision-router setup-model`')
265
+ }
266
+ doc.budget = { ...budgets }
267
+ const temp = `${path}.tui.tmp`
268
+ writeFileSync(temp, `${JSON.stringify(doc, null, 2)}\n`, { mode: 0o600 })
269
+ renameSync(temp, path)
270
+ }
271
+
136
272
  function updateCheckStatePath(): string {
137
273
  const stateDir = process.env.XDG_STATE_HOME ?? join(process.env.HOME ?? '', '.local', 'state')
138
274
  return join(stateDir, 'pantheon', 'update-check.json')
@@ -172,9 +308,16 @@ function persistUpdateCheckState(previous: UpdateCheckState, latest: string | nu
172
308
  }
173
309
 
174
310
  function resolveRunningVersion(): string {
311
+ // The tsdown embed (same source the sidebar footer uses) is authoritative —
312
+ // the naive ../../package.json read breaks in every real layout (the dev
313
+ // tree and the installed TUI copy both put package.json one level above
314
+ // dist, not two — field report beta.5: the header showed vunknown).
315
+ if (typeof __PANTHEON_VERSION__ !== 'undefined' && __PANTHEON_VERSION__ !== '') {
316
+ return __PANTHEON_VERSION__
317
+ }
175
318
  try {
176
319
  const manifest = JSON.parse(
177
- readFileSync(new URL('../../package.json', import.meta.url), 'utf8'),
320
+ readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
178
321
  ) as { version?: string }
179
322
  return manifest.version ?? 'unknown'
180
323
  } catch {
@@ -184,7 +327,7 @@ function resolveRunningVersion(): string {
184
327
 
185
328
  // ── The window view (presentational; both surfaces render it) ──────────
186
329
 
187
- const NAME_WIDTH = 26
330
+ const NAME_WIDTH = 28
188
331
  const VALUE_WIDTH = 22
189
332
 
190
333
  export function SettingsWindow(props: {
@@ -203,12 +346,13 @@ export function SettingsWindow(props: {
203
346
  return (
204
347
  <box flexDirection="column" paddingLeft={1} paddingRight={1} paddingTop={1}>
205
348
  <box flexDirection="row">
206
- <text attributes={1} fg={props.fg}>
349
+ <text flexShrink={0} attributes={1} fg={props.fg}>
207
350
  {`Pantheon v${props.version}`}
208
351
  </text>
209
352
  <For each={props.tabs()}>
210
353
  {(t, index) => (
211
354
  <text
355
+ flexShrink={0}
212
356
  fg={index() === props.page() ? props.fg : props.muted}
213
357
  {...(index() === props.page() ? { attributes: 1 } : {})}
214
358
  >
@@ -216,7 +360,10 @@ export function SettingsWindow(props: {
216
360
  </text>
217
361
  )}
218
362
  </For>
219
- <text fg={props.muted}>{' esc'}</text>
363
+ <box flexGrow={1} />
364
+ <text flexShrink={0} fg={props.muted}>
365
+ {'esc'}
366
+ </text>
220
367
  </box>
221
368
  <text fg={props.muted}>{'─'.repeat(72)}</text>
222
369
  <For each={tab().groups}>
@@ -263,7 +410,9 @@ export function SettingsWindow(props: {
263
410
  )}
264
411
  </For>
265
412
  <Show when={props.notice() !== undefined}>
266
- <text fg={props.warn ?? props.muted}>{`⚠ ${props.notice()}`}</text>
413
+ <text fg={props.notice()?.startsWith('saved') ? props.muted : (props.warn ?? props.muted)}>
414
+ {props.notice()?.startsWith('saved') ? props.notice() : `⚠ ${props.notice()}`}
415
+ </text>
267
416
  </Show>
268
417
  <text fg={draftDirty(props.draft()) ? (props.warn ?? props.fg) : props.muted}>
269
418
  {draftDirty(props.draft())
@@ -310,6 +459,9 @@ function createWindowController(
310
459
  const [selected, setSelected] = createSignal(0)
311
460
  const [load, setLoad] = createSignal(readOverridesLoad())
312
461
  const [decision, setDecision] = createSignal<DecisionConfigRead>(readDecisionRouterConfig())
462
+ const [goalLoop, setGoalLoop] = createSignal<GoalLoopPrefs>(readGoalLoopPrefs())
463
+ const [budgets, setBudgets] = createSignal<DecisionBudgets>(readDecisionBudgets())
464
+ const [autonomyRestartPending, setAutonomyRestartPending] = createSignal(false)
313
465
  const [presetTick, setPresetTick] = createSignal(0)
314
466
  const [lastChecked, setLastChecked] = createSignal<string | undefined>(undefined)
315
467
  const [checking, setChecking] = createSignal(false)
@@ -343,6 +495,11 @@ function createWindowController(
343
495
  buildDecisionTab(decision()),
344
496
  buildPresetTab(presetInput()),
345
497
  buildTuiTab(tuiPrefs()),
498
+ buildAutonomyTab({
499
+ goalLoop: goalLoop(),
500
+ budgets: budgets(),
501
+ goalLoopRestartPending: autonomyRestartPending(),
502
+ }),
346
503
  buildJ1Tab(process.env, false),
347
504
  buildUpdatesTab(updatesInput()),
348
505
  buildDoctorTab({
@@ -421,6 +578,28 @@ function createWindowController(
421
578
  return { ok: false, reason: 'decision-router disk write failed' }
422
579
  }
423
580
  }
581
+ if (
582
+ id === 'decision.selection.mode' ||
583
+ id === 'decision.selection.target' ||
584
+ id === 'decision.consent'
585
+ ) {
586
+ const current = decision()
587
+ if (current.corrupt) {
588
+ return {
589
+ ok: false,
590
+ reason: 'decision-router.json unreadable — repair via `decision-router setup-model`',
591
+ }
592
+ }
593
+ const staged = applyDecisionRow(current.config, id, value)
594
+ if (staged === current.config) return { ok: false, reason: 'unknown or invalid value' }
595
+ try {
596
+ writeDecisionRouterConfig(staged)
597
+ setDecision({ config: staged, corrupt: false })
598
+ return { ok: true }
599
+ } catch {
600
+ return { ok: false, reason: 'decision-router disk write failed' }
601
+ }
602
+ }
424
603
  if (id === 'preset') {
425
604
  try {
426
605
  if (value === PRESET_NONE) clearActivePreset(globalActivePresetPath())
@@ -434,6 +613,46 @@ function createWindowController(
434
613
  }
435
614
  }
436
615
  }
616
+ if (id.startsWith('autonomy.goal_loop.')) {
617
+ const next = { ...goalLoop() }
618
+ if (id === 'autonomy.goal_loop.enabled') {
619
+ next.enabled = value === 'enabled'
620
+ } else if (id === 'autonomy.goal_loop.maxContinuations') {
621
+ const parsed = Number(value)
622
+ if (!Number.isFinite(parsed) || parsed < 1 || parsed > 200) {
623
+ return { ok: false, reason: 'max continuations must be 1..200' }
624
+ }
625
+ next.maxContinuations = Math.floor(parsed)
626
+ } else if (id === 'autonomy.goal_loop.cooldownMs') {
627
+ const parsed = Number(value)
628
+ if (!Number.isFinite(parsed) || parsed < 1000) {
629
+ return { ok: false, reason: 'cooldown must be >= 1000ms' }
630
+ }
631
+ next.cooldownMs = Math.floor(parsed)
632
+ }
633
+ try {
634
+ writeUserOption('goal_loop', next)
635
+ setGoalLoop(next)
636
+ setAutonomyRestartPending(true)
637
+ return { ok: true }
638
+ } catch {
639
+ return { ok: false, reason: 'opencode.json write failed' }
640
+ }
641
+ }
642
+ if (id === 'autonomy.budget.monthly' || id === 'autonomy.budget.perDecision') {
643
+ const parsed = parseUsd(value)
644
+ if (parsed === null) return { ok: false, reason: 'invalid USD value' }
645
+ const next = { ...budgets() }
646
+ if (id === 'autonomy.budget.monthly') next.monthlyUsd = parsed
647
+ else next.perDecisionUsd = parsed
648
+ try {
649
+ writeDecisionBudget(next)
650
+ setBudgets(next)
651
+ return { ok: true }
652
+ } catch {
653
+ return { ok: false, reason: 'budget write failed' }
654
+ }
655
+ }
437
656
  if (id.startsWith('tui.')) {
438
657
  // The prefs live in the host's durable reactive store: the mutation is
439
658
  // async (persist), but the in-memory store flips immediately — the
@@ -486,20 +705,21 @@ function createWindowController(
486
705
  }
487
706
 
488
707
  const close = () => {
489
- if (draftDirty(draft())) {
708
+ // A dialog.confirm here would render in the home/session view chrome,
709
+ // which a full-screen ROUTE page replaces — an invisible prompt that
710
+ // pends forever (field report beta.5: esc "did nothing" with staged
711
+ // changes). Close always exits; discarding is announced, never asked.
712
+ const staged = draftCount(draft())
713
+ if (staged > 0) {
714
+ setDraft({})
490
715
  try {
491
- void Promise.resolve(
492
- context.ui.dialog.confirm({
493
- title: 'Pantheon settings',
494
- message: 'Discard unsaved settings changes?',
495
- }),
496
- ).then((confirmed) => {
497
- if (confirmed === true) exit()
716
+ context.ui.toast?.show?.({
717
+ variant: 'info',
718
+ message: `settings: ${staged} staged change${staged === 1 ? '' : 's'} discarded`,
498
719
  })
499
720
  } catch {
500
- /* confirm unavailable — stay open; the user can ctrl+r first */
721
+ /* toast unavailable */
501
722
  }
502
- return
503
723
  }
504
724
  exit()
505
725
  }
@@ -548,6 +768,17 @@ function SettingsPage(props: { context: Context; data: Record<string, any> | und
548
768
  )
549
769
  const theme = context.theme?.text ?? {}
550
770
  const warn = (theme?.feedback as any)?.warning?.base ?? theme.muted
771
+ // The page owns the keyboard while mounted: push an input MODE so the
772
+ // composer's base-mode layers sleep (they eat escape and plain letters —
773
+ // the host's own menus push a mode for exactly this). The page layer is
774
+ // scoped to this mode; cleanup pops it.
775
+ try {
776
+ const popMode = context.keymap?.mode?.push?.(ROUTE_MODE)
777
+ if (popMode !== undefined) onCleanup(() => popMode())
778
+ } catch {
779
+ /* mode API unavailable — composer layers stay active; keys still fall
780
+ through to the mode-less fallback layer below */
781
+ }
551
782
  onCleanup(controller.cleanup)
552
783
  setBlocking(true)
553
784
  pageApi = controller.api
@@ -569,9 +800,14 @@ function SettingsPage(props: { context: Context; data: Record<string, any> | und
569
800
  function navigateBack(context: Context, data?: { returnRoute?: WindowRoute }): void {
570
801
  try {
571
802
  const fallback: WindowRoute = { type: 'home' }
572
- context.ui.router.navigate(data?.returnRoute ?? fallback)
803
+ const destination = data?.returnRoute ?? fallback
804
+ context.ui.toast?.show?.({
805
+ variant: 'info',
806
+ message: `settings: navigating ${JSON.stringify(destination)}`,
807
+ })
808
+ context.ui.router.navigate(destination)
573
809
  } catch {
574
- /* router unavailable — nothing to navigate back to */
810
+ /* router unavailable — the failure is observable only as a stuck page */
575
811
  }
576
812
  }
577
813
 
@@ -654,7 +890,21 @@ export function setupPantheonSettings(context: Context): void {
654
890
  title: 'Close settings',
655
891
  bind: 'escape,q',
656
892
  run: () => {
657
- pageApi?.close()
893
+ try {
894
+ context.ui.toast?.show?.({ variant: 'info', message: 'settings: close command fired' })
895
+ } catch {}
896
+ if (pageApi === undefined) {
897
+ try {
898
+ context.ui.toast?.show?.({
899
+ variant: 'warning',
900
+ message: 'settings: no window controller bound',
901
+ })
902
+ } catch {
903
+ /* toast unavailable */
904
+ }
905
+ return undefined
906
+ }
907
+ pageApi.close()
658
908
  return undefined
659
909
  },
660
910
  },
@@ -740,11 +990,14 @@ export function setupPantheonSettings(context: Context): void {
740
990
  },
741
991
  })),
742
992
  ]
743
- // The PAGE layer: gated on the route, priority 1 beats any stale
744
- // same-bind layer while the window is open (beta.2 field report).
993
+ // The PAGE layer: scoped to the mode the page pushes while mounted, so the
994
+ // composer's base-mode layers sleep and escape/q reach the close command
995
+ // (field report beta.5: a global layer on a route lost escape/q to the
996
+ // composer — the host's own menus push a mode for exactly this). The
997
+ // route gate stays as a belt-and-suspenders against stale modes.
745
998
  try {
746
999
  context.keymap.layer(() => ({
747
- mode: 'global' as const,
1000
+ mode: ROUTE_MODE,
748
1001
  priority: 1,
749
1002
  enabled: () => routeGated(),
750
1003
  commands,
@@ -773,9 +1026,10 @@ export async function openPantheonSettings(context: Context): Promise<void> {
773
1026
  let returnRoute: WindowRoute | undefined
774
1027
  try {
775
1028
  const current = context.ui.router.current()
776
- // Never return INTO the settings page itself.
1029
+ // Never return INTO the settings page itself; always pass a PLAIN
1030
+ // route (see plainRoute — live objects are cyclic).
777
1031
  if (!(current.type === 'plugin' && current.name === ROUTE_NAME)) {
778
- returnRoute = current as WindowRoute
1032
+ returnRoute = plainRoute(current as WindowRoute)
779
1033
  }
780
1034
  } catch {
781
1035
  returnRoute = undefined
@@ -14,6 +14,13 @@ description: "Turn a vague multi-concern request into a usable brief — interna
14
14
  | Nível | Gatilho | O que acontece |
15
15
  |---|---|---|
16
16
  | **0 — Passa intacto** | Pedido claro e delimitado ("corrija o typo do README"), cumprimentos e conversa fiada (o `__SKIP__` do prompt-enhancer) | Executa direto, zero token de refinamento |
17
+
18
+ **Anti-padrões que ESCALAM o nível** (qualquer um presente = no mínimo Tier 1; dois ou mais = considere perguntar via tool `question` antes de seguir):
19
+ - **Escopo sem fronteira** — "melhorar tudo", "refatorar o projeto": sem fatias, sem fim.
20
+ - **Adjetivo sem critério** — "mais rápido", "melhor": sem número, sem baseline, sem like-to-like.
21
+ - **Unidade/versão ausente** — "32" de quê? "atualize" pra qual versão? O default pode ser errado.
22
+ - **Multi-concern em um parágrafo** — fix + refactor + redesign sem prioridade (o caso que criou esta skill).
23
+ - **Premissa implícita de ambiente** — assume stack/host/credenciais que o agente não pode inferir.
17
24
  | **1 — Ajuste mínimo INTERNO (automático)** | O sinal determinístico dispara | Reescreve o prompt **silenciosamente, para uso próprio**: PT corrigido, estrutura leve, expansão do implícito, lacunas viram escolhas com default declarado. SEM apresentar contrato, SEM pedir aprovação — o usuário vê o trabalho começar. Limite: o essencial (~10-15 linhas internas); escopo pode ser generoso quando o pedido pede |
18
25
  | **2 — Contrato completo** | **SOMENTE prefixo `>>`** | As seis seções inteiras apresentadas ao usuário para confirmar-ou-ajustar (a ÚNICA via com aprovação explícita) |
19
26
 
@@ -23,7 +30,22 @@ O modelo ativo da sessão faz os dois níveis sem problema — o custo é contro
23
30
 
24
31
  ## The contract shape — tiers and caps
25
32
 
26
- **NÍVEL 1 — Ajuste mínimo INTERNO (o default do sinal determinístico):** reescrita para uso próprio, SEM apresentar ao usuário. O essencial + o que o pedido pedir (o escopo mínimo não é um aperto: expanda o implícito, estime o que falta com default declarado). Exemplo de saída aceitável:
33
+ **NÍVEL 1 — Ajuste mínimo INTERNO (o default do sinal determinístico):** reescrita para uso próprio, SEM apresentar ao usuário. O essencial + o que o pedido pedir (o escopo mínimo não é um aperto: expanda o implícito, estime o que falta com default declarado).
34
+
35
+ **Diagnóstico interno ANTES do rewrite** (os improvers oficiais diagnosticam primeiro — o rewrite que não diagnostica chuta):
36
+ 1. **Tarefa** — qual ação concreta o usuário quer? (verbo + objeto)
37
+ 2. **Restrições ausentes** — o que ele não disse que LIMITA o resultado? (prazo, tamanho, compatibilidade, budget)
38
+ 3. **Sucesso indefinido** — como saber que ficou pronto? Se não dá pra testar, formule o teste.
39
+ 4. **Premissas implícitas** — o que o pedido ASSUME que você sabe? (stack, ambiente, histórico)
40
+ 5. **Conflitos** — o pedido se contradiz? (peça X mas o aceite implica ¬X)
41
+
42
+ Cada ponto do diagnóstico vira OU uma decisão no rewrite OU um default declarado OU uma pergunta bloqueante — nada fica implícito duas vezes. Quando o pedido tiver **duas leituras com resultados materialmente diferentes** ("atualizar o README" = patch ou reescrita?), é bloqueante — a leitura errada executa caro e errado. E é aqui que o **Jev entra quando ativado** (ver a regra de desambiguação nas Operating rules): o decision model resolve a leitura como escalar tipado, e a interrupção do usuário vira exceção, não regra.
43
+
44
+ **Restrições negativas entram no rewrite quando detectadas** — "não tocar em X", "sem nova dependência", "sem migrar ainda". O usuário raramente as diz; o agente que infere incorretamente é quem executa drift.
45
+
46
+ **Formato da resposta**: se o pedido implicar entrega estruturada (relatório, tabela, plano), o rewrite fixa o formato — "responda como tabela com colunas X/Y" custa uma frase e economiza um redo.
47
+
48
+ Exemplo de saída aceitável:
27
49
 
28
50
  ```
29
51
  Objetivo: publicar deploys pendentes e liberar espaço nos VPS sem perder dados.
@@ -32,6 +54,8 @@ Aceite: lista de SHAs por serviço; espaço antes/depois; nada persistente apaga
32
54
  Perguntas: quais VPS? (default: os que rodam estes serviços) | limpeza destrutiva? (default: não).
33
55
  ```
34
56
 
57
+ **Self-check do rewrite** (rubrica interna, custo zero — a versão agent-side do loop OPRO/DSPy): antes de seguir, o rewrite passa por — objetivo único e único verbo? | fatias verificáveis individualmente? | todo default declarado por escrito? | formato da resposta definido (quando a entrega é estruturada)? | restrições negativas registradas? Qualquer não = uma passada de correção interna, não uma nova conversa.
58
+
35
59
  **NÍVEL 2 — Contrato completo (SOMENTE com o prefixo `>>`):** as seis seções abaixo, inteiras, apresentadas ao usuário para confirmar-ou-ajustar.
36
60
 
37
61
  Produce ALL of the following sections, filling from the request and marking real gaps as open questions — never invent requirements silently:
@@ -42,6 +66,7 @@ Produce ALL of the following sections, filling from the request and marking real
42
66
  4. **Entregáveis esperados** — the concrete artifacts (report, route map, dictionary, implementation).
43
67
  5. **Perguntas abertas** — the gaps that change the plan, with your recommended default for each so silence means "proceed with the default".
44
68
  6. **Glossário/nomenclatura proposta** — when the domain has ambiguous terms, propose the canonical names up front.
69
+ 7. **Formato da resposta** — como o usuário recebe cada entregável (tabela, checklist, diff, PR, relatório com seções): o improver oficial trata output structure como parte do prompt, não do acaso.
45
70
 
46
71
  ---
47
72
 
@@ -52,9 +77,14 @@ Produce ALL of the following sections, filling from the request and marking real
52
77
  - **Preserve the user's language** (a PT-BR request refines into PT-BR).
53
78
  - **Falha = fail-open**: qualquer erro no rewrite e o prompt ORIGINAL segue — nunca bloqueia.
54
79
  - **Nudge self-cancel cheap** (do claude-code-prompt-improver): perguntas abertas com "se isso não se aplicar ao seu caso, ignore" — o nudge barato se anula sozinho quando o palpite erra.
55
- - **Perguntas pela tool `question` nativa** (NUNCA Jev — decisão de paid/free; não prosa solta): uma lacuna que BLOQUEIA a execução vira uma pergunta com opções e o default recomendado. Lacuna não-bloqueante vira escolha com default declarado e segue.
80
+ - **Desambiguação — Jev PRIMEIRO quando ativo, `question` como fallback** (revê a regra antiga "NUNCA Jev": com o decision router ATIVO e com budget o usuário já consentiu gastar; a leitura errada custa mais que o escalar):
81
+ 1. Ambiguidade bloqueante (leitores materialmente diferentes) + decision router ATIVO → `jev_decide` modo `choice` — candidatos = as leituras, o default recomendado marcado como tal. Decisão interna, silenciosa (Tier 1).
82
+ 2. Jev OFF / indisponível / veredito UNVERIFIABLE ou FAIL / timeout → tool `question` nativa com opções e o default recomendado — exatamente o comportamento anterior.
83
+ 3. Lacuna NÃO-bloqueante vira escolha com default declarado e segue (nada de Jev nem pergunta — decisa é barata).
84
+ 4. **Fail-open nos dois lados**: qualquer erro do Jev cai na `question`; qualquer erro da `question` segue com o default. Nada bloqueia além de uma pergunta legítima.
85
+ 5. O Jev decide a LEITURA — nunca escreve o rewrite (prosa é do modelo de sessão).
56
86
  - **`extra_instructions` do projeto**: convenções do projeto (stack, hosts de deploy, domínios como cupons ML/AliExpress) têm PRIORIDADE sobre os defaults recomendados — leia o AGENTS.md do projeto antes de propor defaults.
57
- - **Referências**: `omkarxpatel/prompt-enhancer` (prefixo opt-in, cap de saída, fail-open) e `severity1/claude-code-prompt-improver` (nudges self-cancel, clarificação com opções) — os dois designs que este skill incorpora.
87
+ - **Referências**: `omkarxpatel/prompt-enhancer` (prefixo opt-in, cap de saída, fail-open) e `severity1/claude-code-prompt-improver` (nudges self-cancel, clarificação com opções) — os dois designs que este skill incorpora. Fundação teórica dos padrões de diagnóstico-e-rewrite: os prompt improvers oficiais (Anthropic/OpenAI), meta-prompting (LLMs guiando LLMs) e o loop de otimização com verificação (OPRO/DSPy) — esta skill é a versão agent-side de custo-controlado: um turno, sem loop de API.
58
88
  - **Modelo**: o rewrite roda no modelo ativo da sessão; o controle de custo é o CAP de cada nível (interno ~10-15 linhas; completo = as seis seções) — quando houver modelo free/rápido no preset ativo (ex.: mimo-v2.5-free, deepseek-v4-flash-free), prefira-o via routing para o turno de rewrite.
59
- - **One refinement turn.** The rewrite is a single planning pass on the session model — no extra provider call, no Jev needed for the rewrite itself (decision models answer typed scalars, they do not write prose).
89
+ - **One refinement turn + no máx. um escalar.** The rewrite is a single planning pass on the session model — no extra provider call, no Jev for the rewrite itself (decision models answer typed scalars, they do not write prose). The ONE exception is the ambiguity `choice` above: quando o router está ativo, é um escalar a mais no budget — se o budget recusar, cai na `question` sem cerimônia.
60
90
  - **Cost honesty**: the refinement costs roughly one planning turn (~1–4K tokens each way). The expensive thing is executing a mis-specified request; this skill buys that back.