pi-odd-worktree 3.6.4 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,6 +28,8 @@ The file cards are not a preference of this package either: they belong to that
28
28
 
29
29
  The jobs card follows the same value. Gentle Shell registers `bash_background`, `monitor`, `job_stop` and `job_list` with no renderer of their own, so Pi draws them in a plain box and neither `neon` nor `float` ever reaches them. While the bridge answers that `activity` draws the tool being painted, they are drawn on the same card substrate in the style the shell has chosen: the job's mark and name (its label, else the first line of its command), the whole command when expanded, and the job's own answer below. Under the `minimal` card content level the call is drawn alone, and a failure still says why. Any other answer on `Card tags`, no bridge, or a bridge older than 0.7.0 leaves Pi's own box exactly as it was. Unlike the file cards, the answer is read when a job card is built, because there is no host drawing to hand back on a later paint: a switch made mid-session reaches the next job card. See [the jobs card](docs/reference.md#the-jobs-card).
30
30
 
31
+ The two advisory messages Gentle Shell sends follow that same value, through the bridge's message-design surface rather than a tool renderer: `gentle-pi.exploration-budget` heads as `⌕ Exploration budget` and `gentle-pi.verifier-settle-reminder` as `⚑ Verifier reminder`, each with the numbers the message states as its detail, drawn on the same card substrate in the style the shell has chosen. Their body is never clipped — both are instructions the agent must read, so every row is drawn at any card content level, with no preview and no expand hint — and the bridge's own `[customType]` label row is dropped because the card's heading already names the alert. There is no second switch: each design FOLLOWS the `Card tags` line, so `activity` paints both alerts, live — flipping that line repaints the messages on screen and turns them off again — and `/gentle:customize` gains no row for them. A bridge older than `0.12.1` cannot keep that follow promise — `0.12.0` let a leftover stored value veto it — and gets no registration at all, so Pi's own box stays byte-identical; only a clean numeric release is trusted, and there is no capability probe. An inactive alert costs a registry walk and at most one tool-document read, and paints nothing. See [the message cards](docs/reference.md#the-message-cards).
32
+
31
33
  ## Quick Start
32
34
 
33
35
  | Requirement | Why it is needed |
@@ -74,6 +76,7 @@ The full rules of each step, including every refusal, are in [Create, list, move
74
76
  - **Tool headings can name the activity.** With `activity` chosen on the `Card tags` line, a bash card whose heading shows the whole command is headed with the family its command names (mark and word) instead of `$`, and a `grep`, `find` or `ls` card is headed `⌕ exploring` instead of its own glyph and name, while a `read` — which runs no shell command — keeps the host's own card, colour and width; a bash command the classifier cannot name, or a heading that hides part of it, keeps the host's `$`. See [the cards the `activity` design paints](docs/reference.md#the-cards-the-activity-design-paints).
75
77
  - **File calls on a skill or an ODD are cards too.** While `Card tags` answers with `activity` for the tool being painted, a `read`, `edit` or `write` call whose path names a skill (anything below a `skills` folder) or an ODD (anything below an `odd` folder) heads as that file, with the tool, the path and a read's line range; its Markdown body — the whole document when expanded, the first rows when collapsed — is drawn by Pi's own renderer in the theme's Markdown roles — for an `edit`, the fragment it leaves behind, never its diff, and a call that leaves no fragment falls back to its own rows. Any other file call, and every call while that line answers anything else, is the host's own row. See [the file cards](docs/reference.md#the-file-cards).
76
78
  - **Background-job tools are cards too.** While `Card tags` answers with `activity` for the tool being painted, `bash_background`, `monitor`, `job_stop` and `job_list` are drawn in the shell's own card style instead of Pi's plain box. Any other answer leaves Pi's box untouched. See [the jobs card](docs/reference.md#the-jobs-card).
79
+ - **The two advisory messages are cards too.** While `Card tags` answers with `activity`, `gentle-pi.exploration-budget` and `gentle-pi.verifier-settle-reminder` are drawn as `⌕ Exploration budget` and `⚑ Verifier reminder` in the shell's own card style, the whole body at every content level. They follow that line — no second switch, no row added to `Cards`, and a flip repaints the messages on screen and turns them off again. Any other answer hands the message back as Pi drew it, for the price of a registry walk and at most one tool-document read, and a bridge older than `0.12.1` — or one whose release string is not a clean numeric release — registers nothing at all. See [the message cards](docs/reference.md#the-message-cards).
77
80
  - **`edit` and `write` cannot land in the principal checkout's default branch.** A write whose path is inside the principal checkout of the session's repository, while that checkout is on the default branch, is refused with one line pointing at `worktree_list` and `worktree_create`. Paths outside the repository, anything under the OS temp directories, other repositories and linked worktrees are never blocked. See [the guard](docs/reference.md#the-edit-and-write-guard).
78
81
  - **`bash` cannot leave the principal checkout's default branch.** A `git worktree add` or `git worktree list` is refused in any cwd and pointed at `worktree_create` and `worktree_list`; in the principal checkout, a switch that would leave the branch it is on is refused while that branch is the repository's default, and creating a branch is not blocked. See [the guards](docs/reference.md#the-bash-guards).
79
82
  - **Two blocks in the system prompt.** `## ODD worktrees` tells the agent how worktrees and ODDs work. `## CodeGraph` tells a session that already holds a CodeGraph tool how to use it, with one text per role. Both are appended after the host's own text, and `ODD_WORKTREE_PROMPT=0` suppresses them. See [the prompt blocks](docs/reference.md#the--odd-worktrees-block-in-the-system-prompt).
@@ -10031,6 +10031,18 @@ function registerOddWorktreeSurfaceEntries(pi) {
10031
10031
  } catch {
10032
10032
  // The card is cosmetic.
10033
10033
  }
10034
+ // The two ODD advisory MESSAGES, on the bridge's message-design surface: `gentle-pi.exploration-budget`
10035
+ // and `gentle-pi.verifier-settle-reminder` are custom messages no extension renders, so Pi draws its
10036
+ // default box. Each design FOLLOWS the `Card tags` line above, so the `activity` value that already
10037
+ // paints the jobs card paints both alerts too: no second switch, no row added to `Cards`, and the
10038
+ // follow is resolved on every pass, so a flip repaints — and turns off — what is already on screen.
10039
+ // A bridge that cannot express a follow registers nothing at all: an older one would create a
10040
+ // `Message <type>` switch of its own, which is the parallel switch this package refuses to add.
10041
+ try {
10042
+ libRequire("message-card.js").registerMessageCards({ metrics: () => resolveWorktreeToolCardMetrics() });
10043
+ } catch {
10044
+ // The card is cosmetic.
10045
+ }
10034
10046
  // The live-checkout scan is DISPATCHED and never awaited. Its only product is
10035
10047
  // `warpDiscoveryCache`, which nothing reads — every warp lists fresh before
10036
10048
  // acting — so the old "startup barrier" awaited three git reads for a result the
@@ -804,6 +804,9 @@ function registerBashDesign(api) {
804
804
  module.exports = {
805
805
  BASH_DESIGN_ID,
806
806
  BASH_DESIGN_LABEL,
807
+ // The line key itself, for a surface that must name the switch this design is selected on
808
+ // (`lib/message-card.js` follows it) instead of re-typing it.
809
+ TOOLS_LINE,
807
810
  applyBashActivityHeading,
808
811
  bashActivityDesign,
809
812
  carryOverLineSelection,
package/lib/jobs-card.js CHANGED
@@ -43,10 +43,12 @@ const { cardText } = require('./codegraph-card-preview.js');
43
43
  /** The four tools this card owns, in the order the bridge's `Card tags` line declares them. */
44
44
  const JOB_TOOLS = Object.freeze(['bash_background', 'monitor', 'job_stop', 'job_list']);
45
45
 
46
- // Each tool's mark, its one-word label and the theme role the heading wears.
46
+ // Each tool's mark, its label and the theme role the heading wears. The two job tools share one
47
+ // mark and one role, so a `monitor` and a `bash_background` read as the same family the report
48
+ // card states, while their words say which TOOL ran what the report is about.
47
49
  const IDENTITY = Object.freeze({
48
- bash_background: { glyph: '⧗', title: 'background', titleRole: 'bashMode' },
49
- monitor: { glyph: '◉', title: 'monitor', titleRole: 'mdLink' },
50
+ bash_background: { glyph: '⧗', title: 'bash background', titleRole: 'bashMode' },
51
+ monitor: { glyph: '⧗', title: 'bash monitor', titleRole: 'bashMode' },
50
52
  job_stop: { glyph: '■', title: 'stop', titleRole: 'warning' },
51
53
  job_list: { glyph: '≡', title: 'jobs', titleRole: 'syntaxFunction' },
52
54
  });
@@ -0,0 +1,327 @@
1
+ 'use strict';
2
+ // The two advisory message cards: `gentle-pi.exploration-budget` and
3
+ // `gentle-pi.verifier-settle-reminder`, drawn on this package's card substrate
4
+ // (`lib/shell-card.js`), in whichever style the shell has chosen and always in full.
5
+ //
6
+ // Gentle Shell sends both messages with no renderer registered for either type, so Pi draws
7
+ // its plain default box and the conversation's card style never reaches them. This module is
8
+ // the drawing half, registered through gentle-shell-bridge's message-design surface; the
9
+ // bridge owns Pi's renderer, the customize line and its persistence, exactly as it does for
10
+ // the tool designs (`lib/bash-design.js`, `lib/diff-design.js`).
11
+ //
12
+ // What a design receives, and what this card owns:
13
+ // * For a type with NO host renderer the bridge hands `apply` the message's own body plainly
14
+ // — its `[customType]` label, a blank row and its text — and the DESIGN owns the frame
15
+ // (bridge `docs/contract.md` §15). The label and the blank row are the bridge's plain-body
16
+ // decorations, not the message, so they are dropped here: the card's own heading already
17
+ // names the alert, and the body starts at the message's first row.
18
+ // * THE BODY IS NEVER CLIPPED (S2). Both alerts are instructions the agent must read, so
19
+ // every row is drawn at any card content level: no `previewRows`, no `minimal`
20
+ // withholding, no expand hint — nothing is hidden, so a hint would lie. That is the exact
21
+ // opposite of the jobs card's result body (`lib/jobs-card.js`), and it is this consumer's
22
+ // decision: the bridge clips nothing and reads no content level.
23
+ // * COLOUR is a tone, never a palette: `info` for the budget and `warning` for the reminder,
24
+ // and the substrate turns each into the theme's own roles. No escape sequence is written
25
+ // here.
26
+ // * MEASUREMENT is the substrate's, through the injected seam: rows are composed as PLAIN
27
+ // text, wrapped and clipped, and painted last. Without a usable seam the design throws, and
28
+ // the bridge's own fallback draws Pi's box — a message the agent must read is never
29
+ // unmeasured into a frame Pi would refuse.
30
+ // * THE STYLE is the HOST's, read on every paint by `floatRows` (`lib/card-style.js`), never
31
+ // `ctx.cardStyle`: that field is the BRIDGE's Card style selection, not float/neon chrome
32
+ // (S3). A mid-session flip therefore repaints a message already on screen.
33
+ //
34
+ // THE SWITCH (S1). Both alerts are selected by the SAME value that already draws this package's
35
+ // tool cards, and this module owns no switch of its own: each design FOLLOWS the tool design line
36
+ // this package registers — `follows: { line: TOOLS_LINE, id: BASH_DESIGN_ID }` — so `Card tags`
37
+ // answering `activity` is what paints them. The bridge resolves that LIVE on every pass, reading
38
+ // the tool document and never writing it: a flip on the line repaints a message already on screen
39
+ // and turns it off again, with no re-registration, no seed and no second store. A following design
40
+ // contributes no value to the customize menu, so the human sees no `Message …` row at all.
41
+ //
42
+ // FOLLOWS NEEDS 0.12.1, AND AN OLDER BRIDGE GETS NOTHING. `follows` arrived at 0.12.0, but 0.12.0
43
+ // let a value left in the message document VETO a follow, which turns the one switch this card
44
+ // promises back into a silent second one; 0.12.1 answers the follow first and is the first release
45
+ // that keeps the promise. A bridge below it ignores `follows` while accepting the registration and
46
+ // would silently mint the parallel `Message <type>` switch this card must never have. So the surface
47
+ // is registered only where the release string reads as at least 0.12.1 (a prerelease or build suffix
48
+ // of the cutoff does not meet it), and an unreadable string registers NOTHING — no probe, because a
49
+ // probe cannot tell a refusal for an unrelated reason from a validated `follows`.
50
+ //
51
+ // Rendering never breaks the transcript: a hostile message is filtered to plain rows, and a
52
+ // context this card cannot measure through throws into the bridge's own fallback instead of
53
+ // answering rows Pi would have to refuse.
54
+
55
+ const { CARD_TONE, cardBodyRows, cardBottom, cardTopRows, floatRows } = require('./shell-card.js');
56
+ // The one reader of text as a card draws it: no terminal sequences, however the text was written.
57
+ const { cardText } = require('./codegraph-card-preview.js');
58
+ const { bridgeApi } = require('./file-card-resolver.js');
59
+ const { themeFor } = require('./file-card.js');
60
+ // The line and the tool design id this card follows: the SAME switch the tool cards obey, named
61
+ // from the module that registers it, so no literal is re-typed here.
62
+ const { BASH_DESIGN_ID, TOOLS_LINE } = require('./bash-design.js');
63
+
64
+ /** The two custom types this module paints, in the order the line lists them. */
65
+ const EXPLORATION_TYPE = 'gentle-pi.exploration-budget';
66
+ const VERIFIER_TYPE = 'gentle-pi.verifier-settle-reminder';
67
+ const MESSAGE_TYPES = Object.freeze([EXPLORATION_TYPE, VERIFIER_TYPE]);
68
+
69
+ /**
70
+ * The switch each design follows: the tool design line this package registers, and the tool design
71
+ * that line answers with. One object per design, so no two registrations share a mutable field.
72
+ */
73
+ function messageFollow() {
74
+ return { line: TOOLS_LINE, id: BASH_DESIGN_ID };
75
+ }
76
+
77
+ // The bridge release that can keep the follow promise (gentle-shell-bridge 0.12.1: the follow is
78
+ // answered BEFORE the message document is opened, so a value left behind by a disposed design can no
79
+ // longer veto it). 0.12.0 has `follows` but not that order, which is why the floor is 0.12.1. An older
80
+ // release ignores the field, which is the one outcome this card must never produce: a second switch. So
81
+ // the release string is the ONLY answer accepted, and anything this module cannot read as at least
82
+ // 0.12.1 — absent, unreadable, a prerelease, a build suffix — registers NOTHING. The trade is
83
+ // deliberate and it is the safe side of it: an unreadable release loses the card and keeps Pi's own box,
84
+ // while a capability probe cannot. A probe is refused for an unrelated reason by 0.11.0 (a competing type
85
+ // claim) long before it inspects `follows`, and then the real designs are accepted WITHOUT follow
86
+ // semantics — exactly the parallel `Message <type>` switch this module exists not to create — and an
87
+ // accepted-then-disposed probe can leave the bridge's row provider installed on an armed bridge.
88
+ const FOLLOWS_VERSION = [0, 12, 1];
89
+
90
+ // Below this the frame's two side rails and the glyph column leave no room for one body row, so the
91
+ // rows come straight back instead of a heading painted over nothing.
92
+ const MIN_PAINT_WIDTH = 6;
93
+
94
+ // The attribution name every bridge surface of this package registers under (`lib/bash-design.js`).
95
+ const PLUGIN_NAME = 'Odd worktree';
96
+
97
+ // Each card's mark, title, tone, registration id and the label the bridge asks every registration
98
+ // for. The label is not shown: a following design contributes no value to the customize menu, and
99
+ // neither `default` nor `native` may be used as one. The id is identity, never shown either.
100
+ const IDENTITY = Object.freeze({
101
+ [EXPLORATION_TYPE]: {
102
+ glyph: '⌕',
103
+ title: 'Exploration budget',
104
+ tone: CARD_TONE.INFO,
105
+ id: 'odd-worktree.exploration-budget-card',
106
+ label: 'card',
107
+ description: 'draws the exploration budget alert as a card, in the style the shell has chosen',
108
+ },
109
+ [VERIFIER_TYPE]: {
110
+ glyph: '⚑',
111
+ title: 'Verifier reminder',
112
+ tone: CARD_TONE.WARNING,
113
+ id: 'odd-worktree.verifier-settle-reminder-card',
114
+ label: 'card',
115
+ description: 'draws the verifier reminder as a card, in the style the shell has chosen',
116
+ },
117
+ });
118
+
119
+ const METRICS_FUNCTIONS = ['visibleWidth', 'truncateToWidth', 'wrapTextWithAnsi'];
120
+
121
+ const asObject = (value) => (value !== null && typeof value === 'object' ? value : {});
122
+ const hasFunction = (value, name) => value !== null && typeof value === 'object' && typeof value[name] === 'function';
123
+ const usableMetrics = (value) => (METRICS_FUNCTIONS.every((name) => hasFunction(value, name)) ? value : undefined);
124
+
125
+ /** The measurement seam: an object, or a function asked on every paint (the host may load late). */
126
+ function metricsSeam(value) {
127
+ if (typeof value === 'function') {
128
+ return () => {
129
+ try {
130
+ return usableMetrics(value());
131
+ } catch {
132
+ return undefined;
133
+ }
134
+ };
135
+ }
136
+ return () => usableMetrics(value);
137
+ }
138
+
139
+ /** The width the host asked this message component to render at, or 0 when it stated none. */
140
+ function paintWidth(context) {
141
+ const width = asObject(context).width;
142
+ return typeof width === 'number' && Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 0;
143
+ }
144
+
145
+ /**
146
+ * The message's own rows, without the plain-body decorations the bridge hands a type with no
147
+ * host renderer: the `[customType]` label row, and the blank row it puts after it. Everything
148
+ * else — every row the message states, blank rows between paragraphs included — is kept.
149
+ */
150
+ function messageCardBody(lines, customType) {
151
+ const rows = (Array.isArray(lines) ? lines : []).filter((line) => typeof line === 'string').map((line) => cardText(line));
152
+ if (rows[0] !== `[${customType}]`) return rows;
153
+ const rest = rows.slice(1);
154
+ return rest.length > 0 && rest[0].trim() === '' ? rest.slice(1) : rest;
155
+ }
156
+
157
+ // The numbers an advisory message tracks, read from the message's own text. The budget states
158
+ // its lookups and its byte count; the reminder states the risk item whose verification is
159
+ // missing. A message that states none is headed by its name alone, never by a guess.
160
+ const TRACKED = new Map([
161
+ [EXPLORATION_TYPE, (text) => {
162
+ const lookups = text.match(/(\d[\d,]*)\s+tracked\s+lookups?/iu);
163
+ const bytes = text.match(/(\d[\d,]*)\s+UTF-8\s+text\s+bytes/iu);
164
+ return [
165
+ ...(lookups === null ? [] : [`${lookups[1]} tracked lookups`]),
166
+ ...(bytes === null ? [] : [`${bytes[1]} text bytes`]),
167
+ ];
168
+ }],
169
+ [VERIFIER_TYPE, (text) => {
170
+ const item = text.match(/Risk:\s*item\s+(\d+)/iu);
171
+ return item === null ? [] : [`Risk: item ${item[1]}`];
172
+ }],
173
+ ]);
174
+
175
+ /** The numbers one message states, as the detail the heading wears — empty when it states none. */
176
+ function trackedNumbers(customType, body) {
177
+ const read = TRACKED.get(customType);
178
+ if (read === undefined) return [];
179
+ try {
180
+ return read(body.join('\n'));
181
+ } catch {
182
+ return [];
183
+ }
184
+ }
185
+
186
+ /** The heading one message wears: its mark and name, then the numbers the message states. */
187
+ function messageCardHeading(customType, body) {
188
+ const identity = IDENTITY[customType];
189
+ if (identity === undefined) return undefined;
190
+ const detail = trackedNumbers(customType, body);
191
+ const card = {
192
+ glyph: identity.glyph,
193
+ title: identity.title,
194
+ tone: identity.tone,
195
+ // The label is bolded inside the card's own role, exactly as the file and job cards do.
196
+ labelBold: true,
197
+ };
198
+ // The detail rides the heading only when the message states one: no invented numbers, no
199
+ // empty separator.
200
+ if (detail.length > 0) card.subtitle = detail.join(' · ');
201
+ return card;
202
+ }
203
+
204
+ /**
205
+ * The rows of one message card, for one width, rebuilt on every pass: the heading, the whole
206
+ * body — with no preview budget and no content level in sight — and the closing rule. `floatRows`
207
+ * decides the style once, here, from the host's own setting.
208
+ */
209
+ function messageCardRows(customType, lines, paint, metrics, width) {
210
+ const body = messageCardBody(lines, customType);
211
+ const heading = messageCardHeading(customType, body);
212
+ if (heading === undefined) return [];
213
+ return floatRows(heading.tone, paint, width, (inner) => ({
214
+ head: cardTopRows(heading, paint, inner, undefined, metrics),
215
+ // `expanded` is always true — the substrate's own "draw every row" — because the body is an
216
+ // instruction the agent must read, whatever the conversation's content level says.
217
+ body: cardBodyRows(body, heading.tone, paint, inner, { expanded: true }, metrics),
218
+ bottom: cardBottom(heading.tone, paint, inner, undefined, metrics),
219
+ }));
220
+ }
221
+
222
+ /**
223
+ * One design, as the bridge registers it: the custom type it paints, the switch it follows, and
224
+ * `apply(lines, ctx)` — the bridge's rows in, the rows to draw out.
225
+ *
226
+ * `follows` is the whole switch (S1): the design is selected exactly while this package's tool
227
+ * design line answers this package's activity design, resolved by the bridge on every pass. The
228
+ * module registers no value of its own and writes no store, so there is nothing to seed and the
229
+ * customize menu gains no row.
230
+ *
231
+ * `apply` reads the style, the width, the theme and the measurement seam on every pass, so a
232
+ * preference switched or a seam that arrives while the message is on screen applies to the next
233
+ * paint. A context this card cannot measure through throws: the bridge answers that by drawing
234
+ * Pi's own box (`docs/contract.md` §15), which keeps an alert readable and inside the frame.
235
+ */
236
+ function messageCardDesign(customType, seams) {
237
+ const identity = IDENTITY[customType];
238
+ if (identity === undefined) return undefined;
239
+ return {
240
+ customType,
241
+ name: PLUGIN_NAME,
242
+ id: identity.id,
243
+ label: identity.label,
244
+ description: identity.description,
245
+ follows: messageFollow(),
246
+ apply(lines, context) {
247
+ const ctx = asObject(context);
248
+ const width = paintWidth(ctx);
249
+ const metrics = seams.metrics();
250
+ if (metrics === undefined || width <= 0) {
251
+ throw new TypeError(`the ${customType} card needs a positive width and the host's measurement helpers`);
252
+ }
253
+ // Too narrow for one body row: hand the bridge's own rows straight back rather than paint a
254
+ // heading over nothing.
255
+ if (width < MIN_PAINT_WIDTH) return [...lines];
256
+ const paint = themeFor(ctx.theme, seams.theme);
257
+ return messageCardRows(customType, lines, paint, metrics, width);
258
+ },
259
+ };
260
+ }
261
+
262
+ /**
263
+ * Whether the bridge's published release is at least `floor`, or `undefined` when the release string
264
+ * cannot be read as a clean numeric release.
265
+ *
266
+ * STRICT BY CHOICE: this card is worth nothing if it registers where `follows` is not honoured, so a
267
+ * string is trusted only when it is `N`, `N.N` or `N.N.N` and nothing else. A prerelease or build
268
+ * suffix (`0.12.1-rc.1`, `0.12.2+build.7`), trailing text (`0.12.2garbage`) and a four-part string
269
+ * (`1.0.0.0`) are all UNREADABLE and register nothing — the numbers are never compared on their own,
270
+ * because a higher number would otherwise carry a string nobody can validate past the floor.
271
+ */
272
+ function releaseAtLeast(version, floor) {
273
+ if (typeof version !== 'string' || !/^\d+(?:\.\d+){0,2}$/u.test(version)) return undefined;
274
+ const parts = version.split('.').map((part) => Number(part));
275
+ if (parts.length < 2 || parts.some((part) => !Number.isFinite(part))) return undefined;
276
+ const [major, minor, patch = 0] = parts;
277
+ if (major !== floor[0]) return major > floor[0];
278
+ if (minor !== floor[1]) return minor > floor[1];
279
+ return patch >= floor[2];
280
+ }
281
+
282
+ /**
283
+ * Whether a published bridge can keep the follow promise (gentle-shell-bridge 0.12.1): its release
284
+ * string, and nothing else. There is no probe path by design — see `FOLLOWS_VERSION` for what one costs.
285
+ */
286
+ function bridgeTakesFollows(api) {
287
+ return releaseAtLeast(api?.VERSION, FOLLOWS_VERSION) === true;
288
+ }
289
+
290
+ /**
291
+ * `registerMessageCards({ metrics, theme })` — the extension's one wiring point, shaped like
292
+ * `registerJobsCard`. Both designs follow `Card tags` → `activity`, so the human's existing choice
293
+ * is the switch and the bridge decides per pass; this module registers whenever the bridge can
294
+ * express that follow, and NOTHING at all on an older one (a bridge that ignores `follows` would
295
+ * silently create a `Message <type>` switch of its own).
296
+ *
297
+ * Nothing here is seeded and no store is written: the follow reads the tool document, never writes
298
+ * it. An absent bridge, an absent message-design surface, a release below 0.12.1 and a refused
299
+ * registration are all "register nothing": Pi's own box stays exactly as it was.
300
+ *
301
+ * The measurement seam and the theme fallback are the caller's: the seam may be a function, so a
302
+ * host whose TUI arrives later still measures, and it throws only into the bridge's fallback.
303
+ */
304
+ function registerMessageCards(options) {
305
+ const opts = asObject(options);
306
+ const none = { registered: false, designs: [], dispose: undefined };
307
+ const api = bridgeApi();
308
+ if (api === undefined || typeof api.registerMessageDesign !== 'function') return none;
309
+ if (!bridgeTakesFollows(api)) return none;
310
+ const seams = { theme: opts.theme, metrics: metricsSeam(opts.metrics) };
311
+ const designs = MESSAGE_TYPES.map((customType) => messageCardDesign(customType, seams)).filter((design) => design !== undefined);
312
+ try {
313
+ const dispose = api.registerMessageDesign(designs);
314
+ return { registered: true, designs, dispose: typeof dispose === 'function' ? dispose : undefined };
315
+ } catch {
316
+ // A refused registration is no design at all: the bridge keeps drawing Pi's own box.
317
+ return none;
318
+ }
319
+ }
320
+
321
+ module.exports = {
322
+ MESSAGE_TYPES,
323
+ bridgeTakesFollows,
324
+ messageCardDesign,
325
+ messageCardRows,
326
+ registerMessageCards,
327
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-odd-worktree",
3
- "version": "3.6.4",
3
+ "version": "3.7.0",
4
4
  "description": "Pi package for odd-worktree: the Git worktree tools a Pi session uses (create and list the checkouts the agent works in), the /warp worktree panel, the /odd ODD viewer, and the /issues GitHub issue reader. Needs only Pi and git: no companion app, no extra service.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -167,7 +167,7 @@ test('a background job heads with its mark, its label and nothing it did not sta
167
167
  const rows = callRows(jobsResolver(), 'bash_background', { command: COMMAND, label: LABEL }, taggedTheme);
168
168
  assert.equal(rows.length, 1, 'collapsed, a finished call is one rule');
169
169
  const text = unpaint(rows[0]);
170
- assert.match(text, /^╭─ ⧗ background · Release runs for 1\.9\.1 /u, text);
170
+ assert.match(text, /^╭─ ⧗ bash background · Release runs for 1\.9\.1 /u, text);
171
171
  assert.match(text, /╮$/u);
172
172
  assert.ok(rows[0].includes('<bashMode>⧗</bashMode>'), 'the mark wears the identity role');
173
173
  assert.doesNotMatch(text, /sleep 20/u, 'the command waits for the expanded view');
@@ -177,12 +177,22 @@ test('a background job heads with its mark, its label and nothing it did not sta
177
177
  test('without a label the first line of the command names the job; the other tools name their target', () => {
178
178
  publishBridge(ACTIVITY);
179
179
  const resolver = jobsResolver();
180
- assert.match(unpaint(callRows(resolver, 'bash_background', { command: '\n npm test --silent\nnpm run lint' }, plainTheme)[0]), /⧗ background · npm test --silent/u);
181
- assert.match(unpaint(callRows(resolver, 'monitor', { command: 'tail -f app.log', label: 'app log', timeout_seconds: 60 }, plainTheme)[0]), /◉ monitor · app log/u);
180
+ assert.match(unpaint(callRows(resolver, 'bash_background', { command: '\n npm test --silent\nnpm run lint' }, plainTheme)[0]), /⧗ bash background · npm test --silent/u);
181
+ assert.match(unpaint(callRows(resolver, 'monitor', { command: 'tail -f app.log', label: 'app log', timeout_seconds: 60 }, plainTheme)[0]), /⧗ bash monitor · app log/u);
182
182
  assert.match(unpaint(callRows(resolver, 'job_stop', { job_id: 'job-2' }, plainTheme)[0]), /■ stop · job-2/u);
183
183
  assert.match(unpaint(callRows(resolver, 'job_list', {}, plainTheme)[0]), /≡ jobs · this session/u);
184
184
  });
185
185
 
186
+ test('both job tools wear one mark and one role, so a monitor reads as a background job', () => {
187
+ publishBridge(ACTIVITY);
188
+ const resolver = jobsResolver();
189
+ const background = callRows(resolver, 'bash_background', { command: COMMAND, label: LABEL }, taggedTheme)[0];
190
+ const monitor = callRows(resolver, 'monitor', { command: COMMAND, label: LABEL, timeout_seconds: 60 }, taggedTheme)[0];
191
+ for (const row of [background, monitor]) assert.ok(row.includes('<bashMode>⧗</bashMode>'), 'the mark wears the identity role');
192
+ assert.match(unpaint(background), /⧗ bash background ·/u);
193
+ assert.match(unpaint(monitor), /⧗ bash monitor ·/u);
194
+ });
195
+
186
196
  test('expanded, the whole command is stated below the heading, every line of it', () => {
187
197
  publishBridge(ACTIVITY);
188
198
  const rows = callRows(jobsResolver(), 'bash_background', { command: 'sleep 20\n\ngh run list --repo acme/api', label: LABEL }, plainTheme, 70, { isPartial: false, expanded: true }).map(unpaint);
@@ -0,0 +1,534 @@
1
+ 'use strict';
2
+ // The two advisory message cards: `gentle-pi.exploration-budget` and
3
+ // `gentle-pi.verifier-settle-reminder` are sent by Gentle Shell with no renderer registered
4
+ // for either, so Pi draws its default box and no card style ever reaches them. This package
5
+ // paints them on its own card substrate (`lib/shell-card.js`) through gentle-shell-bridge's
6
+ // message-design surface, in whichever style the host has chosen and always in full.
7
+ //
8
+ // Both designs FOLLOW the `Card tags` line this package's tool design is selected on, so the
9
+ // human picks `activity` once and these paint with it — live, per pass, with no switch of their
10
+ // own. Every case below goes through the public surface: `registerMessageCards` (the wire), the
11
+ // designs it registers, and the rows `apply` answers for a width. The text seam and the themes
12
+ // are the fakes `tools/jobs-card.test.js` uses; the bridge is the published object a
13
+ // process-wide slot holds.
14
+ const assert = require('node:assert/strict');
15
+ const { after, afterEach, beforeEach, test } = require('node:test');
16
+
17
+ const { MESSAGE_TYPES, bridgeTakesFollows, registerMessageCards } = require('../lib/message-card.js');
18
+ const { BASH_DESIGN_ID, TOOLS_LINE, toolsActivityDesign } = require('../lib/bash-design.js');
19
+ const { CARD_CONTENT, CARD_CONTENT_SLOT } = require('../lib/card-content.js');
20
+ const { CARD_STYLE, CARD_STYLE_SLOT } = require('../lib/card-style.js');
21
+
22
+ const ANSI = /\x1b\[[0-9;]*m/g;
23
+ const stripAnsi = (value) => value.replace(ANSI, '');
24
+ const chars = (value) => [...stripAnsi(value)];
25
+
26
+ const metrics = {
27
+ visibleWidth: (value) => chars(value).length,
28
+ truncateToWidth(value, width, ellipsis = '') {
29
+ if (width <= 0) return '';
30
+ if (this.visibleWidth(value) <= width) return value;
31
+ const tail = ellipsis ?? '';
32
+ return chars(value).slice(0, Math.max(0, width - [...tail].length)).join('') + tail;
33
+ },
34
+ wrapTextWithAnsi(value, width) {
35
+ const text = stripAnsi(value);
36
+ if (width <= 0) return [text];
37
+ return text.split('\n').flatMap((line) => {
38
+ const lines = [];
39
+ let current = '';
40
+ for (const word of line.split(' ')) {
41
+ const candidate = current === '' ? word : `${current} ${word}`;
42
+ if ([...candidate].length <= width) { current = candidate; continue; }
43
+ if (current !== '') { lines.push(current); current = ''; }
44
+ const rest = [...word];
45
+ while (rest.length > width) lines.push(rest.splice(0, width).join(''));
46
+ current = rest.join('');
47
+ }
48
+ lines.push(current);
49
+ return lines;
50
+ });
51
+ },
52
+ };
53
+
54
+ const plainTheme = { fg: (_role, value) => value };
55
+ const taggedTheme = { fg: (role, value) => `<${role}>${value}</${role}>` };
56
+ const bandTheme = { fg: (_role, value) => value, bg: (_role, value) => `\x1b[48;5;240m${value}\x1b[49m` };
57
+ const unpaint = (value) => stripAnsi(value).replace(/<\/?[a-zA-Z][a-zA-Z0-9]*>/g, '');
58
+
59
+ const BRIDGE_API_SLOT = Symbol.for('gentle-shell-bridge/api/v1');
60
+ const EXPLORATION = 'gentle-pi.exploration-budget';
61
+ const VERIFIER = 'gentle-pi.verifier-settle-reminder';
62
+ const ACTIVITY = 'odd-worktree.bash-activity';
63
+ const OTHER_DESIGN = 'acme.tools';
64
+
65
+ beforeEach(() => {
66
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.NEON;
67
+ delete globalThis[CARD_CONTENT_SLOT];
68
+ delete globalThis[BRIDGE_API_SLOT];
69
+ });
70
+ afterEach(() => { delete globalThis[BRIDGE_API_SLOT]; });
71
+ after(() => {
72
+ delete globalThis[CARD_STYLE_SLOT];
73
+ delete globalThis[CARD_CONTENT_SLOT];
74
+ delete globalThis[BRIDGE_API_SLOT];
75
+ });
76
+
77
+ /** A follow the bridge validates: `{ line, id }`, both non-empty, never the reserved `native`. */
78
+ const validFollow = (follow) => follow !== null
79
+ && typeof follow === 'object'
80
+ && typeof follow.line === 'string' && follow.line.trim() !== ''
81
+ && typeof follow.id === 'string' && follow.id.trim() !== ''
82
+ && follow.id.trim() !== 'native';
83
+
84
+ /**
85
+ * The published bridge object (gentle-shell-bridge@0.12.0's shape, and the older one it replaced).
86
+ * `validatesFollows` is the 0.12.0 discipline — a registration whose `follows` is malformed is
87
+ * refused whole; without it, the object is a pre-0.12.0 bridge that ignores the unknown field.
88
+ * `toolLine` is the `Card tags` line's live value: `undefined` means the line does not exist.
89
+ */
90
+ function publishBridge(options = {}) {
91
+ const settings = options !== null && typeof options === 'object' ? options : {};
92
+ const state = {
93
+ designs: [],
94
+ calls: [],
95
+ disposed: 0,
96
+ applies: 0,
97
+ resolutions: 0,
98
+ toolLine: settings.toolLine,
99
+ version: settings.version,
100
+ };
101
+ const api = {
102
+ schema: 'gentle-shell-bridge/api',
103
+ version: 1,
104
+ registerToolDesign: () => () => {},
105
+ resolveToolDesignSelection: () => ({ kind: 'native' }),
106
+ registerMessageDesign(registrations) {
107
+ const list = Array.isArray(registrations) ? registrations : [registrations];
108
+ state.calls.push(list);
109
+ if (settings.validatesFollows === true) {
110
+ for (const design of list) {
111
+ if (design.follows !== undefined && !validFollow(design.follows)) throw new Error('gentle-shell-bridge: invalid message design: follows must be `{ line, id }`');
112
+ }
113
+ }
114
+ const disposers = list.map((design) => {
115
+ state.designs.push(design);
116
+ return () => {
117
+ state.disposed += 1;
118
+ state.designs = state.designs.filter((kept) => kept !== design);
119
+ };
120
+ });
121
+ return () => { for (const dispose of disposers) dispose(); };
122
+ },
123
+ };
124
+ if (settings.version !== undefined) api.VERSION = settings.version;
125
+ globalThis[BRIDGE_API_SLOT] = api;
126
+ return state;
127
+ }
128
+
129
+ /** The module's own report, plus the bridge it registered on. */
130
+ function registered(options = {}) {
131
+ const bridge = publishBridge({ version: '0.12.1', toolLine: ACTIVITY, validatesFollows: true, ...options });
132
+ const outcome = registerMessageCards({ metrics, theme: plainTheme });
133
+ return { ...outcome, bridge };
134
+ }
135
+
136
+ const designFor = (outcome, customType) => outcome.designs.find((design) => design.customType === customType);
137
+
138
+ /**
139
+ * The bridge's own follow rule (`docs/contract.md` §15, "Following a tool design's switch"): a
140
+ * design is selected exactly while the tool line it follows answers its id, resolved LIVE, and
141
+ * with no design selected the message keeps the host's own output, byte for byte.
142
+ */
143
+ function selectedDesign(state, customType) {
144
+ state.resolutions += 1;
145
+ const design = state.designs.find((candidate) => candidate.customType === customType);
146
+ if (design === undefined || design.follows === undefined) return undefined;
147
+ if (state.toolLine === undefined) return undefined;
148
+ return state.toolLine === design.follows.id ? design : undefined;
149
+ }
150
+
151
+ /** One pass of the message's component, exactly as the bridge runs it. */
152
+ function renderMessage(state, customType, lines, width = 70) {
153
+ const design = selectedDesign(state, customType);
154
+ if (design === undefined) return lines;
155
+ state.applies += 1;
156
+ return design.apply([...lines], { width, customType, theme: plainTheme, render: { expanded: false, outputPad: 1, message: {} } });
157
+ }
158
+
159
+ /** The plain body the bridge hands a design for a host-less type: `[customType]`, a blank row, the text. */
160
+ const plainBody = (customType, text) => [`[${customType}]`, '', ...text.split('\n')];
161
+
162
+ /** The rows one design paints for a message, through the context Pi hands a message renderer. */
163
+ function cards(outcome, customType, text, context = {}, width = 70) {
164
+ const design = designFor(outcome, customType);
165
+ assert.notEqual(design, undefined, `${customType} is registered`);
166
+ return design.apply(plainBody(customType, text), { width, customType, theme: plainTheme, render: { expanded: false, outputPad: 1, message: {} }, ...context });
167
+ }
168
+
169
+ function assertFramed(rows, width) {
170
+ for (const row of rows) assert.equal(metrics.visibleWidth(unpaint(row)), width, `"${unpaint(row)}" is not ${width} wide`);
171
+ }
172
+
173
+ /** The body text of a neon card: each drawn row stripped of the frame, joined and squeezed. */
174
+ const bodyText = (rows) => rows
175
+ .map(unpaint)
176
+ .filter((row) => row.startsWith('│'))
177
+ .map((row) => row.replace(/^│ ?/u, '').replace(/ *│$/u, ''))
178
+ .join(' ')
179
+ .replace(/\s+/gu, ' ');
180
+
181
+ /** The exact top rule of a neon card: the frame, the heading and the fill that closes it. */
182
+ function headOf(heading, width) {
183
+ return `╭─ ${heading} ${'─'.repeat(width - metrics.visibleWidth(heading) - 5)}╮`;
184
+ }
185
+
186
+ const STARTED = [
187
+ 'Exploration budget: 1,234 tracked lookups and 56,789 UTF-8 text bytes (an approximate evidence budget).',
188
+ 'Ongoing discovery needs one configured explorer, even if read-only or initially small.',
189
+ 'This is runtime context for the original task, not a new user request.',
190
+ ].join('\n');
191
+ const VERIFIER_TEXT = 'Verification reminder: your final message declares `Risk: item 3`, but no independent verifier was launched for this prompt. Now launch `gentle-ai-verify` with the `Risk: item 3` line in its `task`.';
192
+ const EXPLORATION_HEADING = '⌕ Exploration budget · 1,234 tracked lookups · 56,789 text bytes';
193
+ const VERIFIER_HEADING = '⚑ Verifier reminder · Risk: item 3';
194
+
195
+ // ---- the wire, and the one switch ----
196
+
197
+ test('both alerts register on the message-design surface, one design per custom type', () => {
198
+ const outcome = registered();
199
+ assert.equal(outcome.registered, true);
200
+ assert.equal(outcome.bridge.calls.length, 1, 'one all-or-nothing registration');
201
+ assert.equal(outcome.bridge.designs.length, 2);
202
+ assert.deepEqual(outcome.bridge.designs.map((design) => design.customType), [EXPLORATION, VERIFIER]);
203
+ for (const design of outcome.bridge.designs) {
204
+ assert.equal(design.line, undefined, 'an ungrouped design, not a line');
205
+ assert.equal(design.types, undefined);
206
+ assert.equal(typeof design.id, 'string');
207
+ assert.ok(design.id.length > 0);
208
+ assert.equal(typeof design.label, 'string');
209
+ assert.ok(design.label.length > 0);
210
+ assert.ok(design.label !== 'default' && design.label !== 'native', 'a reserved label is refused by the bridge');
211
+ assert.equal(typeof design.apply, 'function');
212
+ }
213
+ assert.equal(new Set(outcome.bridge.designs.map((design) => design.id)).size, 2, 'one id per design');
214
+ assert.deepEqual([...MESSAGE_TYPES], [EXPLORATION, VERIFIER]);
215
+ });
216
+
217
+ test('each design FOLLOWS the line and the design id this package already registers its tool design on', () => {
218
+ const outcome = registered();
219
+ const toolDesign = toolsActivityDesign({ scopes: false });
220
+ for (const design of outcome.bridge.designs) {
221
+ assert.deepEqual(design.follows, { line: TOOLS_LINE, id: BASH_DESIGN_ID }, design.customType);
222
+ assert.equal(design.follows.line, toolDesign.line, 'the follow names the line the bash design registers on');
223
+ assert.equal(design.follows.id, toolDesign.id, 'and the id that line answers with');
224
+ }
225
+ // A card that follows contributes no value of its own: the menu gains no `Message …` row.
226
+ assert.deepEqual(outcome.bridge.designs.map((design) => design.follows.id), [ACTIVITY, ACTIVITY]);
227
+ assert.notEqual(outcome.bridge.designs[0].follows, outcome.bridge.designs[1].follows, 'one follow object per design');
228
+ });
229
+
230
+ test('while Card tags answers activity the message is the card', () => {
231
+ const wire = registered({ toolLine: ACTIVITY });
232
+ const rows = renderMessage(wire.bridge, EXPLORATION, plainBody(EXPLORATION, STARTED));
233
+ assert.equal(unpaint(rows[0]), headOf(EXPLORATION_HEADING, 70));
234
+ assert.equal(wire.bridge.applies, 1);
235
+ });
236
+
237
+ test('the line answering native, another design or nothing hands the message back byte-identical', () => {
238
+ for (const [name, toolLine] of [
239
+ ['the host\'s own value', 'native'],
240
+ ['another plugin\'s design', OTHER_DESIGN],
241
+ ['a value naming a design that is gone', 'odd-worktree.bash-activity-gone'],
242
+ ['a line that does not exist', undefined],
243
+ ]) {
244
+ const wire = registered({ toolLine });
245
+ assert.equal(wire.registered, true, `${name}: the designs are registered whatever the line says`);
246
+ assert.equal(wire.bridge.designs.length, 2);
247
+ for (const [customType, text] of [[EXPLORATION, STARTED], [VERIFIER, VERIFIER_TEXT]]) {
248
+ const input = plainBody(customType, text);
249
+ const rows = renderMessage(wire.bridge, customType, input);
250
+ assert.deepEqual(rows, input, `${name}: ${customType} keeps the host's rows, bytes included`);
251
+ assert.equal(wire.bridge.applies, 0, `${name}: ${customType} never reaches the card`);
252
+ }
253
+ }
254
+ });
255
+
256
+ test('a live flip repaints the message and turns it off again, with no re-registration', () => {
257
+ const wire = registered({ toolLine: 'native' });
258
+ assert.equal(wire.registered, true, 'the bridge decides per pass, so the designs are always registered');
259
+ const input = plainBody(EXPLORATION, STARTED);
260
+ assert.deepEqual(renderMessage(wire.bridge, EXPLORATION, input), input, 'off');
261
+ wire.bridge.toolLine = ACTIVITY;
262
+ const on = renderMessage(wire.bridge, EXPLORATION, input);
263
+ assert.equal(unpaint(on[0]), headOf(EXPLORATION_HEADING, 70), 'flipped on');
264
+ assert.ok(on.length > 1 + STARTED.split('\n').length - 1, 'the body is there');
265
+ wire.bridge.toolLine = 'native';
266
+ assert.deepEqual(renderMessage(wire.bridge, EXPLORATION, input), input, 'flipped off again');
267
+ wire.bridge.toolLine = ACTIVITY;
268
+ assert.deepEqual(renderMessage(wire.bridge, EXPLORATION, input), on, 'and back on, unchanged');
269
+ assert.equal(wire.bridge.calls.length, 1, 'one registration for all of it');
270
+ assert.ok(wire.bridge.resolutions >= 4, 'the follow was read on every pass');
271
+ });
272
+
273
+ test('registration needs no store, so no seed is written for a switch that already exists', () => {
274
+ // The fake publishes no `createStore`: a module that seeded anything would have to throw here.
275
+ const outcome = registered();
276
+ assert.equal(outcome.registered, true);
277
+ assert.equal(globalThis[BRIDGE_API_SLOT].createStore, undefined);
278
+ });
279
+
280
+ // ---- the older bridge: never a switch of our own ----
281
+
282
+ test('a bridge that cannot express the follow gets NO registration, never a Message switch of its own', () => {
283
+ for (const [name, version] of [
284
+ ['the release before it', '0.11.0'],
285
+ ['a much older one', '0.7.0'],
286
+ ['the release that has follows but not the order', '0.12.0'],
287
+ ['the cutoff with a prerelease suffix', '0.12.1-rc.1'],
288
+ ['the cutoff with a build suffix', '0.12.1+build.7'],
289
+ ]) {
290
+ const bridge = publishBridge({ version, toolLine: ACTIVITY, validatesFollows: false });
291
+ assert.deepEqual(registerMessageCards({ metrics, theme: plainTheme }), { registered: false, designs: [], dispose: undefined }, name);
292
+ assert.equal(bridge.calls.length, 0, `${name}: nothing reached the bridge`);
293
+ }
294
+ });
295
+
296
+ test('a release that cannot be read registers nothing at all: no probe, no api call, no store read', () => {
297
+ for (const [name, version] of [['no release member', undefined], ['a release that cannot be read', 'v0.12'], ['the release before the floor', '0.12.0'], ['a prerelease of the floor', '0.12.1-rc.1'], ['a build suffix on the floor', '0.12.1+build.7'], ['a prerelease above the floor', '0.12.2-rc.1'], ['a build suffix above the floor', '0.12.2+build.7'], ['trailing text after the numbers', '0.12.2garbage'], ['four parts', '1.0.0.0'], ['empty', '']]) {
298
+ for (const validatesFollows of [false, true]) {
299
+ const bridge = publishBridge({ version, toolLine: ACTIVITY, validatesFollows });
300
+ assert.deepEqual(registerMessageCards({ metrics, theme: plainTheme }), { registered: false, designs: [], dispose: undefined }, name);
301
+ // The api is never asked: a probe cannot tell a refused follow from an unrelated refusal, and a
302
+ // bridge that ignores the field would take the real designs as a `Message <type>` switch.
303
+ assert.equal(bridge.calls.length, 0, `${name}: nothing reaches the bridge`);
304
+ assert.deepEqual(bridge.designs, [], `${name}: nothing of ours can become a switch`);
305
+ }
306
+ }
307
+ });
308
+
309
+ test('a width too narrow for one body row hands the rows straight back', () => {
310
+ const outcome = registered();
311
+ for (const customType of MESSAGE_TYPES) {
312
+ const design = designFor(outcome, customType);
313
+ const lines = plainBody(customType, 'Exploration budget: 3 tracked lookups.');
314
+ for (const width of [1, 4, 5]) {
315
+ const context = { width, customType, theme: plainTheme, render: { expanded: false, outputPad: 1, message: {} } };
316
+ assert.deepEqual(design.apply(lines, context), lines, `${customType} at width ${width}`);
317
+ }
318
+ const painted = design.apply(lines, { width: 40, customType, theme: plainTheme, render: { expanded: false, outputPad: 1, message: {} } });
319
+ assert.notDeepEqual(painted, lines, `${customType}: a usable width still paints`);
320
+ }
321
+ });
322
+
323
+ test('a later release registers, and a bridge with no message-design surface registers nothing', () => {
324
+ for (const version of ['0.12.1', '0.12.2', '0.13.0', '1.0.0']) {
325
+ assert.equal(registered({ version }).registered, true, version);
326
+ }
327
+ // The capability itself, asked of two bridges: the release string decides, and nothing is asked of
328
+ // the bridge when it cannot be read as at least 0.12.1 (fail closed, never a probe).
329
+ assert.equal(bridgeTakesFollows({ VERSION: '0.12.1' }), true);
330
+ assert.equal(bridgeTakesFollows({ VERSION: '0.12.0' }), false, 'the follow exists there, but a stale message id could veto it');
331
+ assert.equal(bridgeTakesFollows({ VERSION: '0.11.9' }), false);
332
+ assert.equal(bridgeTakesFollows({ VERSION: '0.12.1-rc.1' }), false);
333
+ assert.equal(bridgeTakesFollows({ VERSION: '0.12.2-rc.1' }), false, 'a suffix above the floor is unreadable, not newer');
334
+ assert.equal(bridgeTakesFollows({ VERSION: '0.12.2garbage' }), false, 'trailing text is unreadable');
335
+ assert.equal(bridgeTakesFollows({ VERSION: '1.0.0.0' }), false, 'four parts are unreadable');
336
+ assert.equal(bridgeTakesFollows({ VERSION: '0.12' }), false, 'a two-part release below the floor is still below it');
337
+ assert.equal(bridgeTakesFollows({}), false, 'an unreadable release is not asked and not used');
338
+ const bare = publishBridge({ version: '0.12.1' });
339
+ delete globalThis[BRIDGE_API_SLOT].registerMessageDesign;
340
+ assert.deepEqual(registerMessageCards({ metrics, theme: plainTheme }), { registered: false, designs: [], dispose: undefined });
341
+ assert.equal(bare.calls.length, 0);
342
+ delete globalThis[BRIDGE_API_SLOT];
343
+ assert.deepEqual(registerMessageCards({ metrics, theme: plainTheme }), { registered: false, designs: [], dispose: undefined }, 'no bridge');
344
+ });
345
+
346
+ test('a refused registration is a no-registration, never a throw', () => {
347
+ const bridge = publishBridge({ version: '0.12.1', toolLine: ACTIVITY, validatesFollows: true });
348
+ const api = globalThis[BRIDGE_API_SLOT];
349
+ api.registerMessageDesign = () => { bridge.calls.push('refused'); throw new Error('refused'); };
350
+ assert.deepEqual(registerMessageCards({ metrics, theme: plainTheme }), { registered: false, designs: [], dispose: undefined });
351
+ assert.equal(bridge.calls.length, 1);
352
+ });
353
+
354
+ // ---- the heading (S5) ----
355
+
356
+ test('the exploration alert heads with its own mark, its name and the numbers the message states', () => {
357
+ const rows = cards(registered(), EXPLORATION, STARTED);
358
+ assert.equal(rows[0], headOf(EXPLORATION_HEADING, 70));
359
+ });
360
+
361
+ test('the verifier alert heads with its own mark, its name and the risk item the message states', () => {
362
+ const rows = cards(registered(), VERIFIER, VERIFIER_TEXT);
363
+ assert.equal(rows[0], headOf(VERIFIER_HEADING, 70));
364
+ });
365
+
366
+ test('a message that states no numbers is headed by its name alone, with no invented detail', () => {
367
+ const outcome = registered();
368
+ const bare = 'Exploration budget: this request used its lookups.';
369
+ assert.equal(cards(outcome, EXPLORATION, bare)[0], headOf('⌕ Exploration budget', 70));
370
+ assert.equal(cards(outcome, VERIFIER, 'Verification reminder: launch the verifier.')[0], headOf('⚑ Verifier reminder', 70));
371
+ });
372
+
373
+ test('the marks are this package\'s own: ⌕ for the budget, ⚑ for the reminder', () => {
374
+ const outcome = registered();
375
+ assert.match(unpaint(cards(outcome, EXPLORATION, STARTED)[0]), /^╭─ ⌕ Exploration budget/u);
376
+ assert.match(unpaint(cards(outcome, VERIFIER, VERIFIER_TEXT)[0]), /^╭─ ⚑ Verifier reminder/u);
377
+ });
378
+
379
+ // ---- the body (S2) ----
380
+
381
+ test('every row of the message is drawn at every content level, and the bridge\'s own decorations are dropped', () => {
382
+ const outcome = registered();
383
+ for (const level of [CARD_CONTENT.DEFAULT, CARD_CONTENT.MINIMAL]) {
384
+ globalThis[CARD_CONTENT_SLOT] = level;
385
+ for (const [customType, text] of [[EXPLORATION, STARTED], [VERIFIER, VERIFIER_TEXT]]) {
386
+ const rows = cards(outcome, customType, text, { content: level, keyHint: () => 'ctrl+o to expand' });
387
+ const joined = rows.map(unpaint).join('\n');
388
+ const body = bodyText(rows);
389
+ assert.doesNotMatch(joined, new RegExp(`\\[${customType.replace(/\./gu, '\\.')}\\]`, 'u'), `${customType} at ${level}: no label row`);
390
+ assert.match(body, /^Exploration budget: 1,234 tracked lookups|^Verification reminder: your final message/u, `${customType} at ${level}: the body starts straight away`);
391
+ for (const line of text.split('\n')) {
392
+ assert.ok(body.includes(line.replace(/\s+/gu, ' ')), `${customType} at ${level}: "${line}" is drawn`);
393
+ }
394
+ assert.doesNotMatch(joined, /to expand|to collapse|ctrl\+o/u, `${customType} at ${level}: no expand hint, even though the host offers one`);
395
+ }
396
+ }
397
+ delete globalThis[CARD_CONTENT_SLOT];
398
+ });
399
+
400
+ test('a long message is never capped: a twelve-row body draws twelve rows at minimal', () => {
401
+ const outcome = registered();
402
+ globalThis[CARD_CONTENT_SLOT] = CARD_CONTENT.MINIMAL;
403
+ const body = Array.from({ length: 12 }, (_unused, index) => `row ${index + 1} of the advisory message`);
404
+ const rows = cards(outcome, VERIFIER, body.join('\n'), {}).map(unpaint);
405
+ for (const line of body) assert.ok(rows.some((row) => row.includes(line)), `"${line}" is drawn`);
406
+ assert.equal(rows.length, 1 + body.length + 1, 'the heading, every body row and the closing rule');
407
+ delete globalThis[CARD_CONTENT_SLOT];
408
+ });
409
+
410
+ test('a body wider than the card is wrapped, never cut: the last words are still drawn', () => {
411
+ const outcome = registered();
412
+ const rows = cards(outcome, EXPLORATION, STARTED, {}, 40);
413
+ const body = bodyText(rows);
414
+ assert.ok(body.includes('initially small.'), 'the tail of the second row survives');
415
+ assert.ok(body.includes('not a new user request.'), 'the tail of the third row survives');
416
+ assertFramed(rows, 40);
417
+ });
418
+
419
+ test('expanding the host card changes nothing: there is nothing behind the card to reveal', () => {
420
+ const outcome = registered();
421
+ const collapsed = cards(outcome, EXPLORATION, STARTED);
422
+ const expanded = cards(outcome, EXPLORATION, STARTED, { render: { expanded: true, outputPad: 1, message: {} } });
423
+ assert.deepEqual(expanded, collapsed);
424
+ });
425
+
426
+ test('the rows the design is handed come back unchanged', () => {
427
+ const input = plainBody(EXPLORATION, STARTED);
428
+ const copy = [...input];
429
+ designFor(registered(), EXPLORATION).apply(input, { width: 70, customType: EXPLORATION, theme: plainTheme, render: { expanded: false, outputPad: 1, message: {} } });
430
+ assert.deepEqual(input, copy);
431
+ });
432
+
433
+ // ---- the style (S3) ----
434
+
435
+ test('the style is read from the host on every paint, never from the context', () => {
436
+ const outcome = registered();
437
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.FLOAT;
438
+ const float = cards(outcome, EXPLORATION, STARTED, { cardStyle: { kind: 'native' }, theme: bandTheme }).map(unpaint);
439
+ assert.match(float[0], /^\s*▎/u, 'the host says float, so the rail is drawn');
440
+ assert.doesNotMatch(float.join('\n'), /[╭╮╰╯]/u);
441
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.NEON;
442
+ const neon = cards(outcome, EXPLORATION, STARTED, { cardStyle: { kind: 'native' }, theme: bandTheme }).map(unpaint);
443
+ assert.match(neon[0], /^╭/u, 'the same design, flipped back, repaints the frame');
444
+ assert.doesNotMatch(neon.join('\n'), /▎/u);
445
+ });
446
+
447
+ test('a mid-session flip repaints a card already on screen, in both directions', () => {
448
+ const outcome = registered();
449
+ const seen = [CARD_STYLE.NEON, CARD_STYLE.FLOAT, CARD_STYLE.NEON].map((style) => {
450
+ globalThis[CARD_STYLE_SLOT] = style;
451
+ return cards(outcome, VERIFIER, VERIFIER_TEXT, { theme: bandTheme }).map(unpaint)[0];
452
+ });
453
+ assert.match(seen[0], /^╭/u);
454
+ assert.match(seen[1], /^\s*▎/u);
455
+ assert.match(seen[2], /^╭/u);
456
+ });
457
+
458
+ // ---- the palette (S5) ----
459
+
460
+ test('each card wears its own tone: info for the budget, warning for the reminder', () => {
461
+ const outcome = registered();
462
+ const budget = designFor(outcome, EXPLORATION).apply(plainBody(EXPLORATION, STARTED), { width: 70, customType: EXPLORATION, theme: taggedTheme, render: { expanded: false, outputPad: 1, message: {} } });
463
+ // INFO: the rounded frame keeps the theme's plain border role while the name carries the accent.
464
+ assert.ok(budget[0].includes('<accent>⌕</accent>'), budget[0]);
465
+ assert.ok(budget[0].includes('<border>╭'), 'the frame keeps the plain border role');
466
+ const reminder = designFor(outcome, VERIFIER).apply(plainBody(VERIFIER, VERIFIER_TEXT), { width: 70, customType: VERIFIER, theme: taggedTheme, render: { expanded: false, outputPad: 1, message: {} } });
467
+ // WARNING owns the box: frame and name both carry the warning role.
468
+ assert.ok(reminder[0].includes('<warning>⚑</warning>'), reminder[0]);
469
+ assert.ok(reminder[0].includes('<warning>╭'), 'the frame carries the tone');
470
+ });
471
+
472
+ test('every row fits the width the host asked for, at narrow and wide terminals, in both styles', () => {
473
+ const outcome = registered();
474
+ for (const style of [CARD_STYLE.NEON, CARD_STYLE.FLOAT]) {
475
+ globalThis[CARD_STYLE_SLOT] = style;
476
+ for (const width of [24, 40, 70, 120]) {
477
+ for (const [customType, text] of [[EXPLORATION, STARTED], [VERIFIER, VERIFIER_TEXT]]) {
478
+ const design = designFor(outcome, customType);
479
+ const rows = design.apply(plainBody(customType, text), { width, customType, theme: bandTheme, render: { expanded: false, outputPad: 1, message: {} } });
480
+ assertFramed(rows, width);
481
+ assert.ok(rows.length > 2, `${customType} at ${width}/${style} draws a body`);
482
+ for (const row of rows) assert.equal(typeof row, 'string');
483
+ }
484
+ }
485
+ }
486
+ });
487
+
488
+ // ---- the fallbacks (S4) ----
489
+
490
+ const PI_BOX = Object.freeze(['╭ Pi\'s own box ╮', '│ the body │', '╰──────────╯']);
491
+
492
+ test('a design that cannot measure hands the message back to Pi, because only the bridge knows its box', () => {
493
+ const outcome = registered();
494
+ assert.notEqual(designFor(outcome, EXPLORATION), undefined);
495
+ // The bridge's own rule (docs/contract.md §15): a throwing design loses only its own output.
496
+ const drawThrough = (design) => {
497
+ try {
498
+ return design.apply(plainBody(EXPLORATION, STARTED), { width: 70, customType: EXPLORATION, theme: plainTheme, render: { message: {} } });
499
+ } catch {
500
+ return PI_BOX;
501
+ }
502
+ };
503
+ // Registered WITHOUT a measurement seam: the card cannot measure, so it throws instead of
504
+ // answering rows wider than the terminal, and the bridge draws Pi's box.
505
+ const noSeam = registerMessageCards({ theme: plainTheme });
506
+ assert.equal(noSeam.registered, true, 'a host without a seam still registers the design');
507
+ assert.equal(drawThrough(designFor(noSeam, EXPLORATION)), PI_BOX, 'no metrics seam');
508
+ // A seam that is asked per paint and answers nothing usable is the same no.
509
+ const lateSeam = registerMessageCards({ metrics: () => undefined, theme: plainTheme });
510
+ assert.equal(drawThrough(designFor(lateSeam, EXPLORATION)), PI_BOX, 'a seam that answers nothing');
511
+ // The seam arriving later draws the card, with no re-registration.
512
+ let seam;
513
+ const arriving = registerMessageCards({ metrics: () => seam, theme: plainTheme });
514
+ assert.equal(drawThrough(designFor(arriving, EXPLORATION)), PI_BOX, 'still nothing to measure');
515
+ seam = metrics;
516
+ assert.match(drawThrough(designFor(arriving, EXPLORATION))[0], /^╭─ ⌕ Exploration budget/u, 'the seam is read on every paint');
517
+ });
518
+
519
+ test('a hostile message or context is never turned into rows that break the frame', () => {
520
+ const outcome = registered();
521
+ const design = designFor(outcome, EXPLORATION);
522
+ const context = { width: 70, customType: EXPLORATION, theme: plainTheme, render: { message: {} } };
523
+ // Not an array, no rows at all, and members that are not rows: the card still draws, and every
524
+ // row it answers is a string.
525
+ for (const lines of ['garbage', undefined, [], [null, 42, {}, 'the message']]) {
526
+ const rows = design.apply(lines, context);
527
+ assert.ok(Array.isArray(rows));
528
+ for (const row of rows) assert.equal(typeof row, 'string');
529
+ }
530
+ assert.ok(design.apply([null, 42, {}, 'the message'], context).some((row) => unpaint(row).includes('the message')));
531
+ // A theme that throws repaints nothing rather than breaking the render loop.
532
+ const throwing = { fg: () => { throw new Error('boom'); }, bg: () => { throw new Error('boom'); } };
533
+ assert.throws(() => design.apply(plainBody(EXPLORATION, STARTED), { ...context, theme: throwing }));
534
+ });