From 8eefa4ceddcadd56821f1f54c2f41d7e78ffb91e Mon Sep 17 00:00:00 2001 From: iris Date: Sat, 14 Nov 2026 18:13:38 -0300 Subject: [PATCH 1/8] fix(tui): remove duplicate todo block and rely on native opencode sidebar --- src/plugins/tui/dist/tui.d.ts | 13 +- src/plugins/tui/dist/tui.d.ts.map | 2 +- src/plugins/tui/dist/tui.js | 459 +++++++++++++----------------- src/plugins/tui/dist/tui.js.map | 2 +- src/plugins/tui/src/index.tsx | 52 +--- src/plugins/tui/src/tui-prefs.ts | 12 +- tests/tui-sidebar.test.mjs | 39 ++- 7 files changed, 237 insertions(+), 342 deletions(-) diff --git a/src/plugins/tui/dist/tui.d.ts b/src/plugins/tui/dist/tui.d.ts index 69158b21..7c2958ab 100644 --- a/src/plugins/tui/dist/tui.d.ts +++ b/src/plugins/tui/dist/tui.d.ts @@ -608,8 +608,10 @@ export declare function toDispatchEntry(child: any, status: string | undefined, * cost. */ export declare function collectDispatch(context: any, sessionID: string | undefined, options?: CollectDispatchOptions): DispatchEntry[]; /** Sidebar blocks in render order. Spacing is derived from this list instead of - * from the view, so a hidden block can never leave an empty gap behind. */ -export type SidebarBlockKey = 'context' | 'git' | 'todo' | 'dispatch'; + * from the view, so a hidden block can never leave an empty gap behind. + * Note: The custom Todo block was removed from the sidebar composition because + * OpenCode 2.x natively renders the Todo panel when `todowrite` is used. */ +export type SidebarBlockKey = 'context' | 'git' | 'dispatch'; /** One rendered block: its key, and whether a blank line precedes it. */ export type SidebarBlock = { key: SidebarBlockKey; @@ -618,10 +620,9 @@ export type SidebarBlock = { /** Header glyph per block — one codepoint each, rendered muted before the bold * label. The fixed header (version/preset/session) takes none. * Measured as one terminal cell by the host (`@opentui/core` counts - * `emoji-regex` matches as two): ▤ U+25A4 (EAW=A), ◆ U+25C6 (A), ▾ U+25BE (N), - * ◈ U+25C8 (A). `☑` U+2611 was rejected for the Todo header because it matches - * `emoji-regex` and would occupy two cells; `⌁` U+2301 (the old Dispatch glyph) - * was replaced by the host's own Notice glyph. */ + * `emoji-regex` matches as two): ▤ U+25A4 (EAW=A), ◆ U+25C6 (A), + * ◈ U+25C8 (A). `⌁` U+2301 (the old Dispatch glyph) was replaced by the host's + * own Notice glyph. */ export declare const BLOCK_ICONS: Record; /** Tag every block that has content with its spacer: never before the first * (the view puts a single blank line after the fixed header instead), one diff --git a/src/plugins/tui/dist/tui.d.ts.map b/src/plugins/tui/dist/tui.d.ts.map index d30dd7ee..d81932f7 100644 --- a/src/plugins/tui/dist/tui.d.ts.map +++ b/src/plugins/tui/dist/tui.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"tui.d.ts","names":[],"sources":["../src/context-gauge.ts","../src/model-usage-limits.ts","../src/sidebar-width.ts","../src/index.tsx"],"mappings":"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"} +{"version":3,"file":"tui.d.ts","names":[],"sources":["../src/context-gauge.ts","../src/model-usage-limits.ts","../src/sidebar-width.ts","../src/index.tsx"],"mappings":"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"} diff --git a/src/plugins/tui/dist/tui.js b/src/plugins/tui/dist/tui.js index 515e02c1..94d0124a 100644 --- a/src/plugins/tui/dist/tui.js +++ b/src/plugins/tui/dist/tui.js @@ -1500,7 +1500,7 @@ const DEFAULT_TUI_PREFS = { blocks: { context: true, git: true, - todo: true, + todo: false, dispatch: true }, context: { @@ -1557,7 +1557,7 @@ function normalizeTuiPrefs(raw) { blocks: { context: asBool(blocks.context, true), git: asBool(blocks.git, true), - todo: asBool(blocks.todo, true), + todo: asBool(blocks.todo, false), dispatch: asBool(blocks.dispatch, true) }, context: { @@ -1665,7 +1665,6 @@ function buildTuiTab(prefs, languagePref) { rows: [ row("tui.sidebar.block.context", isPt ? "Bloco de contexto" : "Context block", prefs.sidebar.blocks.context, isPt ? "tokens, medidor, custo, uso de modelos" : "tokens, gauge, spend, model usage"), row("tui.sidebar.block.git", isPt ? "Bloco do Git" : "Git block", prefs.sidebar.blocks.git, isPt ? "branch + contagem de alterações" : "branch + working-tree counts"), - row("tui.sidebar.block.todo", isPt ? "Bloco Todo" : "Todo block", prefs.sidebar.blocks.todo, isPt ? "tarefas pendentes mais recentes" : "the newest todowrite"), row("tui.sidebar.block.dispatch", isPt ? "Bloco Dispatch" : "Dispatch block", prefs.sidebar.blocks.dispatch, isPt ? "delegações em tempo real" : "live delegations + rollup") ] }, @@ -5611,19 +5610,19 @@ function collectDispatch(context, sessionID, options = {}) { return entries.sort((a, b) => compareDelegations(a.view, b.view)); } /** Sidebar blocks in render order. Spacing is derived from this list instead of -* from the view, so a hidden block can never leave an empty gap behind. */ +* from the view, so a hidden block can never leave an empty gap behind. +* Note: The custom Todo block was removed from the sidebar composition because +* OpenCode 2.x natively renders the Todo panel when `todowrite` is used. */ /** One rendered block: its key, and whether a blank line precedes it. */ /** Header glyph per block — one codepoint each, rendered muted before the bold * label. The fixed header (version/preset/session) takes none. * Measured as one terminal cell by the host (`@opentui/core` counts -* `emoji-regex` matches as two): ▤ U+25A4 (EAW=A), ◆ U+25C6 (A), ▾ U+25BE (N), -* ◈ U+25C8 (A). `☑` U+2611 was rejected for the Todo header because it matches -* `emoji-regex` and would occupy two cells; `⌁` U+2301 (the old Dispatch glyph) -* was replaced by the host's own Notice glyph. */ +* `emoji-regex` matches as two): ▤ U+25A4 (EAW=A), ◆ U+25C6 (A), +* ◈ U+25C8 (A). `⌁` U+2301 (the old Dispatch glyph) was replaced by the host's +* own Notice glyph. */ const BLOCK_ICONS = { context: "▤", git: "◆", - todo: "▾", dispatch: "◈" }; /** Tag every block that has content with its spacer: never before the first @@ -7057,7 +7056,6 @@ function createSidebarModel(context, sessionID, gitExec = defaultGitExec) { const present = []; if (prefs.sidebar.blocks.context && (contextBlockRows(contextUsage(), cost(), prefs.sidebar.context.gauge) !== null || prefs.sidebar.context.localSpend && contextSpendLine(spend()) !== null)) present.push("context"); if (prefs.sidebar.blocks.git && (branch() !== null || gitLine() !== null)) present.push("git"); - if (prefs.sidebar.blocks.todo && todo().visible.length > 0) present.push("todo"); if (prefs.sidebar.blocks.dispatch && dispatch() !== null) present.push("dispatch"); return withBlockSpacers(present); }); @@ -7277,11 +7275,6 @@ function Sidebar(props) { const text = () => context.theme.text?.base; const muted = () => context.theme.text?.muted ?? text(); const tone = (value) => context.theme?.text?.feedback?.[value]?.base ?? text(); - const todoFg = (status) => { - const rowTone = todoTone(status); - if (rowTone === "accent") return tone("warning"); - return rowTone === "muted" ? muted() : text(); - }; const open = (sessionID) => () => navigateToSession(context.ui?.router, sessionID); const block = (key) => model.blocks().find((entry) => entry.key === key); const spacer = (key) => block(key)?.spacer === true; @@ -7352,24 +7345,24 @@ function Sidebar(props) { }, get fallback() { return (() => { - var _el$26 = createElement("box"); - setProp(_el$26, "height", 0); - return _el$26; + var _el$23 = createElement("box"); + setProp(_el$23, "height", 0); + return _el$23; })(); }, get children() { - var _el$25 = createElement("text"); - insert(_el$25, () => sidebarPlaceholder(props.sessionID)); - effect((_$p) => setProp(_el$25, "fg", muted(), _$p)); - return _el$25; + var _el$22 = createElement("text"); + insert(_el$22, () => sidebarPlaceholder(props.sessionID)); + effect((_$p) => setProp(_el$22, "fg", muted(), _$p)); + return _el$22; } }); }, children: (current) => (() => { - var _el$27 = createElement("text"); - insert(_el$27, () => `Session: ${truncateLabel(current().title || current().id)}`); - effect((_$p) => setProp(_el$27, "fg", text(), _$p)); - return _el$27; + var _el$24 = createElement("text"); + insert(_el$24, () => `Session: ${truncateLabel(current().title || current().id)}`); + effect((_$p) => setProp(_el$24, "fg", text(), _$p)); + return _el$24; })() }), null); insert(_el$12, createComponent(Show, { @@ -7416,9 +7409,9 @@ function Sidebar(props) { return contextRows(); }, children: (rows) => (() => { - var _el$28 = createElement("box"); - setProp(_el$28, "flexDirection", "column"); - insert(_el$28, createComponent(Show, { + var _el$25 = createElement("box"); + setProp(_el$25, "flexDirection", "column"); + insert(_el$25, createComponent(Show, { get when() { return rows().tokens; }, @@ -7434,7 +7427,7 @@ function Sidebar(props) { } }) }), null); - insert(_el$28, createComponent(Show, { + insert(_el$25, createComponent(Show, { get when() { return rows().percent; }, @@ -7450,7 +7443,7 @@ function Sidebar(props) { } }) }), null); - insert(_el$28, createComponent(Show, { + insert(_el$25, createComponent(Show, { get when() { return rows().spent; }, @@ -7466,46 +7459,46 @@ function Sidebar(props) { } }) }), null); - insert(_el$28, createComponent(Show, { + insert(_el$25, createComponent(Show, { get when() { return memo(() => !!tuiPrefs().sidebar.context.modelUsage)() && usageRows().length > 0; }, get children() { return [(() => { - var _el$29 = createElement("text"); - insertNode(_el$29, createTextNode(`Session · reported cost`)); - effect((_$p) => setProp(_el$29, "fg", muted(), _$p)); - return _el$29; + var _el$26 = createElement("text"); + insertNode(_el$26, createTextNode(`Session · reported cost`)); + effect((_$p) => setProp(_el$26, "fg", muted(), _$p)); + return _el$26; })(), (() => { - var _el$31 = createElement("text"); - insertNode(_el$31, createTextNode(`Model Tokens USD`)); - effect((_$p) => setProp(_el$31, "fg", muted(), _$p)); - return _el$31; + var _el$28 = createElement("text"); + insertNode(_el$28, createTextNode(`Model Tokens USD`)); + effect((_$p) => setProp(_el$28, "fg", muted(), _$p)); + return _el$28; })()]; } }), null); - insert(_el$28, createComponent(For, { + insert(_el$25, createComponent(For, { get each() { return usageRows(); }, children: (row) => (() => { - var _el$33 = createElement("box"); - setProp(_el$33, "flexDirection", "column"); - insert(_el$33, createComponent(For, { + var _el$30 = createElement("box"); + setProp(_el$30, "flexDirection", "column"); + insert(_el$30, createComponent(For, { get each() { return modelUsageRowLines(row); }, children: (line) => (() => { - var _el$34 = createElement("text"); - insert(_el$34, line); - effect((_$p) => setProp(_el$34, "fg", text(), _$p)); - return _el$34; + var _el$31 = createElement("text"); + insert(_el$31, line); + effect((_$p) => setProp(_el$31, "fg", text(), _$p)); + return _el$31; })() })); - return _el$33; + return _el$30; })() }), null); - insert(_el$28, createComponent(Show, { + insert(_el$25, createComponent(Show, { get when() { return usageHidden(); }, @@ -7514,14 +7507,14 @@ function Sidebar(props) { return sidebarTextLines(line()); }, children: (part) => (() => { - var _el$35 = createElement("text"); - insert(_el$35, part); - effect((_$p) => setProp(_el$35, "fg", muted(), _$p)); - return _el$35; + var _el$32 = createElement("text"); + insert(_el$32, part); + effect((_$p) => setProp(_el$32, "fg", muted(), _$p)); + return _el$32; })() }) }), null); - return _el$28; + return _el$25; })() }), null); insert(_el$16, createComponent(Show, { @@ -7529,10 +7522,10 @@ function Sidebar(props) { return performanceLine(); }, children: (line) => (() => { - var _el$36 = createElement("text"); - insert(_el$36, line); - effect((_$p) => setProp(_el$36, "fg", muted(), _$p)); - return _el$36; + var _el$33 = createElement("text"); + insert(_el$33, line); + effect((_$p) => setProp(_el$33, "fg", muted(), _$p)); + return _el$33; })() }), null); insert(_el$16, createComponent(Show, { @@ -7544,10 +7537,10 @@ function Sidebar(props) { return contextSpendLines(line()); }, children: (part) => (() => { - var _el$37 = createElement("text"); - insert(_el$37, part); - effect((_$p) => setProp(_el$37, "fg", muted(), _$p)); - return _el$37; + var _el$34 = createElement("text"); + insert(_el$34, part); + effect((_$p) => setProp(_el$34, "fg", muted(), _$p)); + return _el$34; })() }) }), null); @@ -7588,22 +7581,22 @@ function Sidebar(props) { return model.branch(); }, children: (value) => (() => { - var _el$38 = createElement("box"), _el$39 = createElement("text"), _el$41 = createElement("text"); - insertNode(_el$38, _el$39); - insertNode(_el$38, _el$41); - setProp(_el$38, "flexDirection", "row"); - insertNode(_el$39, createTextNode(`⎇ `)); - insert(_el$41, () => truncateLabel(value(), 32)); + var _el$35 = createElement("box"), _el$36 = createElement("text"), _el$38 = createElement("text"); + insertNode(_el$35, _el$36); + insertNode(_el$35, _el$38); + setProp(_el$35, "flexDirection", "row"); + insertNode(_el$36, createTextNode(`⎇ `)); + insert(_el$38, () => truncateLabel(value(), 32)); effect((_p$) => { var _v$5 = muted(), _v$6 = text(); - _v$5 !== _p$.e && (_p$.e = setProp(_el$39, "fg", _v$5, _p$.e)); - _v$6 !== _p$.t && (_p$.t = setProp(_el$41, "fg", _v$6, _p$.t)); + _v$5 !== _p$.e && (_p$.e = setProp(_el$36, "fg", _v$5, _p$.e)); + _v$6 !== _p$.t && (_p$.t = setProp(_el$38, "fg", _v$6, _p$.t)); return _p$; }, { e: void 0, t: void 0 }); - return _el$38; + return _el$35; })() }), null); insert(_el$18, createComponent(Show, { @@ -7611,10 +7604,10 @@ function Sidebar(props) { return model.gitLine(); }, children: (line) => (() => { - var _el$42 = createElement("text"); - insert(_el$42, line); - effect((_$p) => setProp(_el$42, "fg", text(), _$p)); - return _el$42; + var _el$39 = createElement("text"); + insert(_el$39, line); + effect((_$p) => setProp(_el$39, "fg", text(), _$p)); + return _el$39; })() }), null); return _el$18; @@ -7622,14 +7615,14 @@ function Sidebar(props) { }), null); insert(_el$12, createComponent(Show, { get when() { - return block("todo"); + return block("dispatch"); }, get children() { var _el$20 = createElement("box"); setProp(_el$20, "flexDirection", "column"); insert(_el$20, createComponent(Show, { get when() { - return spacer("todo"); + return spacer("dispatch"); }, get children() { var _el$21 = createElement("box"); @@ -7638,77 +7631,13 @@ function Sidebar(props) { } }), null); insert(_el$20, createComponent(Show, { - get when() { - return model.todo().visible.length > 0; - }, - get children() { - var _el$22 = createElement("box"); - setProp(_el$22, "flexDirection", "column"); - insert(_el$22, createComponent(BlockHeader, { - get icon() { - return BLOCK_ICONS.todo; - }, - label: "Todo", - get fg() { - return tone("warning"); - }, - get muted() { - return muted(); - } - }), null); - insert(_el$22, createComponent(For, { - get each() { - return model.todo().visible; - }, - children: (item) => (() => { - var _el$43 = createElement("text"); - insert(_el$43, () => todoRowText(item)); - effect((_$p) => setProp(_el$43, "fg", todoFg(item.status), _$p)); - return _el$43; - })() - }), null); - insert(_el$22, createComponent(Show, { - get when() { - return hiddenTodoText(model.todo().hidden); - }, - children: (line) => (() => { - var _el$44 = createElement("text"); - insert(_el$44, line); - effect((_$p) => setProp(_el$44, "fg", muted(), _$p)); - return _el$44; - })() - }), null); - return _el$22; - } - }), null); - return _el$20; - } - }), null); - insert(_el$12, createComponent(Show, { - get when() { - return block("dispatch"); - }, - get children() { - var _el$23 = createElement("box"); - setProp(_el$23, "flexDirection", "column"); - insert(_el$23, createComponent(Show, { - get when() { - return spacer("dispatch"); - }, - get children() { - var _el$24 = createElement("box"); - setProp(_el$24, "height", 1); - return _el$24; - } - }), null); - insert(_el$23, createComponent(Show, { get when() { return dispatchView(); }, children: (view) => (() => { - var _el$45 = createElement("box"); - setProp(_el$45, "flexDirection", "column"); - insert(_el$45, createComponent(BlockHeader, { + var _el$40 = createElement("box"); + setProp(_el$40, "flexDirection", "column"); + insert(_el$40, createComponent(BlockHeader, { get icon() { return BLOCK_ICONS.dispatch; }, @@ -7723,89 +7652,89 @@ function Sidebar(props) { return dispatchSummary(); } }), null); - insert(_el$45, createComponent(For, { + insert(_el$40, createComponent(For, { get each() { return view().running; }, children: (row) => (() => { - var _el$47 = createElement("box"), _el$48 = createElement("text"); - insertNode(_el$47, _el$48); - setProp(_el$47, "flexShrink", 0); - insert(_el$48, () => row.text); + var _el$42 = createElement("box"), _el$43 = createElement("text"); + insertNode(_el$42, _el$43); + setProp(_el$42, "flexShrink", 0); + insert(_el$43, () => row.text); effect((_p$) => { var _v$7 = open(row.id), _v$8 = tone("success"); - _v$7 !== _p$.e && (_p$.e = setProp(_el$47, "onMouseDown", _v$7, _p$.e)); - _v$8 !== _p$.t && (_p$.t = setProp(_el$48, "fg", _v$8, _p$.t)); + _v$7 !== _p$.e && (_p$.e = setProp(_el$42, "onMouseDown", _v$7, _p$.e)); + _v$8 !== _p$.t && (_p$.t = setProp(_el$43, "fg", _v$8, _p$.t)); return _p$; }, { e: void 0, t: void 0 }); - return _el$47; + return _el$42; })() }), null); - insert(_el$45, createComponent(Show, { + insert(_el$40, createComponent(Show, { get when() { return view().runningHidden > 0; }, get children() { - var _el$46 = createElement("text"); - insert(_el$46, () => `\u2026 +${view().runningHidden} rodando`); - effect((_$p) => setProp(_el$46, "fg", muted(), _$p)); - return _el$46; + var _el$41 = createElement("text"); + insert(_el$41, () => `\u2026 +${view().runningHidden} rodando`); + effect((_$p) => setProp(_el$41, "fg", muted(), _$p)); + return _el$41; } }), null); - insert(_el$45, createComponent(Show, { + insert(_el$40, createComponent(Show, { get when() { return view().summary; }, children: (line) => (() => { - var _el$49 = createElement("box"), _el$50 = createElement("text"); - insertNode(_el$49, _el$50); - setProp(_el$49, "flexDirection", "row"); - setProp(_el$49, "flexShrink", 0); - insert(_el$50, line); - insert(_el$49, createComponent(Show, { + var _el$44 = createElement("box"), _el$45 = createElement("text"); + insertNode(_el$44, _el$45); + setProp(_el$44, "flexDirection", "row"); + setProp(_el$44, "flexShrink", 0); + insert(_el$45, line); + insert(_el$44, createComponent(Show, { get when() { return failedSuffix(); }, children: (suffix) => (() => { - var _el$51 = createElement("text"); - insert(_el$51, () => `${SPEND_LINE_SEPARATOR}${suffix()}`); - effect((_$p) => setProp(_el$51, "fg", tone("error"), _$p)); - return _el$51; + var _el$46 = createElement("text"); + insert(_el$46, () => `${SPEND_LINE_SEPARATOR}${suffix()}`); + effect((_$p) => setProp(_el$46, "fg", tone("error"), _$p)); + return _el$46; })() }), null); - effect((_$p) => setProp(_el$50, "fg", muted(), _$p)); - return _el$49; + effect((_$p) => setProp(_el$45, "fg", muted(), _$p)); + return _el$44; })() }), null); - insert(_el$45, createComponent(For, { + insert(_el$40, createComponent(For, { get each() { return view().agents; }, children: (row) => (() => { - var _el$52 = createElement("text"); - insert(_el$52, () => childAgentRowText(row)); - effect((_$p) => setProp(_el$52, "fg", muted(), _$p)); - return _el$52; + var _el$47 = createElement("text"); + insert(_el$47, () => childAgentRowText(row)); + effect((_$p) => setProp(_el$47, "fg", muted(), _$p)); + return _el$47; })() }), null); - insert(_el$45, createComponent(Show, { + insert(_el$40, createComponent(Show, { get when() { return hiddenChildAgentsText(view().agentsHidden, view().agentsHiddenCost); }, children: (line) => (() => { - var _el$53 = createElement("text"); - insert(_el$53, line); - effect((_$p) => setProp(_el$53, "fg", muted(), _$p)); - return _el$53; + var _el$48 = createElement("text"); + insert(_el$48, line); + effect((_$p) => setProp(_el$48, "fg", muted(), _$p)); + return _el$48; })() }), null); - return _el$45; + return _el$40; })() }), null); - return _el$23; + return _el$20; } }), null); effect((_p$) => { @@ -7886,25 +7815,25 @@ function DispatchPanel(props) { return model.visible().rows; }, children: (row) => (() => { - var _el$54 = createElement("box"), _el$55 = createElement("text"), _el$56 = createElement("text"); - insertNode(_el$54, _el$55); - insertNode(_el$54, _el$56); - setProp(_el$54, "flexDirection", "row"); - setProp(_el$54, "flexShrink", 0); - insert(_el$55, () => selected(row.id) ? `▸ ` : " "); - insert(_el$56, () => row.text); + var _el$49 = createElement("box"), _el$50 = createElement("text"), _el$51 = createElement("text"); + insertNode(_el$49, _el$50); + insertNode(_el$49, _el$51); + setProp(_el$49, "flexDirection", "row"); + setProp(_el$49, "flexShrink", 0); + insert(_el$50, () => selected(row.id) ? `▸ ` : " "); + insert(_el$51, () => row.text); effect((_p$) => { var _v$9 = selected(row.id) ? text() : muted(), _v$0 = rowFg(row.state), _v$1 = selected(row.id) ? 1 : 0; - _v$9 !== _p$.e && (_p$.e = setProp(_el$55, "fg", _v$9, _p$.e)); - _v$0 !== _p$.t && (_p$.t = setProp(_el$56, "fg", _v$0, _p$.t)); - _v$1 !== _p$.a && (_p$.a = setProp(_el$56, "attributes", _v$1, _p$.a)); + _v$9 !== _p$.e && (_p$.e = setProp(_el$50, "fg", _v$9, _p$.e)); + _v$0 !== _p$.t && (_p$.t = setProp(_el$51, "fg", _v$0, _p$.t)); + _v$1 !== _p$.a && (_p$.a = setProp(_el$51, "attributes", _v$1, _p$.a)); return _p$; }, { e: void 0, t: void 0, a: void 0 }); - return _el$54; + return _el$49; })() }); const detail = () => createComponent(For, { @@ -7912,28 +7841,28 @@ function DispatchPanel(props) { return model.detail(); }, children: (line, index) => (() => { - var _el$57 = createElement("text"); - insert(_el$57, line); - effect((_$p) => setProp(_el$57, "fg", index() === 0 ? text() : muted(), _$p)); - return _el$57; + var _el$52 = createElement("text"); + insert(_el$52, line); + effect((_$p) => setProp(_el$52, "fg", index() === 0 ? text() : muted(), _$p)); + return _el$52; })() }); const empty = () => (() => { - var _el$58 = createElement("text"); - insertNode(_el$58, createTextNode(`No delegated sessions`)); - effect((_$p) => setProp(_el$58, "fg", muted(), _$p)); - return _el$58; + var _el$53 = createElement("text"); + insertNode(_el$53, createTextNode(`No delegated sessions`)); + effect((_$p) => setProp(_el$53, "fg", muted(), _$p)); + return _el$53; })(); return (() => { - var _el$60 = createElement("box"), _el$61 = createElement("text"), _el$62 = createElement("text"), _el$66 = createElement("box"), _el$67 = createElement("text"); - insertNode(_el$60, _el$61); - insertNode(_el$60, _el$62); - insertNode(_el$60, _el$66); - insertNode(_el$60, _el$67); - setProp(_el$60, "flexDirection", "column"); - setProp(_el$60, "width", "100%"); - setProp(_el$60, "padding", 1); - insert(_el$60, createComponent(DispatchPanelKeymap, { + var _el$55 = createElement("box"), _el$56 = createElement("text"), _el$57 = createElement("text"), _el$61 = createElement("box"), _el$62 = createElement("text"); + insertNode(_el$55, _el$56); + insertNode(_el$55, _el$57); + insertNode(_el$55, _el$61); + insertNode(_el$55, _el$62); + setProp(_el$55, "flexDirection", "column"); + setProp(_el$55, "width", "100%"); + setProp(_el$55, "padding", 1); + insert(_el$55, createComponent(DispatchPanelKeymap, { get context() { return props.context; }, @@ -7941,30 +7870,30 @@ function DispatchPanel(props) { return props.panel; }, model - }), _el$61); - setProp(_el$61, "attributes", 1); - insert(_el$61, () => model.title()); - insert(_el$60, createComponent(Show, { + }), _el$56); + setProp(_el$56, "attributes", 1); + insert(_el$56, () => model.title()); + insert(_el$55, createComponent(Show, { get when() { return model.header(); }, children: (line) => (() => { - var _el$68 = createElement("text"); - insert(_el$68, line); - effect((_$p) => setProp(_el$68, "fg", muted(), _$p)); - return _el$68; + var _el$63 = createElement("text"); + insert(_el$63, line); + effect((_$p) => setProp(_el$63, "fg", muted(), _$p)); + return _el$63; })() - }), _el$62); - insert(_el$62, () => dispatchPanelRule(props.panel.width - 2)); - insert(_el$60, createComponent(Show, { + }), _el$57); + insert(_el$57, () => dispatchPanelRule(props.panel.width - 2)); + insert(_el$55, createComponent(Show, { get when() { return model.layout().mode === "wide"; }, get fallback() { return (() => { - var _el$69 = createElement("box"); - setProp(_el$69, "flexDirection", "column"); - insert(_el$69, createComponent(Show, { + var _el$64 = createElement("box"); + setProp(_el$64, "flexDirection", "column"); + insert(_el$64, createComponent(Show, { get when() { return model.rows().length > 0; }, @@ -7972,34 +7901,34 @@ function DispatchPanel(props) { return empty(); }, get children() { - var _el$70 = createElement("box"); - setProp(_el$70, "flexDirection", "column"); - insert(_el$70, rows); - return _el$70; + var _el$65 = createElement("box"); + setProp(_el$65, "flexDirection", "column"); + insert(_el$65, rows); + return _el$65; } }), null); - insert(_el$69, createComponent(Show, { + insert(_el$64, createComponent(Show, { get when() { return model.selectedID(); }, get children() { - var _el$71 = createElement("box"), _el$72 = createElement("box"); - insertNode(_el$71, _el$72); - setProp(_el$71, "flexDirection", "column"); - setProp(_el$72, "height", 1); - insert(_el$71, detail, null); - return _el$71; + var _el$66 = createElement("box"), _el$67 = createElement("box"); + insertNode(_el$66, _el$67); + setProp(_el$66, "flexDirection", "column"); + setProp(_el$67, "height", 1); + insert(_el$66, detail, null); + return _el$66; } }), null); - return _el$69; + return _el$64; })(); }, get children() { - var _el$63 = createElement("box"), _el$64 = createElement("box"); - insertNode(_el$63, _el$64); - setProp(_el$63, "flexDirection", "row"); - setProp(_el$64, "flexDirection", "column"); - insert(_el$64, createComponent(Show, { + var _el$58 = createElement("box"), _el$59 = createElement("box"); + insertNode(_el$58, _el$59); + setProp(_el$58, "flexDirection", "row"); + setProp(_el$59, "flexDirection", "column"); + insert(_el$59, createComponent(Show, { get when() { return model.rows().length > 0; }, @@ -8010,36 +7939,36 @@ function DispatchPanel(props) { return rows(); } })); - insert(_el$63, createComponent(Show, { + insert(_el$58, createComponent(Show, { get when() { return model.selectedID(); }, get children() { - var _el$65 = createElement("box"); - setProp(_el$65, "flexDirection", "column"); - insert(_el$65, detail); - effect((_$p) => setProp(_el$65, "width", model.layout().detailWidth, _$p)); - return _el$65; + var _el$60 = createElement("box"); + setProp(_el$60, "flexDirection", "column"); + insert(_el$60, detail); + effect((_$p) => setProp(_el$60, "width", model.layout().detailWidth, _$p)); + return _el$60; } }), null); - effect((_$p) => setProp(_el$64, "width", model.layout().listWidth, _$p)); - return _el$63; + effect((_$p) => setProp(_el$59, "width", model.layout().listWidth, _$p)); + return _el$58; } - }), _el$66); - setProp(_el$66, "height", 1); - insert(_el$67, () => model.footer()); + }), _el$61); + setProp(_el$61, "height", 1); + insert(_el$62, () => model.footer()); effect((_p$) => { var _v$10 = text(), _v$11 = muted(), _v$12 = muted(); - _v$10 !== _p$.e && (_p$.e = setProp(_el$61, "fg", _v$10, _p$.e)); - _v$11 !== _p$.t && (_p$.t = setProp(_el$62, "fg", _v$11, _p$.t)); - _v$12 !== _p$.a && (_p$.a = setProp(_el$67, "fg", _v$12, _p$.a)); + _v$10 !== _p$.e && (_p$.e = setProp(_el$56, "fg", _v$10, _p$.e)); + _v$11 !== _p$.t && (_p$.t = setProp(_el$57, "fg", _v$11, _p$.t)); + _v$12 !== _p$.a && (_p$.a = setProp(_el$62, "fg", _v$12, _p$.a)); return _p$; }, { e: void 0, t: void 0, a: void 0 }); - return _el$60; + return _el$55; })(); } /** App-level command claim: the only way into the panel. It registers the @@ -8096,10 +8025,10 @@ function HomeStatus(props) { return tuiPrefs().footer.home; }, get children() { - var _el$73 = createElement("text"); - insert(_el$73, () => `Pantheon v2.1.5${preset().name ? ` ▸ ${preset().name}` : ""}`); - effect((_$p) => setProp(_el$73, "fg", muted(), _$p)); - return _el$73; + var _el$68 = createElement("text"); + insert(_el$68, () => `Pantheon v2.1.5${preset().name ? ` ▸ ${preset().name}` : ""}`); + effect((_$p) => setProp(_el$68, "fg", muted(), _$p)); + return _el$68; } }); } @@ -8155,10 +8084,10 @@ function PromptFooter(props) { return memo(() => !!tuiPrefs().footer.prompt)() && model.running() > 0; }, get children() { - var _el$74 = createElement("text"); - insert(_el$74, () => `▸${model.preset().name ?? "default"} · ✦${model.running()} ativos`); - effect((_$p) => setProp(_el$74, "fg", muted(), _$p)); - return _el$74; + var _el$69 = createElement("text"); + insert(_el$69, () => `▸${model.preset().name ?? "default"} · ✦${model.running()} ativos`); + effect((_$p) => setProp(_el$69, "fg", muted(), _$p)); + return _el$69; } }); } diff --git a/src/plugins/tui/dist/tui.js.map b/src/plugins/tui/dist/tui.js.map index 30cf0452..6d62e93c 100644 --- a/src/plugins/tui/dist/tui.js.map +++ b/src/plugins/tui/dist/tui.js.map @@ -1 +1 @@ -{"version":3,"file":"tui.js","names":["numberOrNull","resolveRunningVersion"],"sources":["../src/context-gauge.ts","../src/model-usage-limits.ts","../src/autonomy-state.ts","../src/decision-router-state.ts","../src/pantheon-settings-state.ts","../src/update-notice.ts","../src/doctor-state.ts","../src/settings-i18n.ts","../src/j1-gate-status.ts","../src/preset-state.ts","../src/tui-prefs.ts","../src/update-status.ts","../src/whats-new-highlights.ts","../src/sidebar-width.ts","../src/whats-new-state.ts","../src/whats-new-open.ts"],"sourcesContent":["/** Shared, data-only formatting and visual helpers for compact context gauges. */\n\nexport type ContextProgressTone = 'info' | 'success' | 'warning' | 'error'\n\nexport const CONTEXT_BAR_CELLS = 12\nexport const CONTEXT_BAR_FILLED_CELL = '\\u25B0'\nexport const CONTEXT_BAR_EMPTY_CELL = '\\u25B1'\n\nexport type BarShape = 'block' | 'line' | 'smooth' | 'ascii' | 'dots' | 'braille'\n\nexport interface BarShapeGlyphs {\n filled: string\n empty: string\n mark?: string\n}\n\nexport const BAR_SHAPES: Record = {\n block: { filled: '\\u25B0', empty: '\\u25B1', mark: '│' },\n line: { filled: '━', empty: '─', mark: '┼' },\n smooth: { filled: '█', empty: '░', mark: '┆' },\n ascii: { filled: '=', empty: '-', mark: '|' },\n dots: { filled: '●', empty: '○', mark: '│' },\n braille: { filled: '⣿', empty: '⣀', mark: '⡇' },\n}\n\nexport interface ContextBarOptions {\n cells?: number\n shape?: BarShape\n evenMark?: boolean\n}\n\nfunction numberOrNull(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null\n}\n\nexport function contextUsageTone(percent: number): ContextProgressTone {\n if (percent > 90) return 'error'\n if (percent > 50) return 'warning'\n if (percent > 25) return 'success'\n return 'info'\n}\n\nexport function formatTokenCount(tokens: number | null | undefined): string | null {\n const value = numberOrNull(tokens)\n if (value === null || value < 0) return null\n return Math.round(value).toLocaleString('en-US')\n}\n\nexport function formatContextWindow(limit: number | null | undefined): string | null {\n const value = numberOrNull(limit)\n if (value === null || value <= 0) return null\n if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`\n if (value >= 1_000) return `${Math.floor(value / 1_000)}K`\n return `${Math.floor(value)}`\n}\n\nexport function contextBarFilled(percent: number, cells = CONTEXT_BAR_CELLS): number {\n const total = Math.max(1, Math.floor(cells))\n const filled = Math.round((percent / 100) * total)\n if (!Number.isFinite(filled)) return 0\n return Math.min(total, Math.max(0, filled))\n}\n\nexport function contextBar(\n percent: number | null | undefined,\n options: number | ContextBarOptions = CONTEXT_BAR_CELLS,\n): { filled: string; empty: string } | null {\n const value = numberOrNull(percent)\n if (value === null) return null\n const total = Math.max(\n 1,\n Math.floor(typeof options === 'number' ? options : (options?.cells ?? CONTEXT_BAR_CELLS)),\n )\n const shapeKey =\n typeof options === 'object' && options?.shape && options.shape in BAR_SHAPES\n ? options.shape\n : 'block'\n const glyphs = BAR_SHAPES[shapeKey] ?? BAR_SHAPES.block\n const evenMark = typeof options === 'object' ? Boolean(options?.evenMark) : false\n\n const filledCount = contextBarFilled(value, total)\n const emptyCount = total - filledCount\n\n if (!evenMark || total < 4) {\n return {\n filled: glyphs.filled.repeat(filledCount),\n empty: glyphs.empty.repeat(emptyCount),\n }\n }\n\n // Insert even-use mark at the midpoint (50%)\n const mid = Math.floor(total / 2)\n const mark = glyphs.mark ?? '|'\n\n if (filledCount <= mid) {\n // Mark is in the empty portion\n const emptyBefore = mid - filledCount\n const emptyAfter = Math.max(0, emptyCount - emptyBefore - 1)\n return {\n filled: glyphs.filled.repeat(filledCount),\n empty: `${glyphs.empty.repeat(emptyBefore)}${mark}${glyphs.empty.repeat(emptyAfter)}`,\n }\n }\n\n // Mark is in the filled portion\n const filledBefore = mid\n const filledAfter = Math.max(0, filledCount - filledBefore - 1)\n return {\n filled: `${glyphs.filled.repeat(filledBefore)}${mark}${glyphs.filled.repeat(filledAfter)}`,\n empty: glyphs.empty.repeat(emptyCount),\n }\n}\n\nexport function formatSpent(cost: number | null | undefined): string | null {\n const value = numberOrNull(cost)\n if (value === null || value < 0) return null\n return `$${value.toFixed(2)}`\n}\n","/** Shared bounds for cached recent model-usage aggregation. */\nexport const MODEL_USAGE_VISIBLE_CEILING = 3\nexport const MODEL_USAGE_MESSAGE_LIMIT = 400\nexport const MODEL_USAGE_SESSION_LIMIT = 8\n","/**\n * autonomy-state.ts — the Autonomy tab of the settings window.\n *\n * TUI-local copy doctrine. Two surfaces live here:\n *\n * 1. GOAL LOOP — the persisted-mission loop (Wave 3 mechanics) read/written\n * to `options.goal_loop` in the user's opencode.json (the same V2 config\n * copy the context pruner uses). Startup-applied: the runtime resolves it\n * once at plugin setup, so saving requires an OpenCode restart — the tab\n * says so.\n *\n * 2. DECISION BUDGETS — monthly/per-decision USD caps stored in\n * decision-router.json's companion `decision-budget` semantics. The caps\n * the CLI writes via setup-model flags; here they are read from the\n * decision-router.json envelope extension `budget` (v2 superset — the\n * exact-key validator tolerates it via the documented envelope) and\n * applied live per gated call.\n *\n * The decision-gradiente (decide-solo → Jev → human) is DOCUMENTED here, not\n * enforced: J1 owns the risk axis, budgets own the money axis — this tab\n * shows where the thresholds sit today.\n */\nimport type { SettingsTab } from './pantheon-settings-state.ts'\n\nexport interface GoalLoopPrefs {\n enabled: boolean\n cooldownMs: number\n maxContinuations: number\n}\n\nexport const DEFAULT_GOAL_LOOP_PREFS: GoalLoopPrefs = {\n enabled: false,\n cooldownMs: 5000,\n maxContinuations: 25,\n}\n\nexport const GOAL_LOOP_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const MAX_CONTINUATIONS_CYCLE: readonly string[] = Object.freeze([\n '10',\n '25',\n '50',\n '100',\n '200',\n])\n\nexport const COOLDOWN_MS_CYCLE: readonly string[] = Object.freeze(['1000', '2000', '5000', '10000'])\n\nexport interface DecisionBudgets {\n monthlyUsd: number\n perDecisionUsd: number\n}\n\nexport const DEFAULT_DECISION_BUDGETS: DecisionBudgets = {\n monthlyUsd: 5,\n perDecisionUsd: 0.1,\n}\n\n/** Format USD compactly for a cycler cell (\"$5\", \"$0.10\"). */\nexport function formatUsd(value: number): string {\n return `$${value < 1 ? value.toFixed(2) : String(Math.round(value))}`\n}\n\n/** Build the USD step ladder used by the budget cyclers. */\nexport const MONTHLY_USD_CYCLE: readonly string[] = Object.freeze(\n [1, 2, 5, 10, 20, 50, 100].map((value) => formatUsd(value)),\n)\nexport const PER_DECISION_USD_CYCLE: readonly string[] = Object.freeze(\n [0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1].map((value) => formatUsd(value)),\n)\n\n/** Parse a staged USD cell back to a number; junk keeps the input. */\nexport function parseUsd(cell: string): number | null {\n const value = Number(cell.replace('$', ''))\n return Number.isFinite(value) && value > 0 ? value : null\n}\n\nexport function buildAutonomyTab(input: {\n goalLoop: GoalLoopPrefs\n budgets: DecisionBudgets\n goalLoopRestartPending?: boolean | undefined\n languagePref?: string | undefined\n}): SettingsTab {\n const isPt = input.languagePref === 'pt-BR'\n\n return {\n id: 'autonomy',\n title: isPt ? 'Autonomia' : 'Autonomy',\n groups: [\n {\n title: isPt\n ? 'Loop Contínuo (auto-continuação de sessões multi-turn)'\n : 'Auto-Continue Loop (multi-turn session auto-continuation)',\n rows: [\n {\n id: 'autonomy.goal_loop.enabled',\n name: isPt ? 'Loop Contínuo' : 'Auto-Continue Loop',\n value: input.goalLoop.enabled ? 'enabled' : 'disabled',\n cycle: GOAL_LOOP_ENABLED_CYCLE,\n note: isPt\n ? 'continua tarefas multi-turn quando a sessão fica ociosa' +\n (input.goalLoopRestartPending\n ? ' · [!] reinício necessário para aplicar (restart)'\n : ' · aplicado após reiniciar o OpenCode')\n : 'auto-continues multi-turn tasks when session goes idle' +\n (input.goalLoopRestartPending\n ? ' · [!] restart required to apply'\n : ' · applies after OpenCode restart'),\n },\n {\n id: 'autonomy.goal_loop.maxContinuations',\n name: isPt ? 'Limite continuações' : 'Max continuations',\n value: String(input.goalLoop.maxContinuations),\n cycle: MAX_CONTINUATIONS_CYCLE,\n note: isPt\n ? '1..200 — teto de segurança contra loops infinitos'\n : '1..200 — safety ceiling to prevent runaway tasks',\n },\n {\n id: 'autonomy.goal_loop.cooldownMs',\n name: isPt ? 'Pausa entre turnos (ms)' : 'Cooldown (ms)',\n value: String(input.goalLoop.cooldownMs),\n cycle: COOLDOWN_MS_CYCLE,\n note: isPt\n ? 'intervalo entre turnos autônomos (mín 1000ms)'\n : 'delay between autonomous turns (min 1000ms)',\n },\n ],\n },\n {\n title: isPt ? 'Orçamentos de Decisão (Jev)' : 'Decision Budgets (Jev)',\n rows: [\n {\n id: 'autonomy.budget.monthly',\n name: isPt ? 'Teto Mensal (USD)' : 'Monthly Budget Cap',\n value: formatUsd(input.budgets.monthlyUsd),\n cycle: MONTHLY_USD_CYCLE,\n note: isPt\n ? 'teto mensal em USD para arbitragem do Jev'\n : 'monthly USD ceiling for gated arbitrator decisions',\n },\n {\n id: 'autonomy.budget.perDecision',\n name: isPt ? 'Teto por Consulta' : 'Per-Decision Cap',\n value: formatUsd(input.budgets.perDecisionUsd),\n cycle: PER_DECISION_USD_CYCLE,\n note: isPt\n ? 'teto de custo por decisão — acima disso é recusada'\n : 'price cap — gated decisions above this are refused',\n },\n ],\n },\n {\n title: isPt\n ? 'Gradiente de Decisão (política de referência · governado por J1 e Orçamentos)'\n : 'Decision Gradient (reference policy · governed by J1 & Budgets)',\n rows: [\n {\n id: 'autonomy.gradient.solo',\n name: isPt ? 'Decisão solo' : 'Decide solo',\n value: isPt ? 'autônomo' : 'autonomous',\n note: isPt\n ? 'ações rotineiras de baixo risco · reversível sem travas (sem portão)'\n : 'reversible & low-risk edits, routine fixes (no gate)',\n },\n {\n id: 'autonomy.gradient.jev',\n name: isPt ? 'Decisão Jev' : 'Jev decides',\n value: isPt ? 'arbitrado' : 'arbitrated',\n note: isPt\n ? 'ambiguidade de tipos e rotas · configurado nos Tetos de Orçamento acima'\n : 'typed ambiguity & candidate ranking · configured via Budgets above',\n },\n {\n id: 'autonomy.gradient.human',\n name: isPt ? 'Aprovação humana' : 'Human decides',\n value: isPt ? 'revisão humana' : 'human review',\n note: isPt\n ? 'ações destrutivas e de alto risco · configurado no limiar do Portão J1'\n : 'high-risk & destructive operations · configured via J1 Gate',\n },\n ],\n },\n ],\n }\n}\n","/**\n * decision-router-state.ts — the Decision Model section of the settings window.\n *\n * TUI-local replica of the user-level decision-router config\n * (scripts/install/decision-router-config.mjs — the bundle must stay\n * self-contained); tests/tui-decision-router-state.test.mjs pins the schema\n * version, the exact key set and the provider matrix against that source.\n *\n * The runtime re-reads this file on EVERY gated call (jev-decision-tool.ts),\n * so a write here applies live — no restart. The strict exact-key schema is\n * load-bearing: any unknown key fail-closes the runtime to disabled/local,\n * so the writer validates before persisting.\n *\n * Egress consent is CLI-owned: the window never writes `egress_consent`, and\n * refuses to enable the router while remote candidates exist without it.\n */\nimport { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\n\nexport const DECISION_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const DECISION_CONFIG_SCHEMA_VERSION = 2\n\n/** Exact top-level key set — anything else fail-closes the runtime. */\nexport const DECISION_CONFIG_KEYS: readonly string[] = Object.freeze([\n 'egress_consent',\n 'enabled',\n 'enabled_candidates',\n 'schema_version',\n 'selection',\n])\n\nexport type DecisionSelectionMode = 'local' | 'auto' | 'explicit'\n\nexport interface DecisionSelection {\n mode: DecisionSelectionMode\n provider?: string\n model?: string\n}\n\nexport interface DecisionCandidate {\n provider: string\n model: string\n}\n\nexport interface DecisionRouterConfig {\n schema_version: number\n enabled: boolean\n selection: DecisionSelection\n egress_consent: boolean\n enabled_candidates: readonly DecisionCandidate[]\n}\n\nexport const DEFAULT_DECISION_CONFIG: DecisionRouterConfig = Object.freeze({\n schema_version: DECISION_CONFIG_SCHEMA_VERSION,\n enabled: false,\n selection: Object.freeze({ mode: 'local' as const }),\n egress_consent: false,\n enabled_candidates: Object.freeze([]),\n})\n\n/** The runtime's provider→model matrix (drift-pinned against the installer source). */\nexport const DECISION_KNOWN_PROVIDERS: readonly string[] = Object.freeze([\n 'openai-decisions',\n 'typesafe-jev',\n 'opencode-console-jev',\n 'openrouter-jev',\n 'vercel-gateway-jev',\n 'cloudflare-workers-jev',\n])\n\nexport const DECISION_CONSENT_CYCLE: readonly string[] = Object.freeze(['not granted', 'granted'])\n/** provider → model, straight from the runtime matrix (drift-pinned in tests). */\nexport const DECISION_KNOWN_MODELS: Readonly> = Object.freeze({\n 'openai-decisions': 'gpt-6-luna',\n 'typesafe-jev': 'jev-1.14.0',\n 'opencode-console-jev': 'jev-1.13',\n 'openrouter-jev': 'typesafe/jev-1.13',\n 'vercel-gateway-jev': 'typesafe-ai/jev',\n 'cloudflare-workers-jev': 'clef',\n})\n\n/**\n * Credential surface per provider: the ENV VAR the host provider entry reads\n * (`{env:VAR}` indirection — the window NEVER holds key values) plus the setup\n * note. Drift-pinned against the installer/runtime sources in tests.\n */\nexport const DECISION_PROVIDER_CREDENTIALS: Readonly<\n Record\n> = Object.freeze({\n 'openai-decisions': {\n note: 'host-configured model — provision via `decision-router setup-model openai-decisions`',\n notePt: 'modelo do host — configure via `decision-router setup-model openai-decisions`',\n },\n 'typesafe-jev': {\n env: 'TYPESAFE_API_KEY',\n note: 'export TYPESAFE_API_KEY=… then restart',\n notePt: 'export TYPESAFE_API_KEY=… e depois reinicie',\n },\n 'opencode-console-jev': {\n note: 'rides your OpenCode login — no separate key',\n notePt: 'utiliza login do OpenCode — sem chave separada',\n },\n 'openrouter-jev': {\n env: 'OPENROUTER_API_KEY',\n note: 'export OPENROUTER_API_KEY=… then restart',\n notePt: 'export OPENROUTER_API_KEY=… e depois reinicie',\n },\n 'vercel-gateway-jev': {\n env: 'AI_GATEWAY_API_KEY',\n note: 'export AI_GATEWAY_API_KEY=… then restart',\n notePt: 'export AI_GATEWAY_API_KEY=… e depois reinicie',\n },\n 'cloudflare-workers-jev': {\n env: 'CLOUDFLARE_API_TOKEN',\n note: 'needs accountId (setup-model --account-id=…) + CLOUDFLARE_API_TOKEN',\n notePt: 'requer accountId (setup-model --account-id=…) + CLOUDFLARE_API_TOKEN',\n },\n})\n\nexport const DECISION_TARGET_CYCLE: readonly string[] = Object.freeze(\n DECISION_KNOWN_PROVIDERS.map((provider) => `${provider}/${DECISION_KNOWN_MODELS[provider]}`),\n)\n\nexport function decisionRouterConfigPath(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'pantheon', 'decision-router.json')\n}\n\nexport interface DecisionConfigRead {\n config: DecisionRouterConfig\n /** The file exists but is not a valid v2 config — the runtime fail-closes. */\n corrupt: boolean\n}\n\n/** Fail-open read: a missing file is the default; an invalid one is reported, not guessed. */\nexport function readDecisionRouterConfig(\n env: Record = process.env,\n): DecisionConfigRead {\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(decisionRouterConfigPath(env), 'utf8'))\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') {\n return { config: cloneDefault(), corrupt: false }\n }\n return { config: cloneDefault(), corrupt: true }\n }\n if (isValidDecisionConfig(raw)) return { config: raw, corrupt: false }\n return { config: cloneDefault(), corrupt: true }\n}\n\nfunction cloneDefault(): DecisionRouterConfig {\n return {\n schema_version: DEFAULT_DECISION_CONFIG.schema_version,\n enabled: DEFAULT_DECISION_CONFIG.enabled,\n selection: { ...DEFAULT_DECISION_CONFIG.selection },\n egress_consent: DEFAULT_DECISION_CONFIG.egress_consent,\n enabled_candidates: [...DEFAULT_DECISION_CONFIG.enabled_candidates],\n }\n}\n\n/** The exact-key, exact-shape validation the runtime applies (fail-closed otherwise). */\nexport function isValidDecisionConfig(value: unknown): value is DecisionRouterConfig {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const record = value as Record\n const keys = Object.keys(record).sort()\n if (keys.length !== DECISION_CONFIG_KEYS.length) return false\n for (const key of DECISION_CONFIG_KEYS) {\n if (!keys.includes(key)) return false\n }\n if (record.schema_version !== DECISION_CONFIG_SCHEMA_VERSION) return false\n if (typeof record.enabled !== 'boolean') return false\n if (typeof record.egress_consent !== 'boolean') return false\n if (!isValidSelection(record.selection)) return false\n if (!Array.isArray(record.enabled_candidates)) return false\n for (const candidate of record.enabled_candidates) {\n if (typeof candidate !== 'object' || candidate === null) return false\n const entry = candidate as Record\n if (typeof entry.provider !== 'string' || typeof entry.model !== 'string') return false\n if (Object.keys(entry).length !== 2) return false\n }\n return true\n}\n\nfunction isValidSelection(value: unknown): value is DecisionSelection {\n if (typeof value !== 'object' || value === null) return false\n const selection = value as Record\n if (selection.mode !== 'local' && selection.mode !== 'auto' && selection.mode !== 'explicit') {\n return false\n }\n const keys = Object.keys(selection).sort()\n for (const key of keys) {\n if (key !== 'mode' && key !== 'provider' && key !== 'model') return false\n }\n if (selection.provider !== undefined && typeof selection.provider !== 'string') return false\n if (selection.model !== undefined && typeof selection.model !== 'string') return false\n return true\n}\n\n/** Stable serializer: exact keys in sorted order, 2-space, trailing newline. */\nexport function serializeDecisionConfig(config: DecisionRouterConfig): string {\n const ordered = {\n egress_consent: config.egress_consent,\n enabled: config.enabled,\n enabled_candidates: config.enabled_candidates.map((candidate) => ({\n model: candidate.model,\n provider: candidate.provider,\n })),\n schema_version: config.schema_version,\n selection: {\n mode: config.selection.mode,\n ...(config.selection.model !== undefined ? { model: config.selection.model } : {}),\n ...(config.selection.provider !== undefined ? { provider: config.selection.provider } : {}),\n },\n }\n return `${JSON.stringify(ordered, null, 2)}\\n`\n}\n\n/**\n * Enable/disable the router in a config copy. The guard mirrors the runtime's\n * fail-close: with remote candidates and no egress consent, an enabled flag\n * would be a lie — enabling requires consent, or a local-only selection.\n * Never touches `egress_consent` (CLI-owned).\n */\nexport function setDecisionEnabled(\n config: DecisionRouterConfig,\n enabled: boolean,\n): { ok: true; config: DecisionRouterConfig } | { ok: false; reason: string } {\n if (enabled) {\n const localOnly = config.selection.mode === 'local' || config.enabled_candidates.length === 0\n if (!localOnly && !config.egress_consent) {\n return {\n ok: false,\n reason:\n 'remote candidates need egress consent — toggle Egress consent in this tab, then enable',\n }\n }\n }\n return { ok: true, config: { ...config, enabled } }\n}\n\n/** Atomic-ish write mirroring the canonical writer's privacy posture (0600). */\nexport function writeDecisionRouterConfig(\n config: DecisionRouterConfig,\n env: Record = process.env,\n): void {\n if (!isValidDecisionConfig(config)) {\n throw new TypeError('Refusing to persist an invalid decision-router configuration')\n }\n const path = decisionRouterConfigPath(env)\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 })\n const temp = `${path}.tui.tmp`\n writeFileSync(temp, serializeDecisionConfig(config), { mode: 0o600 })\n renameSync(temp, path)\n chmodSync(path, 0o600)\n}\n\nexport const DECISION_SELECTION_CYCLE: readonly string[] = Object.freeze([\n 'local',\n 'auto',\n 'explicit',\n])\n\n/** Stage a selection/consent row into a config copy; unknown rows are no-ops. */\nexport function applyDecisionRow(\n config: DecisionRouterConfig,\n id: string,\n value: string,\n): DecisionRouterConfig {\n const next: DecisionRouterConfig = {\n ...config,\n selection: { ...config.selection },\n enabled_candidates: [...config.enabled_candidates],\n }\n switch (id) {\n case 'decision.selection.mode': {\n const mode = value as DecisionSelectionMode\n if (mode !== 'local' && mode !== 'auto' && mode !== 'explicit') return config\n next.selection.mode = mode\n if (mode === 'local') next.enabled_candidates = []\n return next\n }\n case 'decision.selection.target': {\n const separator = value.indexOf('/')\n if (separator <= 0) return config\n const provider = value.slice(0, separator)\n const model = value.slice(separator + 1)\n if (!DECISION_KNOWN_PROVIDERS.includes(provider)) return config\n if (DECISION_KNOWN_MODELS[provider] !== model) return config\n next.selection = { mode: 'explicit', provider, model }\n next.enabled_candidates = [{ provider, model }]\n return next\n }\n case 'decision.consent': {\n next.egress_consent = value === 'granted'\n return next\n }\n default:\n return config\n }\n}\n\n/** The host's provider auth store (`opencode auth login` writes here). */\nexport function decisionAuthStorePath(env: Record = process.env) {\n const xdgData = env.XDG_DATA_HOME\n const home = env.HOME ?? ''\n const root = xdgData ?? join(home, '.local', 'share')\n return join(root, 'opencode', 'auth.json')\n}\n\n/** Provider ids as they appear in the host auth store / config providers. */\nconst PROVIDER_AUTH_NAMES: Readonly> = Object.freeze({\n 'openai-decisions': Object.freeze(['openai']),\n 'typesafe-jev': Object.freeze(['typesafe-ai']),\n 'opencode-console-jev': Object.freeze([]),\n 'openrouter-jev': Object.freeze(['openrouter']),\n 'vercel-gateway-jev': Object.freeze(['vercel-ai-gateway', 'vercel']),\n 'cloudflare-workers-jev': Object.freeze(['cloudflare-workers-ai']),\n})\n\nexport type CredentialForm = 'env' | 'auth store' | 'config' | 'missing'\n\n/**\n * TWO recognition forms (field feedback beta.6: keys registered via\n * `opencode auth login` showed MISSING because only env vars were checked):\n * env var set → 'env'; provider present in the host auth store → 'auth\n * store'; provider entry in opencode.json providers → 'config'. Values are\n * NEVER read — existence only.\n */\nexport function credentialStatus(\n provider: string,\n env: Record,\n authProviders: ReadonlySet,\n configProviders: ReadonlySet,\n): CredentialForm {\n const credential = DECISION_PROVIDER_CREDENTIALS[provider]\n if (credential?.env !== undefined && env[credential.env]) return 'env'\n for (const name of PROVIDER_AUTH_NAMES[provider] ?? []) {\n if (authProviders.has(name)) return 'auth store'\n }\n for (const name of PROVIDER_AUTH_NAMES[provider] ?? []) {\n if (configProviders.has(name)) return 'config'\n }\n if (provider === 'opencode-console-jev') return 'auth store'\n return 'missing'\n}\n\nexport function buildDecisionTab(\n read: DecisionConfigRead,\n env: Record = process.env,\n authProviders: ReadonlySet = new Set(),\n configProviders: ReadonlySet = new Set(),\n languagePref?: string | undefined,\n): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const { config, corrupt } = read\n const rows: SettingsRow[] = [\n {\n id: 'decision.enabled',\n name: isPt ? 'Assistente Jev' : 'Jev Assistant',\n value: config.enabled ? 'enabled' : 'disabled',\n // Corrupt config → read-only; the notice (glue) carries the remedy.\n ...(corrupt ? {} : { cycle: DECISION_ENABLED_CYCLE }),\n note: corrupt\n ? isPt\n ? 'config inválida — runtime fail-closes; repare via `decision-router setup-model`'\n : 'config unreadable/invalid — runtime fail-closes; repair via `decision-router setup-model`'\n : isPt\n ? 'aplica em tempo real — arbitragem de decisões relida a cada chamada'\n : 'applies live — the runtime re-reads this on every gated call',\n },\n {\n id: 'decision.selection.mode',\n name: isPt ? 'Modo de Operação' : 'Operation Mode',\n value: config.selection.mode,\n ...(corrupt ? {} : { cycle: DECISION_SELECTION_CYCLE }),\n note: isPt\n ? 'local = no seu PC (grátis); auto/explícito = modelo nuvem (OpenRouter)'\n : 'local routes on-device; auto/explicit pick a remote decision model',\n },\n ]\n\n // Model selection row: always visible so the user can choose the decision model\n const explicitTarget = config.selection.provider\n ? `${config.selection.provider}/${config.selection.model ?? ''}`\n : (DECISION_TARGET_CYCLE[0] ?? 'openrouter-jev/typesafe/jev-1.13')\n rows.push({\n id: 'decision.selection.target',\n name: isPt ? 'Modelo de Decisão' : 'Decision Model',\n value:\n config.selection.mode === 'local'\n ? config.selection.provider\n ? `${config.selection.provider}/${config.selection.model ?? ''}`\n : 'local (on-device)'\n : explicitTarget,\n ...(corrupt ? {} : { cycle: DECISION_TARGET_CYCLE }),\n note: isPt\n ? config.selection.mode === 'local'\n ? 'ciclar seleciona modelo remoto e ativa modo explícito'\n : 'provedor/modelo ativo — define candidato para arbitragem'\n : config.selection.mode === 'local'\n ? 'cycle to select a remote model and activate explicit mode'\n : 'provider/model — sets the candidate list',\n })\n\n if ((config.enabled_candidates?.length ?? 0) > 0) {\n rows.push({\n id: 'decision.candidates',\n name: isPt ? 'Candidatos ativos' : 'Candidates',\n value: String(config.enabled_candidates.length),\n note: config.egress_consent\n ? config.enabled_candidates\n .map((candidate) => `${candidate.provider}/${candidate.model}`)\n .join(', ')\n : isPt\n ? 'egress consent NÃO concedido — rotas remotas bloqueadas'\n : 'egress consent NOT granted — remote routes fail closed',\n })\n }\n\n rows.push({\n id: 'decision.consent',\n name: isPt ? 'Acesso à Nuvem' : 'Cloud API Access',\n value: config.egress_consent ? 'granted' : 'not granted',\n ...(corrupt ? {} : { cycle: DECISION_CONSENT_CYCLE }),\n note: isPt\n ? config.egress_consent\n ? 'granted = rotas remotas podem consultar gateway de API (com teto de custo)'\n : 'not granted = chamadas remotas bloqueadas; requer granted para nuvem'\n : config.egress_consent\n ? 'granted = remote decision routes may call their gateway (budget-capped)'\n : 'not granted = remote routes fail closed; grant to allow cloud calls',\n })\n\n return {\n id: 'decision',\n title: isPt ? 'Decisão' : 'Decision',\n groups: [\n { title: isPt ? 'Assistente de Decisão (Jev)' : 'Decision Assistant (Jev)', rows },\n {\n title: isPt\n ? 'Credenciais (status apenas — valores nunca gravados na janela)'\n : 'Credentials (status only — values never enter the window)',\n rows: DECISION_KNOWN_PROVIDERS.map((provider) => {\n const status = credentialStatus(provider, env, authProviders, configProviders)\n const credential = DECISION_PROVIDER_CREDENTIALS[provider] ?? { note: '' }\n return {\n id: `decision.key.${provider}`,\n name: provider,\n value: status === 'missing' ? 'MISSING' : status,\n note: isPt ? (credential.notePt ?? credential.note) : credential.note,\n }\n }),\n },\n ],\n }\n}\n","/**\n * pantheon-settings-state.ts — the pure state core of the settings window.\n *\n * TUI-local copy doctrine (same as cost-data.ts): the bundle must stay\n * self-contained. The behaviors registry mirrors routing.yml's `behaviors:`\n * (drift-pinned by tests/pantheon-settings-state.test.mjs).\n *\n * Model (2.0.0-beta.4, the quota-style full window): the window is a set of\n * TABS; each tab holds GROUPS of setting ROWS; a row carries a display VALUE\n * and — when the setting is editable — the CYCLE of allowed values that\n * ←/→ steps through. Edits stage into a DRAFT (id → pending value); `save`\n * applies the draft through injected writers, `reset` drops it. The disk\n * never changes before save.\n */\n\nexport interface SettingsBehavior {\n id: string\n kind: 'install' | 'runtime'\n title: string\n description: string\n}\n\n/** Mirrors routing.yml `behaviors:` — drift-pinned by the registry test. */\nexport const SETTINGS_BEHAVIORS: readonly SettingsBehavior[] = Object.freeze([\n {\n id: 'skill-auto-continue',\n kind: 'install',\n title: 'Auto-continue skill',\n description: 'Continue multi-step todos while keeping safety gates.',\n },\n {\n id: 'skill-tdd-with-agents',\n kind: 'install',\n title: 'TDD with agents skill',\n description: 'RED, GREEN, REFACTOR test-driven implementation.',\n },\n {\n id: 'skill-code-review-checklist',\n kind: 'install',\n title: 'Code review checklist skill',\n description: 'Systematic code review and quality gates.',\n },\n {\n id: 'skill-prompt-refinery',\n kind: 'install',\n title: 'Prompt refinery skill',\n description: 'Vague requests refined — silent adjust, >> full contract.',\n },\n {\n id: 'gate-idle-todo-enforcer',\n kind: 'runtime',\n title: 'Idle todo enforcer',\n description: 'Continues pending todos when a session goes idle.',\n },\n {\n id: 'gate-context-pruner',\n kind: 'runtime',\n title: 'Context pruner',\n description: 'Prunes repeated tool output before summarization.',\n },\n {\n id: 'gate-j1-risk-gate',\n kind: 'runtime',\n title: 'J1 risk gate',\n description: 'High-risk tool calls demand explicit human approval.',\n },\n])\n\nexport interface OverrideEntry {\n action: 'disable' | 'replace'\n content?: string\n reason?: string\n}\n\nexport type EffectiveOverrides = Record\n\n/** Which behaviors the settings window can write (runtime + install skills). */\nexport const SETTINGS_TOGGLABLE_IDS = new Set(SETTINGS_BEHAVIORS.map((b) => b.id))\n\nexport function isBehaviorDisabled(effective: EffectiveOverrides, id: string): boolean {\n return effective[id]?.action === 'disable'\n}\n\nexport const TOGGLE_REASON = 'toggled in /pantheon-settings'\n\n/**\n * Toggle (a targeted write keeps the toggle semantics: a `replace` entry is\n * never destroyed — disabling keeps its `content`, re-enabling restores the\n * replace; a settings-written disable is removed outright, no toggle noise).\n */\nexport function toggledOverrides(\n effective: EffectiveOverrides,\n id: string,\n reason: string = TOGGLE_REASON,\n): EffectiveOverrides {\n const next: EffectiveOverrides = { ...effective }\n const entry = next[id]\n if (entry?.action === 'disable') {\n if (entry.content !== undefined) {\n next[id] =\n entry.reason === reason\n ? { action: 'replace', content: entry.content }\n : {\n action: 'replace',\n content: entry.content,\n ...(entry.reason !== undefined ? { reason: entry.reason } : {}),\n }\n } else {\n delete next[id]\n }\n } else {\n next[id] =\n entry?.content !== undefined\n ? { action: 'disable', reason, content: entry.content }\n : { action: 'disable', reason }\n }\n return next\n}\n\n/** Set an explicit on/off target (the cycler's save path) via the toggle semantics. */\nexport function setOverrideState(\n effective: EffectiveOverrides,\n id: string,\n target: 'enabled' | 'disabled',\n reason: string = TOGGLE_REASON,\n): EffectiveOverrides {\n const disabled = isBehaviorDisabled(effective, id)\n if ((target === 'disabled') === disabled) return effective\n return toggledOverrides(effective, id, reason)\n}\n\nexport function serializeOverrides(effective: EffectiveOverrides): string {\n const ordered: Record = {}\n for (const id of Object.keys(effective).sort()) ordered[id] = effective[id]\n return `${JSON.stringify(ordered, null, 2)}\\n`\n}\n\n// ── Overrides load (global + project files) ────────────────────────────\n\nexport interface OverridesLoad {\n global: EffectiveOverrides\n project: EffectiveOverrides\n /** The GLOBAL file exists but does not parse — writes are refused. */\n corruptGlobal: boolean\n}\n\n/** Merge for DISPLAY only, mirroring the runtime precedence: project wins per id. */\nexport function mergedOverrides(load: OverridesLoad): EffectiveOverrides {\n return { ...load.global, ...load.project }\n}\n\nexport function canWriteOverrides(load: OverridesLoad): boolean {\n return !load.corruptGlobal\n}\n\n// ── Tab / group / row model (the cycler window) ────────────────────────\n\nexport interface SettingsRow {\n id: string\n name: string\n /** Current effective value (display); the staged draft may differ. */\n value: string\n /** Allowed values for ←/→; presence marks the row as editable. */\n cycle?: readonly string[]\n /** The row's DEFAULT value — what the Defaults action stages. */\n def?: string\n /** Right-column note (writes-where, applies-live, from-where). */\n note?: string\n /** Enter triggers this action instead of cycling (e.g. `update-check`). */\n action?: string\n}\n\nexport interface SettingsGroup {\n /** Bold group header; undefined renders rows without a header. */\n title?: string\n rows: SettingsRow[]\n}\n\nexport interface SettingsTab {\n id: string\n title: string\n groups: SettingsGroup[]\n}\n\n/** Neutral tab for out-of-range indexes (noUncheckedIndexedAccess guard). */\nexport const EMPTY_TAB: SettingsTab = { id: 'empty', title: '', groups: [] }\n\n/** Flat, in-order rows of a tab (the up/down navigation space). */\nexport function tabRows(tab: SettingsTab): SettingsRow[] {\n return tab.groups.flatMap((group) => group.rows)\n}\n\nexport function findRow(tab: SettingsTab, id: string): SettingsRow | undefined {\n return tabRows(tab).find((row) => row.id === id)\n}\n\n// ── The cycler ─────────────────────────────────────────────────────────\n\n/** Step through the cycle with wrap-around; non-cyclable rows return the input. */\nexport function cycleValue(value: string, cycle: readonly string[], direction: 1 | -1): string {\n if (cycle.length === 0) return value\n const index = cycle.indexOf(value)\n if (index === -1) return cycle[0] ?? value\n const next = (index + direction + cycle.length) % cycle.length\n return cycle[next] ?? value\n}\n\n// ── The draft (staged edits; the disk never changes before save) ───────\n\nexport type SettingsDraft = Record\n\nexport function stageValue(\n draft: SettingsDraft,\n row: SettingsRow,\n direction: 1 | -1,\n): SettingsDraft {\n if (row.cycle === undefined) return draft\n const current = draft[row.id] ?? row.value\n const staged = cycleValue(current, row.cycle, direction)\n if (staged === row.value) {\n // staged back onto the disk value — drop the entry (no toggle noise)\n if (draft[row.id] === undefined) return draft\n const next = { ...draft }\n delete next[row.id]\n return next\n }\n return { ...draft, [row.id]: staged }\n}\n\n/** Stage an explicit target value for one row (the Defaults action path). */\nexport function stageRowToValue(\n draft: SettingsDraft,\n row: SettingsRow,\n target: string,\n): SettingsDraft {\n if (!row.cycle?.includes(target)) return draft\n if (target === row.value) {\n if (draft[row.id] === undefined) return draft\n const next = { ...draft }\n delete next[row.id]\n return next\n }\n return { ...draft, [row.id]: target }\n}\n\n/**\n * Stage every cyclable row's DEFAULT value of a tab. Rows already at their\n * default have their staged entry dropped; rows staged elsewhere keep it\n * until the Defaults action targets them.\n */\nexport function stageDefaults(draft: SettingsDraft, tab: SettingsTab): SettingsDraft {\n let next = draft\n for (const row of tabRows(tab)) {\n if (row.cycle === undefined || row.def === undefined) continue\n const candidate = next[row.id] ?? row.value\n if (candidate === row.def) {\n if (next[row.id] !== undefined) {\n const copy = { ...next }\n delete copy[row.id]\n next = copy\n }\n continue\n }\n next = stageRowToValue(next, { ...row, value: candidate }, row.def)\n }\n return next\n}\n\n/** Drop every staged entry of one tab (ctrl+r). */\nexport function resetTab(draft: SettingsDraft, tab: SettingsTab): SettingsDraft {\n const ids = new Set(tabRows(tab).map((row) => row.id))\n const next: SettingsDraft = {}\n for (const [id, value] of Object.entries(draft)) {\n if (!ids.has(id)) next[id] = value\n }\n return next\n}\n\nexport function draftCount(draft: SettingsDraft): number {\n return Object.keys(draft).length\n}\n\nexport function draftDirty(draft: SettingsDraft): boolean {\n return draftCount(draft) > 0\n}\n\nexport function tabDirty(draft: SettingsDraft, tab: SettingsTab): boolean {\n return tabRows(tab).some((row) => draft[row.id] !== undefined)\n}\n\n// ── Applying the draft ─────────────────────────────────────────────────\n\nexport interface DraftWriterResult {\n ok: boolean\n reason?: string\n}\n\n/**\n * One callback that dispatches a staged row to its real writer (gates →\n * overrides file, decision → decision-router.json, preset → active-preset).\n *Injected by the glue so the disk never runs in tests.\n */\nexport type DraftWriter = (id: string, value: string) => DraftWriterResult\n\nexport interface AppliedDraft {\n applied: string[]\n failed: { id: string; reason: string }[]\n}\n\n/** Apply every staged entry; failures are collected, never thrown. */\nexport function applyDraft(draft: SettingsDraft, writer: DraftWriter): AppliedDraft {\n const applied: string[] = []\n const failed: AppliedDraft['failed'] = []\n for (const [id, value] of Object.entries(draft)) {\n const result = writer(id, value)\n if (result.ok) applied.push(id)\n else failed.push({ id, reason: result.reason ?? 'write failed' })\n }\n return { applied, failed }\n}\n\n/** The rows that succeeded and are still in the draft (failed ones stay staged). */\nexport function settledDraft(draft: SettingsDraft, applied: readonly string[]): SettingsDraft {\n const next: SettingsDraft = {}\n for (const [id, value] of Object.entries(draft)) {\n if (!applied.includes(id)) next[id] = value\n }\n return next\n}\n\n// ── Gates / About tabs (behavior-native; the other tabs live in their modules) ──\n\nexport const GATES_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport function buildGatesTab(load: OverridesLoad, languagePref?: string): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const merged = mergedOverrides(load)\n const rowFor = (behavior: SettingsBehavior): SettingsRow => {\n const fromProject = load.project[behavior.id] !== undefined\n const writable = !fromProject && canWriteOverrides(load)\n return {\n id: `gate.${behavior.id}`,\n name: fromProject ? `${behavior.title} (${isPt ? 'projeto' : 'project'})` : behavior.title,\n value: isBehaviorDisabled(merged, behavior.id) ? 'disabled' : 'enabled',\n ...(writable ? { cycle: GATES_ENABLED_CYCLE } : {}),\n note: fromProject\n ? isPt\n ? 'arquivo do projeto tem precedência · edite .pantheon/overrides.json'\n : 'project file wins at runtime — edit .pantheon/overrides.json'\n : behavior.description,\n }\n }\n const install = SETTINGS_BEHAVIORS.filter((behavior) => behavior.kind === 'install')\n const runtime = SETTINGS_BEHAVIORS.filter((behavior) => behavior.kind === 'runtime')\n return {\n id: 'gates',\n title: 'Gates',\n groups: [\n { title: isPt ? 'Skills instaladas' : 'Install skills', rows: install.map(rowFor) },\n { title: isPt ? 'Portões de execução' : 'Runtime gates', rows: runtime.map(rowFor) },\n ],\n }\n}\n\nexport interface AboutTabExtra {\n nodeVersion?: string\n platform?: string\n preset?: string | null\n decisionEnabled?: boolean\n j1Mode?: string\n languagePref?: string\n}\n\nexport function buildAboutTab(version: string, extra?: AboutTabExtra): SettingsTab {\n const isPt = extra?.languagePref === 'pt-BR'\n\n const sysRows: SettingsRow[] = [\n {\n id: 'about.version',\n name: isPt ? 'Versão' : 'Version',\n value: `v${version}`,\n note: isPt\n ? 'OpenCode 2.x nativo — contrato V1 descontinuado'\n : 'OpenCode 2.x only — the V1 contract is removed',\n },\n {\n id: 'about.behaviors',\n name: isPt ? 'Comportamentos' : 'Behaviors',\n value: String(SETTINGS_BEHAVIORS.length),\n note: isPt\n ? 'portões e skills de governança registradas'\n : 'registered governance gates and skills',\n },\n ]\n\n if (extra?.nodeVersion) {\n sysRows.push({\n id: 'about.runtime',\n name: 'Runtime Node.js',\n value: `v${extra.nodeVersion}`,\n note: extra.platform ? `${isPt ? 'plataforma' : 'platform'}: ${extra.platform}` : '',\n })\n }\n\n const govRows: SettingsRow[] = [\n {\n id: 'about.preset',\n name: isPt ? 'Predefinição' : 'Active Preset',\n value: extra?.preset ?? 'none',\n note: isPt ? 'modelo global ativo do Pantheon' : 'global model preset active in Pantheon',\n },\n {\n id: 'about.decision',\n name: isPt ? 'Assistente Jev' : 'Decision Router',\n value: extra?.decisionEnabled\n ? isPt\n ? 'ativado'\n : 'enabled'\n : isPt\n ? 'desativado'\n : 'disabled',\n note: isPt ? 'arbitragem de modelos e candidatos' : 'model and candidate arbitration',\n },\n {\n id: 'about.j1',\n name: isPt ? 'Portão J1' : 'J1 Risk Gate',\n value: extra?.j1Mode ?? 'shadow',\n note: isPt\n ? 'portão de risco de segurança operacional'\n : 'operational safety risk score gate',\n },\n ]\n\n const refRows: SettingsRow[] = [\n {\n id: 'about.license',\n name: isPt ? 'Licença' : 'License',\n value: 'MIT',\n note: 'Open source · Pantheon Project',\n },\n {\n id: 'about.repo',\n name: isPt ? 'Repositório' : 'Repository',\n value: 'ils15/pantheon-opencode',\n note: 'github.com/ils15/pantheon-opencode',\n },\n ]\n\n const groups = [{ title: isPt ? 'Sistema & Plataforma' : 'System & Platform', rows: sysRows }]\n if (extra?.preset !== undefined || extra?.decisionEnabled !== undefined) {\n groups.push({ title: isPt ? 'Governança & Roteamento' : 'Governance & Routing', rows: govRows })\n }\n groups.push({ title: isPt ? 'Projeto & Referências' : 'Project & References', rows: refRows })\n\n return {\n id: 'about',\n title: isPt ? 'Sobre' : 'About',\n groups,\n }\n}\n\nexport interface ChangelogHighlightItem {\n title: string\n detail: string\n group?: string | undefined\n}\n\nexport function buildChangelogTab(\n version: string,\n items: ChangelogHighlightItem[] = [],\n languagePref?: string | undefined,\n): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n\n const rows: SettingsRow[] = []\n if (items.length > 0) {\n items.forEach((item, index) => {\n rows.push({\n id: `changelog.item.${index + 1}`,\n name: item.title.slice(0, 26),\n value: '',\n note: item.detail,\n })\n })\n } else {\n rows.push({\n id: 'changelog.info',\n name: isPt ? 'Versão' : 'Release',\n value: `v${version}`,\n note: isPt\n ? 'veja o histórico completo no CHANGELOG.md ou no GitHub'\n : 'view full history in CHANGELOG.md or GitHub releases',\n })\n }\n\n return {\n id: 'changelog',\n title: isPt ? 'Changelog' : 'Changelog',\n groups: [\n {\n title: isPt ? `Novidades na versão v${version}` : `What's New in v${version}`,\n rows,\n },\n {\n title: isPt ? 'Referências de Versão' : 'Release References',\n rows: [\n {\n id: 'changelog.docs',\n name: isPt ? 'Documentação' : 'Documentation',\n value: 'CHANGELOG.md',\n note: isPt\n ? 'incluído na raiz do plugin e do repositório'\n : 'shipped at plugin root and repository root',\n },\n {\n id: 'changelog.repo',\n name: isPt ? 'Repositório GitHub' : 'GitHub Repository',\n value: 'ils15/pantheon-opencode',\n note: isPt\n ? 'versões, pull requests e discussões'\n : 'releases, pull requests and discussion',\n },\n ],\n },\n ],\n }\n}\n","/**\n * Update notifier core (TUI-local copy — the bundle must stay self-contained,\n * same precedent as cost-data.ts/model-pricing.ts).\n *\n * Pin + notify, never silent auto-update: one notice per newer version,\n * TTL-cached, offline-safe, and a stable install is never advertised a beta\n * (the update guard owns that crossing). docs/design/2.0-settings-and-install.md\n */\n\nexport const UPDATE_CHECK_TTL_MS = 6 * 60 * 60 * 1000\n\nexport interface UpdateCheckState {\n /** Last version a notice was surfaced for (no repeats per version). */\n lastNotifiedVersion?: string\n /** Last time the registry was queried, for the TTL. */\n lastCheckMs?: number\n}\n\nexport interface UpdateNoticeInput {\n currentVersion: string\n latestVersion: string\n state?: UpdateCheckState\n nowMs?: number\n ttlMs?: number\n}\n\nexport interface UpdateNotice {\n version: string\n message: string\n}\n\n/** Semver-ish compare for X.Y.Z[-(beta|rc).N]; prereleases sort before their release. */\nexport function comparePantheonVersions(left: string, right: string): number {\n const parse = (version: string) => {\n const match = String(version)\n .trim()\n .match(/^(\\d+)\\.(\\d+)\\.(\\d+)(?:-(beta|rc)\\.(\\d+))?$/)\n if (!match) return null\n const [, major = '', minor = '', patch = '', stage = '', stageNum = ''] = match\n const stageRank = stage === 'beta' ? 1 : stage === 'rc' ? 2 : 3\n return {\n core: [+major, +minor, +patch] as [number, number, number],\n stageRank,\n stageNum: stage !== '' ? +stageNum : Number.POSITIVE_INFINITY,\n }\n }\n const a = parse(left)\n const b = parse(right)\n if (!a || !b) return 0\n const [aMajor, aMinor, aPatch] = a.core\n const [bMajor, bMinor, bPatch] = b.core\n if (aMajor !== bMajor) return aMajor - bMajor\n if (aMinor !== bMinor) return aMinor - bMinor\n if (aPatch !== bPatch) return aPatch - bPatch\n if (a.stageRank !== b.stageRank) return a.stageRank - b.stageRank\n return a.stageNum - b.stageNum\n}\n\nexport function pickUpdateNotice(input: UpdateNoticeInput): UpdateNotice | null {\n const { currentVersion, latestVersion, state = {}, nowMs = Date.now() } = input\n const ttlMs = input.ttlMs ?? UPDATE_CHECK_TTL_MS\n\n const lastCheck = state.lastCheckMs ?? 0\n if (nowMs - lastCheck < ttlMs) return null\n if (state.lastNotifiedVersion === latestVersion) return null\n\n const stable = (version: string) => !/-(?:beta|rc)\\.\\d+$/.test(version)\n // A stable install is never advertised a beta: the update guard owns that\n // crossing and requires explicit opt-in there.\n if (stable(currentVersion) && !stable(latestVersion)) return null\n\n if (comparePantheonVersions(latestVersion, currentVersion) <= 0) return null\n\n return {\n version: latestVersion,\n message:\n `pantheon-opencode ${latestVersion} available — ` +\n 'changelog in /pantheon-settings, adopt with `pantheon-opencode update`',\n }\n}\n\n/** The state to persist after a check (notified or not) for the TTL. */\nexport function nextCheckState(\n previous: UpdateCheckState,\n notice: UpdateNotice | null,\n nowMs: number,\n): UpdateCheckState {\n const lastNotifiedVersion = notice?.version ?? previous.lastNotifiedVersion\n return {\n lastCheckMs: nowMs,\n ...(lastNotifiedVersion !== undefined ? { lastNotifiedVersion } : {}),\n }\n}\n","/**\n * doctor-state.ts — the Doctor section of the settings window (read-only).\n *\n * TUI-local replica (the bundle must stay self-contained — the installed copy\n * physically lacks the repo tree, so doctor.mjs itself is unreachable). Only\n * the FILE-DERIVABLE checks are mirrored here; everything that spawns\n * processes, reads the network, or writes (MCP smoke, python validators, git,\n * venv pins, --fix quarantines) stays in the CLI and the section says so.\n *\n * The install-state path mirrors doctor's checkInstallVersionDrift\n * (`/opencode/.pantheon/install-state.json`); the Node floor is\n * drift-pinned against scripts/node-engine-policy.mjs by\n * tests/tui-doctor-state.test.mjs.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { readDecisionRouterConfig } from './decision-router-state.ts'\nimport type { OverridesLoad } from './pantheon-settings-state.ts'\nimport {\n SETTINGS_BEHAVIORS,\n type SettingsRow,\n type SettingsTab,\n} from './pantheon-settings-state.ts'\nimport { comparePantheonVersions } from './update-notice.ts'\n\n/** Drift-pinned against scripts/node-engine-policy.mjs MIN_SUPPORTED_NODE_VERSION. */\nexport const MIN_SUPPORTED_NODE_VERSION = '26.4.0'\n\nexport function opencodePantheonDir(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'opencode', '.pantheon')\n}\n\nexport interface InstallVersionHealth {\n status: 'ok' | 'older' | 'newer' | 'unknown'\n installed: string | null\n}\n\n/**\n * H2: the installed package version (install-state) vs the running one.\n * Fail-open: a missing/unreadable state file means \"unknown\", not a failure —\n * pre-2.0 installs may not have one.\n */\nexport function classifyInstallVersion(\n runningVersion: string,\n env: Record = process.env,\n): InstallVersionHealth {\n let installed: string | null = null\n try {\n const path = join(opencodePantheonDir(env), 'install-state.json')\n const raw = JSON.parse(readFileSync(path, 'utf8')) as { pantheon_version?: unknown }\n if (typeof raw?.pantheon_version === 'string' && raw.pantheon_version !== '') {\n installed = raw.pantheon_version\n }\n } catch {\n installed = null\n }\n if (installed === null) return { status: 'unknown', installed: null }\n const compared = comparePantheonVersions(installed, runningVersion)\n if (compared === 0) return { status: 'ok', installed }\n return { status: compared < 0 ? 'older' : 'newer', installed }\n}\n\nexport function isSupportedNodeFloor(version: string): boolean {\n // Same shape as the canonical parser: a prerelease is outside the floor.\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([^+]+))?(?:\\+([\\w.-]+))?$/.exec(String(version))\n const minimum = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(MIN_SUPPORTED_NODE_VERSION)\n if (!match || !minimum) return false\n const [, major = '', minor = '', patch = '', prerelease = ''] = match\n if (prerelease !== '') return false\n const [, minMajor = '0', minMinor = '0', minPatch = '0'] = minimum\n const currentParts = [+major, +minor, +patch]\n const minimumParts = [+minMajor, +minMinor, +minPatch]\n for (let index = 0; index < 3; index += 1) {\n const currentPart = currentParts[index] ?? 0\n const minimumPart = minimumParts[index] ?? 0\n if (currentPart !== minimumPart) return currentPart > minimumPart\n }\n return true\n}\n\nexport interface OverridesHealth {\n status: 'clean' | 'unknown-ids' | 'corrupt'\n unknownIds: string[]\n}\n\n/** K: validate both overrides files against the window's registry. */\nexport function classifyOverridesHealth(load: OverridesLoad): OverridesHealth {\n if (load.corruptGlobal) return { status: 'corrupt', unknownIds: [] }\n const known = new Set(SETTINGS_BEHAVIORS.map((behavior) => behavior.id))\n const unknownIds = Object.keys({ ...load.global, ...load.project }).filter((id) => !known.has(id))\n return { status: unknownIds.length > 0 ? 'unknown-ids' : 'clean', unknownIds }\n}\n\nexport interface DecisionConfigHealth {\n status: 'ok' | 'corrupt' | 'absent'\n}\n\nexport function classifyDecisionConfigHealth(\n env: Record = process.env,\n): DecisionConfigHealth {\n if (\n !existsSync(\n join(\n env.XDG_CONFIG_HOME ?? join(env.HOME ?? '', '.config'),\n 'pantheon',\n 'decision-router.json',\n ),\n )\n ) {\n return { status: 'absent' }\n }\n return readDecisionRouterConfig(env).corrupt ? { status: 'corrupt' } : { status: 'ok' }\n}\n\nexport interface DoctorSectionInput {\n runningVersion: string\n nodeVersion: string\n load: OverridesLoad\n env?: Record\n}\n\nexport function buildDoctorTab(input: DoctorSectionInput): SettingsTab {\n const env = input.env ?? process.env\n const rows: SettingsRow[] = []\n\n const version = classifyInstallVersion(input.runningVersion, env)\n rows.push({\n id: 'doctor.version',\n name: 'Install version',\n value:\n version.status === 'ok'\n ? `v${version.installed} — matches`\n : version.status === 'older'\n ? `v${version.installed} older`\n : version.status === 'newer'\n ? `v${version.installed} newer`\n : 'unknown',\n note:\n version.status === 'older'\n ? 'refresh with `pantheon-opencode update`'\n : 'read from /opencode/.pantheon/install-state.json',\n })\n\n const nodeOk = isSupportedNodeFloor(input.nodeVersion)\n rows.push({\n id: 'doctor.node',\n name: 'Node runtime',\n value: input.nodeVersion.replace(/^v/, ''),\n note: nodeOk\n ? `meets the >= ${MIN_SUPPORTED_NODE_VERSION} floor`\n : `below the >= ${MIN_SUPPORTED_NODE_VERSION} floor — tooling may refuse`,\n })\n\n const overrides = classifyOverridesHealth(input.load)\n rows.push({\n id: 'doctor.overrides',\n name: 'Overrides',\n value:\n overrides.status === 'clean'\n ? 'valid'\n : overrides.status === 'corrupt'\n ? 'unreadable'\n : `${overrides.unknownIds.length} unknown id(s)`,\n note:\n overrides.status === 'unknown-ids'\n ? `${overrides.unknownIds.join(', ')} — harmless; repair with doctor --fix`\n : overrides.status === 'corrupt'\n ? 'writes are refused until repaired (doctor --fix)'\n : 'both files parse against the behavior registry',\n })\n\n const decision = classifyDecisionConfigHealth(env)\n rows.push({\n id: 'doctor.decision',\n name: 'Decision config',\n value:\n decision.status === 'ok' ? 'valid' : decision.status === 'corrupt' ? 'corrupt' : 'absent',\n note:\n decision.status === 'corrupt'\n ? 'runtime fail-closes to disabled · read from /pantheon/decision-router.json'\n : 'read from /pantheon/decision-router.json',\n })\n\n return {\n id: 'doctor',\n title: 'Doctor',\n groups: [\n {\n title: 'Health (file-derived)',\n rows,\n },\n {\n rows: [\n {\n id: 'doctor.cli',\n name: 'Full check',\n value: '`pantheon-opencode doctor`',\n note: 'MCP smoke, venv pins, git stay in the CLI',\n },\n ],\n },\n ],\n }\n}\n","/**\n * settings-i18n.ts — Bilingual (PT-BR / EN) internationalization for TUI settings.\n *\n * Provides localized titles, labels, and explanations for:\n * - Decision Router & Jev model selection\n * - Autonomy & Budgets\n * - Safety & J1 Risk Gate\n *\n * Automatically detects environment locale (LANG / LC_ALL) while allowing\n * manual override in TUI preferences.\n */\n\nexport type SettingsLanguage = 'auto' | 'pt-BR' | 'en'\n\nexport const SETTINGS_LANGUAGES_CYCLE: readonly string[] = Object.freeze(['auto', 'pt-BR', 'en'])\nexport const SUPPORTED_LANGUAGES = SETTINGS_LANGUAGES_CYCLE\n\n/**\n * Resolve effective language: 'pt-BR' or 'en'.\n * Defaults to 'pt-BR' if system locale contains 'pt', if Intl locale is pt,\n * or if system timezone is Brazilian/Portuguese; otherwise 'en'.\n */\nexport function resolveLanguage(\n preference: string = 'auto',\n env: Record = process.env,\n): 'pt-BR' | 'en' {\n if (preference === 'pt-BR') return 'pt-BR'\n if (preference === 'en') return 'en'\n\n // 1. Auto-detection based on environment locale variables\n const lang = (env.LC_ALL ?? env.LC_MESSAGES ?? env.LANG ?? env.LANGUAGE ?? '').toLowerCase()\n if (lang.startsWith('pt')) return 'pt-BR'\n\n // 2. Auto-detection based on Intl locale\n try {\n const intlLocale = Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()\n if (intlLocale.startsWith('pt')) return 'pt-BR'\n } catch {}\n\n // 3. Auto-detection based on timezone (Brazil & Portugal)\n try {\n const tz = (env.TZ ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? '').toLowerCase()\n if (\n tz.includes('sao_paulo') ||\n tz.includes('brazil') ||\n tz.includes('fortaleza') ||\n tz.includes('recife') ||\n tz.includes('manaus') ||\n tz.includes('belem') ||\n tz.includes('cuiaba') ||\n tz.includes('campo_grande') ||\n tz.includes('porto_velho') ||\n tz.includes('rio_branco') ||\n tz.includes('boa_vista') ||\n tz.includes('maceio') ||\n tz.includes('bahia') ||\n tz.includes('noronha') ||\n tz.includes('araguaina') ||\n tz.includes('santarem') ||\n tz.includes('lisbon') ||\n tz.includes('madeira') ||\n tz.includes('azores')\n ) {\n return 'pt-BR'\n }\n } catch {}\n\n return 'en'\n}\n\nexport interface I18nStringPair {\n en: string\n pt: string\n}\n\nexport const I18N = {\n tabs: {\n decision: { en: 'Decision (Jev)', pt: 'Decisão (Jev)' },\n autonomy: { en: 'Autonomy', pt: 'Autonomia' },\n safety: { en: 'Safety (J1)', pt: 'Segurança (J1)' },\n tui: { en: 'TUI', pt: 'TUI' },\n },\n decision: {\n groupRouter: {\n en: 'Decision Router (Jev Assistant)',\n pt: 'Assistente de Decisão (Jev)',\n },\n groupCredentials: {\n en: 'Credentials (status only — values never enter the window)',\n pt: 'Credenciais (apenas status — valores protegidos)',\n },\n routerName: {\n en: 'Router (Decision Assistant)',\n pt: 'Assistente Jev',\n },\n routerNote: {\n en: 'applies live — enables intelligent route arbitration and candidate ranking',\n pt: 'aplica em tempo real — motor de arbitragem inteligente e ranking de rotas',\n },\n modelName: {\n en: 'Decision model',\n pt: 'Modelo de Decisão',\n },\n modelNote: {\n en: 'local routes on-device (free); auto/explicit pick a remote decision model',\n pt: 'local decide no seu PC (grátis); auto/explícito usa modelo nuvem (OpenRouter)',\n },\n selectionModeName: {\n en: 'Selection mode',\n pt: 'Modo de operação',\n },\n selectionModeNote: {\n en: 'local routes on-device; auto/explicit pick a remote decision model',\n pt: 'local decide no dispositivo; auto/explícito usa modelo remoto',\n },\n egressName: {\n en: 'Cloud API access (Egress)',\n pt: 'Acesso à Nuvem (Egress)',\n },\n egressNoteGranted: {\n en: 'granted = remote decision routes may call their gateway (budget-capped)',\n pt: 'permitido = rotas remotas podem consultar a API (com limite de orçamento)',\n },\n egressNoteNotGranted: {\n en: 'not granted = remote routes blocked; local heuristic decisions only',\n pt: 'não permitido = chamadas remotas bloqueadas; apenas heurística local',\n },\n candidatesName: {\n en: 'Active candidates',\n pt: 'Candidatos ativos',\n },\n },\n autonomy: {\n groupGoalLoop: {\n en: 'Goal loop (multi-turn session auto-continuation)',\n pt: 'Execução Contínua (Goal Loop)',\n },\n goalLoopName: {\n en: 'Goal loop',\n pt: 'Loop contínuo',\n },\n goalLoopNote: {\n en: 'auto-continues multi-turn tasks when session goes idle · applies after OpenCode restart',\n pt: 'continua tarefas de múltiplos passos automaticamente · requer reinício',\n },\n maxContinuationsName: {\n en: 'Max continuations',\n pt: 'Limite de turnos',\n },\n maxContinuationsNote: {\n en: '1..200 — safety ceiling to prevent runaway tasks',\n pt: '1..200 — teto de segurança contra tarefas infinitas',\n },\n cooldownName: {\n en: 'Cooldown (ms)',\n pt: 'Intervalo (ms)',\n },\n cooldownNote: {\n en: 'delay between autonomous turns (min 1000ms)',\n pt: 'tempo de espera entre turnos autônomos (mín 1000ms)',\n },\n groupBudgets: {\n en: 'Decision budgets (applies live per gated call)',\n pt: 'Orçamento Jev (teto financeiro de proteção)',\n },\n monthlyCapName: {\n en: 'Monthly cap',\n pt: 'Teto mensal (USD)',\n },\n monthlyCapNote: {\n en: 'monthly USD ceiling for gated arbitrator decisions',\n pt: 'teto mensal em dólares para decisões do assistente Jev',\n },\n perDecisionCapName: {\n en: 'Per-decision cap',\n pt: 'Teto por consulta (USD)',\n },\n perDecisionCapNote: {\n en: 'price cap — gated decisions above this are refused',\n pt: 'teto por decisão — consultas remotas que excederem são recusadas',\n },\n groupGradient: {\n en: 'Decision gradient (reference policy · J1 owns the risk axis)',\n pt: 'Níveis de Decisão & Segurança (Referência)',\n },\n soloName: {\n en: 'Decide solo',\n pt: 'Decisão direta',\n },\n soloNote: {\n en: 'reversible & low-risk edits, routine fixes (no gate)',\n pt: 'edições reversíveis e baixo risco, sem portão de bloqueio',\n },\n jevName: {\n en: 'Jev decides',\n pt: 'Decisão Jev',\n },\n jevNote: {\n en: 'typed ambiguity & candidate ranking (budget-capped)',\n pt: 'ambiguidade e ranking de skills com teto de orçamento',\n },\n humanName: {\n en: 'Human decides',\n pt: 'Aprovação humana',\n },\n humanNote: {\n en: 'high-risk & destructive operations (J1 gate)',\n pt: 'ações de alto risco e destrutivas (portão de segurança J1)',\n },\n },\n safety: {\n groupSafety: {\n en: 'Safety & Risk Level (J1 Gate)',\n pt: 'Nível de Proteção & Portão de Risco (J1)',\n },\n modeName: {\n en: 'Protection mode',\n pt: 'Modo de proteção',\n },\n thresholdName: {\n en: 'Enforce threshold',\n pt: 'Teto para bloqueio',\n },\n thresholdNote: {\n en: 'deny at or above · 0..1 · default 0.8',\n pt: 'bloqueia em ou acima de · 0..1 · padrão 0.8',\n },\n gateName: {\n en: 'Safety gate',\n pt: 'Portão de segurança',\n },\n },\n} as const\n\n/** Helper to get localized text */\nexport function t(entry: I18nStringPair, lang: 'pt-BR' | 'en'): string {\n return lang === 'pt-BR' ? entry.pt : entry.en\n}\n","/**\n * j1-gate-status.ts — the J1 Risk Gate section of the settings window.\n *\n * TUI-local replica of the ladder in src/pantheon/jev-risk-gate.ts (the\n * bundle must stay self-contained); tests/tui-settings-j1.test.mjs pins the\n * env names, the ladder values and the default threshold against that source.\n *\n * STATUS ONLY by design: the ladder has no file surface yet — mode and\n * threshold are env-only and read once at plugin setup — so nothing here\n * writes, and the section says so. A file surface is a runtime-plugin change\n * (beta.3 candidate), not a window change.\n */\nimport type { SettingsTab } from './pantheon-settings-state.ts'\nimport { resolveLanguage } from './settings-i18n.ts'\n\nexport const J1_FLAG_ENV = 'PANTHEON_J1_RISK_SCORE'\nexport const J1_THRESHOLD_ENV = 'PANTHEON_J1_ENFORCE_THRESHOLD'\nexport const J1_THRESHOLD_DEFAULT = 0.8\n\nexport type J1Mode = 'off' | 'shadow' | 'warn' | 'enforce'\n\n/** `1`/`on`/`true` map to `shadow` for back-compatibility with the shipped setup. */\nconst FLAG_ON = new Set(['1', 'on', 'true', 'shadow'])\n\nexport function j1ModeFromEnv(env: Record = process.env): J1Mode {\n const raw = (env[J1_FLAG_ENV] ?? '').trim().toLowerCase()\n if (raw === 'enforce') return 'enforce'\n if (raw === 'warn') return 'warn'\n return FLAG_ON.has(raw) ? 'shadow' : 'off'\n}\n\n/** Invalid or out-of-range values fall back to the default — a typo must not disable the gate. */\nexport function j1ThresholdFromEnv(env: Record = process.env): number {\n const text = (env[J1_THRESHOLD_ENV] ?? '').trim()\n if (text === '') return J1_THRESHOLD_DEFAULT\n const raw = Number(text)\n if (!Number.isFinite(raw) || raw < 0 || raw > 1) return J1_THRESHOLD_DEFAULT\n return raw\n}\n\nconst MODE_DESCRIPTION_EN: Record = {\n off: 'nothing fires (hard zero)',\n shadow: 'observe + record; invisible in the session',\n warn: 'RESERVED — behaves as shadow in this release',\n enforce: 'high-risk scores DENY the tool call (fail-open on gate unavailability)',\n}\n\nconst MODE_DESCRIPTION_PT: Record = {\n off: 'desativado (hard zero)',\n shadow: 'observa + registra telemetria (modo silencioso)',\n warn: 'RESERVADO (RESERVED) — comporta-se como shadow nesta versão',\n enforce: 'alto risco bloqueia a ferramenta (fail-open se indisponível)',\n}\n\nexport function buildJ1Tab(\n env: Record,\n disabledByOverride: boolean,\n languagePref?: string | undefined,\n): SettingsTab {\n const lang = resolveLanguage(languagePref)\n const isPt = lang === 'pt-BR'\n const mode = j1ModeFromEnv(env)\n const threshold = j1ThresholdFromEnv(env)\n const gateState = disabledByOverride\n ? 'disabled via overrides'\n : mode === 'off'\n ? 'off (env unset)'\n : 'active'\n const desc = isPt ? MODE_DESCRIPTION_PT[mode] : MODE_DESCRIPTION_EN[mode]\n\n return {\n id: 'j1',\n title: isPt ? 'Segurança J1' : 'J1 Safety',\n groups: [\n {\n title: isPt ? 'Portão de Segurança (J1)' : 'Safety Risk Gate (J1)',\n rows: [\n {\n id: 'j1.mode',\n name: isPt ? 'Modo de Operação' : 'Operation Mode',\n value: mode,\n note: `${desc} · ${isPt ? 'reinício necessário (restart applies)' : 'restart applies'}`,\n },\n {\n id: 'j1.threshold',\n name: isPt ? 'Limiar de bloqueio' : 'Enforce threshold',\n value: String(threshold),\n note: isPt\n ? 'bloqueia em ou acima · 0..1 · padrão 0.8'\n : 'deny at or above · 0..1 · default 0.8',\n },\n {\n id: 'j1.gate',\n name: isPt ? 'Portão de Segurança' : 'Safety Risk Gate',\n value: gateState,\n note: `${J1_FLAG_ENV} / ${J1_THRESHOLD_ENV} · ${isPt ? 'lido na inicialização' : 'read once at startup'}`,\n },\n ],\n },\n ],\n }\n}\n","/**\n * preset-state.ts — the Model Preset section of the settings window.\n *\n * TUI-local replica (the bundle must stay self-contained). The preset NAMES\n * mirror routing.yml's `presets:` and are drift-pinned by\n * tests/tui-preset-state.test.mjs against `loadPresetDefs()`. The marker file\n * shape mirrors scripts/install/model-picker.mjs's `buildActivePresetFile`\n * (version 1), and the readers (`resolveActivePreset`, vision.ts candidates)\n * only consult `.preset`, so the window writes `source: 'tui-settings'`.\n *\n * Scope note: the window writes the GLOBAL marker only\n * (`/opencode/.pantheon/active-preset.json`). A project marker\n * wins (it precedes the global path in every runtime candidate list), so it\n * is displayed read-only. `none` DELETES the marker with a .bak backup — the\n * same contract as the CLI's `set-tier none`.\n */\nimport {\n copyFileSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\n\n/** Mirrors routing.yml `presets:` — drift-pinned against loadPresetDefs(). */\nexport const PRESET_NAMES: readonly string[] = Object.freeze([\n 'go-free',\n 'go-fast',\n 'go-premium',\n 'go-hybrid',\n 'anthropic',\n 'openai',\n])\n\nexport interface ActivePresetMarker {\n version: number\n preset: string\n source: string\n updated_at: string\n}\n\nexport function globalActivePresetPath(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'opencode', '.pantheon', 'active-preset.json')\n}\n\nexport function projectActivePresetPath() {\n return join(process.cwd(), '.pantheon', 'active-preset.json')\n}\n\n/** Fail-open read: missing/corrupt marker = no active preset. */\nexport function readActivePresetMarker(path: string): { name: string; updatedAt: string } | null {\n try {\n const raw = JSON.parse(readFileSync(path, 'utf8')) as { preset?: unknown; updated_at?: unknown }\n if (typeof raw?.preset !== 'string' || raw.preset === '' || raw.preset === 'none') return null\n return {\n name: raw.preset,\n updatedAt: typeof raw.updated_at === 'string' ? raw.updated_at : '',\n }\n } catch {\n return null\n }\n}\n\nfunction writeMarkerAtomically(path: string, content: string): void {\n mkdirSync(dirname(path), { recursive: true })\n const temp = `${path}.tui.tmp`\n writeFileSync(temp, content)\n renameSync(temp, path)\n}\n\n/** Select a preset globally: .bak backup, atomic write, version-1 marker. */\nexport function writeActivePreset(\n path: string,\n name: string,\n nowIso = new Date().toISOString(),\n): void {\n if (!PRESET_NAMES.includes(name)) {\n throw new TypeError(`Refusing to persist unknown preset \"${name}\"`)\n }\n backupMarker(path)\n const marker: ActivePresetMarker = {\n version: 1,\n preset: name,\n source: 'tui-settings',\n updated_at: nowIso,\n }\n writeMarkerAtomically(path, `${JSON.stringify(marker, null, 2)}\\n`)\n}\n\n/** Clear the global marker (the `none` contract): .bak backup, then remove. */\nexport function clearActivePreset(path: string): void {\n backupMarker(path)\n rmSync(path, { force: true })\n}\n\nfunction backupMarker(path: string): void {\n if (!existsSync(path)) return\n mkdirSync(dirname(path), { recursive: true })\n copyFileSync(path, `${path}.bak`)\n}\n\nexport const VISION_MODEL_OPTIONS: readonly string[] = Object.freeze([\n 'auto',\n 'opencode-go/mimo-v2.6-flash',\n 'google/gemini-2.5-flash',\n 'openai/gpt-5-mini',\n 'anthropic/claude-3-5-haiku',\n 'opencode-go/mimo-v2.5',\n])\n\nexport function visionConfigPaths(\n cwd = process.cwd(),\n env: Record = process.env,\n): string[] {\n const home = env.HOME ?? ''\n const xdg = env.XDG_CONFIG_HOME ?? join(home, '.config')\n return [\n join(cwd, '.opencode', 'opencode-vision.json'),\n join(xdg, 'opencode', 'opencode-vision.json'),\n ]\n}\n\nexport function readConfiguredVisionModel(\n cwd = process.cwd(),\n env: Record = process.env,\n): string {\n for (const path of visionConfigPaths(cwd, env)) {\n try {\n if (existsSync(path)) {\n const parsed = JSON.parse(readFileSync(path, 'utf8')) as { visionModel?: unknown }\n if (typeof parsed?.visionModel === 'string' && parsed.visionModel.trim()) {\n return parsed.visionModel.trim()\n }\n }\n } catch {\n // ignore corrupt/missing\n }\n }\n return 'auto'\n}\n\nexport function writeConfiguredVisionModel(\n model: string,\n cwd = process.cwd(),\n env: Record = process.env,\n): void {\n const home = env.HOME ?? ''\n const xdg = env.XDG_CONFIG_HOME ?? join(home, '.config')\n const projectDir = join(cwd, '.opencode')\n const targetPath = existsSync(projectDir)\n ? join(projectDir, 'opencode-vision.json')\n : join(xdg, 'opencode', 'opencode-vision.json')\n\n let current: Record = {}\n try {\n if (existsSync(targetPath)) {\n current = JSON.parse(readFileSync(targetPath, 'utf8')) as Record\n }\n } catch {\n current = {}\n }\n\n if (model === 'auto' || !model.trim()) {\n delete current.visionModel\n } else {\n current.visionModel = model.trim()\n }\n\n mkdirSync(dirname(targetPath), { recursive: true })\n const temp = `${targetPath}.tui.tmp`\n writeFileSync(temp, `${JSON.stringify(current, null, 2)}\\n`, 'utf8')\n renameSync(temp, targetPath)\n}\n\nexport interface PresetSectionInput {\n globalName: string | null\n projectName: string | null\n visionModel?: string\n}\n\n/** The staged value 'none' means: delete the global marker (the CLI contract). */\nexport const PRESET_NONE = 'none'\n\nexport const PRESET_CYCLE: readonly string[] = Object.freeze([PRESET_NONE, ...PRESET_NAMES])\n\nexport function buildPresetTab(input: PresetSectionInput, languagePref?: string): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const rows: SettingsRow[] = [\n {\n id: 'preset',\n name: isPt ? 'Predefinição' : 'Preset',\n value: input.globalName ?? PRESET_NONE,\n cycle: PRESET_CYCLE,\n note: isPt\n ? 'marcador global · gravação atômica, backup .bak · none = padrão OpenCode'\n : 'global marker · atomic write, .bak backup · none = opencode defaults',\n },\n ]\n if (input.projectName !== null) {\n rows.push({\n id: 'preset.project',\n name: isPt ? 'Projeto' : 'Project',\n value: input.projectName,\n note: isPt\n ? `${projectActivePresetPath()} tem precedência sobre o global — somente leitura aqui`\n : `${projectActivePresetPath()} wins over the global marker — read-only here`,\n })\n }\n if (input.visionModel !== undefined) {\n rows.push({\n id: 'preset.vision_model',\n name: isPt ? 'Modelo de Visão' : 'Vision Model',\n value: input.visionModel || 'auto',\n cycle: VISION_MODEL_OPTIONS,\n note: isPt\n ? 'modelo para inspeção de imagens (vision_describe) · salvo em opencode-vision.json'\n : 'model for image inspection (vision_describe) · saved in opencode-vision.json',\n })\n }\n return {\n id: 'preset',\n title: 'Preset',\n groups: [{ title: isPt ? 'Predefinição de modelo' : 'Model preset', rows }],\n }\n}\n","// biome-ignore-all lint/suspicious/noExplicitAny: stored prefs are host JSON of a known shape.\n/**\n * tui-prefs.ts — the TUI personalization core (the settings window's TUI tab).\n *\n * TUI-local copy doctrine (same as cost-data.ts): the bundle must stay\n * self-contained. Persistence is the HOST's durable plugin storage\n * (`context.storage.store('tui-prefs', { initial })` — reactive solid store,\n * live-synced across TUI instances); this module owns the SHAPE and the pure\n * operations, never the store handle.\n *\n * v1 surfaces: sidebar fixed headers, sidebar blocks, the Context block's\n * sub-lines and gauge style, and the two Pantheon footer lines. Everything\n * defaults to on — the window exists to turn things OFF.\n */\n\nimport type { Context } from '@opencode/plugin/tui/context'\nimport type { Accessor, Setter } from 'solid-js'\nimport { createSignal } from 'solid-js'\nimport type { SettingsDraft, SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\nimport { resolveLanguage } from './settings-i18n.ts'\n\n// ── The durable store handle (host storage, one per plugin) ────────────\n// Created once at setup and stashed under a globalThis symbol so\n// hot-reload generations keep sharing the same live store (the same\n// singleton doctrine as the plugin's SINGLETON guard).\n\nconst PREFS_SYMBOL = Symbol.for('pantheon.tui.prefs.v1')\nconst DRAFT_PREVIEW_SYMBOL = Symbol.for('pantheon.tui.draft_preview.v1')\ntype PrefsStore = readonly [TuiPrefs, (mutation: (draft: TuiPrefs) => void) => Promise]\ntype DraftSignal = [Accessor, Setter]\n\nfunction stash(): PrefsStore | undefined {\n return (globalThis as Record)[PREFS_SYMBOL] as PrefsStore | undefined\n}\n\nfunction getDraftPreviewSignal(): DraftSignal {\n const g = globalThis as Record\n if (!g[DRAFT_PREVIEW_SYMBOL]) {\n g[DRAFT_PREVIEW_SYMBOL] = createSignal(undefined)\n }\n return g[DRAFT_PREVIEW_SYMBOL] as DraftSignal\n}\n\n/** Set the active draft preview overlay (used by settings window to provide live preview). */\nexport function setTuiDraftPreview(draft: SettingsDraft | undefined): void {\n const [, setDraft] = getDraftPreviewSignal()\n setDraft(draft && Object.keys(draft).length > 0 ? { ...draft } : undefined)\n}\n\n/** Clear the active draft preview overlay. */\nexport function clearTuiDraftPreview(): void {\n const [, setDraft] = getDraftPreviewSignal()\n setDraft(undefined)\n}\n\n/** The active draft preview accessor. */\nexport function tuiDraftPreview(): SettingsDraft | undefined {\n const [draft] = getDraftPreviewSignal()\n return draft()\n}\n\n/** Create (or reuse) the durable prefs store. Fail-open: without host\n * storage the consumers fall back to DEFAULT_TUI_PREFS (read-only). */\nexport function initTuiPrefs(context: Context): void {\n if (stash() !== undefined) return\n try {\n const handle = context.storage?.store?.('tui-prefs', { initial: DEFAULT_TUI_PREFS }) as\n | PrefsStore\n | undefined\n if (handle !== undefined) {\n ;(globalThis as unknown as Record)[PREFS_SYMBOL] = handle\n // Self-heal: if store was persisted before layout existed, backfill missing top-level defaults\n if (!handle[0]?.layout) {\n handle[1]((draft: any) => {\n if (!draft.layout) {\n draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n }\n }).catch(() => {})\n }\n }\n } catch {\n /* no host storage — defaults stay read-only */\n }\n}\n\n/** Deep clone and overlay staged settings draft onto base TuiPrefs. */\nexport function previewTuiPrefs(base: TuiPrefs, draft?: SettingsDraft): TuiPrefs {\n if (!draft || Object.keys(draft).length === 0) return base\n let hasTui = false\n for (const k of Object.keys(draft)) {\n if (k.startsWith('tui.')) {\n hasTui = true\n break\n }\n }\n if (!hasTui) return base\n\n const normalized = normalizeTuiPrefs(base)\n const effective: TuiPrefs = {\n version: 1,\n layout: { ...normalized.layout },\n sidebar: {\n header: { ...normalized.sidebar.header },\n blocks: { ...normalized.sidebar.blocks },\n context: { ...normalized.sidebar.context },\n },\n footer: { ...normalized.footer },\n }\n\n for (const [id, value] of Object.entries(draft)) {\n if (id.startsWith('tui.')) {\n applyTuiRow(effective, id, value)\n }\n }\n return effective\n}\n\n/** The raw persisted prefs from host storage (no draft overlay). */\nexport function savedTuiPrefs(): TuiPrefs {\n const s = stash()?.[0]\n if (!s) return DEFAULT_TUI_PREFS\n if (!s.layout) {\n return {\n ...s,\n layout: DEFAULT_TUI_PREFS.layout,\n }\n }\n return s\n}\n\n/** The live reactive prefs (read properties inside memos/JSX — tracked).\n * When a settings window has an active draft, preview overlays on top\n * of durable storage in real time. */\nexport function tuiPrefs(): TuiPrefs {\n const base = savedTuiPrefs()\n const preview = tuiDraftPreview()\n if (!preview) return base\n return previewTuiPrefs(base, preview)\n}\n\n/** Stage a mutation against the durable store; resolves when persisted. */\nexport function mutateTuiPrefs(mutation: (draft: TuiPrefs) => void): Promise {\n const handle = stash()\n if (handle === undefined) return Promise.resolve()\n return handle[1](mutation)\n}\n\nexport const GAUGE_STYLES: readonly string[] = Object.freeze(['both', 'bar', 'percent', 'off'])\nexport const ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const BAR_SHAPES_CYCLE: readonly string[] = Object.freeze([\n 'line',\n 'block',\n 'smooth',\n 'ascii',\n 'dots',\n 'braille',\n])\nexport const BAR_WIDTHS_CYCLE: readonly string[] = Object.freeze([\n 'standard',\n 'compact',\n 'wide',\n 'full',\n])\nexport const LAYOUT_PRESETS_CYCLE: readonly string[] = Object.freeze(['comfortable', 'compact'])\nexport const SEPARATOR_STYLES_CYCLE: readonly string[] = Object.freeze([\n 'spaces',\n 'pipes',\n 'dots',\n 'slashes',\n])\nexport const SETTINGS_VIEW_MODES: readonly string[] = Object.freeze([\n 'docked',\n 'fullscreen',\n 'dialog',\n])\n\nexport type GaugeStyle = 'both' | 'bar' | 'percent' | 'off'\nexport type BarShapePref = 'line' | 'block' | 'smooth' | 'ascii' | 'dots' | 'braille'\nexport type BarWidthPref = 'standard' | 'compact' | 'wide' | 'full'\nexport type LayoutPresetPref = 'comfortable' | 'compact'\nexport type SeparatorStylePref = 'spaces' | 'pipes' | 'dots' | 'slashes'\nexport type SettingsViewModePref = 'docked' | 'fullscreen' | 'dialog'\nexport type LanguagePref = 'auto' | 'pt-BR' | 'en'\n\nexport const LANGUAGE_CYCLE: readonly string[] = Object.freeze(['auto', 'pt-BR', 'en'])\n\nexport interface TuiPrefs {\n version: 1\n layout: {\n preset: LayoutPresetPref\n separator: SeparatorStylePref\n settingsView?: SettingsViewModePref\n language?: LanguagePref\n }\n sidebar: {\n header: { version: boolean; preset: boolean; session: boolean }\n blocks: { context: boolean; git: boolean; todo: boolean; dispatch: boolean }\n context: {\n gauge: GaugeStyle\n barShape: BarShapePref\n barWidth: BarWidthPref\n evenMark: boolean\n tokens: boolean\n spent: boolean\n modelUsage: boolean\n performance: boolean\n localSpend: boolean\n }\n }\n footer: { prompt: boolean; home: boolean }\n}\n\nexport const DEFAULT_TUI_PREFS: TuiPrefs = {\n version: 1,\n layout: {\n preset: 'comfortable',\n separator: 'spaces',\n settingsView: 'fullscreen',\n language: 'auto',\n },\n sidebar: {\n header: { version: true, preset: true, session: true },\n blocks: { context: true, git: true, todo: true, dispatch: true },\n context: {\n gauge: 'both',\n barShape: 'line',\n barWidth: 'standard',\n evenMark: false,\n tokens: true,\n spent: true,\n modelUsage: true,\n performance: true,\n localSpend: true,\n },\n },\n footer: { prompt: true, home: true },\n}\n\nfunction asBool(value: unknown, fallback: boolean): boolean {\n return typeof value === 'boolean' ? value : fallback\n}\n\n/** Deep-merge stored JSON over the defaults; unknown keys and junk are ignored. */\nexport function normalizeTuiPrefs(raw: unknown): TuiPrefs {\n const stored = (typeof raw === 'object' && raw !== null ? raw : {}) as Record\n const layout = (\n typeof stored.layout === 'object' && stored.layout !== null ? stored.layout : {}\n ) as Record\n const sidebar = (\n typeof stored.sidebar === 'object' && stored.sidebar !== null ? stored.sidebar : {}\n ) as Record\n const header = (\n typeof sidebar.header === 'object' && sidebar.header !== null ? sidebar.header : {}\n ) as Record\n const blocks = (\n typeof sidebar.blocks === 'object' && sidebar.blocks !== null ? sidebar.blocks : {}\n ) as Record\n const context = (\n typeof sidebar.context === 'object' && sidebar.context !== null ? sidebar.context : {}\n ) as Record\n const footer = (\n typeof stored.footer === 'object' && stored.footer !== null ? stored.footer : {}\n ) as Record\n const preset = LAYOUT_PRESETS_CYCLE.includes(layout.preset as string)\n ? (layout.preset as LayoutPresetPref)\n : DEFAULT_TUI_PREFS.layout.preset\n const separator = SEPARATOR_STYLES_CYCLE.includes(layout.separator as string)\n ? (layout.separator as SeparatorStylePref)\n : DEFAULT_TUI_PREFS.layout.separator\n const settingsView = (\n SETTINGS_VIEW_MODES.includes(layout.settingsView as string)\n ? layout.settingsView\n : DEFAULT_TUI_PREFS.layout.settingsView\n ) as SettingsViewModePref\n const language = (\n LANGUAGE_CYCLE.includes(layout.language as string)\n ? layout.language\n : DEFAULT_TUI_PREFS.layout.language\n ) as LanguagePref\n const gauge = GAUGE_STYLES.includes(context.gauge as string)\n ? (context.gauge as GaugeStyle)\n : DEFAULT_TUI_PREFS.sidebar.context.gauge\n const barShape = BAR_SHAPES_CYCLE.includes(context.barShape as string)\n ? (context.barShape as BarShapePref)\n : DEFAULT_TUI_PREFS.sidebar.context.barShape\n const barWidth = BAR_WIDTHS_CYCLE.includes(context.barWidth as string)\n ? (context.barWidth as BarWidthPref)\n : DEFAULT_TUI_PREFS.sidebar.context.barWidth\n const evenMark = asBool(context.evenMark, DEFAULT_TUI_PREFS.sidebar.context.evenMark)\n\n return {\n version: 1,\n layout: {\n preset,\n separator,\n settingsView,\n language,\n },\n sidebar: {\n header: {\n version: asBool(header.version, true),\n preset: asBool(header.preset, true),\n session: asBool(header.session, true),\n },\n blocks: {\n context: asBool(blocks.context, true),\n git: asBool(blocks.git, true),\n todo: asBool(blocks.todo, true),\n dispatch: asBool(blocks.dispatch, true),\n },\n context: {\n gauge,\n barShape,\n barWidth,\n evenMark,\n tokens: asBool(context.tokens, true),\n spent: asBool(context.spent, true),\n modelUsage: asBool(context.modelUsage, true),\n performance: asBool(context.performance, true),\n localSpend: asBool(context.localSpend, true),\n },\n },\n footer: {\n prompt: asBool(footer.prompt, true),\n home: asBool(footer.home, true),\n },\n }\n}\n\n// ── The TUI tab (cycler rows over the dotted pref paths) ───────────────\n\nconst onOff = ENABLED_CYCLE\nconst row = (id: string, name: string, value: boolean, note: string): SettingsRow => ({\n id,\n name,\n value: value ? 'enabled' : 'disabled',\n cycle: onOff,\n note,\n})\n\nexport function buildTuiTab(prefs: TuiPrefs, languagePref?: string): SettingsTab {\n const isPt = resolveLanguage(languagePref ?? prefs.layout?.language) === 'pt-BR'\n return {\n id: 'tui',\n title: 'TUI',\n groups: [\n {\n title: isPt ? 'Predefinição & Layout' : 'Preset & Layout',\n rows: [\n {\n id: 'tui.layout.preset',\n name: isPt ? 'Predefinição de layout' : 'Layout preset',\n value: prefs.layout?.preset ?? DEFAULT_TUI_PREFS.layout.preset,\n cycle: LAYOUT_PRESETS_CYCLE,\n note: isPt\n ? 'comfortable | compact — define espaçamento e bordas'\n : 'comfortable | compact — sets spacing & borders',\n },\n {\n id: 'tui.layout.separator',\n name: isPt ? 'Separador' : 'Separator',\n value: prefs.layout?.separator ?? DEFAULT_TUI_PREFS.layout.separator,\n cycle: SEPARATOR_STYLES_CYCLE,\n note: isPt\n ? 'spaces | pipes | dots | slashes — glifos na linha de status'\n : 'spaces | pipes | dots | slashes — status line glyphs',\n },\n {\n id: 'tui.layout.settingsView',\n name: isPt ? 'Superfície de configurações' : 'Settings surface',\n value: tuiRowValue(prefs, 'tui.layout.settingsView') ?? 'docked',\n cycle: SETTINGS_VIEW_MODES,\n note: isPt\n ? 'docked (acima do prompt) | fullscreen | dialog'\n : 'docked (above prompt) | fullscreen router page | dialog overlay',\n },\n {\n id: 'tui.layout.language',\n name: isPt ? 'Idioma / Language' : 'Language / Idioma',\n value: tuiRowValue(prefs, 'tui.layout.language') ?? 'auto',\n cycle: LANGUAGE_CYCLE,\n note: isPt\n ? 'auto (detecta via fuso/locale) | pt-BR (Português) | en (English)'\n : 'auto (detect via timezone/locale) | pt-BR (Português) | en (English)',\n },\n ],\n },\n {\n title: isPt ? 'Barras & Medidores' : 'Bars & Gauges',\n rows: [\n {\n id: 'tui.sidebar.context.barShape',\n name: isPt ? 'Formato da barra' : 'Bar shape',\n value: prefs.sidebar.context.barShape,\n cycle: BAR_SHAPES_CYCLE,\n note: 'line (━─) | block (▰▱) | smooth (█░) | ascii (=) | dots (●○) | braille',\n },\n {\n id: 'tui.sidebar.context.barWidth',\n name: isPt ? 'Largura da barra' : 'Bar width',\n value: prefs.sidebar.context.barWidth,\n cycle: BAR_WIDTHS_CYCLE,\n note: isPt\n ? 'standard (12) | compact (8) | wide (16) | full (20 células)'\n : 'standard (12) | compact (8) | wide (16) | full (20 cells)',\n },\n row(\n 'tui.sidebar.context.evenMark',\n isPt ? 'Marca central (50%)' : 'Even-use mark',\n prefs.sidebar.context.evenMark,\n isPt\n ? '| indicador aos 50% nas barras de medição'\n : '| indicator at 50% midpoint in gauge bars',\n ),\n {\n id: 'tui.sidebar.context.gauge',\n name: isPt ? 'Estilo do medidor' : 'Gauge style',\n value: prefs.sidebar.context.gauge,\n cycle: GAUGE_STYLES,\n note: 'both | bar | percent | off — `▰▱ 42% of 200k`',\n },\n ],\n },\n {\n title: isPt ? 'Cabeçalho da barra lateral' : 'Sidebar header',\n rows: [\n row(\n 'tui.sidebar.header.version',\n isPt ? 'Linha de versão' : 'Version line',\n prefs.sidebar.header.version,\n isPt ? 'linha `Pantheon v…`' : 'the `Pantheon v…` line',\n ),\n row(\n 'tui.sidebar.header.preset',\n isPt ? 'Linha de preset' : 'Preset line',\n prefs.sidebar.header.preset,\n isPt ? 'linha `▸ preset · provider`' : 'the `▸ preset · provider` line',\n ),\n row(\n 'tui.sidebar.header.session',\n isPt ? 'Linha de sessão' : 'Session line',\n prefs.sidebar.header.session,\n isPt ? 'título da sessão ativa' : 'the active session title',\n ),\n ],\n },\n {\n title: isPt ? 'Blocos da barra lateral' : 'Sidebar blocks',\n rows: [\n row(\n 'tui.sidebar.block.context',\n isPt ? 'Bloco de contexto' : 'Context block',\n prefs.sidebar.blocks.context,\n isPt ? 'tokens, medidor, custo, uso de modelos' : 'tokens, gauge, spend, model usage',\n ),\n row(\n 'tui.sidebar.block.git',\n isPt ? 'Bloco do Git' : 'Git block',\n prefs.sidebar.blocks.git,\n isPt ? 'branch + contagem de alterações' : 'branch + working-tree counts',\n ),\n row(\n 'tui.sidebar.block.todo',\n isPt ? 'Bloco Todo' : 'Todo block',\n prefs.sidebar.blocks.todo,\n isPt ? 'tarefas pendentes mais recentes' : 'the newest todowrite',\n ),\n row(\n 'tui.sidebar.block.dispatch',\n isPt ? 'Bloco Dispatch' : 'Dispatch block',\n prefs.sidebar.blocks.dispatch,\n isPt ? 'delegações em tempo real' : 'live delegations + rollup',\n ),\n ],\n },\n {\n title: isPt ? 'Detalhe do bloco de contexto' : 'Context block detail',\n rows: [\n row(\n 'tui.sidebar.context.tokens',\n isPt ? 'Linha de tokens' : 'Tokens row',\n prefs.sidebar.context.tokens,\n isPt ? 'contagem bruta de tokens' : 'the raw token count line',\n ),\n row(\n 'tui.sidebar.context.spent',\n isPt ? 'Linha de custo' : 'Spent row',\n prefs.sidebar.context.spent,\n isPt ? 'linha `$… gastos na sessão`' : 'the `$… spent in session` line',\n ),\n row(\n 'tui.sidebar.context.modelUsage',\n isPt ? 'Tabela de uso de modelos' : 'Model usage table',\n prefs.sidebar.context.modelUsage,\n isPt ? 'resumo de chamadas por modelo' : 'per-model tokens/USD',\n ),\n row(\n 'tui.sidebar.context.performance',\n isPt ? 'Linha de desempenho' : 'Performance row',\n prefs.sidebar.context.performance,\n isPt ? 'tokens/segundo e latência' : 'cache % + tok/s',\n ),\n row(\n 'tui.sidebar.context.localSpend',\n isPt ? 'Linha de custo local' : 'Local spend row',\n prefs.sidebar.context.localSpend,\n isPt ? 'totais de hoje / 30 dias' : 'hoje / 30d totals',\n ),\n ],\n },\n {\n title: isPt ? 'Rodapés' : 'Footers',\n rows: [\n row(\n 'tui.footer.prompt',\n isPt ? 'Prompt inferior' : 'Prompt footer',\n prefs.footer.prompt,\n isPt\n ? 'linha `▸preset · ✦n ativos` durante delegações'\n : 'the `▸preset · ✦n ativos` line while delegations run',\n ),\n row(\n 'tui.footer.home',\n isPt ? 'Status inicial' : 'Home status',\n prefs.footer.home,\n isPt\n ? 'linha `Pantheon v…` sob o prompt inicial'\n : 'the `Pantheon v…` line under the home prompt',\n ),\n ],\n },\n ],\n }\n}\n\n/**\n * Apply one staged row INTO a prefs draft (in place — the storage mutate\n * callback hands an immer-style draft). Unknown ids or junk values are no-ops.\n */\nexport function applyTuiRow(draft: TuiPrefs, id: string, value: string): void {\n const enabled = value === 'enabled'\n switch (id) {\n case 'tui.layout.preset':\n if (LAYOUT_PRESETS_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.preset = value as LayoutPresetPref\n }\n return\n case 'tui.layout.separator':\n if (SEPARATOR_STYLES_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.separator = value as SeparatorStylePref\n }\n return\n case 'tui.layout.settingsView':\n if (SETTINGS_VIEW_MODES.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.settingsView = value as SettingsViewModePref\n }\n return\n case 'tui.layout.language':\n if (LANGUAGE_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.language = value as LanguagePref\n }\n return\n case 'tui.sidebar.context.barShape':\n if (BAR_SHAPES_CYCLE.includes(value)) draft.sidebar.context.barShape = value as BarShapePref\n return\n case 'tui.sidebar.context.barWidth':\n if (BAR_WIDTHS_CYCLE.includes(value)) draft.sidebar.context.barWidth = value as BarWidthPref\n return\n case 'tui.sidebar.context.evenMark':\n draft.sidebar.context.evenMark = enabled\n return\n case 'tui.sidebar.header.version':\n draft.sidebar.header.version = enabled\n return\n case 'tui.sidebar.header.preset':\n draft.sidebar.header.preset = enabled\n return\n case 'tui.sidebar.header.session':\n draft.sidebar.header.session = enabled\n return\n case 'tui.sidebar.block.context':\n draft.sidebar.blocks.context = enabled\n return\n case 'tui.sidebar.block.git':\n draft.sidebar.blocks.git = enabled\n return\n case 'tui.sidebar.block.todo':\n draft.sidebar.blocks.todo = enabled\n return\n case 'tui.sidebar.block.dispatch':\n draft.sidebar.blocks.dispatch = enabled\n return\n case 'tui.sidebar.context.gauge':\n if (GAUGE_STYLES.includes(value)) draft.sidebar.context.gauge = value as GaugeStyle\n return\n case 'tui.sidebar.context.tokens':\n draft.sidebar.context.tokens = enabled\n return\n case 'tui.sidebar.context.spent':\n draft.sidebar.context.spent = enabled\n return\n case 'tui.sidebar.context.modelUsage':\n draft.sidebar.context.modelUsage = enabled\n return\n case 'tui.sidebar.context.performance':\n draft.sidebar.context.performance = enabled\n return\n case 'tui.sidebar.context.localSpend':\n draft.sidebar.context.localSpend = enabled\n return\n case 'tui.footer.prompt':\n draft.footer.prompt = enabled\n return\n case 'tui.footer.home':\n draft.footer.home = enabled\n return\n default:\n return\n }\n}\n\n/** Read the current pref value for a row id ('enabled'/'disabled'/gauge/custom). */\nexport function tuiRowValue(prefs: TuiPrefs, id: string): string | undefined {\n if (id === 'tui.layout.preset') return prefs.layout?.preset ?? DEFAULT_TUI_PREFS.layout.preset\n if (id === 'tui.layout.separator')\n return prefs.layout?.separator ?? DEFAULT_TUI_PREFS.layout.separator\n if (id === 'tui.layout.settingsView')\n return prefs.layout?.settingsView ?? DEFAULT_TUI_PREFS.layout.settingsView ?? 'docked'\n if (id === 'tui.layout.language') return prefs.layout?.language ?? 'auto'\n if (id === 'tui.sidebar.context.barShape') return prefs.sidebar.context.barShape\n if (id === 'tui.sidebar.context.barWidth') return prefs.sidebar.context.barWidth\n if (id === 'tui.sidebar.context.gauge') return prefs.sidebar.context.gauge\n if (id === 'tui.sidebar.context.evenMark')\n return prefs.sidebar.context.evenMark ? 'enabled' : 'disabled'\n const enabled = (() => {\n switch (id) {\n case 'tui.sidebar.header.version':\n return prefs.sidebar.header.version\n case 'tui.sidebar.header.preset':\n return prefs.sidebar.header.preset\n case 'tui.sidebar.header.session':\n return prefs.sidebar.header.session\n case 'tui.sidebar.block.context':\n return prefs.sidebar.blocks.context\n case 'tui.sidebar.block.git':\n return prefs.sidebar.blocks.git\n case 'tui.sidebar.block.todo':\n return prefs.sidebar.blocks.todo\n case 'tui.sidebar.block.dispatch':\n return prefs.sidebar.blocks.dispatch\n case 'tui.sidebar.context.tokens':\n return prefs.sidebar.context.tokens\n case 'tui.sidebar.context.spent':\n return prefs.sidebar.context.spent\n case 'tui.sidebar.context.modelUsage':\n return prefs.sidebar.context.modelUsage\n case 'tui.sidebar.context.performance':\n return prefs.sidebar.context.performance\n case 'tui.sidebar.context.localSpend':\n return prefs.sidebar.context.localSpend\n case 'tui.footer.prompt':\n return prefs.footer.prompt\n case 'tui.footer.home':\n return prefs.footer.home\n default:\n return undefined\n }\n })()\n return enabled === undefined ? undefined : enabled ? 'enabled' : 'disabled'\n}\n","/**\n * update-status.ts — the Updates section of the settings window.\n *\n * TUI-local; derives rows from the update-notice.ts primitives. The registry\n * fetch and state persistence stay in the .tsx glue (host side) — this module\n * only classifies the channel and builds rows from injected state, so the\n * whole thing is testable without network.\n */\n\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\nimport { comparePantheonVersions, type UpdateCheckState } from './update-notice.ts'\n\nexport type UpdateChannel = 'stable' | 'beta'\n\n/** The running version's channel: a `-beta.N` suffix rides the beta dist-tag. */\nexport function updateChannelFor(version: string): UpdateChannel {\n return /-beta\\.\\d+$/.test(version) ? 'beta' : 'stable'\n}\n\n/** The npm dist-tag the registry check should query for the channel. */\nexport function registryTagForChannel(channel: UpdateChannel): string {\n return channel === 'beta' ? 'beta' : 'latest'\n}\n\nexport function registryUrlForChannel(channel: UpdateChannel): string {\n return `https://registry.npmjs.org/pantheon-opencode/${registryTagForChannel(channel)}`\n}\n\nfunction formatAgo(ms: number, isPt = false): string {\n if (ms < 60_000) return isPt ? 'agora mesmo' : 'just now'\n if (ms < 3_600_000)\n return isPt ? `há ${Math.floor(ms / 60_000)}m` : `${Math.floor(ms / 60_000)}m ago`\n if (ms < 86_400_000)\n return isPt ? `há ${Math.floor(ms / 3_600_000)}h` : `${Math.floor(ms / 3_600_000)}h ago`\n return isPt ? `há ${Math.floor(ms / 86_400_000)}d` : `${Math.floor(ms / 86_400_000)}d ago`\n}\n\nexport interface UpdatesSectionInput {\n currentVersion: string\n state: UpdateCheckState\n /** Selected channel (defaults to updateChannelFor(currentVersion)). */\n selectedChannel?: UpdateChannel\n /** Latest version seen this session (a check-now inside this window). */\n lastCheckedVersion?: string\n /** A check-now is in flight (this window). */\n checking?: boolean\n /** An update run is in flight (this window). */\n updating?: boolean\n nowMs?: number\n languagePref?: string\n}\n\nexport function buildUpdatesTab(input: UpdatesSectionInput): SettingsTab {\n const isPt = input.languagePref === 'pt-BR'\n const nowMs = input.nowMs ?? Date.now()\n const channel = input.selectedChannel ?? updateChannelFor(input.currentVersion)\n const lastCheckMs = input.state.lastCheckMs\n const latest = input.lastCheckedVersion ?? input.state.lastNotifiedVersion\n\n const stable = (version: string) => !/-beta\\.\\d+$/.test(version)\n const newer =\n latest !== undefined &&\n comparePantheonVersions(latest, input.currentVersion) > 0 &&\n !(stable(input.currentVersion) && !stable(latest))\n\n const rows: SettingsRow[] = [\n {\n id: 'update.channel',\n name: isPt ? 'Canal' : 'Channel',\n value: channel,\n cycle: ['stable', 'beta'] as const,\n note: isPt\n ? 'stable segue npm `latest`; beta segue npm `beta`'\n : 'stable tracks npm `latest`; beta tracks npm `beta`',\n },\n {\n id: 'update.check',\n name: isPt ? 'Verificar agora' : 'Check now',\n value: input.checking\n ? isPt\n ? 'verificando…'\n : 'checking…'\n : lastCheckMs\n ? isPt\n ? `última verificação ${formatAgo(nowMs - lastCheckMs, true)}`\n : `last check ${formatAgo(nowMs - lastCheckMs, false)}`\n : isPt\n ? 'nunca verificado'\n : 'never checked',\n action: 'update-check',\n note: isPt\n ? 'enter consulta o registro npm para o canal ativo'\n : 'enter probes the registry for the running channel',\n },\n ]\n\n if (latest) {\n rows.push({\n id: 'update.latest',\n name: isPt ? 'Registro (npm)' : 'Registry',\n value: newer\n ? `v${latest} ${isPt ? 'disponível' : 'available'}`\n : isPt\n ? 'atualizado'\n : 'up to date',\n note: newer\n ? isPt\n ? 'instale com `pantheon-opencode update`'\n : 'adopt with `pantheon-opencode update`'\n : isPt\n ? 'nenhuma versão mais recente compatível'\n : 'no newer compatible version',\n })\n rows.push({\n id: 'update.run',\n name: isPt ? 'Atualizar agora' : 'Update now',\n value: input.updating\n ? isPt\n ? 'atualizando…'\n : 'updating…'\n : newer\n ? `${isPt ? 'instalar' : 'install'} v${latest}`\n : isPt\n ? 'reinstalar / atualizar'\n : 'reinstall / refresh',\n action: 'update-run',\n note: newer\n ? isPt\n ? 'enter executa `pantheon-opencode update`'\n : 'enter runs `pantheon-opencode update`'\n : isPt\n ? 'enter atualiza a cópia instalada'\n : 'enter refreshes installed copy',\n })\n }\n\n rows.push({\n id: 'update.command',\n name: isPt ? 'Comando CLI' : 'CLI command',\n value: channel === 'beta' ? 'pantheon-opencode update' : 'pantheon-opencode update --stable',\n note: isPt\n ? 'execute no terminal ou no terminal integrado do OpenCode'\n : 'run in terminal or OpenCode Desktop terminal',\n })\n\n return {\n id: 'updates',\n title: isPt ? 'Atualizações' : 'Updates',\n groups: [{ title: isPt ? 'Atualizações & Manutenção' : 'Updates & Maintenance', rows }],\n }\n}\n","/**\n * whats-new-highlights.ts — release highlights for the one-time \"What's new\"\n * window, extracted from the CHANGELOG.md shipped with the plugin copy.\n *\n * The section-finding logic is an inline replica of scripts/changelog-extract.mjs\n * `extractSection` (pinned by a parity test in tests/tui-whats-new.test.mjs):\n * the copied plugin ships only dist/ + package.json (+ CHANGELOG.md, copied by\n * both installers), so it cannot reach scripts/ at runtime — the same reason\n * the preset resolver is mirrored in index.tsx/index-v2.tsx rather than\n * imported. The script's CLI main is NOT replicated; the plugin only needs the\n * pure extraction.\n *\n * Everything is reduced to bounded plain text: no markdown syntax artifacts,\n * at most WHATS_NEW_MAX_ITEMS bullets. Missing CHANGELOG.md, an unknown\n * version or an empty section all resolve to an empty highlight set — the\n * window simply does not show (fail-open, like the rest of the plugin).\n */\nimport { readFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\n/** Hard cap on bullets shown in the window (the remainder is counted). */\nexport const WHATS_NEW_MAX_ITEMS = 12\n\n/**\n * Cap for the curated `🆕 What's New` summary block — the window shows the\n * summary, never the full Added/Changed/Fixed walls.\n */\nexport const WHATS_NEW_SUMMARY_MAX_ITEMS = 6\n\n/** Bullets longer than this are truncated with an ellipsis (one-line rule). */\nexport const WHATS_NEW_ITEM_MAX_CHARS = 140\n\n/** Prefix of the \"+N more\" line appended when the bullet budget is exceeded. */\nexport const WHATS_NEW_MORE_PREFIX = '… +'\n\n/** H3 subsection headings are kept as plain-text group labels. */\nexport interface WhatsNewGroup {\n heading: string | null\n items: string[]\n}\n\nexport interface WhatsNewHighlights {\n /** Normalized version the highlights belong to (null when not found). */\n version: string | null\n found: boolean\n groups: WhatsNewGroup[]\n /** Total bullets in the section, before the WHATS_NEW_MAX_ITEMS cut. */\n totalItems: number\n /** True when totalItems exceeded WHATS_NEW_MAX_ITEMS. */\n truncated: boolean\n}\n\nexport const EMPTY_HIGHLIGHTS: WhatsNewHighlights = {\n version: null,\n found: false,\n groups: [],\n totalItems: 0,\n truncated: false,\n}\n\n/** Escape regex metacharacters so a version like 1.0.0 matches literally. */\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Extract the body of a version section from changelog text — inline replica\n * of scripts/changelog-extract.mjs `extractSection` (see that file for the\n * full contract: `## [] - YYYY-MM-DD`, leading `v` and the date\n * optional, `## [Unreleased]` never matched).\n */\nexport function extractSection(\n changelogText: string,\n version: string,\n): { found: boolean; body: string | null } {\n const normalized = String(version).trim().replace(/^v/i, '')\n if (!normalized || /^unreleased$/i.test(normalized)) return { found: false, body: null }\n\n const escaped = escapeRegExp(normalized)\n // Single-line heading: `## [v?1.2.1]` optionally followed by ` - YYYY-MM-DD`.\n // [ \\t] (not \\s) keeps the match from crossing newlines; the lookahead\n // requires end-of-line or whitespace so `[1.0.0-beta]` can never match `1.0.0`.\n const headingRe = new RegExp(\n `^##[ \\\\t]+\\\\[v?${escaped}\\\\](?:[ \\\\t]*-[ \\\\t]*\\\\d{4}-\\\\d{2}-\\\\d{2})?(?=[ \\\\t]|$)`,\n 'm',\n )\n const match = headingRe.exec(changelogText)\n if (!match) return { found: false, body: null }\n\n // Advance past the heading line (match.index may point mid-line).\n const newline = changelogText.indexOf('\\n', match.index)\n const start = newline === -1 ? changelogText.length : newline + 1\n\n // Body ends at the next `## [` heading or end of text.\n const nextHeading = /^##[ \\t]+\\[/m.exec(changelogText.slice(start))\n const end = nextHeading ? start + nextHeading.index : changelogText.length\n\n return { found: true, body: changelogText.slice(start, end).trim() }\n}\n\n/**\n * Reduce one markdown line to plain text: links keep their label, emphasis\n * and inline-code markers are dropped, HTML comment fragments are removed,\n * and whitespace collapses. Deliberately simple — the input is our own\n * CHANGELOG (lint-capped at 200 chars per bullet), not hostile input.\n */\nexport function stripMarkdown(text: string): string {\n return text\n .replace(//g, ' ')\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1')\n .replace(/(\\*\\*|__)/g, '')\n .replace(/`/g, '')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** Strip the leading H3 marker (`### Added` → `Added`). */\nfunction stripHeading(text: string): string {\n return text.replace(/^#{1,6}[ \\t]+/, '').trim()\n}\n\n/**\n * Extract the curated summary block (`### 🆕 What's New` or `## 🆕 What's New`)\n * from a section body: its bullets only, each truncated to\n * WHATS_NEW_ITEM_MAX_CHARS, capped to WHATS_NEW_SUMMARY_MAX_ITEMS. Null when\n * the section carries no summary block (the full-section fallback applies).\n */\nexport function extractWhatsNewSummary(body: string): string[] | null {\n const lines = body.split('\\n')\n const start = lines.findIndex((line) => /^#{2,3}[ \\t]+.*What'?s New/i.test(line.trim()))\n if (start === -1) return null\n const items: string[] = []\n for (const rawLine of lines.slice(start + 1)) {\n const line = rawLine.trim()\n if (line === '' || line.startsWith('/g, ' ')\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1')\n .replace(/(\\*\\*|__)/g, '')\n .replace(/`/g, '')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** Strip the leading H3 marker (`### Added` → `Added`). */\nfunction stripHeading(text: string): string {\n return text.replace(/^#{1,6}[ \\t]+/, '').trim()\n}\n\n/**\n * Extract the curated summary block (`### 🆕 What's New` or `## 🆕 What's New`)\n * from a section body: its bullets only, each truncated to\n * WHATS_NEW_ITEM_MAX_CHARS, capped to WHATS_NEW_SUMMARY_MAX_ITEMS. Null when\n * the section carries no summary block (the full-section fallback applies).\n */\nexport function extractWhatsNewSummary(body: string): string[] | null {\n const lines = body.split('\\n')\n const start = lines.findIndex((line) => /^#{2,3}[ \\t]+.*What'?s New/i.test(line.trim()))\n if (start === -1) return null\n const items: string[] = []\n for (const rawLine of lines.slice(start + 1)) {\n const line = rawLine.trim()\n if (line === '' || line.startsWith(' Z["Zeus
orchestrator"] + Z -->|"delegates"| S["14 specialists
hermes · aphrodite · demeter · themis …"] + Z -->|"ambiguous route"| J["Jev decision router
typed · budgeted · reversible"] + J -->|"orders · ranks · verifies"| S + S -->|"last resort"| M["Native MCP
memory · persistence · vision
code-mode · resources"] + Z --> G["J1 risk gate
off / shadow / warn / enforce"] + G -->|"high risk"| H["Human approval"] +``` + +**The escalation ladder every agent follows**: session context first → free local selector → one typed Jev decision when genuinely ambiguous → native MCP call only as the last resort for state the session cannot reconstruct. + +```mermaid +flowchart LR + R["rough request"] --> T0{"clear &
bounded?"} + T0 -->|yes| X["execute directly"] + T0 -->|"vague /
multi-concern"| T1["Tier 1 — internal
minimal adjust ≤15 lines
(silent, no approval)"] + T1 --> T2q{">> given?"} + T2q -->|yes| T2["Tier 2 — full contract
6 sections, confirm-or-adjust"] + T2q -->|no| X +``` + +**Skill discovery runs a trust cascade** — canonical first, popularity never compensates for provenance: + +```mermaid +flowchart LR + L["installed pool
(always first)"] -->|"gap"| C1["anthropics/skills
canonical"] + C1 -->|"no fit"| C2["skills.sh
install-count signal"] + C2 -->|"no fit"| C3["GitHub raw
widest, weakest"] + C3 --> J["Jev orders
the candidates"] + J --> P["YOU review
and run the install"] +``` -## Installation +## Why use it? -Requirements: [OpenCode](https://opencode.ai/docs/) **2.x** and Node.js **≥ 26.4.0** -([compatibility](docs/COMPATIBILITY.md)). +- **Fast-Track execution:** Bounded micro-edits (<= 2 files, <= 50 lines) bypass all heavy ceremony and verify in < 10 seconds. +- **Mandatory test slicing:** Sub-second targeted test execution instead of running sluggish repository-wide test suites during dev loops. +- **Execution proof receipts:** Cryptographic SHA-256 fingerprinting on modified files and test slice exit codes prevents false-positive task reports. +- **KV-cache prefix optimization:** Strict invariant-first prompt layering maximizes LLM cache hits (up to 90% cost and latency savings). +- **Reactive event bus & zero polling:** Process-wide in-memory event bus delivers instant updates across jobs and agents without disk polling. +- **Themis local reflex loops:** Specialist self-healing resolves isolated lint and test slice discrepancies before escalating to Zeus. +- **Assertive council (`/pantheon`):** Parallel specialist consultations resolved decisively via domain authority and JEV multi-criteria decisions without endless debate turns. +- **You stay in charge:** Pantheon supports your judgment; it never silently alters permissions or runs unapproved destructive actions. +- **Non-destructive upgrades:** Updating Pantheon (`pantheon-opencode update`) refreshes skills, MCPs, and instructions while strictly preserving all user models, presets, permissions, and custom configs. +## Start in 2 minutes + +Requirements: [OpenCode](https://opencode.ai/docs/) **2.x** and Node.js **>=26.4.0**. (See [Compatibility](docs/COMPATIBILITY.md)). + +### 1. Install + +**Option A — Quick Plugin Add (Global or Project):** ```bash -# Option A — as an OpenCode plugin (global or project) opencode plugin add pantheon-opencode +# Or pin a specific version: +opencode plugin add pantheon-opencode@2.0.0-rc.1 +``` -# Option B — global CLI install with full MCP tooling +**Option B — Global CLI Install with Full MCP Tooling:** +```bash npm install -g pantheon-opencode@beta pantheon-opencode init --yes +``` -# Verify the install +### 2. Verify Health +```bash pantheon-opencode doctor +``` +Runs a diagnostic checking Decision Router & budget ledger accessibility, MCP initialization, Python virtual environments, Node version, permissions, and config integrity. In containerized or JupyterHub environments with group-writable homes, set `PANTHEON_ALLOW_GROUP_WRITABLE=1` if needed. -# Later: update without losing models, presets or permissions +### 3. Updating Pantheon Without Overwriting Settings +When a new version is released: +```bash pantheon-opencode update ``` +The updater verifies package identity, pulls the latest release, and runs a non-destructive configuration refresh. **Your custom models, active preset, custom permissions, plugin options, and user-defined AGENTS.md sections are preserved verbatim.** + +--- + +## Optimal Workflow & Execution Modes + +Pantheon balances speed and rigor through three distinct execution modes: + +```mermaid +flowchart TD + Req["User Request"] --> Size{"Scope / Risk"} + Size -->|"≤ 2 files · ≤ 50 lines
routine fix / typo / CSS"| Fast["Fast-Track
(Sub-10s · Inline Test Slicing)"] + Size -->|"Architecture / Tech choice
Security / Multi-stakeholder"| Council["Council Synthesis (/pantheon)
(2-3 Specialists in Parallel · Domain Authority)"] + Size -->|"Multi-phase feature
Heavy refactor · Breaking changes"| Deep["Deepwork (/pantheon-deepwork)
(Athena Plan · Phase Gates · Checkpoints)"] +``` -## Usage +### 1. Fast-Track & Test Slicing (Micro-Edits < 10s) +For routine bug fixes, style adjustments, or localized refactors: +- **No planning ceremony:** Directly executes bounded changes. +- **Targeted test slicing:** Runs ONLY the test slice relevant to the modified file (e.g. `node --test tests/foo.test.mjs` or `pytest -k `). Full repository test suites are reserved for CI and release gates. +- **Single-turn delivery:** Verifies and completes in under 10 seconds. -Inside OpenCode, dispatch the orchestrator or a workflow: +### 2. Assertive Council Synthesis (`/pantheon`) +When confronting architectural crossroads, technology evaluations, or security tradeoffs: +```text +/pantheon Should we use WebSockets or Server-Sent Events for live push notifications? +``` +- **Parallel Dispatch:** Dispatches 2–3 specialist agents simultaneously with independent prompts. +- **Assertive Arbitration:** Rather than looping in repetitive debate rounds, divergences are resolved immediately via **Domain Authority Precedence**: + - **Security / Auth:** `@themis` has veto power over vulnerable designs. + - **Database / Schema:** `@demeter` carries authoritative weight on query performance and transaction safety. + - **Frontend / UX / A11y:** `@aphrodite` governs user interface responsiveness and accessibility. + - **Infrastructure / CI:** `@prometheus` governs deployment contracts and container isolation. + - **API / Protocols:** `@hermes` governs contract consistency and transport schemas. + - **Architecture / Modularity:** `@athena` governs separation of concerns. +- **JEV Multi-Criteria Decision:** If trade-offs balance competing requirements equally, Zeus invokes `pantheon_jev_decide` (or local decision matrix) to rank candidates deterministically in one tool call. +### 3. Checkpointed Deepwork (`/pantheon-deepwork`) +For multi-phase tasks spanning 10+ turns or multiple sessions: ```text -@zeus: Add CSV export to the reports page /pantheon-deepwork "Implement OAuth2 PKCE authentication flow" ``` +- **The Plan is the Artifact:** The canonical ground truth is stored in `.pantheon/deepwork//plan.json` with an append-only event log (`journal.ndjson`) for resilient crash recovery. +- **Native OpenCode Gates (Strictly No HTML):** Approvals (Gate 1) and decision resolutions use OpenCode's native interactive `question` tool directly in the chat UI. +- **Dependency DAG:** Automatically projects task dependencies into live Mermaid diagrams (`flowchart LR`) inside `PLAN.md` and chat status. +- **Fail-First Acceptance:** Every task defines concrete acceptance criteria (`kind: test|command|file|manual`, `fails_now: true`) verified with cryptographic receipts. +- **Tool Automation (`pantheon_deepwork`):** Structured tool for `init`, `status`, `update_task`, `verify_acceptance`, and `resolve_decision`. Resiliently normalizes complex multi-decision plans, single-option constraints, string criteria, and agent aliases with atomic file locking. +- **Resumability:** Checkpoints persisted to `.pantheon/deepwork//`. Resume anytime with `/pantheon-deepwork --resume `. -`@zeus` routes to the specialists; `/pantheon` arbitrates architectural choices across -specialists; `/pantheon-deepwork` runs a multi-phase plan with checkpoints and gates. You -approve each gate and you run every commit. +--- -## Structure +## The 14 Specialized Agents -``` -src/agents/ 14 canonical agent definitions -src/skills/ skills loaded on demand -src/mcp/ local MCP servers (memory, persistence, resources, code-mode, vision) -src/plugins/ OpenCode plugin + TUI -scripts/ installer, doctor, test-slice, release tooling -bin/ pantheon-opencode CLI -docs/ documentation (also published as the docs portal) -examples/ runnable reference projects -tests/ Node and TypeScript test suites -``` +For a complete breakdown of permissions, tools, MCP access, and boundary constraints per agent, see the [Agent Capability Matrix](docs/AGENT-CAPABILITY-MATRIX.md). + +Every root dispatch carries a concise handoff brief — objective, bounded scope, relevant inputs, constraints, expected return format, and verification. Work is routed qualitatively — uncertainty, domain expertise, dependencies, risk, and verification — not by fixed file or line thresholds. Return contracts are role-specific: implementation uses `## subtask_summary`, investigation returns structured findings, Athena returns the complete plan, and council responses use `## specialist_response`. + +| Agent | Domain Authority | Core Responsibilities | +|---|---|---| +| **@zeus** | Central Orchestrator | Directs workflow, manages delegations, arbitrates council decisions, enforces token efficiency. Never implements directly. | +| **@athena** | Architecture & Planning | Research-first planning, system boundaries, LTS policy, dependency analysis. Plan-only; never implements. | +| **@hermes** | Backend & APIs | FastAPI, Python async, Node/TypeScript backends, API contracts, protocol conformance. | +| **@aphrodite** | Frontend & UX | React 19, strict TypeScript, responsive design, WCAG accessibility, CSS optimization. | +| **@demeter** | Database & Persistence | Schema migrations, query optimization, N+1 query prevention, transaction integrity. | +| **@themis** | Security & Quality Gate | OWASP audits, static analysis (Biome/ruff), authorization gates, dead code removal. Reviews material changes. | +| **@prometheus** | DevOps & Infrastructure | Docker, CI/CD pipelines, runtime configuration, provider abstraction, telemetry infra. | +| **@talos** | Hotfix Fast Lane | Rapid, standalone fixes for small bugs, typos, and minor logic without subagent overhead. | +| **@apollo** | Investigation Scout | Read-only discovery: parallel codebase and web searches. Returns structured findings. | +| **@hephaestus**| AI Pipelines & RAG | Embeddings, vector stores, prompt engineering, agent pipelines. | +| **@gaia** | Geospatial & Sensing | Remote sensing, SAR, geospatial analysis, ML/DL raster classification (read-only). | +| **@iris** | Git & Release Ops | Branching, PRs, issue triage, release notes. Never pushes or merges without human approval. | +| **@mnemosyne** | Project Memory Bank | Maintains `.pantheon/memory-bank/` and records ADRs when explicitly requested. | +| **@nyx** | Observability & Telemetry| OpenTelemetry tracing, token/cost monitoring, execution profiling. | + +--- + +## Skills & MCP Tooling + +- **In-Process Skill Search (`pantheon_skill_search`) & Proactive Installation:** Quickly discovers local and external ecosystem skills; when gaps are identified, Zeus proactively invokes the interactive `question` tool for 1-click project-scoped installation into `.agents/skills/` (via `npx skills add -a opencode -y`), delegated to execution specialists with zero manual shell typing required. +- **25 Production Skills:** Includes `test-slicing`, `fast-path-execution`, `tdd-with-agents`, `instruction-forge`, and `incremental-implementation`. +- **5 Local MCP Servers:** + - `pantheon-memory`: Shared project memory with atomic SQLite locking. + - `pantheon-persistence`: File and context persistence. + - `pantheon-resources`: Local documentation and asset serving. + - `pantheon-code-mode`: Sandboxed Python execution. + - `pantheon-vision`: Image analysis and diagnostic visual inspection. +- **Advisory JEV Decision Router:** Evaluates candidate options (`pantheon_jev_decide`), orders trade-offs, and provides formal multi-criteria decision making with strict, flattened schema validation. +- **Project Working Directory Awareness:** Native shell tool resolution dynamically binds to the active project workspace instead of defaulting to `$HOME`. + +--- + +## Settings & TUI Window (`/pantheon-settings`) + +Run `/pantheon-settings` (or `Pantheon: Settings` in the command palette) to open the interactive settings window: + +- **Gates & Overrides:** Toggle named behaviors live; persists to `pantheon-overrides.json`. +- **Model Presets:** Switch active model tier globally or per project. +- **Decision Model Selector:** Interactive selector to cycle across all remote decision models (`openrouter-jev`, `typesafe-jev`, `openai-decisions`, `vercel-gateway-jev`, etc.) directly from the UI. +- **Bilingual Settings (PT-BR / EN):** Full visual localization for Decision, Autonomy, and Safety tabs, auto-detecting environment locale with manual toggle in the TUI tab. +- **Updates:** Check registry channel (`beta` / `stable`) and trigger upgrades. +- **Doctor:** Run inline system health diagnostics. +- **TUI Personalization:** Adjust spacing (`comfortable` vs `compact`), separators, gauge bar styles, context display rows, and language. +- **Non-Destructive Overlay & Mouse Navigation:** Opens as a floating dialog overlay over the active session without blanking the workspace (configurable via `dialog` vs `fullscreen`), with full mouse click support for tabs, sidebar, rows, value cyclers, and actions. +- **Modernized What's New Window:** Card layout with rounded border, pagination buttons, and a dedicated `[OK, Entendido]` button with keyboard (`Enter`/`Esc`/`Q`) and mouse click support. + +--- + +## Documentation & Tutorials + +> 📖 **Official Documentation Portal:** Explore full searchable guides, interactive Mermaid diagrams, and versioned releases at **[https://ils15.github.io/pantheon-opencode/](https://ils15.github.io/pantheon-opencode/)**. + +| Guides & Tutorials | Architecture & Deep Dives | Reference & Operations | +|---|---|---| +| [First Project (End-to-End)](docs/guides/first-project.md) | [Architecture](docs/ARCHITECTURE.md) | [MCP Tools](docs/mcp-tools.md) | +| [Agent Capability Matrix](docs/AGENT-CAPABILITY-MATRIX.md) | [Delegation & Gates](docs/PERMISSIONS-QUALITY-DELEGATION.md) | [Native Decisions (Jev)](docs/reference/native-decisions.md) | +| [Deepwork Blueprint](docs/guides/deepwork.md) | [Memory System](docs/MEMORY.md) | [Model Routing](docs/reference/model-routing.md) | +| [Pantheon Vision](docs/guides/vision.md) | [OpenCode Integration](docs/opencode.md) | [Changelog](CHANGELOG.md) | +| [Cookbook](docs/guides/cookbook.md) | [Compatibility](docs/COMPATIBILITY.md) | [Wiki](wiki/Home.md) | + +--- + +## Real-World Examples + +Working runnable reference projects demonstrating Pantheon orchestration in practice: + +* **[SaaS Performance Dashboard](examples/saas-dashboard/) (`examples/saas-dashboard`):** Fullstack web application with React 19, Fastify backend, streaming CSV export, automated tests, and a real Deepwork execution plan (`plan.json`, `journal.ndjson`, `PLAN.md`). +* **[Repo Health CLI](examples/cli-tool/) (`examples/cli-tool`):** Sub-second diagnostic CLI tool demonstrating the fast-path execution of `@talos` and `@hermes`. + +--- + +## What's New in v2.1.5 + +- **Risk-Based Validation Protocol (#444):** Explicit multi-tier protocol distinguishing focused test slices (<10s), package integration suites, and mandatory repository CI gates. Escalation to broad suites requires explicit triggers (cross-module, breaking contracts, auth, DB migrations). +- **Tool Execution Resilience & Fallback:** Added `execute` fallback tool alias executing commands directly in `/bin/bash`, preventing `SyntaxError: Assigning to rvalue` when models call `execute` with CLI commands or scripts. +- **CLI Execution Mandate:** Enforced CLI execution via `shell`/`bash` for binaries like `opencode-quota` with an anti-panic ban on speculative recursive `glob`/`grep` in `~/.config`. +- **Validation Scope Transparency (#444):** `subtask_summary` observable receipts report `validation_scope` and deferred `pending_validation` repository CI pipeline gates. + +--- + +## What's New in v2.1.4 + +- **Global Install Shadowing & PATH Hygiene (#424):** Doctor check (H2b) detects multiple global binaries, dangling symlinks, and prefix skew. Version skew validation prevents `_npx` from binding to older global packages. +- **Strict Test Slice Ordering (#442):** Reordered `--test-name-pattern` flag ahead of the test file path in `scripts/test-slice.mjs` so Node's native test runner filters tests during failure/fix loops. +- **Security Boundaries on Internal Folders (#441):** Hardened `auto-permissions` and `zeusReadGuard` to exclude `.git/` and `node_modules/` from autonomous reads. +- **Universal Session Todo Tool Availability (#439):** Granted `todowrite` and `todoread` across all 14 specialist agent manifests. +- **Session Auto-Discovery for Zen Vision (#440):** Automated active session discovery from environment (`OPENCODE_SESSION_ID`) and SQLite `opencode.db` (`session_v2`) for `vision_describe`. + +--- + +## What's New in v2.0.1 + +- **Bilingual TUI Settings (PT-BR / EN):** Visual localization for Decision Router, Autonomy & Budgets, and J1 Safety Gate tabs, with intelligent system locale auto-detection (`LANG` / `LC_ALL`) and manual preference cycling (`auto`, `pt-BR`, `en`). +- **Interactive Decision Model Selector:** Permanently accessible selector row in `/pantheon-settings` to cycle across all 6 remote decision models without manual JSON configuration. +- **Modernized Council Synthesis (`/pantheon`):** Rich synthesis artifacts featuring Domain Authority breakdown, Mermaid arbitration diagrams, and immediate action checklists. +- **Modernized Strategic Planning (`/pantheon-deepwork`):** Athena plans now enforce mandatory sub-10s test slicing, execution dependency diagrams, blast radius impact matrix, and rollback blueprints. +- **Demystified J1 Safety Ladder:** Plain-language descriptions for J1 execution modes (`shadow`, `enforce`, `off`), making telemetry and protection gates clear. + +--- + +## What's New in v2.0.0-rc.1 + +- **Release Candidate Series Inauguration:** Production-ready multi-agent orchestration for OpenCode 2.x. +- **Agent Token Compaction (-44.3%):** Removed duplicated backend code in Apollo/Prometheus, saving 8,150 tokens per turn (~29.3M tokens/month). +- **Pragmatism & Anti-Pedantry Directive:** Safe diagnostic operations are authorized without bureaucratic gates, ending agent sluggishness. +- **Batched Suite TDD & Test-Slicing:** Cohesive multi-endpoint testing and sub-100ms targeted test execution. +- **Proactive Skill Discovery & Query Caching:** Cached skill lookups (24h TTL) and automated recommendation for external tools. +- **Live JEV Scorecard & Sandbox Web App:** 16/16 pass rate ($0.0000238/decision) verified with an end-to-end sandbox application. + +See [CHANGELOG.md](CHANGELOG.md) for full historical release notes. -## Documentation +## Contributing -| Start here | Go deeper | -|---|---| -| [Docs portal](https://ils15.github.io/pantheon-opencode/) | [Architecture](docs/ARCHITECTURE.md) | -| [Quick Start](docs/QUICKSTART.md) | [Overview and routing ladders](docs/OVERVIEW.md) | -| [Installation](docs/INSTALLATION.md) | [Execution modes](docs/guides/execution-modes.md) | -| [First project end-to-end](docs/guides/first-project.md) | [Agent Capability Matrix](docs/AGENT-CAPABILITY-MATRIX.md) | -| [Settings & TUI window](docs/SETTINGS.md) | [Permissions, gates & delegation](docs/PERMISSIONS-QUALITY-DELEGATION.md) | -| [v2.x highlights](docs/releases/v2-highlights.md) | [CHANGELOG](CHANGELOG.md) | +Ideas, bug reports, and contributions are welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) before submitting a PR. -Runnable examples: [SaaS performance dashboard](examples/saas-dashboard/) and -[repo health CLI](examples/cli-tool/). Contributing: -[CONTRIBUTING.md](CONTRIBUTING.md). +## Citation and License -## License +Pantheon is open-source software licensed under the [MIT License](LICENSE). +Cite via Zenodo concept DOI: [10.5281/zenodo.22650136](https://doi.org/10.5281/zenodo.22650136). Citation metadata is available in [CITATION.cff](CITATION.cff). -MIT — see [LICENSE](LICENSE). Cite via Zenodo concept DOI -[10.5281/zenodo.22650136](https://doi.org/10.5281/zenodo.22650136) -([CITATION.cff](CITATION.cff)). +Canonical repository: From 4a0761a561ecdb434b5f0abb9e0ca202c355ac3c Mon Sep 17 00:00:00 2001 From: iris Date: Mon, 16 Nov 2026 06:19:59 -0300 Subject: [PATCH 6/8] chore(release): bump manifests and promote changelog to v2.1.6 --- .zenodo.json | 8 +++---- AGENTS.global.md | 2 +- AGENTS.md | 5 ++++- CHANGELOG.md | 21 +++++++++++++++++++ CITATION.cff | 6 +++--- README.md | 11 ++++++++++ package-lock.json | 6 +++--- package.json | 2 +- plugin.json | 2 +- pyproject.toml | 2 +- scripts/build-agents-md.mjs | 3 +++ scripts/install/opencode.mjs | 12 +++++++++++ src/agents/roster.json | 2 +- src/agents/zeus.md | 5 ++++- .../backend-standards.instructions.md | 5 +++++ src/mcp/pantheon_vision.py | 5 ++++- src/plugins/tui/package-lock.json | 4 ++-- src/plugins/tui/package.json | 2 +- tests/skill-decision-proactive.test.mjs | 2 +- 19 files changed, 83 insertions(+), 22 deletions(-) diff --git a/.zenodo.json b/.zenodo.json index 22d38f6e..ebe2e13f 100644 --- a/.zenodo.json +++ b/.zenodo.json @@ -1,18 +1,18 @@ { "title": "Pantheon Opencode", "upload_type": "software", - "description": "Pantheon v2.1.5 is an OpenCode plugin coordinating 14 specialized agents, with a typed decision router (Jev), 25 curated skills with progressive disclosure, named-behavior overrides, an on-demand agent forge, and a cost-aware skill discovery cascade. OpenCode 2.x only - the V1 contract is removed.", + "description": "Pantheon v2.1.6 is an OpenCode plugin coordinating 14 specialized agents, with a typed decision router (Jev), 25 curated skills with progressive disclosure, named-behavior overrides, an on-demand agent forge, and a cost-aware skill discovery cascade. OpenCode 2.x only - the V1 contract is removed.", "creators": [ { "name": "Igor Leite da Silva", "orcid": "0000-0001-7787-7562" } ], - "version": "2.1.5", + "version": "2.1.6", "license": "MIT", "language": "eng", "keywords": ["opencode", "ai-agents", "multi-agent", "orchestration", "developer-tools"], - "url": "https://github.com/ils15/pantheon-opencode/releases/tag/v2.1.5", + "url": "https://github.com/ils15/pantheon-opencode/releases/tag/v2.1.6", "related_identifiers": [ { "identifier": "https://github.com/ils15/pantheon-opencode", @@ -20,5 +20,5 @@ "resource_type": "software" } ], - "publication_date": "2026-11-14" + "publication_date": "2026-11-16" } diff --git a/AGENTS.global.md b/AGENTS.global.md index 70b0d49a..80873393 100644 --- a/AGENTS.global.md +++ b/AGENTS.global.md @@ -1,7 +1,7 @@ - + # Pantheon Agent System — OpenCode diff --git a/AGENTS.md b/AGENTS.md index bca9c72b..1f92da21 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ - + # Pantheon — Repository Setup @@ -25,10 +25,13 @@ Validate global installation AS A REAL USER in the sandbox `~/pantheon-sandbox/` - Never create worktrees inside the main project; use `/.pantheon-worktrees//`. - Worktrees do not live inside `.pantheon/`. +- If the project is not a Git repository (no `.git` directory), worktrees cannot be used; specialists must use disjoint file paths and directory separation within the project workspace instead. ## Conventions - TDD: RED→GREEN→REFACTOR for testable behavior; use focused checks for micro-edits +- Fail-Fast: Never create fake mock servers or listeners on real service/application ports to mask missing dependencies; fail fast with explicit error details. +- Background processes: Long-running servers (FastAPI/uvicorn, Vite, dev servers) must always be decoupled from subshells using `setsid nohup > 2>&1 &` (or `disown`). - Stronger gates (auth, security, data-integrity, coverage) are canonical in the global `Test Economy` section - Async/await on all I/O - Type hints on all functions diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bd3120b..93338a8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,27 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). `node scripts/versioning.mjs apply --notes` pre-fills the generated sections from conventional commits. Running apply will move this section to a versioned entry and reset the template below. --> +## [v2.1.6] - 2026-11-16 + +### 🆕 What's New + +- **Deepwork Resilient Normalization**: Supported multi-decision blueprints, single-option policy constraints, and string acceptance criteria. +- **Fail-Fast Anti-Mocking Rule**: Strictly prohibited mock servers on real service ports to fake missing dependencies; fail fast with explicit errors. +- **Workspace Tool Working Directory**: Native shell tools dynamically resolve to the active project root rather than falling back to `$HOME`. +- **Atomic Skill Installation**: Enforced sequential `&&` chaining for `npx skills add` to prevent silent dropping of trailing targets. +- **Project Bootstrap Git Init**: `init --project` automatically initializes an empty Git repo when absent, enabling worktree and branch support. +- **Decoupled Background Processes**: Mandated `setsid nohup > 2>&1 &` (or `disown`) for long-running service processes. + +### Fixed + +- **deepwork** — fixed `readPlan` schema rejection on single-option decision policies and auto-inferred acceptance criteria kinds (`test|command|file|manual`). +- **deepwork** — added atomic plan locking and safe temp files preventing write race conditions during concurrent decision resolutions. +- **tools** — flattened JSON schema for `pantheon_jev_decide` to eliminate upstream validator rejections on top-level `oneOf`/`anyOf`. +- **tools** — bound `shellTool` fallback execution directory dynamically to `hostLocationDirectory`. +- **mcp** — improved `pantheon-vision` error reporting with status code diagnostics and actionable fallback to native `vision_describe`. +- **tui** — removed duplicate todo block from settings preferences in favor of native sidebar. +- **agents** — updated Zeus and backend instructions with Fail-Fast, resource exclusivity, and decoupled server execution standards. + ## [v2.1.5] - 2026-11-14 ### 🆕 What's New diff --git a/CITATION.cff b/CITATION.cff index 6e8d53e3..14740c0a 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -2,11 +2,11 @@ cff-version: 1.2.0 message: "If you use Pantheon, please cite this software." title: "Pantheon Opencode" abstract: >- - Pantheon v2.1.5 is an OpenCode plugin and installer coordinating 14 + Pantheon v2.1.6 is an OpenCode plugin and installer coordinating 14 specialized agents with high-speed direct dispatch, native subagents, and progressive skill disclosure for OpenCode 2.x. -version: 2.1.5 -url: https://github.com/ils15/pantheon-opencode/releases/tag/v2.1.5 +version: 2.1.6 +url: https://github.com/ils15/pantheon-opencode/releases/tag/v2.1.6 doi: 10.5281/zenodo.22650136 repository-code: https://github.com/ils15/pantheon-opencode license: MIT diff --git a/README.md b/README.md index 4ce6f6d3..e8a9ba57 100644 --- a/README.md +++ b/README.md @@ -226,6 +226,17 @@ Working runnable reference projects demonstrating Pantheon orchestration in prac --- +## What's New in v2.1.6 + +- **Deepwork Resilient Normalization:** Full support for multi-decision plans, single-option policy constraints, string criteria auto-inference, and agent handle normalization with atomic plan locking. +- **Fail-Fast Anti-Mocking Rule:** Strict standard forbidding ad-hoc mock servers on production ports to mask missing dependencies; agents fail fast with explicit diagnostics. +- **Project Tool Working Directory:** Dynamic binding of shell tools to the project workspace instead of falling back to `$HOME`. +- **Atomic Skill Installation:** Sequential `&&` chaining for `npx skills add` commands preventing silent omissions when installing multiple skills. +- **Project Bootstrap Git Init:** `init --project` automatically initializes an empty Git repo when absent, enabling worktree and branch isolation out of the box. +- **Decoupled Background Processes:** Mandatory `setsid nohup > 2>&1 &` (or `disown`) for background servers surviving subshell termination. + +--- + ## What's New in v2.1.5 - **Risk-Based Validation Protocol (#444):** Explicit multi-tier protocol distinguishing focused test slices (<10s), package integration suites, and mandatory repository CI gates. Escalation to broad suites requires explicit triggers (cross-module, breaking contracts, auth, DB migrations). diff --git a/package-lock.json b/package-lock.json index 2e4ab2e2..dbf031ac 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "pantheon-opencode", - "version": "2.1.5", + "version": "2.1.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "pantheon-opencode", - "version": "2.1.5", + "version": "2.1.6", "hasInstallScript": true, "license": "MIT", "workspaces": [ @@ -8982,7 +8982,7 @@ }, "src/plugins/tui": { "name": "pantheon-tui", - "version": "2.1.5", + "version": "2.1.6", "license": "MIT", "dependencies": { "@opencode/plugin": "2.0.26", diff --git a/package.json b/package.json index 953df96b..584657c1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pantheon-opencode", - "version": "2.1.5", + "version": "2.1.6", "description": "Multi-agent orchestration for OpenCode \u2014 14 specialized agents, TDD, Themis review gates.", "type": "module", "workspaces": [ diff --git a/plugin.json b/plugin.json index 37670858..e6947405 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "name": "pantheon", "publisher": "ils15", - "version": "2.1.5", + "version": "2.1.6", "displayName": "Pantheon", "description": "Conductor-Delegate orchestration platform with 14 specialized agents, 25 skills, and OpenCode support.", "agents": "./src/agents", diff --git a/pyproject.toml b/pyproject.toml index d907dc07..a9c1559d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.backends._legacy:_Backend" [project] name = "pantheon" -version = "2.1.5" +version = "2.1.6" description = "Multi-agent orchestration framework" requires-python = ">=3.11" # Python sources under src/mcp/ import fastmcp/pydantic at runtime, but those diff --git a/scripts/build-agents-md.mjs b/scripts/build-agents-md.mjs index 8e11bfcf..20755da3 100644 --- a/scripts/build-agents-md.mjs +++ b/scripts/build-agents-md.mjs @@ -150,10 +150,13 @@ Validate global installation AS A REAL USER in the sandbox \`~/pantheon-sandbox/ - Never create worktrees inside the main project; use \`/.pantheon-worktrees//\`. - Worktrees do not live inside \`.pantheon/\`. +- If the project is not a Git repository (no \`.git\` directory), worktrees cannot be used; specialists must use disjoint file paths and directory separation within the project workspace instead. ## Conventions - TDD: RED→GREEN→REFACTOR for testable behavior; use focused checks for micro-edits +- Fail-Fast: Never create fake mock servers or listeners on real service/application ports to mask missing dependencies; fail fast with explicit error details. +- Background processes: Long-running servers (FastAPI/uvicorn, Vite, dev servers) must always be decoupled from subshells using \`setsid nohup > 2>&1 &\` (or \`disown\`). - Stronger gates (auth, security, data-integrity, coverage) are canonical in the global \`Test Economy\` section - Async/await on all I/O - Type hints on all functions diff --git a/scripts/install/opencode.mjs b/scripts/install/opencode.mjs index 9673aeaf..fc5da003 100644 --- a/scripts/install/opencode.mjs +++ b/scripts/install/opencode.mjs @@ -3290,6 +3290,18 @@ async function installPass( markAppliedWrite() stateStep(true) advancePhase() + + if (opts.isProject && !existsSync(join(target, '.git'))) { + try { + const { spawnSync } = await import('node:child_process') + const gitProbe = spawnSync('git', ['--version'], { stdio: 'ignore' }) + if (gitProbe.status === 0) { + spawnSync('git', ['init', '-q'], { cwd: target, stdio: 'ignore' }) + } + } catch { + // git probe or initialization failed; harmless + } + } } // Fail closed only after the degraded state is persisted. The caller records diff --git a/src/agents/roster.json b/src/agents/roster.json index dbb1f54f..84cee499 100644 --- a/src/agents/roster.json +++ b/src/agents/roster.json @@ -556,7 +556,7 @@ }, "execute": "deny" }, - "body": "## Fast Greeting & Direct Query Bypass\n\n- **Greetings and casual queries** (\"oi\", \"olá\", \"hello\", \"hi\", \"good morning\", \"how are you\", greetings, general questions about Pantheon or capabilities, simple clarifications, or direct calculations that do not require reading or editing project code): **Respond directly and immediately in 1 concise turn.**\n- **DO NOT dispatch subagents**, do not call Athena/Apollo, do not call Jev or council, and do not invoke tools for greetings and direct queries.\n\n## Prompt Refinery & Request Disambiguation (`prompt-refinery`)\n\n- **Prefix `>>` (Tier 2 Visual Contract):**\n - When the user's prompt begins with `>>`: DO NOT execute immediately. Trigger Tier 2 Visual Contract.\n - Present the structured engineering brief:\n - Slices table (`Slice | Focus Area | Target Files | Verification Gate`)\n - In Scope, Out of Scope & Negative Constraints\n - Acceptance Criteria\n - Open Questions with Recommended Defaults\n - **MANDATORY `question` tool:** When Open Questions, decisions needed, or scope trade-offs are present, ALWAYS invoke the native `question` tool with structured choices (marking the recommended choice with `(Recomendado)`) alongside the execution approval question (e.g. `[\"(Recomendado) Aprovar escopo e iniciar execução\", \"Ajustar escopo/premissas\"]`). NEVER leave open questions as inert text bullets in chat and proceed blindly.\n- **Ambiguous or Multi-Concern Prompts (Tier 1 Silent Lean):**\n - When a request mixes refactor/fix/redesign without clear acceptance criteria, extract internal lean brief (Target, Slices, Constraints, Verification, Defaults).\n - If ambiguity blocks safe execution or presents critical trade-offs, **always invoke the native `question` tool** with concrete options (recommended option first) rather than making blind assumptions or writing plain-text questions.\n\n\n## Strict Test Slicing & Anti-Fatigue Mandate (Issue #437)\n\n- **Repo Selector First:** Prefer the repository's own focused selector (e.g. `npm run test:quick`, `node scripts/test-slice.mjs`, `pytest -k`) over path guessing.\n- **Mandatory Sliced Checks (<10s):** When dispatching implementation specialists (@hermes, @aphrodite, @talos, @demeter, @prometheus), ALWAYS provide the exact, narrow test slice command for the changed file (e.g. `node --test tests/.test.mjs`, `pytest tests/test_.py -k `).\n- **Global Suites Forbidden in Dev Loops:** STRICTLY FORBID specialists from running global repository-wide test suites (`npm test`, `npm run test:all`, unconstrained `pytest`). Full suites cause massive timeouts, context bloating, and token waste. Full suites are reserved exclusively for the final release/PR gate.\n- **Failure/Fix Loop (No Redundant Passes):** When fixing a failed test, specialists MUST rerun ONLY the failed test (`-k ` or `--test-name-pattern`). DO NOT repeat passing tests if code was unchanged.\n- **Mapping Gaps & Scope Justification:** If no direct test file exists, report the mapping gap and run static lint/typecheck fallback (`npx biome check ` or `ruff check `) plus nearest slice; never escalate silently to full suites. Any broader-than-slice run requires visible scope justification.\n- **Observable Summary Receipt:** Require the specialist to return the structured receipt: `**tests:** [PASS|WARN|FAIL] (targets: N, duration: s, selection: )`.\n\n## Fast-Path Direct Implementation (Default Coding Workflow)\n\n- **Direct coding requests (features, bug fixes, refactoring, tests, hotfixes)**:\n - **Dispatch directly to the domain specialist in 1 turn.** Send a concise 3-5 line brief: goal, files, acceptance criteria, test command.\n - Domain mapping: Backend/API/logic to `@hermes`; Frontend/UI/styles to `@aphrodite`; Hotfixes/typos/CSS to `@talos`; Database schemas/migrations to `@demeter`; Infra/Docker/CI to `@prometheus`; Read-only broad research to `@apollo`.\n - **DO NOT invoke @athena.** DO NOT force planning or ask for plan approval on direct coding requests.\n - **DO NOT invoke Council synthesis.** Council is reserved strictly for `/pantheon-council` or explicit multi-perspective trade-off requests.\n - When the specialist returns, report the concise deliverable and test result directly to the user.\n - **Skill-Informed Handoff**: When a task involves an installed skill (built-in Pantheon skill or external in `.opencode/skills/` / `.agents/skills/`), Zeus includes `Skill: (Path: .opencode/skills//SKILL.md)` in the brief and instructs the specialist to read `SKILL.md` before implementation.\n- **Asynchronous parallel subagents**: When running long test suites, heavy builds, or independent exploratory research, use `task(..., background: true)` where supported by the runtime so the main workflow does not block.\n- **Planning via @athena is strictly gated**:\n - ONLY invoke Athena when the user explicitly runs `/pantheon-deepwork` or explicitly requests a plan in the prompt (\"plan this first\", \"create a plan\", \"planeje\").\n\n## Session Task Checklist & TUI Todo Panel (`todowrite`)\n\n- **Live TUI Progress:** Whenever coordinating a workflow with two or more steps, or executing an architecture/deepwork plan:\n - **Initialize:** Call `todowrite` immediately with the sequential task checklist (all items marked `pending`).\n - **Transition:** As each phase or specialist delegation starts, update the active item to `in_progress` via `todowrite`.\n - **Complete:** Upon verification or specialist return, mark the item `completed` (or `cancelled` if discarded) via `todowrite`.\n - This ensures the active session's task status is visible in real-time in the Pantheon TUI Todo block.\n\n## Golden Rule & Boundaries\n\n**Coordinator and router.** Zeus never edits or implements code (delegates to @hermes, @aphrodite, @talos, etc.), but may perform bounded reads (≤50 lines) for fast routing without unnecessary subagent dispatches. Broad investigations or exploratory research go to @apollo. Routing and inspecting files across the `.pantheon/` directory (`.pantheon/**`, including plans, memory-bank, reports, configs) and active worktrees (`.pantheon-worktrees/**`) is fully permitted without restriction. Avoid broad recursive scans across `.git/**` or `node_modules/**`.\n\nZeus NEVER edits files (`edit: deny`, `hashline_edit: deny`). Zero terminal access (`bash: deny`, `shell: deny`). OpenCode's native terminal tool is `bash` (aliased to `shell`). Zeus has NO terminal access.\nNEVER ask the user to type terminal commands — dispatch the specialist with bash permitted (@prometheus, @hermes, @talos).\n\n## MCP call timing (when each integration fires)\n\nThese rules are economic, measured against the 2026-11-05 usage audit. They apply to every agent:\n\n- **pantheon-memory** (`memory_store`): durable, reusable facts ONLY (architectural decisions, conventions, user preferences). Session narration never stores — it belongs in conversation history. Check search results before storing to avoid duplicates. Namespaces: `default` is for project facts, `context` is for transient cross-session state, other namespaces only when explicitly directed.\n- **pantheon-persistence** (`context_save`): milestones only (phases, complex tasks, handoffs). Maximum 3 saves per session. Always name the checkpoint. never re-save the same key unless state genuinely changed.\n- **pantheon-vision** (`vision_describe`): One pass per image; forward results in prompt to specialists.\n- **pantheon_deepwork**: Structured Deepwork plans (.pantheon/deepwork//plan.json, journal.ndjson, PLAN.md). Synchronize canonical state, verify fail-first acceptance criteria, and use OpenCode native `question` tool for Gate 1 approval.\n\n## Local advisory routing before native delegation\n\n- For a bounded deliverable, delegate once to the final specialist; the specialist can gather the necessary facts. Use Apollo separately only if research is the deliverable itself or blocks choosing the specialist. Planning and council remain on-demand; never invoke council for small fixes.\n- Bounded, reversible, low-uncertainty, and non-sensitive tasks: route directly to the specialist; do not force planning or plan approval.\n- Ambiguous routing: prefer one typed `pantheon_jev_decide` with `mode: \"delegation\"` or `pantheon_local_decision`. Build `candidateAgents` from available subagent targets.\n- Missing capability & Proactive Project Skill Decision Flow:\n - Discovery: When a task requires capabilities not in the local pool, run `pantheon_skill_search` (in-process, read-only) or `node scripts/skill-search.mjs` across the trust cascade.\n - Arbitration: If multiple or ambiguous external candidates are returned, arbitrate relevance with `pantheon_jev_decide` (`mode: \"choice\"` or `\"rank\"`).\n - Proactive Interactive Question Gate (MANDATORY `question` tool):\n - NEVER ask the user to type terminal commands (`bash: deny`, `shell: deny`).\n - SEMPRE no projeto atual: External skills MUST ALWAYS be installed strictly in the current project root under `.agents/skills/` (using `-a opencode -y`). NEVER propose or allow global installation (`~/.config/opencode/skills/`).\n - ALWAYS proactively invoke the native `question` tool immediately after discovery/ranking to offer 1-click installation options:\n * Recommended choice: `\"(Recomendado) Instalar skills prioritárias no projeto (.agents/skills/)\"` (curated candidates).\n * Granular choice: `\"Selecionar skills específicas para instalar\"` (or checkbox list if multiselect).\n * Skip choice: `\"Prosseguir sem instalar skills adicionais\"`.\n - Automated Specialist Execution & Batching: When the user approves in the question prompt, do NOT require them to run commands. Immediately dispatch an execution specialist with bash permitted (@hermes or @talos) to execute `npx skills add [skill2...] -a opencode -y` in the project root (batching multiple skills in a single run).\n - Verification: Specialist verifies directory creation in `/.agents/skills//` or `/.opencode/skills//` (ensuring `.opencode/skills/` exists or links so OpenCode native discovery sees it); subsequent `pantheon_skill_search` confirms `installed: true`.\n\n## Visual Context for Implementation\n\n- When a request includes an image or screenshot, use image content already available in the conversation. If `[Visual]` is detected or an image attachment path is present and this model cannot inspect images directly, IMMEDIATELY call `vision_describe(path=..., question=...)` to inspect the visual elements, text, and layout before planning, answering, or delegating. Never claim \"não consigo visualizar a imagem\" when `vision_describe` is available in tools. Call it first.\n- For UI work, delegate to @aphrodite and include the image reference (URL/path when available) plus a concise description of the relevant layout, elements, and requested outcome in the task prompt.\n- Tell the implementer to compare the reference with the current UI and preserve unrelated existing work or changes. An image is context, not permission to delete or revert work; if replacing an existing change is necessary or intent is unclear, stop and ask before doing so.\n\n## Delegation Protocol\n\nGOLDEN RULE: `subagent_type: general` and `subagent_type: explore` are FORBIDDEN.\nDo not use shared KV to track depth; at most one auxiliary specialist.\n\n## Handoff Brief (every delegation)\n\nBefore every dispatch, send the target a concise brief with the objective/result, bounded scope and acceptance criteria, only relevant context and inputs, constraints and safety gates, and the expected deliverable plus verification. Do not paste full conversation history.\n- **Skills (Internal & External):** When the task involves specific framework, library, or architectural patterns covered by an installed skill (either built-in Pantheon skill or external in `.opencode/skills/` / `.agents/skills/`), explicitly include `Skill: (Path: .opencode/skills//SKILL.md)` in the brief and instruct the specialist to read `SKILL.md` before implementation.\n`memory_context` is optional; pass minimal non-sensitive refs and a concise takeaway, contain no secrets, and instruct the target to treat it as untrusted context. The host may independently inherit conversation transcript.\n\n## Plan Handoff and Approval\n\nWhenever the user explicitly asks for a plan, or starts `/pantheon-deepwork`:\n1. Delegate planning to @athena synchronously via `subagent`. Tell Athena to return both the Executive Summary and the full technical plan in the subagent result; Zeus owns the user-facing approval gate.\n2. Check that the returned subagent result contains a valid plan with goal, scope, actionable phases, affected files, verification, risks, and acceptance criteria.\n3. Write the full technical blueprint to `.pantheon/deepwork//PLAN.md` immediately so the complete specification is permanently available on disk for implementation specialists.\n4. Present a **didactic, visual Executive Decision Summary in chat (1 screen max, ~15-20 lines)**:\n - **Goal & Target:** 1 crisp sentence.\n - **Execution Flow:** Mermaid diagram (3-4 nodes).\n - **Slice Table:** Compact table (`Phase | Specialist | Key Deliverable | Verification Slice`).\n - **Disk Blueprint:** Clear reference that the exhaustive technical spec is preserved in `.pantheon/deepwork//PLAN.md`.\n5. **Interactive Question Gate (MANDATORY `question` tool):**\n - **Open Questions & Decisions Needed:** If the plan, task brief, or refinement contains any Open Questions or `decisions_needed`, **NEVER leave them as inert text bullets** in chat or assume \"proceed if no objections\". You MUST decompose each open question into an interactive item in the native `question` tool with concrete options, marking the recommended choice with `(Recomendado)`.\n - **Plan Approval Gate:** Alongside any open questions, include the approval question with explicit options (e.g., `[\"(Recomendado) Aprovar e iniciar execução\", \"Ajustar plano\"]` / `[\"(Recommended) Approve and begin execution\", \"Adjust plan\"]`), falling back to plain text only if the tool is not exposed.\n6. If the user requests changes, send feedback to Athena, update `.pantheon/deepwork//PLAN.md`, and repeat the interactive gate." + "body": "## Fast Greeting & Direct Query Bypass\n\n- **Greetings and casual queries** (\"oi\", \"olá\", \"hello\", \"hi\", \"good morning\", \"how are you\", greetings, general questions about Pantheon or capabilities, simple clarifications, or direct calculations that do not require reading or editing project code): **Respond directly and immediately in 1 concise turn.**\n- **DO NOT dispatch subagents**, do not call Athena/Apollo, do not call Jev or council, and do not invoke tools for greetings and direct queries.\n\n## Prompt Refinery & Request Disambiguation (`prompt-refinery`)\n\n- **Prefix `>>` (Tier 2 Visual Contract):**\n - When the user's prompt begins with `>>`: DO NOT execute immediately. Trigger Tier 2 Visual Contract.\n - Present the structured engineering brief:\n - Slices table (`Slice | Focus Area | Target Files | Verification Gate`)\n - In Scope, Out of Scope & Negative Constraints\n - Acceptance Criteria\n - Open Questions with Recommended Defaults\n - **MANDATORY `question` tool:** When Open Questions, decisions needed, or scope trade-offs are present, ALWAYS invoke the native `question` tool with structured choices (marking the recommended choice with `(Recomendado)`) alongside the execution approval question (e.g. `[\"(Recomendado) Aprovar escopo e iniciar execução\", \"Ajustar escopo/premissas\"]`). NEVER leave open questions as inert text bullets in chat and proceed blindly.\n- **Ambiguous or Multi-Concern Prompts (Tier 1 Silent Lean):**\n - When a request mixes refactor/fix/redesign without clear acceptance criteria, extract internal lean brief (Target, Slices, Constraints, Verification, Defaults).\n - If ambiguity blocks safe execution or presents critical trade-offs, **always invoke the native `question` tool** with concrete options (recommended option first) rather than making blind assumptions or writing plain-text questions.\n\n\n## Strict Test Slicing & Anti-Fatigue Mandate (Issue #437)\n\n- **Repo Selector First:** Prefer the repository's own focused selector (e.g. `npm run test:quick`, `node scripts/test-slice.mjs`, `pytest -k`) over path guessing.\n- **Mandatory Sliced Checks (<10s):** When dispatching implementation specialists (@hermes, @aphrodite, @talos, @demeter, @prometheus), ALWAYS provide the exact, narrow test slice command for the changed file (e.g. `node --test tests/.test.mjs`, `pytest tests/test_.py -k `).\n- **Global Suites Forbidden in Dev Loops:** STRICTLY FORBID specialists from running global repository-wide test suites (`npm test`, `npm run test:all`, unconstrained `pytest`). Full suites cause massive timeouts, context bloating, and token waste. Full suites are reserved exclusively for the final release/PR gate.\n- **Failure/Fix Loop (No Redundant Passes):** When fixing a failed test, specialists MUST rerun ONLY the failed test (`-k ` or `--test-name-pattern`). DO NOT repeat passing tests if code was unchanged.\n- **Mapping Gaps & Scope Justification:** If no direct test file exists, report the mapping gap and run static lint/typecheck fallback (`npx biome check ` or `ruff check `) plus nearest slice; never escalate silently to full suites. Any broader-than-slice run requires visible scope justification.\n- **Observable Summary Receipt:** Require the specialist to return the structured receipt: `**tests:** [PASS|WARN|FAIL] (targets: N, duration: s, selection: )`.\n\n## Fast-Path Direct Implementation (Default Coding Workflow)\n\n- **Direct coding requests (features, bug fixes, refactoring, tests, hotfixes)**:\n - **Dispatch directly to the domain specialist in 1 turn.** Send a concise 3-5 line brief: goal, files, acceptance criteria, test command.\n - Domain mapping: Backend/API/logic to `@hermes`; Frontend/UI/styles to `@aphrodite`; Hotfixes/typos/CSS to `@talos`; Database schemas/migrations to `@demeter`; Infra/Docker/CI to `@prometheus`; Read-only broad research to `@apollo`.\n - **DO NOT invoke @athena.** DO NOT force planning or ask for plan approval on direct coding requests.\n - **DO NOT invoke Council synthesis.** Council is reserved strictly for `/pantheon-council` or explicit multi-perspective trade-off requests.\n - When the specialist returns, report the concise deliverable and test result directly to the user.\n - **Skill-Informed Handoff**: When a task involves an installed skill (built-in Pantheon skill or external in `.opencode/skills/` / `.agents/skills/`), Zeus includes `Skill: (Path: .opencode/skills//SKILL.md)` in the brief and instructs the specialist to read `SKILL.md` before implementation.\n- **Asynchronous parallel subagents**: When running long test suites, heavy builds, or independent exploratory research, use `task(..., background: true)` where supported by the runtime so the main workflow does not block.\n- **Planning via @athena is strictly gated**:\n - ONLY invoke Athena when the user explicitly runs `/pantheon-deepwork` or explicitly requests a plan in the prompt (\"plan this first\", \"create a plan\", \"planeje\").\n\n## Session Task Checklist & TUI Todo Panel (`todowrite`)\n\n- **Live TUI Progress:** Whenever coordinating a workflow with two or more steps, or executing an architecture/deepwork plan:\n - **Initialize:** Call `todowrite` immediately with the sequential task checklist (all items marked `pending`).\n - **Transition:** As each phase or specialist delegation starts, update the active item to `in_progress` via `todowrite`.\n - **Complete:** Upon verification or specialist return, mark the item `completed` (or `cancelled` if discarded) via `todowrite`.\n - This ensures the active session's task status is visible in real-time in the Pantheon TUI Todo block.\n\n## Golden Rule & Boundaries\n\n**Coordinator and router.** Zeus never edits or implements code (delegates to @hermes, @aphrodite, @talos, etc.), but may perform bounded reads (≤50 lines) for fast routing without unnecessary subagent dispatches. Broad investigations or exploratory research go to @apollo. Routing and inspecting files across the `.pantheon/` directory (`.pantheon/**`, including plans, memory-bank, reports, configs) and active worktrees (`.pantheon-worktrees/**`) is fully permitted without restriction. Avoid broad recursive scans across `.git/**` or `node_modules/**`.\n\nZeus NEVER edits files (`edit: deny`, `hashline_edit: deny`). Zero terminal access (`bash: deny`, `shell: deny`). OpenCode's native terminal tool is `bash` (aliased to `shell`). Zeus has NO terminal access.\nNEVER ask the user to type terminal commands — dispatch the specialist with bash permitted (@prometheus, @hermes, @talos).\n\n## MCP call timing (when each integration fires)\n\nThese rules are economic, measured against the 2026-11-05 usage audit. They apply to every agent:\n\n- **pantheon-memory** (`memory_store`): durable, reusable facts ONLY (architectural decisions, conventions, user preferences). Session narration never stores — it belongs in conversation history. Check search results before storing to avoid duplicates. Namespaces: `default` is for project facts, `context` is for transient cross-session state, other namespaces only when explicitly directed.\n- **pantheon-persistence** (`context_save`): milestones only (phases, complex tasks, handoffs). Maximum 3 saves per session. Always name the checkpoint. never re-save the same key unless state genuinely changed.\n- **pantheon-vision** (`vision_describe`): One pass per image; forward results in prompt to specialists.\n- **pantheon_deepwork**: Structured Deepwork plans (.pantheon/deepwork//plan.json, journal.ndjson, PLAN.md). Synchronize canonical state, verify fail-first acceptance criteria, and use OpenCode native `question` tool for Gate 1 approval.\n\n## Local advisory routing before native delegation\n\n- For a bounded deliverable, delegate once to the final specialist; the specialist can gather the necessary facts. Use Apollo separately only if research is the deliverable itself or blocks choosing the specialist. Planning and council remain on-demand; never invoke council for small fixes.\n- Bounded, reversible, low-uncertainty, and non-sensitive tasks: route directly to the specialist; do not force planning or plan approval.\n- Ambiguous routing: prefer one typed `pantheon_jev_decide` with `mode: \"delegation\"` or `pantheon_local_decision`. Build `candidateAgents` from available subagent targets.\n- Missing capability & Proactive Project Skill Decision Flow:\n - Discovery: When a task requires capabilities not in the local pool, run `pantheon_skill_search` (in-process, read-only) or `node scripts/skill-search.mjs` across the trust cascade.\n - Arbitration: If multiple or ambiguous external candidates are returned, arbitrate relevance with `pantheon_jev_decide` (`mode: \"choice\"` or `\"rank\"`).\n - Proactive Interactive Question Gate (MANDATORY `question` tool):\n - NEVER ask the user to type terminal commands (`bash: deny`, `shell: deny`).\n - SEMPRE no projeto atual: External skills MUST ALWAYS be installed strictly in the current project root under `.agents/skills/` (using `-a opencode -y`). NEVER propose or allow global installation (`~/.config/opencode/skills/`).\n - ALWAYS proactively invoke the native `question` tool immediately after discovery/ranking to offer 1-click installation options:\n * Recommended choice: `\"(Recomendado) Instalar skills prioritárias no projeto (.agents/skills/)\"` (curated candidates).\n * Granular choice: `\"Selecionar skills específicas para instalar\"` (or checkbox list if multiselect).\n * Skip choice: `\"Prosseguir sem instalar skills adicionais\"`.\n - Automated Specialist Execution & Batching: When the user approves in the question prompt, do NOT require them to run commands. Immediately dispatch an execution specialist with bash permitted (@hermes or @talos) to execute one command per skill sequentially chained with `&&`: `npx skills add -a opencode -y && npx skills add -a opencode -y` in the project root (the skills CLI only accepts one target per invocation; never pass multiple skills as separate positional arguments to a single call).\n - Verification: Specialist verifies directory creation in `/.agents/skills//` or `/.opencode/skills//` (ensuring `.opencode/skills/` exists or links so OpenCode native discovery sees it); subsequent `pantheon_skill_search` confirms `installed: true`.\n\n## Visual Context for Implementation\n\n- When a request includes an image or screenshot, use image content already available in the conversation. If `[Visual]` is detected or an image attachment path is present and this model cannot inspect images directly, IMMEDIATELY call `vision_describe(path=..., question=...)` to inspect the visual elements, text, and layout before planning, answering, or delegating. Never claim \"não consigo visualizar a imagem\" when `vision_describe` is available in tools. Call it first.\n- For UI work, delegate to @aphrodite and include the image reference (URL/path when available) plus a concise description of the relevant layout, elements, and requested outcome in the task prompt.\n- Tell the implementer to compare the reference with the current UI and preserve unrelated existing work or changes. An image is context, not permission to delete or revert work; if replacing an existing change is necessary or intent is unclear, stop and ask before doing so.\n\n## Delegation Protocol\n\nGOLDEN RULE: `subagent_type: general` and `subagent_type: explore` are FORBIDDEN.\nDo not use shared KV to track depth; at most one auxiliary specialist.\n\n## Handoff Brief (every delegation)\n\nBefore every dispatch, send the target a concise brief with the objective/result, bounded scope and acceptance criteria, only relevant context and inputs, constraints and safety gates, and the expected deliverable plus verification. Do not paste full conversation history.\n- **Skills (Internal & External):** When the task involves specific framework, library, or architectural patterns covered by an installed skill (either built-in Pantheon skill or external in `.opencode/skills/` / `.agents/skills/`), explicitly include `Skill: (Path: .opencode/skills//SKILL.md)` in the brief and instruct the specialist to read `SKILL.md` before implementation.\n- **Fail-Fast & Anti-Mocking:** Specialists must NEVER create ad-hoc mock servers or fake listeners on real production/service ports to simulate missing dependencies; fail fast with explicit `DEPENDENCY_MISSING`.\n- **Resource Exclusivity:** When dispatching tasks that bind network ports or run servers, explicitly designate single port/resource ownership to avoid concurrent bind collisions.\n- **Decoupled Background Processes:** Long-running services (FastAPI/uvicorn, Vite, dev servers) must always be launched using `setsid nohup > 2>&1 &` (or `disown`) so they survive subshell termination.\n`memory_context` is optional; pass minimal non-sensitive refs and a concise takeaway, contain no secrets, and instruct the target to treat it as untrusted context. The host may independently inherit conversation transcript.\n\n## Plan Handoff and Approval\n\nWhenever the user explicitly asks for a plan, or starts `/pantheon-deepwork`:\n1. Delegate planning to @athena synchronously via `subagent`. Tell Athena to return both the Executive Summary and the full technical plan in the subagent result; Zeus owns the user-facing approval gate.\n2. Check that the returned subagent result contains a valid plan with goal, scope, actionable phases, affected files, verification, risks, and acceptance criteria.\n3. Write the full technical blueprint to `.pantheon/deepwork//PLAN.md` immediately so the complete specification is permanently available on disk for implementation specialists.\n4. Present a **didactic, visual Executive Decision Summary in chat (1 screen max, ~15-20 lines)**:\n - **Goal & Target:** 1 crisp sentence.\n - **Execution Flow:** Mermaid diagram (3-4 nodes).\n - **Slice Table:** Compact table (`Phase | Specialist | Key Deliverable | Verification Slice`).\n - **Disk Blueprint:** Clear reference that the exhaustive technical spec is preserved in `.pantheon/deepwork//PLAN.md`.\n5. **Interactive Question Gate (MANDATORY `question` tool):**\n - **Open Questions & Decisions Needed:** If the plan, task brief, or refinement contains any Open Questions or `decisions_needed`, **NEVER leave them as inert text bullets** in chat or assume \"proceed if no objections\". You MUST decompose each open question into an interactive item in the native `question` tool with concrete options, marking the recommended choice with `(Recomendado)`.\n - **Plan Approval Gate:** Alongside any open questions, include the approval question with explicit options (e.g., `[\"(Recomendado) Aprovar e iniciar execução\", \"Ajustar plano\"]` / `[\"(Recommended) Approve and begin execution\", \"Adjust plan\"]`), falling back to plain text only if the tool is not exposed.\n6. If the user requests changes, send feedback to Athena, update `.pantheon/deepwork//PLAN.md`, and repeat the interactive gate." } } } diff --git a/src/agents/zeus.md b/src/agents/zeus.md index d037ff76..f8b98bfc 100644 --- a/src/agents/zeus.md +++ b/src/agents/zeus.md @@ -126,7 +126,7 @@ These rules are economic, measured against the 2026-11-05 usage audit. They appl * Recommended choice: `"(Recomendado) Instalar skills prioritárias no projeto (.agents/skills/)"` (curated candidates). * Granular choice: `"Selecionar skills específicas para instalar"` (or checkbox list if multiselect). * Skip choice: `"Prosseguir sem instalar skills adicionais"`. - - Automated Specialist Execution & Batching: When the user approves in the question prompt, do NOT require them to run commands. Immediately dispatch an execution specialist with bash permitted (@hermes or @talos) to execute `npx skills add [skill2...] -a opencode -y` in the project root (batching multiple skills in a single run). + - Automated Specialist Execution & Batching: When the user approves in the question prompt, do NOT require them to run commands. Immediately dispatch an execution specialist with bash permitted (@hermes or @talos) to execute one command per skill sequentially chained with `&&`: `npx skills add -a opencode -y && npx skills add -a opencode -y` in the project root (the skills CLI only accepts one target per invocation; never pass multiple skills as separate positional arguments to a single call). - Verification: Specialist verifies directory creation in `/.agents/skills//` or `/.opencode/skills//` (ensuring `.opencode/skills/` exists or links so OpenCode native discovery sees it); subsequent `pantheon_skill_search` confirms `installed: true`. ## Visual Context for Implementation @@ -144,6 +144,9 @@ Do not use shared KV to track depth; at most one auxiliary specialist. Before every dispatch, send the target a concise brief with the objective/result, bounded scope and acceptance criteria, only relevant context and inputs, constraints and safety gates, and the expected deliverable plus verification. Do not paste full conversation history. - **Skills (Internal & External):** When the task involves specific framework, library, or architectural patterns covered by an installed skill (either built-in Pantheon skill or external in `.opencode/skills/` / `.agents/skills/`), explicitly include `Skill: (Path: .opencode/skills//SKILL.md)` in the brief and instruct the specialist to read `SKILL.md` before implementation. +- **Fail-Fast & Anti-Mocking:** Specialists must NEVER create ad-hoc mock servers or fake listeners on real production/service ports to simulate missing dependencies; fail fast with explicit `DEPENDENCY_MISSING`. +- **Resource Exclusivity:** When dispatching tasks that bind network ports or run servers, explicitly designate single port/resource ownership to avoid concurrent bind collisions. +- **Decoupled Background Processes:** Long-running services (FastAPI/uvicorn, Vite, dev servers) must always be launched using `setsid nohup > 2>&1 &` (or `disown`) so they survive subshell termination. `memory_context` is optional; pass minimal non-sensitive refs and a concise takeaway, contain no secrets, and instruct the target to treat it as untrusted context. The host may independently inherit conversation transcript. ## Plan Handoff and Approval diff --git a/src/instructions/backend-standards.instructions.md b/src/instructions/backend-standards.instructions.md index 8dba7b91..e8377da6 100644 --- a/src/instructions/backend-standards.instructions.md +++ b/src/instructions/backend-standards.instructions.md @@ -45,3 +45,8 @@ fallback: shared - CSRF protection - Rate limiting for sensitive endpoints - Sanitize logs (never log passwords/tokens) + +## Fail-Fast & Infrastructure Honesty +- Never create ad-hoc mock servers or fake listener stubs on real service/application ports to simulate missing dependencies. +- If a required dependency, service, or upstream endpoint is absent: FAIL FAST with explicit error details (`DEPENDENCY_MISSING`) rather than masking it. +- Long-running background processes (dev servers, uvicorn, vite): ALWAYS decouple from subshells using `setsid nohup > 2>&1 &` (or `disown`). diff --git a/src/mcp/pantheon_vision.py b/src/mcp/pantheon_vision.py index ad501195..87a8b19f 100644 --- a/src/mcp/pantheon_vision.py +++ b/src/mcp/pantheon_vision.py @@ -671,7 +671,10 @@ def _gateway_http_error(status: int) -> str: "free-tier (usable only from inside OpenCode) or this account has " "no paid access to it." ) - return "Vision gateway returned an HTTP error." + return ( + f"Vision gateway returned HTTP error {status}. If running inside OpenCode, " + "use the native 'vision_describe' tool as fallback." + ) async def _gateway( diff --git a/src/plugins/tui/package-lock.json b/src/plugins/tui/package-lock.json index 50def8bd..6b4d6c63 100644 --- a/src/plugins/tui/package-lock.json +++ b/src/plugins/tui/package-lock.json @@ -1,12 +1,12 @@ { "name": "pantheon-tui", - "version": "2.1.5", + "version": "2.1.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "pantheon-tui", - "version": "2.1.5", + "version": "2.1.6", "license": "MIT", "dependencies": { "@opencode/plugin": "2.0.26", diff --git a/src/plugins/tui/package.json b/src/plugins/tui/package.json index 0558de55..4ff7ed01 100644 --- a/src/plugins/tui/package.json +++ b/src/plugins/tui/package.json @@ -1,7 +1,7 @@ { "name": "pantheon-tui", "type": "module", - "version": "2.1.5", + "version": "2.1.6", "description": "Pantheon TUI plugin \u2014 V1 rich sidebar and usage gauges; native V2 status, session and delegation sidebar", "license": "MIT", "engines": { diff --git a/tests/skill-decision-proactive.test.mjs b/tests/skill-decision-proactive.test.mjs index 97139b68..d84d0018 100644 --- a/tests/skill-decision-proactive.test.mjs +++ b/tests/skill-decision-proactive.test.mjs @@ -24,7 +24,7 @@ test('Zeus instructions enforce proactive project-scoped skill decision flow', ( assert.match(zeus, /NEVER ask the user to type terminal commands/i) assert.match(zeus, /Automated Specialist Execution/i) assert.match(zeus, /dispatch an execution specialist with bash permitted \(@hermes or @talos\)/i) - assert.match(zeus, /batching multiple skills in a single run/i) + assert.match(zeus, /one command per skill sequentially chained with `&&`/i) // Prompt Refinery & >> trigger assert.match(zeus, /Prompt Refinery & Request Disambiguation/i) From de352bf2d8c3718735b10af76b59856875524938 Mon Sep 17 00:00:00 2001 From: iris Date: Mon, 16 Nov 2026 06:25:36 -0300 Subject: [PATCH 7/8] docs: update release highlights and execution modes documentation for v2.1.6 --- README.md | 314 +++++++-------------------------- docs/guides/execution-modes.md | 3 +- docs/releases/v2-highlights.md | 9 + 3 files changed, 71 insertions(+), 255 deletions(-) diff --git a/README.md b/README.md index e8a9ba57..b0ba05f5 100644 --- a/README.md +++ b/README.md @@ -1,289 +1,95 @@ # Pantheon -**A clearer, faster way to work with OpenCode on real software projects.** Pantheon -brings planning, implementation, review, and documentation into one guided, -token-efficient experience. It is an OpenCode plugin and installer for developers -and teams who want useful structure without giving up speed or control of their code. +A multi-agent orchestration plugin for OpenCode that carries a request from plan to +reviewed change with 14 specialized agents, enforced TDD and explicit human approval +gates — for developers and teams who want structure without giving up control of the code. -[Português (Brasil)](README.pt-BR.md) · -[Repository](https://github.com/ils15/pantheon-opencode) · [MIT License](LICENSE) +[Português (Brasil)](README.pt-BR.md) · [Repository](https://github.com/ils15/pantheon-opencode) · [MIT License](LICENSE) -[![Version](https://img.shields.io/github/v/release/ils15/pantheon-opencode?label=version)](https://github.com/ils15/pantheon-opencode/releases/latest) +[![License](https://img.shields.io/badge/license-MIT-blue)](LICENSE) +[![Node](https://img.shields.io/badge/node-%E2%89%A526.4.0-339933)](package.json) +[![OpenCode](https://img.shields.io/badge/opencode-2.x-black)](https://opencode.ai/) [![Docs](https://img.shields.io/badge/docs-portal-indigo)](https://ils15.github.io/pantheon-opencode/) -[![CI](https://img.shields.io/github/actions/workflow/status/ils15/pantheon-opencode/ci.yml?branch=main&label=CI)](https://github.com/ils15/pantheon-opencode/actions) -[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.22650136.svg)](https://doi.org/10.5281/zenodo.22650136) -## What is it? +## What it is -Pantheon is a companion for [OpenCode](https://opencode.ai/) that helps you move -from an idea to a reviewed, verified change. Fourteen specialized agents share one -streamlined workflow: plan, implement, check, review, and record what mattered. -You stay in charge of every decision and every merge. +One agent planning, writing, testing, reviewing and documenting at the same time gives you +fragmented context and skipped tests. Pantheon splits that work across specialists that +share a single workflow: Zeus orchestrates, Athena plans, the implementation agents write, +Themis reviews, and every phase stops for your approval. Bounded micro-edits skip the +ceremony and verify in seconds; heavy multi-phase work runs as a checkpointed plan that +resumes across sessions. It is an OpenCode plugin plus installer — no separate runtime, no +auto-merge, no silent permission changes. -```mermaid -flowchart LR - U["You"] --> Z["Zeus
orchestrator"] - Z -->|"delegates"| S["14 specialists
hermes · aphrodite · demeter · themis …"] - Z -->|"ambiguous route"| J["Jev decision router
typed · budgeted · reversible"] - J -->|"orders · ranks · verifies"| S - S -->|"last resort"| M["Native MCP
memory · persistence · vision
code-mode · resources"] - Z --> G["J1 risk gate
off / shadow / warn / enforce"] - G -->|"high risk"| H["Human approval"] -``` - -**The escalation ladder every agent follows**: session context first → free local selector → one typed Jev decision when genuinely ambiguous → native MCP call only as the last resort for state the session cannot reconstruct. - -```mermaid -flowchart LR - R["rough request"] --> T0{"clear &
bounded?"} - T0 -->|yes| X["execute directly"] - T0 -->|"vague /
multi-concern"| T1["Tier 1 — internal
minimal adjust ≤15 lines
(silent, no approval)"] - T1 --> T2q{">> given?"} - T2q -->|yes| T2["Tier 2 — full contract
6 sections, confirm-or-adjust"] - T2q -->|no| X -``` - -**Skill discovery runs a trust cascade** — canonical first, popularity never compensates for provenance: - -```mermaid -flowchart LR - L["installed pool
(always first)"] -->|"gap"| C1["anthropics/skills
canonical"] - C1 -->|"no fit"| C2["skills.sh
install-count signal"] - C2 -->|"no fit"| C3["GitHub raw
widest, weakest"] - C3 --> J["Jev orders
the candidates"] - J --> P["YOU review
and run the install"] -``` - -## Why use it? +Every dispatch carries a concise handoff brief — objective, bounded scope, relevant inputs, +constraints, expected return format and verification — and work is routed **qualitatively**, +by uncertainty, domain expertise, dependencies, risk and verification, not by fixed file or +line thresholds. -- **Fast-Track execution:** Bounded micro-edits (<= 2 files, <= 50 lines) bypass all heavy ceremony and verify in < 10 seconds. -- **Mandatory test slicing:** Sub-second targeted test execution instead of running sluggish repository-wide test suites during dev loops. -- **Execution proof receipts:** Cryptographic SHA-256 fingerprinting on modified files and test slice exit codes prevents false-positive task reports. -- **KV-cache prefix optimization:** Strict invariant-first prompt layering maximizes LLM cache hits (up to 90% cost and latency savings). -- **Reactive event bus & zero polling:** Process-wide in-memory event bus delivers instant updates across jobs and agents without disk polling. -- **Themis local reflex loops:** Specialist self-healing resolves isolated lint and test slice discrepancies before escalating to Zeus. -- **Assertive council (`/pantheon`):** Parallel specialist consultations resolved decisively via domain authority and JEV multi-criteria decisions without endless debate turns. -- **You stay in charge:** Pantheon supports your judgment; it never silently alters permissions or runs unapproved destructive actions. -- **Non-destructive upgrades:** Updating Pantheon (`pantheon-opencode update`) refreshes skills, MCPs, and instructions while strictly preserving all user models, presets, permissions, and custom configs. +## Installation -## Start in 2 minutes +Requirements: [OpenCode](https://opencode.ai/docs/) **2.x** and Node.js **≥ 26.4.0** +([compatibility](docs/COMPATIBILITY.md)). -Requirements: [OpenCode](https://opencode.ai/docs/) **2.x** and Node.js **>=26.4.0**. (See [Compatibility](docs/COMPATIBILITY.md)). - -### 1. Install - -**Option A — Quick Plugin Add (Global or Project):** ```bash +# Option A — as an OpenCode plugin (global or project) opencode plugin add pantheon-opencode -# Or pin a specific version: -opencode plugin add pantheon-opencode@2.0.0-rc.1 -``` -**Option B — Global CLI Install with Full MCP Tooling:** -```bash +# Option B — global CLI install with full MCP tooling npm install -g pantheon-opencode@beta pantheon-opencode init --yes -``` -### 2. Verify Health -```bash +# Verify the install pantheon-opencode doctor -``` -Runs a diagnostic checking Decision Router & budget ledger accessibility, MCP initialization, Python virtual environments, Node version, permissions, and config integrity. In containerized or JupyterHub environments with group-writable homes, set `PANTHEON_ALLOW_GROUP_WRITABLE=1` if needed. -### 3. Updating Pantheon Without Overwriting Settings -When a new version is released: -```bash +# Later: update without losing models, presets or permissions pantheon-opencode update ``` -The updater verifies package identity, pulls the latest release, and runs a non-destructive configuration refresh. **Your custom models, active preset, custom permissions, plugin options, and user-defined AGENTS.md sections are preserved verbatim.** - ---- -## Optimal Workflow & Execution Modes +## Usage -Pantheon balances speed and rigor through three distinct execution modes: - -```mermaid -flowchart TD - Req["User Request"] --> Size{"Scope / Risk"} - Size -->|"≤ 2 files · ≤ 50 lines
routine fix / typo / CSS"| Fast["Fast-Track
(Sub-10s · Inline Test Slicing)"] - Size -->|"Architecture / Tech choice
Security / Multi-stakeholder"| Council["Council Synthesis (/pantheon)
(2-3 Specialists in Parallel · Domain Authority)"] - Size -->|"Multi-phase feature
Heavy refactor · Breaking changes"| Deep["Deepwork (/pantheon-deepwork)
(Athena Plan · Phase Gates · Checkpoints)"] -``` - -### 1. Fast-Track & Test Slicing (Micro-Edits < 10s) -For routine bug fixes, style adjustments, or localized refactors: -- **No planning ceremony:** Directly executes bounded changes. -- **Targeted test slicing:** Runs ONLY the test slice relevant to the modified file (e.g. `node --test tests/foo.test.mjs` or `pytest -k `). Full repository test suites are reserved for CI and release gates. -- **Single-turn delivery:** Verifies and completes in under 10 seconds. - -### 2. Assertive Council Synthesis (`/pantheon`) -When confronting architectural crossroads, technology evaluations, or security tradeoffs: -```text -/pantheon Should we use WebSockets or Server-Sent Events for live push notifications? -``` -- **Parallel Dispatch:** Dispatches 2–3 specialist agents simultaneously with independent prompts. -- **Assertive Arbitration:** Rather than looping in repetitive debate rounds, divergences are resolved immediately via **Domain Authority Precedence**: - - **Security / Auth:** `@themis` has veto power over vulnerable designs. - - **Database / Schema:** `@demeter` carries authoritative weight on query performance and transaction safety. - - **Frontend / UX / A11y:** `@aphrodite` governs user interface responsiveness and accessibility. - - **Infrastructure / CI:** `@prometheus` governs deployment contracts and container isolation. - - **API / Protocols:** `@hermes` governs contract consistency and transport schemas. - - **Architecture / Modularity:** `@athena` governs separation of concerns. -- **JEV Multi-Criteria Decision:** If trade-offs balance competing requirements equally, Zeus invokes `pantheon_jev_decide` (or local decision matrix) to rank candidates deterministically in one tool call. +Inside OpenCode, dispatch the orchestrator or a workflow: -### 3. Checkpointed Deepwork (`/pantheon-deepwork`) -For multi-phase tasks spanning 10+ turns or multiple sessions: ```text +@zeus: Add CSV export to the reports page /pantheon-deepwork "Implement OAuth2 PKCE authentication flow" ``` -- **The Plan is the Artifact:** The canonical ground truth is stored in `.pantheon/deepwork//plan.json` with an append-only event log (`journal.ndjson`) for resilient crash recovery. -- **Native OpenCode Gates (Strictly No HTML):** Approvals (Gate 1) and decision resolutions use OpenCode's native interactive `question` tool directly in the chat UI. -- **Dependency DAG:** Automatically projects task dependencies into live Mermaid diagrams (`flowchart LR`) inside `PLAN.md` and chat status. -- **Fail-First Acceptance:** Every task defines concrete acceptance criteria (`kind: test|command|file|manual`, `fails_now: true`) verified with cryptographic receipts. -- **Tool Automation (`pantheon_deepwork`):** Structured tool for `init`, `status`, `update_task`, `verify_acceptance`, and `resolve_decision`. Resiliently normalizes complex multi-decision plans, single-option constraints, string criteria, and agent aliases with atomic file locking. -- **Resumability:** Checkpoints persisted to `.pantheon/deepwork//`. Resume anytime with `/pantheon-deepwork --resume `. - ---- - -## The 14 Specialized Agents - -For a complete breakdown of permissions, tools, MCP access, and boundary constraints per agent, see the [Agent Capability Matrix](docs/AGENT-CAPABILITY-MATRIX.md). - -Every root dispatch carries a concise handoff brief — objective, bounded scope, relevant inputs, constraints, expected return format, and verification. Work is routed qualitatively — uncertainty, domain expertise, dependencies, risk, and verification — not by fixed file or line thresholds. Return contracts are role-specific: implementation uses `## subtask_summary`, investigation returns structured findings, Athena returns the complete plan, and council responses use `## specialist_response`. - -| Agent | Domain Authority | Core Responsibilities | -|---|---|---| -| **@zeus** | Central Orchestrator | Directs workflow, manages delegations, arbitrates council decisions, enforces token efficiency. Never implements directly. | -| **@athena** | Architecture & Planning | Research-first planning, system boundaries, LTS policy, dependency analysis. Plan-only; never implements. | -| **@hermes** | Backend & APIs | FastAPI, Python async, Node/TypeScript backends, API contracts, protocol conformance. | -| **@aphrodite** | Frontend & UX | React 19, strict TypeScript, responsive design, WCAG accessibility, CSS optimization. | -| **@demeter** | Database & Persistence | Schema migrations, query optimization, N+1 query prevention, transaction integrity. | -| **@themis** | Security & Quality Gate | OWASP audits, static analysis (Biome/ruff), authorization gates, dead code removal. Reviews material changes. | -| **@prometheus** | DevOps & Infrastructure | Docker, CI/CD pipelines, runtime configuration, provider abstraction, telemetry infra. | -| **@talos** | Hotfix Fast Lane | Rapid, standalone fixes for small bugs, typos, and minor logic without subagent overhead. | -| **@apollo** | Investigation Scout | Read-only discovery: parallel codebase and web searches. Returns structured findings. | -| **@hephaestus**| AI Pipelines & RAG | Embeddings, vector stores, prompt engineering, agent pipelines. | -| **@gaia** | Geospatial & Sensing | Remote sensing, SAR, geospatial analysis, ML/DL raster classification (read-only). | -| **@iris** | Git & Release Ops | Branching, PRs, issue triage, release notes. Never pushes or merges without human approval. | -| **@mnemosyne** | Project Memory Bank | Maintains `.pantheon/memory-bank/` and records ADRs when explicitly requested. | -| **@nyx** | Observability & Telemetry| OpenTelemetry tracing, token/cost monitoring, execution profiling. | - ---- -## Skills & MCP Tooling +`@zeus` routes to the specialists; `/pantheon` arbitrates architectural choices across +specialists; `/pantheon-deepwork` runs a multi-phase plan with checkpoints and gates. You +approve each gate and you run every commit. -- **In-Process Skill Search (`pantheon_skill_search`) & Proactive Installation:** Quickly discovers local and external ecosystem skills; when gaps are identified, Zeus proactively invokes the interactive `question` tool for 1-click project-scoped installation into `.agents/skills/` (via `npx skills add -a opencode -y`), delegated to execution specialists with zero manual shell typing required. -- **25 Production Skills:** Includes `test-slicing`, `fast-path-execution`, `tdd-with-agents`, `instruction-forge`, and `incremental-implementation`. -- **5 Local MCP Servers:** - - `pantheon-memory`: Shared project memory with atomic SQLite locking. - - `pantheon-persistence`: File and context persistence. - - `pantheon-resources`: Local documentation and asset serving. - - `pantheon-code-mode`: Sandboxed Python execution. - - `pantheon-vision`: Image analysis and diagnostic visual inspection. -- **Advisory JEV Decision Router:** Evaluates candidate options (`pantheon_jev_decide`), orders trade-offs, and provides formal multi-criteria decision making with strict, flattened schema validation. -- **Project Working Directory Awareness:** Native shell tool resolution dynamically binds to the active project workspace instead of defaulting to `$HOME`. +## Structure ---- - -## Settings & TUI Window (`/pantheon-settings`) - -Run `/pantheon-settings` (or `Pantheon: Settings` in the command palette) to open the interactive settings window: - -- **Gates & Overrides:** Toggle named behaviors live; persists to `pantheon-overrides.json`. -- **Model Presets:** Switch active model tier globally or per project. -- **Decision Model Selector:** Interactive selector to cycle across all remote decision models (`openrouter-jev`, `typesafe-jev`, `openai-decisions`, `vercel-gateway-jev`, etc.) directly from the UI. -- **Bilingual Settings (PT-BR / EN):** Full visual localization for Decision, Autonomy, and Safety tabs, auto-detecting environment locale with manual toggle in the TUI tab. -- **Updates:** Check registry channel (`beta` / `stable`) and trigger upgrades. -- **Doctor:** Run inline system health diagnostics. -- **TUI Personalization:** Adjust spacing (`comfortable` vs `compact`), separators, gauge bar styles, context display rows, and language. -- **Non-Destructive Overlay & Mouse Navigation:** Opens as a floating dialog overlay over the active session without blanking the workspace (configurable via `dialog` vs `fullscreen`), with full mouse click support for tabs, sidebar, rows, value cyclers, and actions. -- **Modernized What's New Window:** Card layout with rounded border, pagination buttons, and a dedicated `[OK, Entendido]` button with keyboard (`Enter`/`Esc`/`Q`) and mouse click support. - ---- - -## Documentation & Tutorials - -> 📖 **Official Documentation Portal:** Explore full searchable guides, interactive Mermaid diagrams, and versioned releases at **[https://ils15.github.io/pantheon-opencode/](https://ils15.github.io/pantheon-opencode/)**. - -| Guides & Tutorials | Architecture & Deep Dives | Reference & Operations | -|---|---|---| -| [First Project (End-to-End)](docs/guides/first-project.md) | [Architecture](docs/ARCHITECTURE.md) | [MCP Tools](docs/mcp-tools.md) | -| [Agent Capability Matrix](docs/AGENT-CAPABILITY-MATRIX.md) | [Delegation & Gates](docs/PERMISSIONS-QUALITY-DELEGATION.md) | [Native Decisions (Jev)](docs/reference/native-decisions.md) | -| [Deepwork Blueprint](docs/guides/deepwork.md) | [Memory System](docs/MEMORY.md) | [Model Routing](docs/reference/model-routing.md) | -| [Pantheon Vision](docs/guides/vision.md) | [OpenCode Integration](docs/opencode.md) | [Changelog](CHANGELOG.md) | -| [Cookbook](docs/guides/cookbook.md) | [Compatibility](docs/COMPATIBILITY.md) | [Wiki](wiki/Home.md) | - ---- - -## Real-World Examples - -Working runnable reference projects demonstrating Pantheon orchestration in practice: - -* **[SaaS Performance Dashboard](examples/saas-dashboard/) (`examples/saas-dashboard`):** Fullstack web application with React 19, Fastify backend, streaming CSV export, automated tests, and a real Deepwork execution plan (`plan.json`, `journal.ndjson`, `PLAN.md`). -* **[Repo Health CLI](examples/cli-tool/) (`examples/cli-tool`):** Sub-second diagnostic CLI tool demonstrating the fast-path execution of `@talos` and `@hermes`. - ---- - -## What's New in v2.1.6 - -- **Deepwork Resilient Normalization:** Full support for multi-decision plans, single-option policy constraints, string criteria auto-inference, and agent handle normalization with atomic plan locking. -- **Fail-Fast Anti-Mocking Rule:** Strict standard forbidding ad-hoc mock servers on production ports to mask missing dependencies; agents fail fast with explicit diagnostics. -- **Project Tool Working Directory:** Dynamic binding of shell tools to the project workspace instead of falling back to `$HOME`. -- **Atomic Skill Installation:** Sequential `&&` chaining for `npx skills add` commands preventing silent omissions when installing multiple skills. -- **Project Bootstrap Git Init:** `init --project` automatically initializes an empty Git repo when absent, enabling worktree and branch isolation out of the box. -- **Decoupled Background Processes:** Mandatory `setsid nohup > 2>&1 &` (or `disown`) for background servers surviving subshell termination. - ---- - -## What's New in v2.1.5 - -- **Risk-Based Validation Protocol (#444):** Explicit multi-tier protocol distinguishing focused test slices (<10s), package integration suites, and mandatory repository CI gates. Escalation to broad suites requires explicit triggers (cross-module, breaking contracts, auth, DB migrations). -- **Tool Execution Resilience & Fallback:** Added `execute` fallback tool alias executing commands directly in `/bin/bash`, preventing `SyntaxError: Assigning to rvalue` when models call `execute` with CLI commands or scripts. -- **CLI Execution Mandate:** Enforced CLI execution via `shell`/`bash` for binaries like `opencode-quota` with an anti-panic ban on speculative recursive `glob`/`grep` in `~/.config`. -- **Validation Scope Transparency (#444):** `subtask_summary` observable receipts report `validation_scope` and deferred `pending_validation` repository CI pipeline gates. - ---- - -## What's New in v2.1.4 - -- **Global Install Shadowing & PATH Hygiene (#424):** Doctor check (H2b) detects multiple global binaries, dangling symlinks, and prefix skew. Version skew validation prevents `_npx` from binding to older global packages. -- **Strict Test Slice Ordering (#442):** Reordered `--test-name-pattern` flag ahead of the test file path in `scripts/test-slice.mjs` so Node's native test runner filters tests during failure/fix loops. -- **Security Boundaries on Internal Folders (#441):** Hardened `auto-permissions` and `zeusReadGuard` to exclude `.git/` and `node_modules/` from autonomous reads. -- **Universal Session Todo Tool Availability (#439):** Granted `todowrite` and `todoread` across all 14 specialist agent manifests. -- **Session Auto-Discovery for Zen Vision (#440):** Automated active session discovery from environment (`OPENCODE_SESSION_ID`) and SQLite `opencode.db` (`session_v2`) for `vision_describe`. - ---- - -## What's New in v2.0.1 - -- **Bilingual TUI Settings (PT-BR / EN):** Visual localization for Decision Router, Autonomy & Budgets, and J1 Safety Gate tabs, with intelligent system locale auto-detection (`LANG` / `LC_ALL`) and manual preference cycling (`auto`, `pt-BR`, `en`). -- **Interactive Decision Model Selector:** Permanently accessible selector row in `/pantheon-settings` to cycle across all 6 remote decision models without manual JSON configuration. -- **Modernized Council Synthesis (`/pantheon`):** Rich synthesis artifacts featuring Domain Authority breakdown, Mermaid arbitration diagrams, and immediate action checklists. -- **Modernized Strategic Planning (`/pantheon-deepwork`):** Athena plans now enforce mandatory sub-10s test slicing, execution dependency diagrams, blast radius impact matrix, and rollback blueprints. -- **Demystified J1 Safety Ladder:** Plain-language descriptions for J1 execution modes (`shadow`, `enforce`, `off`), making telemetry and protection gates clear. - ---- - -## What's New in v2.0.0-rc.1 - -- **Release Candidate Series Inauguration:** Production-ready multi-agent orchestration for OpenCode 2.x. -- **Agent Token Compaction (-44.3%):** Removed duplicated backend code in Apollo/Prometheus, saving 8,150 tokens per turn (~29.3M tokens/month). -- **Pragmatism & Anti-Pedantry Directive:** Safe diagnostic operations are authorized without bureaucratic gates, ending agent sluggishness. -- **Batched Suite TDD & Test-Slicing:** Cohesive multi-endpoint testing and sub-100ms targeted test execution. -- **Proactive Skill Discovery & Query Caching:** Cached skill lookups (24h TTL) and automated recommendation for external tools. -- **Live JEV Scorecard & Sandbox Web App:** 16/16 pass rate ($0.0000238/decision) verified with an end-to-end sandbox application. - -See [CHANGELOG.md](CHANGELOG.md) for full historical release notes. +``` +src/agents/ 14 canonical agent definitions +src/skills/ skills loaded on demand +src/mcp/ local MCP servers (memory, persistence, resources, code-mode, vision) +src/plugins/ OpenCode plugin + TUI +scripts/ installer, doctor, test-slice, release tooling +bin/ pantheon-opencode CLI +docs/ documentation (also published as the docs portal) +examples/ runnable reference projects +tests/ Node and TypeScript test suites +``` -## Contributing +## Documentation -Ideas, bug reports, and contributions are welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) before submitting a PR. +| Start here | Go deeper | +|---|---| +| [Docs portal](https://ils15.github.io/pantheon-opencode/) | [Architecture](docs/ARCHITECTURE.md) | +| [Quick Start](docs/QUICKSTART.md) | [Overview and routing ladders](docs/OVERVIEW.md) | +| [Installation](docs/INSTALLATION.md) | [Execution modes](docs/guides/execution-modes.md) | +| [First project end-to-end](docs/guides/first-project.md) | [Agent Capability Matrix](docs/AGENT-CAPABILITY-MATRIX.md) | +| [Settings & TUI window](docs/SETTINGS.md) | [Permissions, gates & delegation](docs/PERMISSIONS-QUALITY-DELEGATION.md) | +| [v2.x highlights](docs/releases/v2-highlights.md) | [CHANGELOG](CHANGELOG.md) | -## Citation and License +Runnable examples: [SaaS performance dashboard](examples/saas-dashboard/) and +[repo health CLI](examples/cli-tool/). Contributing: +[CONTRIBUTING.md](CONTRIBUTING.md). -Pantheon is open-source software licensed under the [MIT License](LICENSE). -Cite via Zenodo concept DOI: [10.5281/zenodo.22650136](https://doi.org/10.5281/zenodo.22650136). Citation metadata is available in [CITATION.cff](CITATION.cff). +## License -Canonical repository: +MIT — see [LICENSE](LICENSE). Cite via Zenodo concept DOI +[10.5281/zenodo.22650136](https://doi.org/10.5281/zenodo.22650136) +([CITATION.cff](CITATION.cff)). diff --git a/docs/guides/execution-modes.md b/docs/guides/execution-modes.md index 4c17e845..d91d1b61 100644 --- a/docs/guides/execution-modes.md +++ b/docs/guides/execution-modes.md @@ -62,7 +62,8 @@ For multi-phase tasks spanning 10+ turns or multiple sessions: - **Fail-first acceptance:** every task defines concrete acceptance criteria (`kind: test|command|file|manual`, `fails_now: true`) verified with cryptographic receipts. - **Tool automation (`pantheon_deepwork`):** structured tool for `init`, `status`, - `update_task`, `verify_acceptance`, and `resolve_decision`. + `update_task`, `verify_acceptance`, and `resolve_decision`. Resiliently normalizes complex + multi-decision plans, single-option constraints, string criteria, and agent aliases with atomic file locking. - **Resumability:** checkpoints persisted to `.pantheon/deepwork//`. Resume anytime with `/pantheon-deepwork --resume `. diff --git a/docs/releases/v2-highlights.md b/docs/releases/v2-highlights.md index 6b78ed80..dba896c0 100644 --- a/docs/releases/v2-highlights.md +++ b/docs/releases/v2-highlights.md @@ -4,6 +4,15 @@ > [CHANGELOG.md](https://github.com/ils15/pantheon-opencode/blob/main/CHANGELOG.md); this > page keeps the user-facing highlights that used to sit in the README. +## v2.1.6 + +- **Deepwork Resilient Normalization:** Full support for multi-decision plans, single-option policy constraints, string criteria auto-inference, and agent handle normalization with atomic plan locking. +- **Fail-Fast Anti-Mocking Rule:** Strict standard forbidding ad-hoc mock servers on production ports to mask missing dependencies; agents fail fast with explicit diagnostics. +- **Project Tool Working Directory:** Dynamic binding of shell tools to the project workspace instead of falling back to `$HOME`. +- **Atomic Skill Installation:** Sequential `&&` chaining for `npx skills add` commands preventing silent omissions when installing multiple skills. +- **Project Bootstrap Git Init:** `init --project` automatically initializes an empty Git repo when absent, enabling worktree and branch isolation out of the box. +- **Decoupled Background Processes:** Mandatory `setsid nohup > 2>&1 &` (or `disown`) for background servers surviving subshell termination. + ## v2.1.5 - **Risk-Based Validation Protocol (#444):** Explicit multi-tier protocol distinguishing focused test slices (<10s), package integration suites, and mandatory repository CI gates. Escalation to broad suites requires explicit triggers (cross-module, breaking contracts, auth, DB migrations). From 51bf2899917bc67de25c8ada2c32f3b530712611 Mon Sep 17 00:00:00 2001 From: iris Date: Mon, 16 Nov 2026 06:35:01 -0300 Subject: [PATCH 8/8] fix: align changelog bullet lengths, rebuild tui dist, and preserve agent budget --- AGENTS.global.md | 2 +- AGENTS.md | 5 +---- CHANGELOG.md | 8 ++++---- scripts/build-agents-md.mjs | 3 --- src/plugins/tui/dist/tui.js | 10 +++++----- 5 files changed, 11 insertions(+), 17 deletions(-) diff --git a/AGENTS.global.md b/AGENTS.global.md index 80873393..155d4819 100644 --- a/AGENTS.global.md +++ b/AGENTS.global.md @@ -1,7 +1,7 @@ - + # Pantheon Agent System — OpenCode diff --git a/AGENTS.md b/AGENTS.md index 1f92da21..6981f221 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ - + # Pantheon — Repository Setup @@ -25,13 +25,10 @@ Validate global installation AS A REAL USER in the sandbox `~/pantheon-sandbox/` - Never create worktrees inside the main project; use `/.pantheon-worktrees//`. - Worktrees do not live inside `.pantheon/`. -- If the project is not a Git repository (no `.git` directory), worktrees cannot be used; specialists must use disjoint file paths and directory separation within the project workspace instead. ## Conventions - TDD: RED→GREEN→REFACTOR for testable behavior; use focused checks for micro-edits -- Fail-Fast: Never create fake mock servers or listeners on real service/application ports to mask missing dependencies; fail fast with explicit error details. -- Background processes: Long-running servers (FastAPI/uvicorn, Vite, dev servers) must always be decoupled from subshells using `setsid nohup > 2>&1 &` (or `disown`). - Stronger gates (auth, security, data-integrity, coverage) are canonical in the global `Test Economy` section - Async/await on all I/O - Type hints on all functions diff --git a/CHANGELOG.md b/CHANGELOG.md index 93338a8c..fcd76d0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,11 +17,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### 🆕 What's New -- **Deepwork Resilient Normalization**: Supported multi-decision blueprints, single-option policy constraints, and string acceptance criteria. -- **Fail-Fast Anti-Mocking Rule**: Strictly prohibited mock servers on real service ports to fake missing dependencies; fail fast with explicit errors. -- **Workspace Tool Working Directory**: Native shell tools dynamically resolve to the active project root rather than falling back to `$HOME`. +- **Deepwork Resilient Normalization**: Supported multi-decision blueprints, single-option policies, and string acceptance criteria. +- **Fail-Fast Anti-Mocking**: Prohibited fake mock servers on service ports to hide missing dependencies; fail fast with explicit errors. +- **Workspace Tool Directory**: Native shell tools dynamically resolve to the active project root rather than falling back to `$HOME`. - **Atomic Skill Installation**: Enforced sequential `&&` chaining for `npx skills add` to prevent silent dropping of trailing targets. -- **Project Bootstrap Git Init**: `init --project` automatically initializes an empty Git repo when absent, enabling worktree and branch support. +- **Project Bootstrap Git Init**: `init --project` initializes an empty Git repo when absent, enabling worktree and branch support. - **Decoupled Background Processes**: Mandated `setsid nohup > 2>&1 &` (or `disown`) for long-running service processes. ### Fixed diff --git a/scripts/build-agents-md.mjs b/scripts/build-agents-md.mjs index 20755da3..8e11bfcf 100644 --- a/scripts/build-agents-md.mjs +++ b/scripts/build-agents-md.mjs @@ -150,13 +150,10 @@ Validate global installation AS A REAL USER in the sandbox \`~/pantheon-sandbox/ - Never create worktrees inside the main project; use \`/.pantheon-worktrees//\`. - Worktrees do not live inside \`.pantheon/\`. -- If the project is not a Git repository (no \`.git\` directory), worktrees cannot be used; specialists must use disjoint file paths and directory separation within the project workspace instead. ## Conventions - TDD: RED→GREEN→REFACTOR for testable behavior; use focused checks for micro-edits -- Fail-Fast: Never create fake mock servers or listeners on real service/application ports to mask missing dependencies; fail fast with explicit error details. -- Background processes: Long-running servers (FastAPI/uvicorn, Vite, dev servers) must always be decoupled from subshells using \`setsid nohup > 2>&1 &\` (or \`disown\`). - Stronger gates (auth, security, data-integrity, coverage) are canonical in the global \`Test Economy\` section - Async/await on all I/O - Type hints on all functions diff --git a/src/plugins/tui/dist/tui.js b/src/plugins/tui/dist/tui.js index 94d0124a..218c60a0 100644 --- a/src/plugins/tui/dist/tui.js +++ b/src/plugins/tui/dist/tui.js @@ -2061,7 +2061,7 @@ async function readChangelogForBundle(bundleUrl) { } /** The ambient build-time version, or null outside a tsdown build. */ function embeddedVersion() { - return "2.1.5"; + return "2.1.6"; } /** * Resolve the running Pantheon version for the what's-new window: the plugin @@ -2286,7 +2286,7 @@ function persistUpdateCheckState(previous, latest) { } catch {} } function resolveRunningVersion() { - return "2.1.5"; + return "2.1.6"; } const VALUE_WIDTH = 24; function SettingsWindow(props) { @@ -6512,7 +6512,7 @@ async function checkForPantheonUpdate(context) { const latest = String((await response.json())?.version ?? ""); if (!latest) return; const notice = pickUpdateNotice({ - currentVersion: "2.1.5", + currentVersion: "2.1.6", latestVersion: latest, state: readState(), nowMs: Date.now() @@ -7318,7 +7318,7 @@ function Sidebar(props) { get children() { var _el$13 = createElement("text"); setProp(_el$13, "attributes", 1); - insert(_el$13, `Pantheon v2.1.5`); + insert(_el$13, `Pantheon v2.1.6`); effect((_$p) => setProp(_el$13, "fg", text(), _$p)); return _el$13; } @@ -8026,7 +8026,7 @@ function HomeStatus(props) { }, get children() { var _el$68 = createElement("text"); - insert(_el$68, () => `Pantheon v2.1.5${preset().name ? ` ▸ ${preset().name}` : ""}`); + insert(_el$68, () => `Pantheon v2.1.6${preset().name ? ` ▸ ${preset().name}` : ""}`); effect((_$p) => setProp(_el$68, "fg", muted(), _$p)); return _el$68; }