pi-odd-worktree 3.12.3 → 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.
@@ -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(['╭', '╮', '╰', '╯', '─', '│', '▎']);
@@ -697,6 +697,26 @@ describe('the tool_call handler the extension registers', () => {
697
697
  }
698
698
  });
699
699
 
700
+ test('a subagent child is judged by neither worktree guard: they are the orchestrator\'s actions', async () => {
701
+ const before = process.env.GENTLE_PI_AGENTS_CHILD;
702
+ try {
703
+ process.env.GENTLE_PI_AGENTS_CHILD = '1';
704
+ assert.equal(await callTool(loaded.hooks, bash('git worktree add ../odd-b'), principal), undefined, 'worktree add');
705
+ assert.equal(await callTool(loaded.hooks, bash('git checkout -b feat/odd-b'), principal), undefined, 'branch switch');
706
+ const file = path.join(principal, 'src', 'a.js');
707
+ assert.equal(await callTool(loaded.hooks, { toolName: 'write', input: { path: file, content: 'x' } }, principal), undefined, 'write');
708
+ assert.equal(await callTool(loaded.hooks, { toolName: 'edit', input: { path: file, oldText: 'a', newText: 'b' } }, principal), undefined, 'edit');
709
+ } finally {
710
+ if (before === undefined) delete process.env.GENTLE_PI_AGENTS_CHILD;
711
+ else process.env.GENTLE_PI_AGENTS_CHILD = before;
712
+ }
713
+ assert.deepEqual(
714
+ await callTool(loaded.hooks, bash('git worktree add ../odd-b'), principal),
715
+ { block: true, reason: WORKTREE_ADD_REFUSAL },
716
+ 'the primary session is still judged',
717
+ );
718
+ });
719
+
700
720
  test('refuses the switches that leave the principal checkout\'s default branch', async () => {
701
721
  const expected = [
702
722
  ['git checkout -b feat/odd-b', BRANCH_SWITCH_REFUSAL],