pi-odd-worktree 3.12.4 → 3.13.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
@@ -4,7 +4,7 @@ A Pi package that gives an agent session Git worktrees, ODD documents, GitHub is
4
4
 
5
5
  ## What It Does
6
6
 
7
- Two agent tools, five panels, one background-explorer command, two sidebar sections and two tool designs, loaded from one extension entry point. Each ODD feature gets its own checkout beside the clone, and you move between checkouts and read your ODD documents, files, issues and pull requests without leaving Pi.
7
+ Two agent tools, five panels, the `/identity` command, two sidebar sections and two tool designs, loaded from one extension entry point. Each ODD feature gets its own checkout beside the clone, and you move between checkouts and read your ODD documents, files, issues and pull requests without leaving Pi.
8
8
 
9
9
  | Surface | Kind | What it does |
10
10
  | --- | --- | --- |
@@ -13,6 +13,7 @@ Two agent tools, five panels, one background-explorer command, two sidebar secti
13
13
  | `/warp` | panel | Moves this session to another checkout, creates one, and removes one. |
14
14
  | `/odd` | panel | Reads `odd/tasks/*.md`: list on the left, styled markdown on the right — main's whole listing, plus one collapsible group per worktree the session registered with only what that worktree has that main does not, and `a` toggles between the session's checkouts and every worktree. One optional target — an ODD name or an ODD's name or the absolute path of a document that main or a worktree the session registered lists — opens it on that ODD; anything else is refused. |
15
15
  | `/files` | panel | Browses one checkout's files with a live, language-coloured preview: `enter` pastes the chosen paths into your prompt, `ctrl+e` opens the file in `$EDITOR`. |
16
+ | `/identity` | command | Stores your name: `/identity Jona` heads your prompt cards with it instead of `You` and appends one line about it to the orchestrator's prompt, `/identity clear` unsets it, and `/identity` alone says which name is stored. |
16
17
  | `/issues` | panel | Reads this checkout's GitHub issues — the three scoped tabs on open, every open issue behind `g` — and, when your role allows it, edits them. `enter` inserts the focused issue into the chat input as `ISSUE #63`, and each linked pull request in the pane is its own click that opens that pull request in `/prs`. |
17
18
  | `/prs` | panel | The same reader for pull requests: `My Pull Request`, `Needs My Review` and `Involved` on open, every open pull request of the repository behind `g`, the pane's `Changes` and `Checks` summaries, and — when your role allows it — comment, labels, assignees, the linked issues, merge (after a confirmation naming the method and the commit message) and close. `enter` inserts the focused pull request as `PR #87`, and each linked issue in the pane is its own click that opens that issue in `/issues`. |
18
19
  | `GITHUB` rail section | sidebar section | Lists the open issues of this checkout's repository you authored or are assigned, seven at a time plus a count of the rest, and its header counts the pull requests beside them (`7 issues · 3 pr`: your own plus the ones awaiting your review). A click opens that issue in `/issues` on `Assigned` — or, when the issue carries a linked pull request, that pull request in `/prs` on the bucket it belongs to; the overflow row opens `/issues`. Needs `gh`. |
