pi-odd-worktree 3.15.1 → 3.16.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.
Files changed (126) hide show
  1. package/README.md +48 -25
  2. package/extensions/odd-worktree-tools.ts +64 -211
  3. package/lib/shell-api/api.ts +523 -0
  4. package/lib/shell-api/arm.ts +83 -0
  5. package/lib/shell-api/bus.ts +1389 -0
  6. package/lib/shell-api/capture.ts +1340 -0
  7. package/lib/shell-api/card-style-line.ts +112 -0
  8. package/lib/shell-api/card-style-rows.ts +390 -0
  9. package/lib/shell-api/card-style-transform.ts +862 -0
  10. package/lib/shell-api/card-style-wiring.ts +477 -0
  11. package/lib/shell-api/card-styles.ts +153 -0
  12. package/lib/shell-api/config.ts +71 -0
  13. package/lib/shell-api/extension.ts +247 -0
  14. package/lib/shell-api/hook.ts +322 -0
  15. package/lib/shell-api/index.ts +88 -0
  16. package/lib/shell-api/message-design-adoption.ts +549 -0
  17. package/lib/shell-api/message-design-rows.ts +313 -0
  18. package/lib/shell-api/message-design-wiring.ts +369 -0
  19. package/lib/shell-api/message-designs.ts +746 -0
  20. package/lib/shell-api/notices.ts +137 -0
  21. package/lib/shell-api/plugin-lines.ts +877 -0
  22. package/lib/shell-api/presence.ts +258 -0
  23. package/lib/shell-api/repaint.ts +351 -0
  24. package/lib/shell-api/row-labels.ts +146 -0
  25. package/lib/shell-api/row-names.ts +273 -0
  26. package/lib/shell-api/row-origin.ts +144 -0
  27. package/lib/shell-api/rows.ts +591 -0
  28. package/lib/shell-api/section-panel.ts +378 -0
  29. package/lib/shell-api/section-pointer.ts +164 -0
  30. package/lib/shell-api/sections-preview.ts +275 -0
  31. package/lib/shell-api/sections-rows.ts +133 -0
  32. package/lib/shell-api/sidebar-render.ts +705 -0
  33. package/lib/shell-api/sidebar.ts +1126 -0
  34. package/lib/shell-api/store.ts +279 -0
  35. package/lib/shell-api/tool-design-adoption.ts +263 -0
  36. package/lib/shell-api/tool-design-rows.ts +307 -0
  37. package/lib/shell-api/tool-design-wiring.ts +481 -0
  38. package/lib/shell-api/tool-designs.ts +1411 -0
  39. package/lib/shell-api/transform-pipeline.ts +351 -0
  40. package/lib/shell-api/types.ts +803 -0
  41. package/lib/shell-api/visibility.ts +154 -0
  42. package/package.json +3 -2
  43. package/tools/files-bridge.test.js +81 -66
  44. package/tools/fixtures/load-extension.js +40 -18
  45. package/tools/issues-command.test.js +4 -7
  46. package/tools/issues-section.test.js +71 -81
  47. package/tools/odd-rail-wiring.test.js +16 -10
  48. package/tools/package-surface.test.js +42 -13
  49. package/tools/prs-command.test.js +11 -6
  50. package/tools/shell-api/api.test.ts +484 -0
  51. package/tools/shell-api/apply-on-move.test.ts +529 -0
  52. package/tools/shell-api/arm.test.ts +220 -0
  53. package/tools/shell-api/bridge-ready.test.ts +309 -0
  54. package/tools/shell-api/bus.test.ts +194 -0
  55. package/tools/shell-api/button-rows.test.ts +435 -0
  56. package/tools/shell-api/capture.test.ts +583 -0
  57. package/tools/shell-api/card-style-rows.test.ts +493 -0
  58. package/tools/shell-api/card-style-transform.test.ts +379 -0
  59. package/tools/shell-api/card-style-wiring.test.ts +258 -0
  60. package/tools/shell-api/card-styles-e2e.test.ts +502 -0
  61. package/tools/shell-api/card-styles.test.ts +324 -0
  62. package/tools/shell-api/card-transcript-path.test.ts +178 -0
  63. package/tools/shell-api/compatibility-regression.test.mjs +64 -0
  64. package/tools/shell-api/config.test.ts +93 -0
  65. package/tools/shell-api/docs-coverage.test.ts +82 -0
  66. package/tools/shell-api/e2e.test.ts +562 -0
  67. package/tools/shell-api/example-bash-identity.test.ts +372 -0
  68. package/tools/shell-api/example-bash-matrix.test.ts +856 -0
  69. package/tools/shell-api/example-designs.test.ts +737 -0
  70. package/tools/shell-api/example-neon-transform.test.ts +283 -0
  71. package/tools/shell-api/example-plain-style.test.ts +1225 -0
  72. package/tools/shell-api/extension.test.ts +157 -0
  73. package/tools/shell-api/fake-events.ts +58 -0
  74. package/tools/shell-api/fake-host.ts +211 -0
  75. package/tools/shell-api/fake-sidebar.ts +516 -0
  76. package/tools/shell-api/fake-transcript.ts +486 -0
  77. package/tools/shell-api/frame-telemetry.test.ts +317 -0
  78. package/tools/shell-api/hook.test.ts +196 -0
  79. package/tools/shell-api/manifest.test.ts +47 -0
  80. package/tools/shell-api/message-design-adoption.test.ts +611 -0
  81. package/tools/shell-api/message-design-follows.test.ts +361 -0
  82. package/tools/shell-api/message-design-pi-release.test.mjs +157 -0
  83. package/tools/shell-api/message-design-regressions.test.mjs +162 -0
  84. package/tools/shell-api/message-design-rows.test.ts +266 -0
  85. package/tools/shell-api/message-design-wiring.test.ts +362 -0
  86. package/tools/shell-api/message-designs.test.ts +339 -0
  87. package/tools/shell-api/new-category.test.ts +1101 -0
  88. package/tools/shell-api/notices.test.ts +292 -0
  89. package/tools/shell-api/plugin-integration-lines.test.ts +827 -0
  90. package/tools/shell-api/presence.test.ts +396 -0
  91. package/tools/shell-api/rail-part-hits.test.ts +281 -0
  92. package/tools/shell-api/rail-surfaces.test.ts +402 -0
  93. package/tools/shell-api/rail-width.test.ts +406 -0
  94. package/tools/shell-api/regression.test.ts +434 -0
  95. package/tools/shell-api/repaint-api.test.ts +200 -0
  96. package/tools/shell-api/reserved-categories.test.ts +250 -0
  97. package/tools/shell-api/row-labels.test.ts +261 -0
  98. package/tools/shell-api/row-names.test.ts +407 -0
  99. package/tools/shell-api/row-origin.test.ts +395 -0
  100. package/tools/shell-api/row-placement-regression.test.ts +797 -0
  101. package/tools/shell-api/row-placement.test.ts +410 -0
  102. package/tools/shell-api/section-interaction.test.ts +364 -0
  103. package/tools/shell-api/section-panel.test.ts +430 -0
  104. package/tools/shell-api/section-placement-rail.test.ts +390 -0
  105. package/tools/shell-api/section-placement.test.ts +386 -0
  106. package/tools/shell-api/sections-preview.test.ts +312 -0
  107. package/tools/shell-api/sections-rows.test.ts +293 -0
  108. package/tools/shell-api/sidebar-backend.test.ts +477 -0
  109. package/tools/shell-api/sidebar-e2e.test.ts +317 -0
  110. package/tools/shell-api/sidebar-hover.test.ts +276 -0
  111. package/tools/shell-api/sidebar-independent.test.ts +291 -0
  112. package/tools/shell-api/sidebar-render.test.ts +281 -0
  113. package/tools/shell-api/sidebar-sections.test.ts +247 -0
  114. package/tools/shell-api/store.test.ts +192 -0
  115. package/tools/shell-api/surface-repaint-cost.test.ts +520 -0
  116. package/tools/shell-api/tool-design-card-style.test.ts +308 -0
  117. package/tools/shell-api/tool-design-chain.test.ts +471 -0
  118. package/tools/shell-api/tool-design-cost.test.ts +591 -0
  119. package/tools/shell-api/tool-design-rows.test.ts +627 -0
  120. package/tools/shell-api/tool-design-scopes-audit.test.ts +212 -0
  121. package/tools/shell-api/tool-designs.test.ts +2412 -0
  122. package/tools/shell-api/transform-pipeline.test.ts +376 -0
  123. package/tools/shell-api/transforms-bus.test.ts +233 -0
  124. package/tools/shell-api/verifier-width-regressions.test.ts +147 -0
  125. package/tools/shell-api-rpc.test.js +189 -0
  126. package/tools/user-prompt-card.test.js +8 -9
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Turning visible text into a settings row LABEL (N1–N3).
3
+ *
4
+ * The host prints `choice.setting` as a toggle line's name and `label` as a row's text
5
+ * (`lib/visual-customize-view.ts:583-595`), so anything the bridge puts in either field is read by
6
+ * a human. An id is not a label: `Section: bash-card.status` was a prefix nobody asked for plus a
7
+ * dotted internal key, and a plugin author copying the docs copied the shape.
8
+ *
9
+ * The rule, in one place so both surfaces cannot drift:
10
+ *
11
+ * - `rowLabel`, when the author gives one, is used verbatim — the author knows what a user reads.
12
+ * The one thing it must satisfy is the shape every row name satisfies (one to three plain words,
13
+ * no structural marks): a name that breaks it is rejected at registration and reported, never
14
+ * rewritten (`./row-names.ts`, N7–N9).
15
+ * - otherwise the bridge derives one from the visible text the author already wrote (`title` for a
16
+ * section, `label` for a card style): lowercase words joined by single spaces, dots and the rest
17
+ * of the punctuation dropped, no prefix, clamped to the same word limit. `"BASH CARD"` →
18
+ * `"bash card"`, `"usageCost"` → `"usage cost"`, `"bash-card.status"` → `"bash card status"`,
19
+ * `"MUSIC PLAYER NOW PLAYING"` → `"music player now"`. A derived name therefore always passes the
20
+ * shape check the bridge applies to an explicit one. * - two sections whose labels would read the same are told apart deterministically, and never by
21
+ * appending the raw id: the first keeps `music`, the next gets `music 2`, `music 3`, …
22
+ * the diagnostics record reports the same assignment (see `sectionRowLabels`) instead of recomputing it.
23
+ *
24
+ * The id stays identity: the replacement key, the disposer's key and the visibility store's key.
25
+ * Nothing in this module reads an id, so no id can leak into a row.
26
+ *
27
+ * This module is internal: `src/index.ts` does not re-export it.
28
+ */
29
+
30
+ import { MAX_ROW_NAME_WORDS } from "./row-names.ts";
31
+ import type { CardStyleRegistration, SidebarSection } from "./types.ts";
32
+
33
+ /** Possessives lose the apostrophe instead of splitting one word in two: `Loon's` → `loons`. */
34
+ const APOSTROPHES = /['’]/gu;
35
+ /** `XMLHttp` → `XML Http`, before the lower→upper rule below runs on the remainder. */
36
+ const ACRONYM_BREAK = /(\p{Lu}+)(\p{Lu}\p{Ll})/gu;
37
+ /** `usageCost` → `usage Cost`. */
38
+ const CAMEL_BREAK = /(\p{Ll}|\p{N})(\p{Lu})/gu;
39
+ /** Everything that is not a letter or a digit: dots, dashes, arrows, runs of spaces. */
40
+ const NON_WORD = /[^\p{L}\p{N}]+/gu;
41
+
42
+ /**
43
+ * The readable form of one piece of visible text: lowercase words joined by single spaces, with
44
+ * every non-word character — a dot above all — turned into a word break.
45
+ *
46
+ * Returns the empty string when the text carries no letters or digits at all (`"···"`); the
47
+ * callers then use their surface's fallback word rather than inventing an id-shaped label.
48
+ */
49
+ export function deriveRowLabel(text: string): string {
50
+ return String(text)
51
+ .replace(APOSTROPHES, "")
52
+ .replace(ACRONYM_BREAK, "$1 $2")
53
+ .replace(CAMEL_BREAK, "$1 $2")
54
+ .replace(NON_WORD, " ")
55
+ .trim()
56
+ .toLowerCase();
57
+ }
58
+
59
+ /** A title with no words still needs a label; this is the section one. */
60
+ export const SECTION_LABEL_FALLBACK = "section";
61
+ /** The card-style counterpart, used for a label that carries no words. */
62
+ export const CARD_STYLE_LABEL_FALLBACK = "card style";
63
+
64
+ /**
65
+ * Apply the row-name shape to derived text (N8): the same one-to-three-plain-words limit the bridge
66
+ * enforces on an author's name. Marks are already gone — `NON_WORD` turned every one of them into a
67
+ * word break — so clamping is what keeps a long title from deriving a name the bridge would reject.
68
+ *
69
+ * Clamping is the ONLY transformation the bridge performs, and it is confined to text it derives
70
+ * itself: an author's own `rowLabel` is never rewritten, it is rejected (`./row-names.ts`).
71
+ */
72
+ function clampWords(text: string): string {
73
+ return text
74
+ .split(" ")
75
+ .filter((word) => word !== "")
76
+ .slice(0, MAX_ROW_NAME_WORDS)
77
+ .join(" ");
78
+ }
79
+
80
+ /** The label a section's row reads: the author's `rowLabel`, else the title made readable. */
81
+ export function sectionRowLabelText(section: Pick<SidebarSection, "title" | "rowLabel">): string {
82
+ if (section.rowLabel !== undefined) return section.rowLabel;
83
+ const derived = clampWords(deriveRowLabel(section.title));
84
+ return derived === "" ? SECTION_LABEL_FALLBACK : derived;
85
+ }
86
+
87
+ /** The label a card style's row reads: the author's `rowLabel`, else the style `label`. */
88
+ export function cardStyleRowLabelText(
89
+ style: Pick<CardStyleRegistration, "label" | "rowLabel">,
90
+ ): string {
91
+ if (style.rowLabel !== undefined) return style.rowLabel;
92
+ const derived = clampWords(deriveRowLabel(style.label));
93
+ return derived === "" ? CARD_STYLE_LABEL_FALLBACK : derived;
94
+ }
95
+
96
+ /** One section with the label its two `Sections` rows will read. */
97
+ export interface SectionRowLabel {
98
+ section: SidebarSection;
99
+ /** The label itself; unique among the labels of this build. */
100
+ label: string;
101
+ /** The label before disambiguation: the author's `rowLabel`, or the derived title. */
102
+ base: string;
103
+ /** Present when `base` was already taken: the label this section had to move away from. */
104
+ collision?: string;
105
+ }
106
+
107
+ /**
108
+ * Assign every section its row label, in the order the sections render: an explicit `rowLabel` or
109
+ * the derived title, then the lowest free ordinal suffix (`music 2`, `music 3`, …) when another
110
+ * section already took the label — clamped, like the base, to the row-name word limit.
111
+ *
112
+ * Deterministic by construction: the input order is the render order (`snapshotSections`), the
113
+ * suffix is the lowest free integer, and nothing depends on map iteration or on time. A
114
+ * replacement or a disposal can legitimately move a section between `music` and `music 2`; the
115
+ * result is still one assignment per build, and the diagnostics record reports the one in force.
116
+ *
117
+ * Equality is exact, the way the host compares `choice.setting`: `Music` and `music` are two
118
+ * different line names. A derived label is always lowercase, so a clash between two derived labels
119
+ * is always caught.
120
+ */
121
+ /**
122
+ * The label an equal base takes when another registration already reads it: the base plus the
123
+ * lowest free ordinal. The result still honours the row-name word limit, so a three-word base yields
124
+ * `music player 2` (the ordinal replaces its last word) instead of a four-word name the bridge would
125
+ * have refused from an author. Deterministic: the input order is the render order and the ordinal is
126
+ * the lowest free integer.
127
+ */
128
+ function disambiguate(base: string, suffix: number): string {
129
+ const words = base.split(" ");
130
+ const kept = words.length >= MAX_ROW_NAME_WORDS ? words.slice(0, MAX_ROW_NAME_WORDS - 1) : words;
131
+ return `${kept.join(" ")} ${suffix}`;
132
+ }
133
+
134
+ export function sectionRowLabels(
135
+ sections: readonly SidebarSection[],
136
+ ): SectionRowLabel[] {
137
+ const taken = new Set<string>();
138
+ return sections.map((section) => {
139
+ const base = sectionRowLabelText(section);
140
+ let label = base;
141
+ let suffix = 2;
142
+ while (taken.has(label)) label = disambiguate(base, suffix++);
143
+ taken.add(label);
144
+ return label === base ? { section, label, base } : { section, label, base, collision: base };
145
+ });
146
+ }
@@ -0,0 +1,273 @@
1
+ /**
2
+ * The row-name SHAPE (N7–N9): one rule, one enforcement point per boundary.
3
+ *
4
+ * A row name is what a human reads where a setting line's name goes — an entry provider's
5
+ * `choice.setting`, or the label of the row a provider, a section or a card style contributes. The
6
+ * host names its own rows in one to three plain words (`Card style`, `stats`); a bridge row read
7
+ * `Bash card → Bash rendering`, which is a breadcrumb with an arrow and a repeated qualifier, not a
8
+ * name. Third instance of one class of defect, so the rule is stated once here and applied by both
9
+ * boundaries that can create a row name:
10
+ *
11
+ * - **registration** (`./bus.ts`): a section's or a card style's row label is checked before the
12
+ * registration is stored. Nothing is stored when it fails, so the rejected entry can never reach
13
+ * the menu and the diagnostics record's registry tables.
14
+ * - **menu build** (`./rows.ts`): a provider's rows exist only when its `rows(ctx)` runs, so the
15
+ * line name (`choice.setting`) and the row label are checked there. A rejected row is dropped from
16
+ * the array the host receives AND from the build record the diagnostics record reads, so it is absent
17
+ * from the "effective set" rather than merely hidden.
18
+ *
19
+ * ## The rule
20
+ *
21
+ * One to `MAX_ROW_NAME_WORDS` plain words (`Bash rendering`, `Loon banner source`), with none of
22
+ * `ROW_NAME_MARKS`: an arrow, a colon, a dot, a pipe, a slash or a bracket. Those are the characters
23
+ * that make a name read as a path, a key or a breadcrumb instead of a name.
24
+ *
25
+ * ## The one reserved category (S15)
26
+ *
27
+ * A second, unrelated rule lives here because it needs the SAME report: `Keymaps` is the host's own
28
+ * interaction (key capture, `keymaps.json`, a category footer promising `Enter assign`) and is
29
+ * closed to plugins. A provider registered with that category is refused at registration
30
+ * (`./bus.ts`), and a single row whose own category is that page is dropped at build time
31
+ * (`./rows.ts`) — the shapes are different, the channel is one, and a reader of
32
+ * the diagnostics record finds every refused row in one list instead of learning a second report. The
33
+ * comparison is trimmed and case-insensitive (`Keymaps`, ` keymaps `, `KEYMAPS`), because they all
34
+ * name the same page; a near miss (`Keymap`, `Key maps`) is an ordinary category of its own.
35
+ *
36
+ * ## Reject and report, never rewrite
37
+ *
38
+ * The bridge does NOT sanitize a name: `Bash card → Bash rendering` staying in a report as
39
+ * `Bash card → Bash rendering` is what lets an author find and fix it. So the offending string is
40
+ * recorded verbatim with the rule it broke, the diagnostics record lists the pair, and the row simply does
41
+ * not exist. Derivation (`./row-labels.ts`) is the one place that transforms text, and it applies the
42
+ * same shape — marks become word breaks with the rest of the punctuation, and the result is clamped
43
+ * to the word limit — so a derived name can never be rejected.
44
+ *
45
+ * The record is keyed by surface + id + field: a rejected registration that is later corrected
46
+ * replaces its own record, and a build that now produces a conforming name clears the stale one, so
47
+ * the report always describes the current state instead of accumulating history.
48
+ *
49
+ * This module is internal: `src/index.ts` does not re-export it.
50
+ */
51
+
52
+ /** A row name is at most this many words. One word is a name (`stats`); four is a sentence. */
53
+ export const MAX_ROW_NAME_WORDS = 3;
54
+
55
+ /**
56
+ * Characters that make a name read as a structure rather than a name: arrows, the colon, the dot,
57
+ * the pipe, both slashes and the bracket family. The docs list them (N9), so they stay one list.
58
+ */
59
+ export const ROW_NAME_MARKS: readonly string[] = [
60
+ "→",
61
+ "←",
62
+ "↑",
63
+ "↓",
64
+ ":",
65
+ ".",
66
+ "|",
67
+ "/",
68
+ "\\",
69
+ "[",
70
+ "]",
71
+ "(",
72
+ ")",
73
+ "{",
74
+ "}",
75
+ ];
76
+
77
+ /**
78
+ * The ways a row can be refused, with `reason` naming it in words: a structural `mark`, the
79
+ * `words` limit, or the `reserved category` rule (S15).
80
+ */
81
+ export type RowNameRule = "mark" | "words" | "reserved category";
82
+
83
+ export interface RowNameProblem {
84
+ rule: RowNameRule;
85
+ /** One sentence naming the offending text and the rule; reported verbatim by the diagnostics record. */
86
+ reason: string;
87
+ }
88
+
89
+ /** The mark rule, quoted in every rejection it produces so the reason stands on its own. */
90
+ const MARK_RULE =
91
+ "a row name is one to three plain words with no arrow, colon, dot, pipe, slash or bracket";
92
+ /** The word rule, likewise. */
93
+ const WORD_RULE = "a row name is one to three plain words";
94
+
95
+ /** Where a rejected name came from: a provider's rows, a section, a card style. */
96
+ export type RowNameSurface = "rows" | "section" | "card style";
97
+
98
+ /**
99
+ * Which part of a row carried it: `choice.setting`, the row's visible label, or the `category` it
100
+ * asked for (the one reserved-category case).
101
+ */
102
+ export type RowNameField = "line name" | "row label" | "category";
103
+
104
+ /**
105
+ * The categories the host owns and works differently (S15): `Keymaps` captures keys and writes
106
+ * `keymaps.json`, and its page footer promises `Enter assign` (`lib/visual-customize-view.ts:40`,
107
+ * `lib/keymaps-customize.ts:49-68`). A plugin row there would be advertised as an assignable binding
108
+ * and could never honour it, so the whole page is closed until the host opens it.
109
+ */
110
+ export const RESERVED_CATEGORIES: readonly string[] = ["Keymaps"];
111
+
112
+ /** Why a reserved category is closed, quoted by every refusal so the reason stands on its own. */
113
+ export const RESERVED_CATEGORY_RULE =
114
+ "works differently in the host (its own key capture and footer); not open to plugins yet";
115
+
116
+ /**
117
+ * The reserved category this value names, or `undefined` when a plugin may use it. Compared trimmed
118
+ * and case-insensitively: the host's page is a literal string, and `KEYMAPS` would render a second
119
+ * page next to the host's own, so a near match is refused instead of creating a twin.
120
+ */
121
+ export function reservedCategory(category: unknown): string | undefined {
122
+ if (typeof category !== "string") return undefined;
123
+ const wanted = category.trim().toLowerCase();
124
+ return RESERVED_CATEGORIES.find((reserved) => reserved.toLowerCase() === wanted);
125
+ }
126
+
127
+ /**
128
+ * Drop one provider row that asked for a reserved category, and record the refusal verbatim (S15).
129
+ * Returns `true` when the row was refused, so the caller drops exactly that row and keeps its
130
+ * siblings. A conforming category records nothing and returns `false`.
131
+ */
132
+ export function rejectReservedCategory(providerId: string, category: unknown): boolean {
133
+ const reserved = reservedCategory(category);
134
+ if (reserved === undefined) return false;
135
+ const value = typeof category === "string" ? category : String(category);
136
+ recordRowNameRejection({
137
+ surface: "rows",
138
+ id: providerId,
139
+ field: "category",
140
+ value,
141
+ rule: "reserved category",
142
+ reason: `it is the reserved category ${JSON.stringify(reserved)}, which ${RESERVED_CATEGORY_RULE}`,
143
+ });
144
+ return true;
145
+ }
146
+
147
+ /** One rejected name, kept verbatim so the author can find it and fix it. */
148
+ export interface RowNameRejection {
149
+ surface: RowNameSurface;
150
+ /** The provider, section or style id the name belonged to. */
151
+ id: string;
152
+ field: RowNameField;
153
+ /** The offending string, EXACTLY as the author wrote it. Never rewritten. */
154
+ value: string;
155
+ rule: RowNameRule;
156
+ reason: string;
157
+ }
158
+
159
+ /** The words in a name; the trim means runs of spaces and a padded string are not extra words. */
160
+ function wordCount(text: string): number {
161
+ const trimmed = text.trim();
162
+ return trimmed === "" ? 0 : trimmed.split(/\s+/u).length;
163
+ }
164
+
165
+ /**
166
+ * What is wrong with this name, or `undefined` when it is a usable row name.
167
+ *
168
+ * Checks run in a fixed order — marks first, then the word limit — so the reported reason is
169
+ * deterministic: `Bash card → Bash rendering` is a mark violation (and a word-limit one), and the
170
+ * author is told about the arrow, the defect the user actually saw.
171
+ */
172
+ export function rowNameProblem(value: string): RowNameProblem | undefined {
173
+ const text = String(value);
174
+ for (const mark of ROW_NAME_MARKS) {
175
+ if (text.includes(mark)) {
176
+ return { rule: "mark", reason: `it contains ${JSON.stringify(mark)}; ${MARK_RULE}` };
177
+ }
178
+ }
179
+ const count = wordCount(text);
180
+ if (count < 1 || count > MAX_ROW_NAME_WORDS) {
181
+ return { rule: "words", reason: `it has ${count} words; ${WORD_RULE}` };
182
+ }
183
+ return undefined;
184
+ }
185
+
186
+ /** Stable process-global slot, like the bus and the notice buffer: two copies must agree. */
187
+ const ROW_NAMES_KEY = Symbol.for("gentle-shell-bridge.row-names.v1");
188
+
189
+ interface RowNameState {
190
+ /** One record per surface + id + field, in the order the first rejection appeared. */
191
+ rejections: RowNameRejection[];
192
+ }
193
+
194
+ function rowNamesHost(): Record<symbol, RowNameState | undefined> {
195
+ // SAFETY: only `rowNameState()` writes this key, and it re-checks the list before trusting a
196
+ // value left by another copy or an earlier load.
197
+ return globalThis as unknown as Record<symbol, RowNameState | undefined>;
198
+ }
199
+
200
+ function rowNameState(): RowNameState {
201
+ const host = rowNamesHost();
202
+ const existing = host[ROW_NAMES_KEY];
203
+ if (existing !== undefined && Array.isArray(existing.rejections)) return existing;
204
+ const created: RowNameState = { rejections: [] };
205
+ host[ROW_NAMES_KEY] = created;
206
+ return created;
207
+ }
208
+
209
+ function sameSlot(
210
+ a: RowNameRejection,
211
+ b: Pick<RowNameRejection, "surface" | "id" | "field" | "value">,
212
+ ): boolean {
213
+ return a.surface === b.surface && a.id === b.id && a.field === b.field && a.value === b.value;
214
+ }
215
+
216
+ /**
217
+ * Record a rejection, replacing an identical one so a build cannot grow the list by repeating
218
+ * itself. Two DIFFERENT offending strings from one registration are two records: each is a name the
219
+ * author has to fix, and collapsing them would hide one.
220
+ */
221
+ export function recordRowNameRejection(rejection: RowNameRejection): void {
222
+ const state = rowNameState();
223
+ const index = state.rejections.findIndex((candidate) => sameSlot(candidate, rejection));
224
+ if (index === -1) state.rejections.push(rejection);
225
+ else state.rejections[index] = rejection;
226
+ }
227
+
228
+ /**
229
+ * Forget every rejection for one registration: a build or a re-registration is the new evidence, so
230
+ * a name that is no longer in force is no longer reported.
231
+ */
232
+ export function clearRowNameRejections(surface: RowNameSurface, id: string): void {
233
+ const state = rowNameState();
234
+ for (let index = state.rejections.length - 1; index >= 0; index -= 1) {
235
+ const candidate = state.rejections[index];
236
+ if (candidate.surface === surface && candidate.id === id) state.rejections.splice(index, 1);
237
+ }
238
+ }
239
+
240
+ /**
241
+ * Apply the rule to one name: record a violation and return `true`, or record nothing and return
242
+ * `false`. The caller decides what "rejected" means on its surface (do not store a registration;
243
+ * drop a row), and the caller clears a previous record when its new state has no violation — only it
244
+ * knows whether the name it is checking replaced the earlier one or sits beside it.
245
+ */
246
+ export function rejectRowName(
247
+ surface: RowNameSurface,
248
+ id: string,
249
+ field: RowNameField,
250
+ value: string,
251
+ ): boolean {
252
+ const problem = rowNameProblem(value);
253
+ if (problem === undefined) return false;
254
+ recordRowNameRejection({
255
+ surface,
256
+ id,
257
+ field,
258
+ value: String(value),
259
+ rule: problem.rule,
260
+ reason: problem.reason,
261
+ });
262
+ return true;
263
+ }
264
+
265
+ /** A fresh copy, so a report cannot mutate the registry. */
266
+ export function getRowNameRejections(): RowNameRejection[] {
267
+ return rowNameState().rejections.map((rejection) => ({ ...rejection }));
268
+ }
269
+
270
+ /** Test-only seam; deliberately not re-exported from `src/index.ts`. */
271
+ export function resetRowNameRejectionsForTests(): void {
272
+ rowNameState().rejections.length = 0;
273
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Row origin (T1): WHICH host child drew each row of a frame the conversation just rendered.
3
+ *
4
+ * ## Why the map is derived, never guessed
5
+ *
6
+ * A plugin that wants to restyle `bash` cards needs the host's own identity for a row. The drawn
7
+ * title cannot carry it: the host heads a bash card with the inferred activity
8
+ * (`theme.bold(identity.activity ?? "bash")`, `cards-bash-v2` `extensions/quiet-tools.ts:672`), so a
9
+ * grammar over the words breaks the next time a title changes. `pi-cinlodev-cute` reads it from the
10
+ * component instead (`src/transcript/transcript-dispatcher.ts:30-40`: `child.toolName === "bash"`).
11
+ *
12
+ * ## Where the map comes from
13
+ *
14
+ * `pi-tui`'s `Container.render(width)` renders each child and publishes the layout it used
15
+ * (`pi-tui/dist/tui.js:136-149`):
16
+ *
17
+ * ```ts
18
+ * this.mouseLayout = { width, children: [{ component, height }] };
19
+ * return lines;
20
+ * ```
21
+ *
22
+ * So the conversation component — the one `./card-style-wiring.ts` wraps — already carries a
23
+ * per-child row count after ITS OWN render returns. This module reads that, and nothing else: it
24
+ * never calls `render` (no second render, no children rendered twice on the normal path), never
25
+ * replaces `Container.render`, and never inspects a child's output.
26
+ *
27
+ * ## An unknown origin is an empty map, never a partial one
28
+ *
29
+ * The layout is host state this package does not own, so every way it can disagree with the frame is
30
+ * a REPORTED absence: no layout at all, a layout measured at another width, heights that do not add
31
+ * up to the returned line count, or an entry of the wrong shape. Each yields `rows: []` plus a
32
+ * `reason`, because a partial map would attribute rows to the wrong child — a plugin would restyle
33
+ * the wrong card, or cut a card in half. Nothing here throws into the host's render loop.
34
+ *
35
+ * This module is internal: `src/index.ts` does not re-export it. The TYPE it produces (`RowOrigin`)
36
+ * is part of the public contract (`./types.ts`), because a transform receives it through `ctx.rows`.
37
+ */
38
+
39
+ import { isRecord } from "./rows.ts";
40
+ import type { RowOrigin } from "./types.ts";
41
+
42
+ /** Why a frame's origins are unknown. Every value is reported, none is a guess. */
43
+ export type RowOriginAbsence =
44
+ /** The component published no `mouseLayout`: not a `Container`, or a render that never ran. */
45
+ | "no-layout"
46
+ /** The layout was measured at a width other than the one this frame was rendered at. */
47
+ | "width-mismatch"
48
+ /** The layout's heights do not add up to the line count the render returned. */
49
+ | "height-mismatch"
50
+ /** The layout itself is malformed: a non-array `children`, a bad `height`, a non-object child. */
51
+ | "bad-layout";
52
+
53
+ /** A frame's origins: one entry per row, or an empty list plus the reason it is empty. */
54
+ export interface RowOriginMap {
55
+ readonly rows: readonly RowOrigin[];
56
+ /** Present exactly when `rows` is empty because the layout could not be trusted. */
57
+ readonly reason?: RowOriginAbsence;
58
+ }
59
+
60
+ /** The empty row list every absence shares; frozen, because nothing may add to it. */
61
+ const NO_ROWS: readonly RowOrigin[] = Object.freeze([]);
62
+
63
+ /** An absent map: no rows, and the reason a caller can report. */
64
+ function absent(reason: RowOriginAbsence): RowOriginMap {
65
+ return { rows: NO_ROWS, reason };
66
+ }
67
+
68
+ /** A child component's `constructor.name`, or `undefined` when it has none worth reporting. */
69
+ function constructorName(child: Record<string, unknown>): string | undefined {
70
+ const constructor = child.constructor;
71
+ if (typeof constructor !== "function") return undefined;
72
+ const name = constructor.name;
73
+ return name === "" ? undefined : name;
74
+ }
75
+
76
+ /**
77
+ * The `toolName` a child carries, when it carries one as a string — the same member
78
+ * `pi-cinlodev-cute` reads (`src/transcript/transcript-dispatcher.ts:30-40`). Anything else (a
79
+ * number, an object, nothing) is not a tool name and is left out rather than coerced.
80
+ */
81
+ function toolNameOf(child: Record<string, unknown>): string | undefined {
82
+ const tool = child.toolName;
83
+ return typeof tool === "string" ? tool : undefined;
84
+ }
85
+
86
+ /**
87
+ * The identity one child contributes to every row it drew. Both members are read ONCE per child, so
88
+ * a row entry is a plain value a plugin can keep: no component reference, no live host object.
89
+ */
90
+ interface ChildIdentity {
91
+ readonly toolName?: string;
92
+ readonly component?: string;
93
+ }
94
+
95
+ function identityOf(child: Record<string, unknown>): ChildIdentity {
96
+ const toolName = toolNameOf(child);
97
+ const component = constructorName(child);
98
+ return {
99
+ ...(toolName === undefined ? {} : { toolName }),
100
+ ...(component === undefined ? {} : { component }),
101
+ };
102
+ }
103
+
104
+ /** Whether a layout entry's `height` is a row count this map may expand: a whole number, not negative. */
105
+ function isHeight(value: unknown): value is number {
106
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
107
+ }
108
+
109
+ /**
110
+ * One `RowOrigin` per row of the frame the host just drew, in row order.
111
+ *
112
+ * `component` is the conversation component AFTER its own `render(width)` returned (so its
113
+ * `mouseLayout` is this frame's layout), `width` is the width that render was asked for, and
114
+ * `lineCount` is how many rows it returned — the frame a transform then receives.
115
+ *
116
+ * Returns a complete map, or `{ rows: [], reason }`: never a throw, never an entry for only part of
117
+ * the frame.
118
+ */
119
+ export function rowOrigins(component: unknown, width: number, lineCount: number): RowOriginMap {
120
+ if (!isRecord(component)) return absent("no-layout");
121
+ const layout = component.mouseLayout;
122
+ if (!isRecord(layout)) return absent("no-layout");
123
+ if (typeof layout.width !== "number") return absent("bad-layout");
124
+ if (layout.width !== width) return absent("width-mismatch");
125
+ const children = layout.children;
126
+ if (!Array.isArray(children)) return absent("bad-layout");
127
+
128
+ const rows: RowOrigin[] = [];
129
+ for (const entry of children) {
130
+ if (!isRecord(entry) || !isRecord(entry.component)) return absent("bad-layout");
131
+ const height = entry.height;
132
+ if (!isHeight(height)) return absent("bad-layout");
133
+ const identity = identityOf(entry.component);
134
+ for (let offset = 0; offset < height; offset += 1) {
135
+ rows.push({ index: rows.length, ...identity });
136
+ }
137
+ }
138
+
139
+ // The layout and the returned frame must describe the same render. When they do not, the layout is
140
+ // a frame behind (or from another width), and attributing these rows to those children would name
141
+ // the wrong card.
142
+ if (rows.length !== lineCount) return absent("height-mismatch");
143
+ return { rows };
144
+ }