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.
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,14 +102,14 @@ 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
- - **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. See [the reminders](docs/reference.md#the-two-codegraph-reminders).
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).
113
114
 
114
115
  ## Documentation
@@ -3301,12 +3301,20 @@ function guardSkillReadBashCall(event) {
3301
3301
  // the identity and the default branch memoized per checkout, the current branch read
3302
3302
  // on demand, so the hot path costs one `Map` hit per call plus one git read for a
3303
3303
  // switch.
3304
+ // Worktree creation and the principal checkout's branch are the ORCHESTRATOR's actions: a subagent child is
3305
+ // handed the worktree it works in and never creates one or leaves the default branch, so neither worktree
3306
+ // guard judges a child (`GENTLE_PI_AGENTS_CHILD`, the signal the prompt blocks use).
3307
+ function oddChildSession() {
3308
+ return process.env.GENTLE_PI_AGENTS_CHILD === "1";
3309
+ }
3310
+
3304
3311
  function guardWorktreeBashCall(event, ctx) {
3305
3312
  try {
3306
3313
  // `ODD_WORKTREE_GUARD=0` turns the guards off for this process, the way
3307
3314
  // `ODD_WORKTREE_PROMPT=0` turns off the prompt blocks. Read per call: a guard is
3308
3315
  // cheap, and an escape hatch that needs a restart is not one.
3309
3316
  if (process.env.ODD_WORKTREE_GUARD === "0") return undefined;
3317
+ if (oddChildSession()) return undefined;
3310
3318
  if (!event || event.toolName !== "bash") return undefined;
3311
3319
  const guard = libRequire("worktree-guard.js");
3312
3320
  if (!guard || typeof guard.decideBashGuard !== "function") return undefined;
@@ -3348,6 +3356,7 @@ const WRITE_GUARD_TOOLS = new Set(["edit", "write"]);
3348
3356
  function guardWorktreeWriteCall(event, ctx) {
3349
3357
  try {
3350
3358
  if (process.env.ODD_WORKTREE_GUARD === "0") return undefined;
3359
+ if (oddChildSession()) return undefined;
3351
3360
  const toolName = oddToolNameOf(event);
3352
3361
  if (!WRITE_GUARD_TOOLS.has(toolName)) return undefined;
3353
3362
  const paths = oddTouchedPaths(oddArgsOf(event));
@@ -8336,6 +8345,98 @@ function registerFilesCommand(pi) {
8336
8345
  filesCommandHandler = handler;
8337
8346
  }
8338
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
+
8339
8440
  // ---------------------------------------------------------------------------
8340
8441
  // `/issues` (T3 S1,S3): a full-screen issues reader over the CURRENT checkout's
8341
8442
  // repository issues, through this package's own migrated pieces
@@ -11091,6 +11192,20 @@ function installUserPromptCard() {
11091
11192
  */
11092
11193
  function requestPromptCardRepaint(outcome) {
11093
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() {
11094
11209
  if (!userPromptCardSessionLive) return;
11095
11210
  try {
11096
11211
  const resolver = libRequire("file-card-resolver.js");
@@ -11098,7 +11213,7 @@ function requestPromptCardRepaint(outcome) {
11098
11213
  if (api === undefined || typeof api.requestRepaint !== "function") return;
11099
11214
  api.requestRepaint();
11100
11215
  } catch {
11101
- // 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.
11102
11217
  }
11103
11218
  }
11104
11219
 
@@ -12074,6 +12189,9 @@ function registerOddWorktreeSurfaceEntries(pi) {
12074
12189
  // T7 (files-picker): the file picker is the fourth command. It mounts its own
12075
12190
  // overlays, reads Git through the package's async runner and adds no tool.
12076
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);
12077
12195
  // S36 (files-picker T15): the picker's ONE key, bound directly on the host and
12078
12196
  // bound once — `alt+p` (S41) unless `GENTLE_PI_FILES_KEY` says otherwise.
12079
12197
  bindFilesShortcut(pi);
@@ -12383,6 +12501,15 @@ function registerOddWorktreeSurfaceEntries(pi) {
12383
12501
  // The prompt block is best effort.
12384
12502
  }
12385
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
+ }
12386
12513
  });
12387
12514
  // CodeGraph, only with its CLI installed: the global MCP entry, create-or-sync at session
12388
12515
  // start, the compaction sync, the observed native init and the edit/write sync. Every
@@ -4,9 +4,9 @@
4
4
  // Guard 1 says a call went to ANOTHER checkout and points the session at
5
5
  // `mcp__codegraph__codegraph_explore` with that checkout as `projectPath`; it belongs to the primary
6
6
  // session and fires once per checkout per session. Guard 2 says to reach CodeGraph first inside the
7
- // session's OWN checkout; it belongs to the primary session and to every child except the `review-*`
8
- // agents, and it reminds once on the first search of a checkout, while the graph is unused in that
9
- // request, and then never again for that checkout in that request (S3, S7).
7
+ // session's OWN checkout; it belongs to the primary session too (a child is short-lived and its own rule
8
+ // text already says it), and it reminds once on the first search of a checkout, while the graph is unused
9
+ // in that request, and then never again for that checkout in that request (S3, S7).
10
10
  //
11
11
  // Both are precise: a checkout the session already explored with the MCP tool silences guard 1, and a
12
12
  // reminder that does not fire uses up no slot. A call that failed is no subject at all: the model got no
@@ -186,6 +186,9 @@ function createCodegraphGuard(deps = {}) {
186
186
  if (event.isError === true) return undefined;
187
187
  const cwd = sessionCwd(event, ctx);
188
188
  if (recordCodegraphUse(state, event, cwd)) return undefined;
189
+ // Both reminders are the primary session's: a child lives a message or two and its own section already
190
+ // states the rule, so a reminder there would only repeat it.
191
+ if (child()) return undefined;
189
192
  // The same gate as the prompt section: the session must hold a CodeGraph tool to be advised.
190
193
  const held = tools();
191
194
  if (!holdsCodegraph(held)) return undefined;
@@ -1,8 +1,7 @@
1
1
  ## CodeGraph
2
2
 
3
- Run one call to the CodeGraph tool you hold before you search or read code — `fd`, `find`, `rg`, `grep`,
4
- `read` or `cat` — when the task needs structure rather than a lookup: where something lives, who calls it,
5
- what a change reaches. Skip it only for an exact string or a file path you were given. The other tools stay
6
- available after the first call.
3
+ Before you search or read code — `fd`, `find`, `rg`, `grep`, `read` or `cat` — your first call is one call to
4
+ the CodeGraph tool you hold: where something lives, who calls it, what a change reaches. The one exemption is
5
+ an exact string or a file path you were given.
7
6
 
8
- The answer is a map, not proof: confirm it in the source, and read a file before editing it.
7
+ Then read the files it points at, and read a file before editing it.
@@ -1,12 +1,11 @@
1
1
  ## CodeGraph
2
2
 
3
3
  Before you `grep`, `rg`, `fd`, `find`, `read` or `cat` to answer where code lives, who calls it, how it
4
- works, or what a change reaches, call CodeGraph first: `codegraph` with `operation: "explore"` and
4
+ works, or what a change reaches, your first call is CodeGraph: `codegraph` with `operation: "explore"` and
5
5
  `query: "<symbols or the question>"` returns the source and the call paths in one call, and it is
6
6
  also what scope, size and any handoff depend on. Use `operation: "query"` only to find where one
7
- symbol is defined. Skip it only for an exact string or a file path the user gave you. The other tools stay for
8
- what the graph does not index. Its answer is a map: confirm it in the source, and a verdict comes
9
- from the source and from tests.
7
+ symbol is defined. The one exemption is an exact string or a file path the user gave you. Then read the
8
+ files it points at: a verdict comes from the source and from tests.
10
9
 
11
10
  `codegraph` answers only for the checkout the session runs in, and each worktree is its own workspace with
12
11
  its own index. An ODD works in its own worktree: when the session runs elsewhere, look at that worktree, at
@@ -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
+ };