@@ -57,7 +58,7 @@ From a local clone, `pi install .` installs the working copy, and `gentle-shell
57
58
 
58
59
  ### Expected result
59
60
 
60
- `/warp`, `/odd`, `/files`, `/issues` and `/prs` are available as commands — `/issues` and `/prs` only where `gh` is on `PATH` — the agent is offered `worktree_create` and `worktree_list`, a Gentle Shell whose rail is drawn shows a `GITHUB` section for this checkout and an `ODD` section listing the ODDs the session is working on, and its `/gentle:customize` → `Cards` page offers `activity` on its `Card activity` line.
61
+ `/warp`, `/odd`, `/files`, `/identity`, `/issues` and `/prs` are available as commands — `/issues` and `/prs` only where `gh` is on `PATH` — the agent is offered `worktree_create` and `worktree_list`, a Gentle Shell whose rail is drawn shows a `GITHUB` section for this checkout and an `ODD` section listing the ODDs the session is working on, and its `/gentle:customize` → `Cards` page offers `activity` on its `Card activity` line.
61
62
 
62
63
  ### Bridge versions
63
64
 
@@ -101,12 +102,12 @@ The full rules of each step, including every refusal, are in [Create, list, move
101
102
  - **File calls on a skill or an ODD are cards too.** While that line answers with `activity` for the tool being painted, a `read`, `edit` or `write` whose path names a skill or an ODD heads as that file — its own mark and label, the tool, the path and a read's line range — and its Markdown body is drawn by Pi's own renderer in the theme's Markdown roles. Any other file call is the host's own row. See [the file cards](docs/reference.md#the-file-cards).
102
103
  - **Background-job tools are cards too.** While that line answers with `activity`, `bash_background`, `monitor`, `job_stop` and `job_list` are drawn in the shell's own card style instead of Pi's plain box, with the job's label, its command and its own answer. See [the jobs card](docs/reference.md#the-jobs-card).
103
104
  - **The two advisory messages are cards too.** `gentle-pi.exploration-budget` and `gentle-pi.verifier-settle-reminder` are drawn as `⌕ Exploration budget` and `⚑ Verifier reminder`, the whole body at every content level. They follow that `Card activity` line, with no second switch and no row added to `Cards`. See [the message cards](docs/reference.md#the-message-cards).
104
- - **Your own prompt can be a card too.** While that `Card activity` line answers `activity`, the message you sent is drawn as a `✿ You` card — the title and the whole frame in the accent role, in whichever card style your shell uses — instead of Pi's plain background block. It is the one host class this package patches, because Pi offers no hook for a `role: "user"` entry: switch the line to `default` and the prompt is Pi's own again, live, byte for byte. It adds no switch of its own. See [the user prompt card](docs/reference.md#the-user-prompt-card).
105
+ - **Your own prompt can be a card too.** While that `Card activity` line answers `activity`, the message you sent is drawn as a `✿ Jona` card — your own name, stored with `/identity`, and `You` while none is stored, the title and the whole frame in the accent role, in whichever card style your shell uses — instead of Pi's plain background block, in the prompts already on screen too, because a name set or cleared repaints them. It is the one host class this package patches, because Pi offers no hook for a `role: "user"` entry: switch the line to `default` and the prompt is Pi's own again, live, byte for byte. It adds no switch of its own. See [the user prompt card](docs/reference.md#the-user-prompt-card).
105
106
  - **The diff card is a design of the same kind.** `Card diff` keeps `default` available and selects `color` once on the first run that finds no choice, so a write or an edit on a skill or an ODD stays the file card's row, because a specific claim wins over a generic one. See [the diff card](docs/reference.md#the-diff-card).
106
107
  - **`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, ODD artifacts, other repositories and linked worktrees are never blocked. See [the guard](docs/reference.md#the-edit-and-write-guard).
107
108
  - **A skill or an ODD is read whole.** A `read` of a `.md` below a `skills/` or an `odd/` folder drops its `offset` and `limit` before the tool runs, so the call delivers the whole document and never half a procedure. It follows the `Worktrees+` module, like the guards.
108
109
  - **`bash` cannot leave the principal checkout's default branch.** A `git worktree add` is refused in any cwd and pointed at `worktree_create`; 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).
109
- - **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 block](docs/reference.md#the--odd-worktrees-block-in-the-system-prompt).
110
+ - **Three 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. `## User identity` states your name in one line, and it is there only while a name is stored. All three are appended after the host's own text; `ODD_WORKTREE_PROMPT=0` suppresses the first two, and the third is the stored name's business alone. See [the prompt block](docs/reference.md#the--odd-worktrees-block-in-the-system-prompt) and [the user identity block](docs/reference.md#the--user-identity-block-in-the-system-prompt).
110
111
  - **CodeGraph stays fresh, only when its CLI is installed.** At session start the package creates or syncs the checkout's index and warms its daemon, and makes sure your global `mcp.json` has the `codegraph` entry. It also syncs after a compaction, after a native `codegraph init` and after an `edit` or `write`, in the background and without ever blocking you. See [CodeGraph](docs/reference.md#codegraph-index-daemon-and-mcp-entry).
111
112
  - **Two reminders keep a session on the CodeGraph rule.** The first `grep`, `find`, `ls`, `read` or `bash` search in a checkout gets one sentence appended to its result: use `codegraph` first, or — for another checkout — call `mcp__codegraph__codegraph_explore` with that path as `projectPath`. Neither is ever a block, and a subagent child hears neither. See [the reminders](docs/reference.md#the-two-codegraph-reminders).
112
113
  - **Deliberately absent.** No customize panel of its own, no plugin-tools toggles, no companion-app integration and no worktree-to-issue association. There is nothing to configure here: the card designs are chosen on the bridge's own lines, so this package owns no preference of its own. See [deliberately absent](docs/reference.md#deliberately-absent).
@@ -8345,6 +8345,98 @@ function registerFilesCommand(pi) {
8345
8345
  filesCommandHandler = handler;
8346
8346
  }
8347
8347
 
8348
+ // ---------------------------------------------------------------------------
8349
+ // `/identity` (identity-command S1/S2/S4): the user's own name.
8350
+ //
8351
+ // TRANSVERSAL, like `/files` and `/odd`: it is registered wherever the bridge is
8352
+ // and takes no module switch, because the name is the person's, not one of the
8353
+ // package's optional halves. The name lives in the bridge's own store
8354
+ // (`lib/user-identity.js`, document `identity`), so it survives a restart, and
8355
+ // the card learns about it by READING that document on every paint — which is
8356
+ // why a change only has to ask for ONE repaint instead of invalidating
8357
+ // anything: every prompt already on screen, old or new, heads with the name the
8358
+ // next frame reads.
8359
+ //
8360
+ // `clear` is RESERVED: it is the one argument that is a verb. Anything else is a
8361
+ // name, normalized by the lib module, and a value that does not normalize is
8362
+ // refused with one sentence and writes nothing.
8363
+ // ---------------------------------------------------------------------------
8364
+
8365
+ // The two state reports and the one refusal. A name that is stored is said as it
8366
+ // was stored (normalized), and an unset one says what the card heads with.
8367
+ function identityStateText(name) {
8368
+ return name === undefined || name === null
8369
+ ? 'identity: not set · messages head with "You"'
8370
+ : `identity: ${name}`;
8371
+ }
8372
+ const IDENTITY_REFUSAL = 'identity: a name needs 1-40 printable characters and no markdown heading';
8373
+
8374
+ function registerIdentityCommand(pi) {
8375
+ if (typeof pi?.registerCommand !== 'function') return;
8376
+ pi.registerCommand('identity', {
8377
+ description: "Store your name, which heads your prompts instead of \"You\" and rides one line of the orchestrator prompt; `clear` is reserved and unsets it",
8378
+ handler: (args, ctx) => {
8379
+ const notify = ctx && ctx.ui && typeof ctx.ui.notify === 'function' ? ctx.ui.notify : undefined;
8380
+ // The optional-call posture every command here uses, plus the one thing a
8381
+ // report can still cost: a UI that throws is never a failed write.
8382
+ const say = (text, level) => {
8383
+ try {
8384
+ if (level === undefined) notify?.(text);
8385
+ else notify?.(text, level);
8386
+ } catch {
8387
+ // A dead UI never turns a report into a throw.
8388
+ }
8389
+ };
8390
+ const raw = String(args ?? '').trim();
8391
+ try {
8392
+ const identity = libRequire('user-identity.js');
8393
+ const resolver = libRequire('file-card-resolver.js');
8394
+ const api = resolver && typeof resolver.bridgeApi === 'function' ? resolver.bridgeApi() : undefined;
8395
+ const before = identity.readIdentityName(api);
8396
+ // No argument: report the state. Nothing is written and nothing repaints.
8397
+ if (raw.length === 0) {
8398
+ say(identityStateText(before));
8399
+ return;
8400
+ }
8401
+ // The reserved word is decided on the NORMALIZED value, in any case: `cle\u0001ar` only
8402
+ // BECOMES `clear` once the control is dropped, and treating it as a name would store a
8403
+ // name the command could never unset — `clear` is always the verb.
8404
+ const normalized = identity.normalizeIdentityName(raw);
8405
+ if (normalized !== undefined && normalized.toLowerCase() === 'clear') {
8406
+ identity.clearIdentityName(api);
8407
+ const after = identity.readIdentityName(api);
8408
+ say(identityStateText(after));
8409
+ // ONE repaint, and only when the stored state actually changed: the
8410
+ // prompts already on screen need it, an unchanged one already has it.
8411
+ if (after !== before) requestPromptCardRepaintNow();
8412
+ return;
8413
+ }
8414
+ // A refused name writes nothing, so it says the one sentence and stops.
8415
+ if (normalized === undefined) {
8416
+ say(IDENTITY_REFUSAL, 'error');
8417
+ return;
8418
+ }
8419
+ // A value the store already holds changes nothing: no write and no repaint, and the
8420
+ // state is still said honestly.
8421
+ if (normalized === before) {
8422
+ say(identityStateText(before));
8423
+ return;
8424
+ }
8425
+ if (!identity.writeIdentityName(api, raw)) {
8426
+ say(IDENTITY_REFUSAL, 'error');
8427
+ return;
8428
+ }
8429
+ say(identityStateText(normalized));
8430
+ // ONE repaint, and only for a change: the prompts already on screen need it.
8431
+ requestPromptCardRepaintNow();
8432
+ } catch {
8433
+ // A store this build cannot read is no name, never a crash of the command.
8434
+ say('identity: the name could not be read or written', 'error');
8435
+ }
8436
+ },
8437
+ });
8438
+ }
8439
+
8348
8440
  // ---------------------------------------------------------------------------
8349
8441
  // `/issues` (T3 S1,S3): a full-screen issues reader over the CURRENT checkout's
8350
8442
  // repository issues, through this package's own migrated pieces
@@ -11100,6 +11192,20 @@ function installUserPromptCard() {
11100
11192
  */
11101
11193
  function requestPromptCardRepaint(outcome) {
11102
11194
  if (outcome === null || typeof outcome !== "object" || outcome.installed !== true) return;
11195
+ requestPromptCardRepaintNow();
11196
+ }
11197
+
11198
+ /**
11199
+ * The one bridge call a repaint IS, extracted so every surface that needs one asks for exactly
11200
+ * one the same way: the card's own install (above) and `/identity` after a successful write or
11201
+ * clear (identity-command D5).
11202
+ *
11203
+ * Nothing is asked for by a session that is not the live one — the caller's outcome may not
11204
+ * decide that, and a repaint belongs to the transcript still on screen. The bridge's member is
11205
+ * OPTIONAL and its answer is irrelevant, so an absent member, an absent bridge and a throw all
11206
+ * end the same way: no repaint, no error.
11207
+ */
11208
+ function requestPromptCardRepaintNow() {
11103
11209
  if (!userPromptCardSessionLive) return;
11104
11210
  try {
11105
11211
  const resolver = libRequire("file-card-resolver.js");
@@ -11107,7 +11213,7 @@ function requestPromptCardRepaint(outcome) {
11107
11213
  if (api === undefined || typeof api.requestRepaint !== "function") return;
11108
11214
  api.requestRepaint();
11109
11215
  } catch {
11110
- // A bridge that refuses its own repaint never breaks the install it belongs to.
11216
+ // A bridge that refuses its own repaint never breaks the surface it belongs to.
11111
11217
  }
11112
11218
  }
11113
11219
 
@@ -12083,6 +12189,9 @@ function registerOddWorktreeSurfaceEntries(pi) {
12083
12189
  // T7 (files-picker): the file picker is the fourth command. It mounts its own
12084
12190
  // overlays, reads Git through the package's async runner and adds no tool.
12085
12191
  registerFilesCommand(pi);
12192
+ // identity-command (S1/S2/S4): the user's own name, transversal like the picker —
12193
+ // it is registered wherever the bridge is and takes no module switch.
12194
+ registerIdentityCommand(pi);
12086
12195
  // S36 (files-picker T15): the picker's ONE key, bound directly on the host and
12087
12196
  // bound once — `alt+p` (S41) unless `GENTLE_PI_FILES_KEY` says otherwise.
12088
12197
  bindFilesShortcut(pi);
@@ -12392,6 +12501,15 @@ function registerOddWorktreeSurfaceEntries(pi) {
12392
12501
  // The prompt block is best effort.
12393
12502
  }
12394
12503
  }
12504
+ // identity-command (D4): the user's own name, one line, in its own try/catch beside the two
12505
+ // blocks above. TRANSVERSAL on purpose: no module switch gates it, and the stored name
12506
+ // itself is the switch — a child session and a named-agent event get nothing, because the
12507
+ // line is the orchestrator's.
12508
+ try {
12509
+ libRequire("user-identity.js").appendUserIdentitySection(event);
12510
+ } catch {
12511
+ // The prompt block is best effort.
12512
+ }
12395
12513
  });
12396
12514
  // CodeGraph, only with its CLI installed: the global MCP entry, create-or-sync at session
12397
12515
  // start, the compaction sync, the observed native init and the edit/write sync. Every
@@ -0,0 +1,236 @@
1
+ 'use strict';
2
+ // identity-command (S1-S4): the user's own name, in ONE persisted document, read by the prompt card
3
+ // and appended to the orchestrator's prompt as a single line.
4
+ //
5
+ // WHERE IT LIVES (D1). The bridge's own store, the same one `lib/modules.js` writes: plugin id
6
+ // `odd-worktree` → document key `identity` → `{ schema: 1, name: "<name>" }`. It is persisted (a
7
+ // stored name survives a restart of Pi) and read SYNCHRONOUSLY through the bridge's published
8
+ // object (`bridgeApi()` from `lib/file-card-resolver.js`), which is exactly what lets a paint read
9
+ // it. A missing, malformed, wrong-version or unreadable document is NO NAME: never a guess and
10
+ // never a throw. Clearing overwrites that one document and touches no other key, so the `modules`
11
+ // document in the same store is never disturbed.
12
+ //
13
+ // WHAT A NAME MAY BE (D2). Trimmed, internal whitespace runs collapsed to one space, C0/C1 control
14
+ // characters dropped, 1 to 40 CODE POINTS after that. The name reaches a system prompt, so it stays
15
+ // one printable line; a value that does not normalize is refused, never repaired.
16
+ //
17
+ // WHERE IT IS INJECTED (D4). `systemPromptOptions.appendSystemPrompt`, append-only, with the same
18
+ // guards the `## ODD worktrees` section follows (`lib/odd-worktrees-prompt.js`): a
19
+ // `GENTLE_PI_AGENTS_CHILD=1` session and a named-agent event get nothing, because this line is the
20
+ // orchestrator's. There is no environment switch: the stored name itself is the switch.
21
+ //
22
+ // The store name is the literal `lib/modules.js` owns (that module keeps the one store name for this
23
+ // package), repeated here with this comment rather than exported from there.
24
+
25
+ const { bridgeApi } = require('./file-card-resolver.js');
26
+
27
+ const OWN_STORE = 'odd-worktree';
28
+ const IDENTITY_KEY = 'identity';
29
+ const IDENTITY_SCHEMA = 1;
30
+ /** The heading the prompt card wears when no name is stored. */
31
+ const IDENTITY_TITLE = 'You';
32
+ /** The heading is the identity of the block, so an already-injected section is never added twice. */
33
+ const SECTION_MARKER = '## User identity';
34
+ const MAX_NAME_LENGTH = 40;
35
+
36
+ // C0 and C1 controls, DEL included: a name is one printable line and nothing else.
37
+ const CONTROL_CHARS = /[\u0000-\u001F\u007F-\u009F]/g;
38
+ // The controls that are ALSO whitespace (tab, LF, VT, FF, CR, NEL). They keep the separator they
39
+ // stood for, so a pasted `"Jona\t\nSoto"` is `Jona Soto` and not one run-together word; every other
40
+ // control is dropped, and the runs collapse AFTER the drop, so a dropped control never leaves the
41
+ // double space of a broken run behind either.
42
+ const CONTROL_WHITESPACE = /[\u0009-\u000D\u0085]/g;
43
+ const WHITESPACE_RUN = /\s+/g;
44
+ // A markdown heading run. Every prompt block this package appends is found by its own
45
+ // `## <heading>` marker, so a name that could form one would make an older block disappear from
46
+ // the next append; a name may not carry the run. A `#` with no `## ` after it is still a name
47
+ // (`C#`, `#designer`), because no block begins that way.
48
+ const HEADING_RUN = '## ';
49
+
50
+ /**
51
+ * The name a command may store, or `undefined` when the value is not one. Never throws.
52
+ *
53
+ * Trimmed, internal runs collapsed to one space, controls dropped in the order stated above, no
54
+ * markdown heading run, and the length counted in CODE POINTS, so an emoji is one character and
55
+ * not two.
56
+ */
57
+ function normalizeIdentityName(value) {
58
+ if (typeof value !== 'string') return undefined;
59
+ const cleaned = value
60
+ .replace(CONTROL_WHITESPACE, ' ')
61
+ .replace(CONTROL_CHARS, '')
62
+ .replace(WHITESPACE_RUN, ' ')
63
+ .trim();
64
+ if (cleaned.length === 0) return undefined;
65
+ if (cleaned.includes(HEADING_RUN)) return undefined;
66
+ return [...cleaned].length > MAX_NAME_LENGTH ? undefined : cleaned;
67
+ }
68
+
69
+ // The store `lib/modules.js` creates, or `null` when the api cannot make one.
70
+ function storeOf(api) {
71
+ if (api === null || typeof api !== 'object' || typeof api.createStore !== 'function') return null;
72
+ return api.createStore(OWN_STORE);
73
+ }
74
+
75
+ // The `identity` document, or `undefined` for every shape that is not an object.
76
+ function storedDocument(store) {
77
+ const stored = store.get(IDENTITY_KEY, undefined);
78
+ return stored !== null && typeof stored === 'object' && !Array.isArray(stored) ? stored : undefined;
79
+ }
80
+
81
+ /** The stored name, normalized, or `undefined` when nothing usable is stored. Never throws. */
82
+ function readIdentityName(api) {
83
+ try {
84
+ const store = storeOf(api);
85
+ if (store === null) return undefined;
86
+ const document = storedDocument(store);
87
+ if (document === undefined || document.schema !== IDENTITY_SCHEMA) return undefined;
88
+ return normalizeIdentityName(document.name);
89
+ } catch {
90
+ return undefined;
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Persist one name, keeping every other document of the store. Answers `true` when it wrote and
96
+ * `false` for a refused name or an api with no store, so a caller never promises a write that did
97
+ * not happen. Never throws.
98
+ */
99
+ function writeIdentityName(api, value) {
100
+ try {
101
+ const name = normalizeIdentityName(value);
102
+ if (name === undefined) return false;
103
+ const store = storeOf(api);
104
+ if (store === null) return false;
105
+ store.set(IDENTITY_KEY, { schema: IDENTITY_SCHEMA, name });
106
+ return true;
107
+ } catch {
108
+ return false;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Remove the stored name, keeping every other document of the store, and answer whether anything
114
+ * was removed (nothing stored is nothing to clear). Never throws.
115
+ *
116
+ * The published store has `get` and `set` only — gentle-shell-bridge's `Store` has no `delete` —
117
+ * so the document is normally OVERWRITTEN with the cleared shape `{ schema: 1, name: null }`, which
118
+ * the strict read above refuses: no name survives it. A store that does publish a `delete` (a fake,
119
+ * or a later bridge) is asked for it instead, so nothing at all survives the clear.
120
+ */
121
+ function clearIdentityName(api) {
122
+ try {
123
+ const store = storeOf(api);
124
+ if (store === null) return false;
125
+ // Nothing USABLE is nothing to clear: a document that already holds no name (the cleared
126
+ // shape a previous clear wrote, a malformed one, another schema) is not written again.
127
+ if (readIdentityName(api) === undefined) return false;
128
+ if (typeof store.delete === 'function') {
129
+ store.delete(IDENTITY_KEY);
130
+ return true;
131
+ }
132
+ store.set(IDENTITY_KEY, { schema: IDENTITY_SCHEMA, name: null });
133
+ return true;
134
+ } catch {
135
+ return false;
136
+ }
137
+ }
138
+
139
+ /** The name the running process has stored right now, or `undefined`. Never throws. */
140
+ function currentIdentityName() {
141
+ try {
142
+ return readIdentityName(bridgeApi());
143
+ } catch {
144
+ return undefined;
145
+ }
146
+ }
147
+
148
+ /** The one sentence the block states, or `''` for a value that is not a name (never a broken one). */
149
+ function identityLine(name) {
150
+ const normalized = normalizeIdentityName(name);
151
+ return normalized === undefined ? '' : `The user's name is ${normalized}.`;
152
+ }
153
+
154
+ /** The block: the marker heading, a blank line, then exactly one sentence. `''` for no name. */
155
+ function identitySection(name) {
156
+ const line = identityLine(name);
157
+ return line === '' ? '' : `${SECTION_MARKER}\n\n${line}`;
158
+ }
159
+
160
+ // The names a named-agent event may carry, copied from `lib/odd-worktrees-prompt.js`: `agent` itself
161
+ // is listed because a plain string there is a named agent too, and an object is read through `.name`.
162
+ function namedAgentOf(event) {
163
+ if (!event || typeof event !== 'object') return null;
164
+ const candidates = [
165
+ event.agentName,
166
+ event.agent,
167
+ event.name,
168
+ event.agent && typeof event.agent === 'object' ? event.agent.name : undefined,
169
+ event.subagent && typeof event.subagent === 'object' ? event.subagent.name : undefined,
170
+ ];
171
+ for (const candidate of candidates) {
172
+ if (typeof candidate === 'string' && candidate.length > 0) return candidate;
173
+ }
174
+ return null;
175
+ }
176
+
177
+ // The separator the existing text needs before the block starts, as the ODD section does it.
178
+ function separatorFor(existing) {
179
+ if (existing.endsWith('\n\n')) return '';
180
+ if (existing.endsWith('\n')) return '\n';
181
+ return '\n\n';
182
+ }
183
+
184
+ // The heading a block is found by, as a LINE of its own: prose that merely mentions the heading
185
+ // is not the block, so it never suppresses the line a stored name states.
186
+ const SECTION_MARKER_LINE = new RegExp(`^${SECTION_MARKER.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`, 'm');
187
+
188
+ /**
189
+ * Append the block for this session to `event.systemPromptOptions.appendSystemPrompt`. Returns
190
+ * nothing: the mutation is the whole contract. `deps.api` is the store seam (the published bridge
191
+ * when it is absent) and `deps.env` the environment the session runs with. Append-only: every
192
+ * existing byte stays the prefix of the new value. Never throws.
193
+ */
194
+ function appendUserIdentitySection(event, deps = {}) {
195
+ try {
196
+ const effectiveDeps = deps || {};
197
+ const env = effectiveDeps.env || process.env;
198
+ // A child and a named-agent event get none of it.
199
+ if (env.GENTLE_PI_AGENTS_CHILD === '1') return;
200
+ if (namedAgentOf(event) !== null) return;
201
+
202
+ const name = effectiveDeps.api !== undefined
203
+ ? readIdentityName(effectiveDeps.api)
204
+ : currentIdentityName();
205
+ const section = identitySection(name);
206
+ // No stored name, no block: the name itself is the switch.
207
+ if (section === '') return;
208
+
209
+ const options = event && event.systemPromptOptions;
210
+ if (!options || typeof options !== 'object') return;
211
+ const existing = typeof options.appendSystemPrompt === 'string' ? options.appendSystemPrompt : '';
212
+ if (SECTION_MARKER_LINE.test(existing)) return;
213
+ options.appendSystemPrompt = existing.length === 0
214
+ ? section
215
+ : `${existing}${separatorFor(existing)}${section}`;
216
+ } catch {
217
+ // The prompt block must never break session start.
218
+ }
219
+ }
220
+
221
+ module.exports = {
222
+ OWN_STORE,
223
+ IDENTITY_KEY,
224
+ IDENTITY_SCHEMA,
225
+ IDENTITY_TITLE,
226
+ SECTION_MARKER,
227
+ MAX_NAME_LENGTH,
228
+ appendUserIdentitySection,
229
+ clearIdentityName,
230
+ currentIdentityName,
231
+ identityLine,
232
+ identitySection,
233
+ normalizeIdentityName,
234
+ readIdentityName,
235
+ writeIdentityName,
236
+ };
@@ -11,12 +11,16 @@
11
11
  // from Pi, so a stub class is enough to exercise all of it.
12
12
  //
13
13
  // WHAT IT DRAWS, and what it never touches:
14
- // * THE HEADING is `✿ You · 14:32`: the mark and the name in the theme's `accent` role (the
14
+ // * THE HEADING is `✿ Jona · 14:32`: the mark and the name in the theme's `accent` role (the
15
15
  // card's `titleRole`), then the substrate's `SEPARATOR` and the prompt's clock in `muted`
16
- // (the subtitle path `lib/shell-card.js` already has, `SUBTITLE_ROLE`). The clock is the
16
+ // (the subtitle path `lib/shell-card.js` already has, `SUBTITLE_ROLE`). THE NAME IS THE USER'S
17
+ // OWN — the `identity` document `lib/user-identity.js` reads from the bridge's store — and it
18
+ // falls back to `You` when nothing usable is stored (S1/S2 of identity-command): it is read on
19
+ // every paint, so a name set or cleared while the transcript is on screen repaints the prompts
20
+ // already there, and no invalidation call exists. The clock is the
17
21
  // host's own `timestamp` when it set one, else the moment of the card's FIRST paint, held
18
22
  // per component so a live prompt does not drift frame by frame; with neither, the heading is
19
- // `✿ You` alone and nothing is invented. The whole closed box still wears the `accent` role
23
+ // `✿ Jona` alone and nothing is invented. The whole closed box still wears the `accent` role
20
24
  // (`railRole`) — corners, lead, rule, sides, rail and bottom. That one role around the entire
21
25
  // frame is what tells this card apart from the tool cards, which paint their tone.
22
26
  // No glyph override is made (the `✿` is the substrate's default mark).
@@ -44,16 +48,17 @@
44
48
  // UNLIKE the file cards, this one fails CLOSED: an absent bridge, an absent reader, a
45
49
  // reader that throws, any other answer and a width too small to draw a frame all hand
46
50
  // the host's own rows back — the very array `render` returned — byte for byte (S6).
47
- // * THE COST, stated honestly, per PAINT: ONE GATE READ ALWAYS, PLUS ONE STYLE READ ONLY WHILE
48
- // THE CARD ACTUALLY DRAWS. The gate asks the bridge's reader on every paint — its reader
49
- // queries the selection store on every call, and that read is what makes the flip live, so
50
- // it is never cached. Any answer but this package's design returns BEFORE the style is
51
- // asked, so a native frame pays the gate read alone; a frame that does draw then pays one
52
- // more live read, `floatRows` asking the shell's style through `lib/card-style.js` (the live
53
- // slot Gentle Shell writes, or `<home>/card-style.json` when nothing is published there).
54
- // Both are deliberate. The memo below covers only the DRAWING (the Markdown rows and the
55
- // composed frame parts), keyed on width, paint and rendered rows, so a steady frame
56
- // recomposes nothing.
51
+ // * THE COST, stated honestly, per PAINT: ONE GATE READ ALWAYS, PLUS ONE STORE READ AND ONE STYLE
52
+ // READ ONLY WHILE THE CARD ACTUALLY DRAWS. The gate asks the bridge's reader on every paint —
53
+ // its reader queries the selection store on every call, and that read is what makes the flip
54
+ // live, so it is never cached. Any answer but this package's design returns BEFORE anything
55
+ // else is read, so a native frame pays the gate read alone; a frame that does draw then pays
56
+ // the `identity` document read (`lib/user-identity.js`, one synchronous `get` through the same
57
+ // published store) and one more live read, `floatRows` asking the shell's style through
58
+ // `lib/card-style.js` (the live slot Gentle Shell writes, or `<home>/card-style.json` when
59
+ // nothing is published there). All are deliberate. The memo below covers only the DRAWING (the
60
+ // Markdown rows and the composed frame parts), keyed on width, paint, the name and the rendered
61
+ // rows, so a steady frame recomposes nothing while a changed name still does.
57
62
  //
58
63
  // The wrapper never throws: any error on this side answers the original rows. `uninstall()`
59
64
  // restores the original `render`, and the extension calls it on `session_shutdown`.
@@ -68,10 +73,14 @@ const {
68
73
  } = require('./shell-card.js');
69
74
  const { ACTIVITY_DESIGN_ID, bridgeApi } = require('./file-card-resolver.js');
70
75
  const { themeFor } = require('./file-card.js');
71
-
72
- // The one heading this card wears: the mark is the substrate's default `✿`, the name is the
73
- // person, and the role is the accent for the name and for the whole closed box. The clock is NOT
74
- // part of it — it belongs to the component being drawn, so `cardParts` adds it per paint (S1).
76
+ // The user's own name, read from the bridge's store on every paint (identity-command S2): the
77
+ // heading is the person, so a name set or cleared mid-session repaints instead of being cached.
78
+ const { currentIdentityName } = require('./user-identity.js');
79
+
80
+ // The one heading this card wears when no name is stored: the mark is the substrate's default `✿`,
81
+ // the name is the person (`IDENTITY.title` is the fallback, the stored name replaces it), and the
82
+ // role is the accent for the name and for the whole closed box. The clock is NOT part of it — it
83
+ // belongs to the component being drawn, so `cardParts` adds it per paint (S1).
75
84
  const IDENTITY = Object.freeze({
76
85
  title: 'You',
77
86
  tone: CARD_TONE.INFO,
@@ -296,7 +305,8 @@ function clockText(at) {
296
305
  *
297
306
  * The memo is keyed on the SOURCE, so the formatting runs once per component (or once per
298
307
  * `timestamp` the host sets) and every later paint reads the string it already made — a steady
299
- * frame formats nothing and reads no file, no store and no bridge.
308
+ * frame formats nothing here, and the only per-paint reads a card pays are the gate's, the stored
309
+ * name's (`paintPrompt`) and the style's.
300
310
  */
301
311
  function headingClock(self) {
302
312
  const field = asObject(self).timestamp;
@@ -327,12 +337,13 @@ function headingClock(self) {
327
337
  * chrome in force is decided by the requested width and the style `floatRows` resolved for it
328
338
  * (`floatOpener(theme, tone, target)`), so `target` and `inner` are both keyed: a style at the
329
339
  * same inner width therefore always recomposes. The paint is keyed because the roles are the
330
- * theme's, and the rendered rows because the body is Pi's own Markdown. A steady frame only
331
- * compares the fields and hands the same parts back. No file, no child process and no store is
332
- * read in here. A paint's live reads are the gate's selection read (always, above) and, only
333
- * while the card actually draws, the shell's style read `floatRows` makes.
340
+ * theme's, `name` because the heading IS the person — `You` is only the fallback, so a name set
341
+ * or cleared under a transcript has to recompose the head already on screen — and the rendered
342
+ * rows because the body is Pi's own Markdown. A steady frame only compares the fields and hands
343
+ * the same parts back. NOTHING IS READ IN HERE: the name arrives already read ONCE by
344
+ * `paintPrompt`, so a card paint pays that one document read once and not once per `inner`.
334
345
  */
335
- function cardParts(self, markdown, target, inner, paint, metrics) {
346
+ function cardParts(self, markdown, target, inner, paint, metrics, name) {
336
347
  const width = cardInnerWidth(inner);
337
348
  const rows = renderedRows(markdown, width);
338
349
  if (rows === undefined) return undefined;
@@ -348,11 +359,14 @@ function cardParts(self, markdown, target, inner, paint, metrics) {
348
359
  && remembered.inner === inner
349
360
  && remembered.paint === paint
350
361
  && remembered.clock === clock
362
+ && remembered.name === name
351
363
  && sameRows(remembered.rows, rows)
352
364
  ) return remembered.parts;
353
- // The clock rides the substrate's subtitle path: the heading states `✿ You`, then the
354
- // separator and the clock in `muted` (`SUBTITLE_ROLE`). No clock, no subtitle at all.
355
- const card = clock === undefined ? { ...IDENTITY } : { ...IDENTITY, subtitle: clock };
365
+ // The clock rides the substrate's subtitle path: the heading states `✿ Jona` — the stored name,
366
+ // or `You` when nothing usable is stored — then the separator and the clock in `muted`
367
+ // (`SUBTITLE_ROLE`). No clock, no subtitle at all.
368
+ const title = name === undefined || name === null ? IDENTITY.title : name;
369
+ const card = clock === undefined ? { ...IDENTITY, title } : { ...IDENTITY, title, subtitle: clock };
356
370
  const parts = {
357
371
  head: cardTopRows(card, paint, inner, undefined, metrics),
358
372
  // The body is never clipped: a prompt is not a preview, so every row is drawn.
@@ -360,7 +374,7 @@ function cardParts(self, markdown, target, inner, paint, metrics) {
360
374
  // No content rides the closing rule: the prompt's clock belongs to the heading alone.
361
375
  bottom: cardBottom(IDENTITY.tone, paint, inner, undefined, metrics),
362
376
  };
363
- cardMemo.set(self, { markdown, target, inner, paint, clock, rows, parts });
377
+ cardMemo.set(self, { markdown, target, inner, paint, clock, name, rows, parts });
364
378
  return parts;
365
379
  }
366
380
 
@@ -387,6 +401,12 @@ function zoneRows(rows) {
387
401
  * The rows one paint answers: the host's own rows for every answer but the activity design,
388
402
  * the card for it. `rows` is exactly what the original `render` returned, so every refusal is
389
403
  * byte for byte (S6).
404
+ *
405
+ * The stored name is read ONCE here, after the gate and the width floor have already refused
406
+ * anything that is not a card: a native frame, a tiny width and an unreadable body pay no store
407
+ * read at all, and a card that does draw pays exactly one — never one per `inner` the style asks
408
+ * for. The read is live on every paint (never cached), which is what makes a name set or cleared
409
+ * while the transcript is on screen reach the prompts already on it without any invalidation.
390
410
  */
391
411
  function paintPrompt(self, rows, width, seams) {
392
412
  if (!Array.isArray(rows) || rows.length === 0) return rows;
@@ -400,9 +420,10 @@ function paintPrompt(self, rows, width, seams) {
400
420
  const paint = themeFor(readTheme(seams.theme), PLAIN_THEME);
401
421
  const markdown = componentMarkdown(self, paint);
402
422
  if (markdown === undefined) return rows;
423
+ const name = currentIdentityName();
403
424
  try {
404
425
  const drawn = floatRows(IDENTITY.tone, paint, target, (inner) => {
405
- const parts = cardParts(self, markdown, target, inner, paint, metrics);
426
+ const parts = cardParts(self, markdown, target, inner, paint, metrics, name);
406
427
  // A body that draws nothing is no card: the host's own rows are the honest answer,
407
428
  // and the throw below is how that leaves `floatRows` untouched.
408
429
  if (parts === undefined) throw new TypeError('the user prompt drew no row');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-odd-worktree",
3
- "version": "3.12.4",
3
+ "version": "3.13.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",
@@ -433,8 +433,8 @@ test('S18/S19 (T14): the ready announcement registers the whole surface, exactly
433
433
  const bridge = installBridge();
434
434
  for (const entry of ready) entry.handler();
435
435
 
436
- assert.deepEqual([...loaded.commands.keys()].sort(), ['files', 'issues', 'odd', 'prs', 'warp'],
437
- 'the five commands arrive with the bridge');
436
+ assert.deepEqual([...loaded.commands.keys()].sort(), ['files', 'identity', 'issues', 'odd', 'prs', 'warp'],
437
+ 'the six commands arrive with the bridge');
438
438
  assert.deepEqual([...loaded.tools.keys()].sort(), ['worktree_create', 'worktree_list'], 'the two tools');
439
439
  assert.deepEqual([...loaded.messageRenderers.keys()], ['worktree-warp'], 'the message renderer');
440
440
  assert.deepEqual([...loaded.entryRenderers.keys()].sort(), ['odd-worktree-issues-refusal', 'odd-worktree-warp-queue'],
@@ -251,9 +251,9 @@ const agentStub = {
251
251
  };
252
252
 
253
253
  describe('/files registration (S17)', () => {
254
- test('the file picker is registered beside the other three panels', async () => {
254
+ test('the file picker is registered beside the other panels', async () => {
255
255
  const { commands } = await loadExtension({});
256
- assert.deepEqual([...commands.keys()].sort(), ['files', 'issues', 'odd', 'prs', 'warp']);
256
+ assert.deepEqual([...commands.keys()].sort(), ['files', 'identity', 'issues', 'odd', 'prs', 'warp']);
257
257
  const files = commands.get('files');
258
258
  assert.equal(typeof files.handler, 'function', 'the command carries its handler');
259
259
  assert.ok(files.description.includes('files'), 'the description says what it browses');
@@ -1567,8 +1567,13 @@ test('F3 preserve: a standard single-root repository still paints plain document
1567
1567
  const pending = doOdd(e, '', ctxFor(repo, host, []));
1568
1568
  try {
1569
1569
  await waitFor(() => host.mounts.length === 1, 'the panel mounts');
1570
- assert.deepEqual(rowLabels(host.mounts[0].component), ['main-two', 'main-one'],
1571
- 'unique names keep their exact plain text, in the recency order the panel always used');
1570
+ // The fixture's mtimes are deliberately the OPPOSITE of its rank (T16 depends on that),
1571
+ // and the panel can paint the cheap mtime scan before the ranked listing lands, so the
1572
+ // frame read here has to be the settled one: wait for the rank, then assert it.
1573
+ await waitFor(() => rowLabels(host.mounts[0].component).join('|') === 'main-one|main-two',
1574
+ 'the settled frame is the ranked listing');
1575
+ assert.deepEqual(rowLabels(host.mounts[0].component), ['main-one', 'main-two'],
1576
+ 'unique names keep their exact plain text, in the rank the panel reads');
1572
1577
  } finally {
1573
1578
  await closePanel(host, pending);
1574
1579
  }
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
- // S4 surface: the standalone package always registers /warp, /odd, /files
3
- // and /issues plus the TWO agent worktree tools (S3/S4: `worktree_delete` and
2
+ // S4 surface: the standalone package always registers /warp, /odd, /files,
3
+ // /issues and /identity plus the TWO agent worktree tools (S3/S4: `worktree_delete` and
4
4
  // `worktree_warp` are not registered, so `/warp` is the only front that moves
5
5
  // the session and the panel's ctrl+d the only one that removes a checkout),
6
6
  // loads in plain Pi with git as its only external dependency, and ships none of
@@ -13,9 +13,10 @@
13
13
  // worktree↔issue association.
14
14
  //
15
15
  // The bash activity is not a preference here: it is a design on gentle-shell-bridge's
16
- // own `Card activity` line, so the shipped surface is exactly five commands, two tools, TWO
16
+ // own `Card activity` line, so the shipped surface is exactly six commands, two tools, TWO
17
17
  // sidebar sections, one tools design and the one `Cards` row group the two file-card
18
- // switches carry.
18
+ // switches carry. `/identity` is the name the person stores for their own prompt card and
19
+ // the orchestrator prompt: transversal like `/files`, so no module switch gates it.
19
20
  //
20
21
  // Everything here reads the observable surface: the registered command and
21
22
  // tool objects, the manifest, the files on disk. No internal state is read.
@@ -85,11 +86,11 @@ describe('manifest', () => {
85
86
  });
86
87
 
87
88
  describe('registration', () => {
88
- test('registers /warp, /odd, /files, /issues, /prs and the two worktree tools', async () => {
89
+ test('registers /warp, /odd, /files, /issues, /prs, /identity and the two worktree tools', async () => {
89
90
  delete process.env.GENTLE_WORKTREE_THREAD;
90
91
  const { commands, tools, messageRenderers } = await loadExtension({});
91
92
  const registered = [...commands.keys()].sort();
92
- assert.deepEqual(registered, ['files', 'issues', 'odd', 'prs', 'warp'], 'the command list is exactly the five panels');
93
+ assert.deepEqual(registered, ['files', 'identity', 'issues', 'odd', 'prs', 'warp'], 'the command list is exactly the six panels');
93
94
  assert.deepEqual([...tools.keys()].sort(), ['worktree_create', 'worktree_list'], 'exactly two agent tools');
94
95
  assert.deepEqual([...messageRenderers.keys()], ['worktree-warp']);
95
96
  });
@@ -0,0 +1,503 @@
1
+ 'use strict';
2
+ // identity-command (S1-S4): the user's own name. `/identity <name>` stores it in the bridge's
3
+ // store, the user prompt card heads with it instead of `You`, and one line about it is appended
4
+ // to the orchestrator's prompt; `/identity clear` takes it away again.
5
+ //
6
+ // Everything below observes the public seam: `lib/user-identity.js`'s own answers, the document a
7
+ // fake store received, the exact string the prompt append produced, and the command the extension
8
+ // registered on a fake host. No internal state is read.
9
+ const { test, describe } = require('node:test');
10
+ const assert = require('node:assert/strict');
11
+
12
+ const identity = require('../lib/user-identity.js');
13
+ const fixture = require('./fixtures/load-extension.js');
14
+
15
+ const BRIDGE_SLOT = Symbol.for('gentle-shell-bridge/api/v1');
16
+ const STORE = 'odd-worktree';
17
+
18
+ // A bridge whose `createStore` keeps ONE in-memory document per plugin id, with the same
19
+ // key-merge the published store has (`get` and `set` only). `deletable: false` models that real
20
+ // store exactly: gentle-shell-bridge's `Store` interface has no `delete`.
21
+ function fakeBridge(initial = {}, options = {}) {
22
+ const documents = new Map(Object.entries(initial));
23
+ const writes = [];
24
+ const store = {
25
+ get(key, fallback) {
26
+ const document = documents.get(STORE);
27
+ return document !== undefined && Object.hasOwn(document, key) ? document[key] : fallback;
28
+ },
29
+ set(key, value) {
30
+ documents.set(STORE, { ...(documents.get(STORE) ?? {}), [key]: value });
31
+ writes.push([key, value]);
32
+ },
33
+ };
34
+ if (options.deletable !== false) {
35
+ store.delete = (key) => {
36
+ const document = { ...(documents.get(STORE) ?? {}) };
37
+ delete document[key];
38
+ documents.set(STORE, document);
39
+ writes.push([key]);
40
+ };
41
+ }
42
+ return { api: { schema: 'gentle-shell-bridge/api', version: 1, createStore: () => store }, documents, writes };
43
+ }
44
+
45
+ const stored = (name) => ({ [STORE]: { identity: { schema: 1, name } } });
46
+
47
+ // ---- D2: what a name may be ----
48
+
49
+ describe('the name a command may store', () => {
50
+ test('it is trimmed, its internal runs collapse to one space, and its control characters are dropped', () => {
51
+ assert.equal(identity.normalizeIdentityName(' Jona '), 'Jona');
52
+ assert.equal(identity.normalizeIdentityName('Jona Soto'), 'Jona Soto');
53
+ assert.equal(identity.normalizeIdentityName('Jona\t\nSoto'), 'Jona Soto');
54
+ assert.equal(identity.normalizeIdentityName('Jo\u0000na'), 'Jona', 'a C0 control is dropped');
55
+ assert.equal(identity.normalizeIdentityName('Jona\u009b'), 'Jona', 'a C1 control is dropped');
56
+ assert.equal(identity.normalizeIdentityName('Jona \u0001 Soto'), 'Jona Soto', 'a dropped control leaves no second space');
57
+ assert.equal(identity.normalizeIdentityName('Jona\u007f'), 'Jona', 'DEL is dropped too');
58
+ });
59
+
60
+ test('an empty, blank, non-string or over-long name is refused', () => {
61
+ for (const bad of ['', ' ', '\u0000\u0001', 42, null, undefined, {}, [], true]) {
62
+ assert.equal(identity.normalizeIdentityName(bad), undefined, String(bad));
63
+ }
64
+ assert.equal(identity.normalizeIdentityName('a'.repeat(40)), 'a'.repeat(40), 'forty characters is a name');
65
+ assert.equal(identity.normalizeIdentityName('a'.repeat(41)), undefined, 'forty-one is not');
66
+ assert.equal(identity.normalizeIdentityName('😀'.repeat(40)), '😀'.repeat(40), 'code points are counted, not UTF-16 units');
67
+ assert.equal(identity.normalizeIdentityName(`😀${'a'.repeat(40)}`), undefined, 'one code point past the limit');
68
+ });
69
+
70
+ test('a name may not carry a markdown heading run, while an ordinary `#` is still a name', () => {
71
+ // A stored name reaches the system prompt, and every one of this package's prompt blocks is
72
+ // found by its `## <heading>` marker: a name that could form one would make an older block
73
+ // disappear (S3). `C#` and `#designer` form no heading and stay names.
74
+ assert.equal(identity.normalizeIdentityName('## CodeGraph'), undefined);
75
+ assert.equal(identity.normalizeIdentityName('Jona ## ODD worktrees'), undefined);
76
+ assert.equal(identity.normalizeIdentityName('Jona ##'), 'Jona ##', 'a `##` with no space after it is no heading run');
77
+ assert.equal(identity.normalizeIdentityName('C#'), 'C#');
78
+ assert.equal(identity.normalizeIdentityName('#designer'), '#designer');
79
+ });
80
+ });
81
+
82
+ // ---- D1: where the name lives ----
83
+
84
+ describe('reading the stored name', () => {
85
+ test('the stored name is read back, and every unreadable document is no name at all', () => {
86
+ assert.equal(identity.readIdentityName(fakeBridge(stored('Jona')).api), 'Jona');
87
+ assert.equal(identity.readIdentityName(fakeBridge(stored(' Jona Soto ')).api), 'Jona Soto', 'read normalizes');
88
+ for (const document of [
89
+ 'Jona',
90
+ 42,
91
+ [],
92
+ null,
93
+ { schema: 2, name: 'Jona' },
94
+ { schema: '1', name: 'Jona' },
95
+ { name: 'Jona' },
96
+ { schema: 1, name: 42 },
97
+ { schema: 1, name: ' ' },
98
+ { schema: 1 },
99
+ ]) {
100
+ const bridge = fakeBridge({ [STORE]: { identity: document } });
101
+ assert.equal(identity.readIdentityName(bridge.api), undefined, JSON.stringify(document));
102
+ }
103
+ });
104
+
105
+ test('no api, no store and a throwing store answer no name and never throw', () => {
106
+ assert.equal(identity.readIdentityName(undefined), undefined);
107
+ assert.equal(identity.readIdentityName(null), undefined);
108
+ assert.equal(identity.readIdentityName({}), undefined);
109
+ assert.equal(identity.readIdentityName({ schema: 'gentle-shell-bridge/api', version: 1 }), undefined);
110
+ assert.equal(identity.readIdentityName({ createStore: () => { throw new Error('disk'); } }), undefined);
111
+ const throwing = fakeBridge();
112
+ throwing.api.createStore = () => ({ get: () => { throw new Error('disk'); }, set: () => {} });
113
+ assert.equal(identity.readIdentityName(throwing.api), undefined);
114
+ });
115
+ });
116
+
117
+ describe('writing the stored name', () => {
118
+ test('the name is one document named `identity`, and every other document survives it', () => {
119
+ const bridge = fakeBridge({ [STORE]: { modules: { worktrees: false } } });
120
+ assert.equal(identity.writeIdentityName(bridge.api, ' Jona '), true);
121
+ assert.deepEqual(bridge.documents.get(STORE), {
122
+ modules: { worktrees: false },
123
+ identity: { schema: 1, name: 'Jona' },
124
+ });
125
+ assert.equal(identity.readIdentityName(bridge.api), 'Jona', 'and it reads back');
126
+ });
127
+
128
+ test('a refused name and an api with no store write nothing and answer false', () => {
129
+ const bridge = fakeBridge();
130
+ for (const bad of ['', ' ', 42, null, 'a'.repeat(41)]) {
131
+ assert.equal(identity.writeIdentityName(bridge.api, bad), false, String(bad));
132
+ }
133
+ assert.deepEqual(bridge.writes, [], 'nothing was written');
134
+ assert.deepEqual(bridge.documents.get(STORE), undefined, 'and no document was created');
135
+ assert.equal(identity.writeIdentityName(undefined, 'Jona'), false);
136
+ assert.equal(identity.writeIdentityName({}, 'Jona'), false);
137
+ assert.equal(identity.writeIdentityName({ createStore: () => { throw new Error('disk'); } }, 'Jona'), false);
138
+ });
139
+ });
140
+
141
+ describe('clearing the stored name', () => {
142
+ test('after a clear there is no name, and every other document survives it', () => {
143
+ const bridge = fakeBridge({ [STORE]: { identity: { schema: 1, name: 'Jona' }, modules: { codegraph: false } } });
144
+ assert.equal(identity.clearIdentityName(bridge.api), true);
145
+ assert.equal(identity.readIdentityName(bridge.api), undefined);
146
+ assert.deepEqual(bridge.documents.get(STORE), { modules: { codegraph: false } }, 'the other document survives');
147
+ });
148
+
149
+ test('a store with no delete (the published one) removes the name by overwriting the document', () => {
150
+ const bridge = fakeBridge({ [STORE]: { identity: { schema: 1, name: 'Jona' }, modules: { codegraph: false } } }, { deletable: false });
151
+ assert.equal(identity.clearIdentityName(bridge.api), true);
152
+ assert.equal(identity.readIdentityName(bridge.api), undefined, 'the strict read refuses the cleared document');
153
+ assert.deepEqual(bridge.documents.get(STORE), {
154
+ modules: { codegraph: false },
155
+ identity: { schema: 1, name: null },
156
+ }, 'no name survives it');
157
+ });
158
+
159
+ test('nothing stored is nothing to clear, and no store clears nothing either', () => {
160
+ assert.equal(identity.clearIdentityName(fakeBridge().api), false);
161
+ assert.equal(identity.clearIdentityName(undefined), false);
162
+ assert.equal(identity.clearIdentityName({}), false);
163
+ assert.equal(identity.clearIdentityName(fakeBridge(), 'x'), false, 'an api that is not an object');
164
+ });
165
+
166
+ test('an already-cleared store is not written again', () => {
167
+ // The published store has no `delete`, so a clear overwrites the document with the cleared
168
+ // shape: a second clear on that store must find no name and write nothing.
169
+ const bridge = fakeBridge({ [STORE]: { identity: { schema: 1, name: 'Jona' } } }, { deletable: false });
170
+ assert.equal(identity.clearIdentityName(bridge.api), true);
171
+ const writes = bridge.writes.length;
172
+ assert.equal(identity.clearIdentityName(bridge.api), false, 'there is nothing left to clear');
173
+ assert.equal(bridge.writes.length, writes, 'and nothing is written');
174
+ });
175
+ });
176
+
177
+ // ---- D3: the exact strings ----
178
+
179
+ describe('the block', () => {
180
+ test('the line is one sentence and the section is the marker plus it', () => {
181
+ assert.equal(identity.identityLine('Jona'), "The user's name is Jona.");
182
+ assert.equal(identity.identitySection('Jona'), "## User identity\n\nThe user's name is Jona.");
183
+ assert.equal(identity.identityLine(' Jona Soto '), "The user's name is Jona Soto.", 'the line is built from the normalized name');
184
+ assert.equal(identity.identityLine(' '), '', 'a name that does not normalize states nothing');
185
+ assert.equal(identity.identitySection(' '), '');
186
+ });
187
+ });
188
+
189
+ // ---- D4: where it is injected ----
190
+
191
+ describe('the prompt append', () => {
192
+ const name = stored('Jona');
193
+
194
+ test('the block is appended after the existing text, keeping every existing byte its prefix', () => {
195
+ const cases = [
196
+ ['', "## User identity\n\nThe user's name is Jona."],
197
+ ['base', "base\n\n## User identity\n\nThe user's name is Jona."],
198
+ ['base\n', "base\n\n## User identity\n\nThe user's name is Jona."],
199
+ ['base\n\n', "base\n\n## User identity\n\nThe user's name is Jona."],
200
+ ];
201
+ for (const [before, after] of cases) {
202
+ const event = { systemPromptOptions: { appendSystemPrompt: before } };
203
+ identity.appendUserIdentitySection(event, { api: fakeBridge(name).api, env: {} });
204
+ assert.equal(event.systemPromptOptions.appendSystemPrompt, after, JSON.stringify(before));
205
+ }
206
+ });
207
+
208
+ test('a second call appends nothing, and a block already there is left alone', () => {
209
+ const event = { systemPromptOptions: { appendSystemPrompt: 'base' } };
210
+ const deps = { api: fakeBridge(name).api, env: {} };
211
+ identity.appendUserIdentitySection(event, deps);
212
+ const once = event.systemPromptOptions.appendSystemPrompt;
213
+ identity.appendUserIdentitySection(event, deps);
214
+ assert.equal(event.systemPromptOptions.appendSystemPrompt, once, 'idempotent');
215
+ assert.equal(once.split(identity.SECTION_MARKER).length - 1, 1, 'the marker is written exactly once');
216
+ });
217
+
218
+ test('no stored name injects nothing', () => {
219
+ const event = { systemPromptOptions: { appendSystemPrompt: 'base' } };
220
+ identity.appendUserIdentitySection(event, { api: fakeBridge().api, env: {} });
221
+ assert.equal(event.systemPromptOptions.appendSystemPrompt, 'base');
222
+ });
223
+
224
+ test('the marker MENTIONED inside other text is not the block', () => {
225
+ // Only a line that IS the heading counts: prose that happens to name the block must not
226
+ // suppress the one line a stored name states.
227
+ const event = { systemPromptOptions: { appendSystemPrompt: 'See ## User identity for the name.' } };
228
+ identity.appendUserIdentitySection(event, { api: fakeBridge(name).api, env: {} });
229
+ assert.equal(event.systemPromptOptions.appendSystemPrompt,
230
+ "See ## User identity for the name.\n\n## User identity\n\nThe user's name is Jona.");
231
+ });
232
+
233
+ test('a name that could form another block heading is refused, so no ordering can cost a block', () => {
234
+ assert.equal(identity.identitySection('## CodeGraph'), '', 'a heading run is not a name');
235
+ assert.equal(identity.identitySection('Jona'), "## User identity\n\nThe user's name is Jona.");
236
+ });
237
+
238
+ test('a child session and a named-agent event get nothing, both keeping the text they had', () => {
239
+ const child = { systemPromptOptions: { appendSystemPrompt: 'base' } };
240
+ identity.appendUserIdentitySection(child, { api: fakeBridge(name).api, env: { GENTLE_PI_AGENTS_CHILD: '1' } });
241
+ assert.equal(child.systemPromptOptions.appendSystemPrompt, 'base', 'a child gets none of it');
242
+ for (const agentEvent of [
243
+ { agentName: 'reviewer' },
244
+ { agent: 'reviewer' },
245
+ { agent: { name: 'reviewer' } },
246
+ { name: 'reviewer' },
247
+ { subagent: { name: 'reviewer' } },
248
+ ]) {
249
+ const event = { systemPromptOptions: { appendSystemPrompt: 'base' }, ...agentEvent };
250
+ identity.appendUserIdentitySection(event, { api: fakeBridge(name).api, env: {} });
251
+ assert.equal(event.systemPromptOptions.appendSystemPrompt, 'base', JSON.stringify(agentEvent));
252
+ }
253
+ });
254
+
255
+ test('a missing or unusable systemPromptOptions writes nothing and throws nothing', () => {
256
+ for (const event of [undefined, null, {}, { systemPromptOptions: null }, { systemPromptOptions: 'text' }, { systemPromptOptions: 42 }]) {
257
+ assert.doesNotThrow(() => identity.appendUserIdentitySection(event, { api: fakeBridge(name).api, env: {} }), String(event));
258
+ }
259
+ const stringly = { systemPromptOptions: { appendSystemPrompt: 42 } };
260
+ identity.appendUserIdentitySection(stringly, { api: fakeBridge(name).api, env: {} });
261
+ assert.equal(stringly.systemPromptOptions.appendSystemPrompt, `## User identity\n\nThe user's name is Jona.`, 'a non-string value is not a prefix');
262
+ });
263
+
264
+ test('without an injected api the name is read from the published bridge, and no bridge injects nothing', () => {
265
+ const bridge = fakeBridge(name);
266
+ const previous = globalThis[BRIDGE_SLOT];
267
+ globalThis[BRIDGE_SLOT] = bridge.api;
268
+ try {
269
+ assert.equal(identity.currentIdentityName(), 'Jona');
270
+ const event = { systemPromptOptions: { appendSystemPrompt: 'base' } };
271
+ identity.appendUserIdentitySection(event, { env: {} });
272
+ assert.equal(event.systemPromptOptions.appendSystemPrompt, "base\n\n## User identity\n\nThe user's name is Jona.");
273
+ delete globalThis[BRIDGE_SLOT];
274
+ assert.equal(identity.currentIdentityName(), undefined, 'no bridge, no name');
275
+ const unset = { systemPromptOptions: { appendSystemPrompt: 'base' } };
276
+ identity.appendUserIdentitySection(unset, { env: {} });
277
+ assert.equal(unset.systemPromptOptions.appendSystemPrompt, 'base');
278
+ } finally {
279
+ if (previous === undefined) delete globalThis[BRIDGE_SLOT];
280
+ else globalThis[BRIDGE_SLOT] = previous;
281
+ }
282
+ });
283
+ });
284
+
285
+ // ---- D6: the command surface ----
286
+
287
+ // The fixture drives registrations through a fake host, so the command is cheap to load here: the
288
+ // bridge is published on the real slot BEFORE the extension loads, exactly as the fixture does,
289
+ // and its store is one this test can read back.
290
+ function commandBridge() {
291
+ const bridge = fixture.defaultBridge();
292
+ const documents = new Map();
293
+ const writes = [];
294
+ const repaints = [];
295
+ bridge.api.createStore = (id) => ({
296
+ get: (key, fallback) => {
297
+ const document = documents.get(id);
298
+ return document !== undefined && Object.hasOwn(document, key) ? document[key] : fallback;
299
+ },
300
+ set: (key, value) => {
301
+ documents.set(id, { ...(documents.get(id) ?? {}), [key]: value });
302
+ writes.push([id, key, value]);
303
+ },
304
+ delete: (key) => {
305
+ const document = { ...(documents.get(id) ?? {}) };
306
+ delete document[key];
307
+ documents.set(id, document);
308
+ writes.push([id, key]);
309
+ },
310
+ });
311
+ bridge.api.requestRepaint = () => repaints.push(repaints.length + 1);
312
+ return { api: bridge.api, documents, writes, repaints };
313
+ }
314
+
315
+ const NOT_SET = 'identity: not set · messages head with "You"';
316
+ const REFUSAL = 'identity: a name needs 1-40 printable characters and no markdown heading';
317
+
318
+ /** The extension loaded over a bridge this test owns, with a live session that owns the repaint. */
319
+ async function loadIdentityCommand(initialIdentity, modules) {
320
+ const made = commandBridge();
321
+ if (initialIdentity !== undefined) made.documents.set(STORE, { identity: initialIdentity });
322
+ if (modules !== undefined) made.documents.set(STORE, { ...(made.documents.get(STORE) ?? {}), modules });
323
+ const previous = globalThis[BRIDGE_SLOT];
324
+ globalThis[BRIDGE_SLOT] = made.api;
325
+ try {
326
+ const loaded = await fixture.loadExtension({});
327
+ for (const [event, handler] of loaded.hooks) {
328
+ if (event === 'session_start') await handler({}, {});
329
+ }
330
+ const command = loaded.commands.get('identity');
331
+ assert.notEqual(command, undefined, '/identity is registered with the bridge present');
332
+ const notifications = [];
333
+ const ctx = { ui: { notify: (text, level) => notifications.push(level === undefined ? [text] : [text, level]) } };
334
+ // Loading seeds documents of its own (the bash design's marker), which are not this
335
+ // command's writes: the baseline starts where the command starts.
336
+ made.writes.length = 0;
337
+ return {
338
+ command,
339
+ ctx,
340
+ notifications,
341
+ hooks: loaded.hooks,
342
+ documents: made.documents,
343
+ writes: made.writes,
344
+ repaints: made.repaints,
345
+ restore: () => {
346
+ if (previous === undefined) delete globalThis[BRIDGE_SLOT];
347
+ else globalThis[BRIDGE_SLOT] = previous;
348
+ },
349
+ };
350
+ } catch (error) {
351
+ if (previous === undefined) delete globalThis[BRIDGE_SLOT];
352
+ else globalThis[BRIDGE_SLOT] = previous;
353
+ throw error;
354
+ }
355
+ }
356
+
357
+ describe('/identity', () => {
358
+ test('the command says what it does, and its bare form reports the state without writing', async () => {
359
+ const loaded = await loadIdentityCommand();
360
+ try {
361
+ assert.match(loaded.command.description, /clear/, 'the description names the reserved word');
362
+ await loaded.command.handler('', loaded.ctx);
363
+ assert.deepEqual(loaded.notifications, [[NOT_SET]], 'nothing set, said plainly');
364
+ assert.deepEqual(loaded.writes, [], 'and nothing written');
365
+ assert.deepEqual(loaded.repaints, [], 'no repaint for a report');
366
+
367
+ await loaded.command.handler(undefined, loaded.ctx);
368
+ assert.deepEqual(loaded.notifications.at(-1), [NOT_SET], 'no argument is the same report');
369
+ } finally {
370
+ loaded.restore();
371
+ }
372
+ });
373
+
374
+ test('a name is stored, the state is said, and exactly one repaint is asked for', async () => {
375
+ const loaded = await loadIdentityCommand();
376
+ try {
377
+ await loaded.command.handler(' Jona ', loaded.ctx);
378
+ assert.deepEqual(loaded.documents.get(STORE).identity, { schema: 1, name: 'Jona' }, 'the name is persisted');
379
+ assert.deepEqual(loaded.notifications, [['identity: Jona']]);
380
+ assert.equal(loaded.repaints.length, 1, 'one repaint, so the prompts already on screen head with the name');
381
+ assert.equal(loaded.documents.get(STORE).identity.schema, 1, 'S1: the name survives a restart, it is a document');
382
+
383
+ await loaded.command.handler('', loaded.ctx);
384
+ assert.deepEqual(loaded.notifications.at(-1), ['identity: Jona'], 'the bare form reports it');
385
+ assert.equal(loaded.repaints.length, 1, 'a report repaints nothing');
386
+ } finally {
387
+ loaded.restore();
388
+ }
389
+ });
390
+
391
+ test('the same name again says it and repaints nothing, and a refused name writes nothing', async () => {
392
+ const loaded = await loadIdentityCommand();
393
+ try {
394
+ await loaded.command.handler('Jona', loaded.ctx);
395
+ const writes = loaded.writes.length;
396
+ await loaded.command.handler('Jona', loaded.ctx);
397
+ assert.deepEqual(loaded.notifications.at(-1), ['identity: Jona'], 'the state is still said');
398
+ assert.equal(loaded.repaints.length, 1, 'an unchanged name repaints nothing');
399
+ assert.deepEqual(loaded.writes.slice(writes), [], 'and rewrites nothing');
400
+
401
+ for (const bad of ['a'.repeat(41), '\u0000']) {
402
+ await loaded.command.handler(bad, loaded.ctx);
403
+ assert.deepEqual(loaded.notifications.at(-1), [REFUSAL, 'error'], `${JSON.stringify(bad)} is refused`);
404
+ assert.deepEqual(loaded.documents.get(STORE).identity, { schema: 1, name: 'Jona' }, 'the stored name is untouched');
405
+ }
406
+ assert.equal(loaded.repaints.length, 1, 'a refusal repaints nothing');
407
+ } finally {
408
+ loaded.restore();
409
+ }
410
+ });
411
+
412
+ test('`clear` (any case) unsets the name, says so, repaints once, and is not a name', async () => {
413
+ const loaded = await loadIdentityCommand();
414
+ try {
415
+ await loaded.command.handler('Jona', loaded.ctx);
416
+ await loaded.command.handler('CLEAR', loaded.ctx);
417
+ assert.equal(Object.hasOwn(loaded.documents.get(STORE), 'identity'), false, 'the document is gone from the store');
418
+ assert.deepEqual(loaded.notifications.at(-1), [NOT_SET], 'the state is back to You');
419
+ assert.equal(loaded.repaints.length, 2, 'the set and the clear each asked for one repaint');
420
+
421
+ await loaded.command.handler('clear', loaded.ctx);
422
+ assert.deepEqual(loaded.notifications.at(-1), [NOT_SET], 'clearing nothing says the state');
423
+ assert.equal(loaded.repaints.length, 2, 'and asks for no second repaint');
424
+ } finally {
425
+ loaded.restore();
426
+ }
427
+ });
428
+
429
+ test('a value that only BECOMES `clear` after normalization is the reserved word, never a name', async () => {
430
+ // The reserved check runs on the NORMALIZED value: otherwise `cle\u0001ar` would be stored as
431
+ // `clear` — a name the command could never unset, because `clear` is always the verb.
432
+ const loaded = await loadIdentityCommand();
433
+ try {
434
+ await loaded.command.handler('Jona', loaded.ctx);
435
+ await loaded.command.handler('cle\u0001ar', loaded.ctx);
436
+ assert.equal(Object.hasOwn(loaded.documents.get(STORE), 'identity'), false, 'it cleared instead of storing `clear`');
437
+ assert.deepEqual(loaded.notifications.at(-1), [NOT_SET]);
438
+ } finally {
439
+ loaded.restore();
440
+ }
441
+ });
442
+
443
+ test('a throwing notify never breaks the handler, and neither does a session with no UI', async () => {
444
+ const loaded = await loadIdentityCommand();
445
+ try {
446
+ const throwing = { ui: { notify: () => { throw new Error('the UI died'); } } };
447
+ assert.doesNotThrow(() => loaded.command.handler('Jona', throwing), 'a dead UI is not a failed write');
448
+ assert.deepEqual(loaded.documents.get(STORE).identity, { schema: 1, name: 'Jona' }, 'the write still happened');
449
+ assert.doesNotThrow(() => loaded.command.handler('', {}), 'a session with no UI says nothing and does not throw');
450
+ assert.doesNotThrow(() => loaded.command.handler('Ana', undefined));
451
+ assert.deepEqual(loaded.documents.get(STORE).identity, { schema: 1, name: 'Ana' });
452
+ } finally {
453
+ loaded.restore();
454
+ }
455
+ });
456
+
457
+ // T4: the wiring itself, through the hook the host actually receives — the module's own append
458
+ // is asserted above, and this is the proof that the extension calls it for every session start.
459
+ test('the extension appends the one line from its before_agent_start hook, and nothing for a child', async () => {
460
+ // This suite may itself run inside a child session (`GENTLE_PI_AGENTS_CHILD=1`), which is a
461
+ // guard the block honours: the orchestrator case is the one that starts from a clean env.
462
+ const savedChild = process.env.GENTLE_PI_AGENTS_CHILD;
463
+ delete process.env.GENTLE_PI_AGENTS_CHILD;
464
+ const loaded = await loadIdentityCommand({ schema: 1, name: 'Jona' }, { worktrees: false, codegraph: false });
465
+ const emit = async (event) => {
466
+ for (const [name, handler] of loaded.hooks) {
467
+ if (name === 'before_agent_start') await handler(event, {});
468
+ }
469
+ return event;
470
+ };
471
+ try {
472
+ const event = await emit({ systemPromptOptions: { appendSystemPrompt: 'base' } });
473
+ assert.equal(event.systemPromptOptions.appendSystemPrompt,
474
+ "base\n\n## User identity\n\nThe user's name is Jona.", 'the block rides the same hook as the other two');
475
+
476
+ process.env.GENTLE_PI_AGENTS_CHILD = '1';
477
+ const child = await emit({ systemPromptOptions: { appendSystemPrompt: 'base' } });
478
+ assert.equal(child.systemPromptOptions.appendSystemPrompt, 'base', 'a child session gets none of it');
479
+ } finally {
480
+ if (savedChild === undefined) delete process.env.GENTLE_PI_AGENTS_CHILD;
481
+ else process.env.GENTLE_PI_AGENTS_CHILD = savedChild;
482
+ loaded.restore();
483
+ }
484
+ });
485
+
486
+ test('the identity block rides BESIDE an older block, and neither loses its marker', async () => {
487
+ // The two older appends run before this one, and each is idempotent by its own heading: with a
488
+ // name stored, one event must carry both blocks, the identity one last.
489
+ const loaded = await loadIdentityCommand({ schema: 1, name: 'Jona' }, { worktrees: true, codegraph: false });
490
+ try {
491
+ const event = { systemPromptOptions: { appendSystemPrompt: 'base' } };
492
+ for (const [name, handler] of loaded.hooks) {
493
+ if (name === 'before_agent_start') await handler(event, {});
494
+ }
495
+ const text = event.systemPromptOptions.appendSystemPrompt;
496
+ assert.ok(text.includes('## ODD worktrees'), 'the older block is still there');
497
+ assert.ok(text.includes('## User identity'), 'and the name block was added');
498
+ assert.ok(text.indexOf('## ODD worktrees') < text.indexOf('## User identity'), 'the identity block goes last');
499
+ } finally {
500
+ loaded.restore();
501
+ }
502
+ });
503
+ });
@@ -352,6 +352,79 @@ test('a width too small to draw a frame hands the rows straight back', () => {
352
352
  assert.notDeepEqual(component.render(6), nativeRows(component, 6), 'a usable width still paints');
353
353
  });
354
354
 
355
+ // ---- identity-command: the heading is the person's name, read on every paint ----
356
+
357
+ /**
358
+ * The published bridge plus the store `lib/user-identity.js` reads: one in-memory document map
359
+ * behind `createStore('odd-worktree')`, merged per key exactly like the bridge's own store. No
360
+ * invalidation call exists: a name is written here and the next paint has to see it.
361
+ */
362
+ function publishIdentityBridge() {
363
+ const documents = new Map();
364
+ publishBridge(ACTIVITY_ANSWER);
365
+ globalThis[BRIDGE_API_SLOT].createStore = (id) => ({
366
+ get: (key, fallback) => {
367
+ const document = documents.get(id);
368
+ return document !== undefined && Object.hasOwn(document, key) ? document[key] : fallback;
369
+ },
370
+ set: (key, value) => {
371
+ documents.set(id, { ...(documents.get(id) ?? {}), [key]: value });
372
+ },
373
+ });
374
+ return {
375
+ documents,
376
+ setName: (name) => documents.set('odd-worktree', { ...(documents.get('odd-worktree') ?? {}), identity: { schema: 1, name } }),
377
+ forgetName: () => documents.set('odd-worktree', {}),
378
+ };
379
+ }
380
+
381
+ const headOf = (component, width = 60) => unpaint(component.render(width)[0]);
382
+
383
+ test('a stored name heads the card instead of You', () => {
384
+ const bridge = publishIdentityBridge();
385
+ bridge.setName('Jona');
386
+ install();
387
+ const rows = promptComponent().render(60);
388
+ assert.match(unpaint(rows[0]), /^╭─ ✿ Jona /u, 'the heading is the name');
389
+ assert.equal(rows.some((row) => unpaint(row).includes('You')), false, 'nothing of the card still heads with You');
390
+ });
391
+
392
+ test('without a stored name the heading is still You, byte for byte as before', () => {
393
+ publishIdentityBridge();
394
+ install();
395
+ assert.match(headOf(promptComponent()), /^╭─ ✿ You /u);
396
+ });
397
+
398
+ test('a name changed between two paints of the SAME component recomposes: no stale You', () => {
399
+ const bridge = publishIdentityBridge();
400
+ install();
401
+ const component = promptComponent();
402
+ assert.match(headOf(component), /^╭─ ✿ You /u, 'nothing stored: You');
403
+ bridge.setName('Jona');
404
+ assert.match(headOf(component), /^╭─ ✿ Jona /u, 'the name is read per paint, so the memo cannot serve the old head');
405
+ bridge.setName('Ana');
406
+ assert.match(headOf(component), /^╭─ ✿ Ana /u, 'and a second change follows the same way');
407
+ bridge.forgetName();
408
+ assert.match(headOf(component), /^╭─ ✿ You /u, 'cleared: You is back on the same component');
409
+ });
410
+
411
+ test('a malformed identity document is no name: the card paints You', () => {
412
+ for (const document of [{ schema: 2, name: 'Jona' }, { schema: 1, name: 42 }, { schema: 1, name: ' ' }, 'Jona', null]) {
413
+ const made = publishIdentityBridge();
414
+ made.documents.set('odd-worktree', { identity: document });
415
+ install();
416
+ assert.match(headOf(promptComponent()), /^╭─ ✿ You /u, JSON.stringify(document));
417
+ uninstallUserPromptCard();
418
+ }
419
+ });
420
+
421
+ test('with no bridge at all the host\'s own rows come back unchanged', () => {
422
+ delete globalThis[BRIDGE_API_SLOT];
423
+ install();
424
+ const component = promptComponent();
425
+ assert.deepEqual(component.render(60), nativeRows(component, 60));
426
+ });
427
+
355
428
  // ---- S3/S4: the accent frame in both styles, the body untouched ----
356
429
 
357
430
  const FRAME_CHARS = new Set(['╭', '╮', '╰', '╯', '─', '│', '▎']);