herdr-gentle-shell 1.5.2 → 1.6.1

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.
@@ -4,8 +4,14 @@
4
4
  //
5
5
  // It opens a Herdr panel running a Pi session AT A PATH:
6
6
  // * the path is a linked Git worktree -> a WORKTREE panel
7
- // (`herdr worktree open --path …`), reusing the workspace Herdr already
8
- // has for that checkout when there is one;
7
+ // (`herdr worktree open --path … --cwd …`), reusing the workspace Herdr
8
+ // already has for that checkout when there is one. The target is passed as
9
+ // `--cwd` as well because herdr resolves a worktree against the
10
+ // repository of the FOCUSED workspace, not against the process cwd, so a
11
+ // worktree of ANOTHER repository resolves instead of answering
12
+ // `worktree_not_found`. When herdr still answers `worktree_not_found` for
13
+ // a path git proves is a linked worktree, the panel falls back to a NORMAL
14
+ // one at the same path and the result says so;
9
15
  // * the path is a repository's primary checkout, any other directory, or a
10
16
  // subdirectory of a checkout -> a NORMAL panel
11
17
  // (`herdr workspace create --cwd …`).
@@ -181,12 +187,23 @@ async function executeSessionOpen(params, ctx, watcherOptions) {
181
187
  let paneId = null;
182
188
  let openedHere = false;
183
189
  const openCall = isWorktree ? "herdr worktree open" : "herdr workspace create";
190
+ // The panel kind that was really OPENED. A worktree panel can degrade to a
191
+ // normal panel on the one documented fallback, and both the rows and the
192
+ // details state the kind that was opened, never the one that was classified.
193
+ let openedKind = kind;
194
+ // The herdr error code that forced that fallback, or null. It is present
195
+ // only when a fallback really happened, so every existing result keeps its
196
+ // exact key order.
197
+ let fallbackCode = null;
184
198
 
185
199
  // One pane choice, used by the reuse path and by the create-then-list path.
186
200
  // Each refusal carries the details object the caller publishes, so every
187
201
  // refusal of this tool has the same key order: path, kind, branch, then the
188
202
  // pane before the workspace it belongs to.
189
- const paneRefusalBase = () => ({ path: target, kind, branch });
203
+ const paneRefusalBase = () => ({
204
+ path: target, kind: openedKind, branch,
205
+ ...(fallbackCode === null ? {} : { fallback: fallbackCode }),
206
+ });
190
207
  const choosePane = async (note) => {
191
208
  const panes = await runHerdr("pane-list", { workspace: workspaceId }, 60000);
192
209
  if (panes.status !== 0) {
@@ -214,22 +231,24 @@ async function executeSessionOpen(params, ctx, watcherOptions) {
214
231
  // Verify the pair a successful open/create reply names, before anything is
215
232
  // started in it: the pane belongs to the workspace, the pane's own workspace
216
233
  // (when reported) agrees, and its cwd is the requested path or inside it.
217
- const verifyOpenedPair = (pair) => {
234
+ // `call` names the call that really produced the panel, so a fallback reply
235
+ // is reported as the `herdr workspace create` it was.
236
+ const verifyOpenedPair = (pair, call = openCall) => {
218
237
  if (pair.workspaceId === null || pair.paneId === null) {
219
- return `herdr session open failed: '${openCall}' for ${target} succeeded but its output named no workspace/pane; no session was started`;
238
+ return `herdr session open failed: '${call}' for ${target} succeeded but its output named no workspace/pane; no session was started`;
220
239
  }
221
240
  if (!pair.paneId.startsWith(`${pair.workspaceId}:`)) {
222
- return `herdr session open failed: '${openCall}' named workspace '${pair.workspaceId}' but pane '${pair.paneId}', which does not belong to it; no session was started`;
241
+ return `herdr session open failed: '${call}' named workspace '${pair.workspaceId}' but pane '${pair.paneId}', which does not belong to it; no session was started`;
223
242
  }
224
243
  if (pair.paneWorkspace !== null && pair.paneWorkspace !== pair.workspaceId) {
225
- return `herdr session open failed: '${openCall}' named workspace '${pair.workspaceId}' but its root pane reports workspace '${pair.paneWorkspace}'; no session was started`;
244
+ return `herdr session open failed: '${call}' named workspace '${pair.workspaceId}' but its root pane reports workspace '${pair.paneWorkspace}'; no session was started`;
226
245
  }
227
246
  if (pair.paneCwd !== null) {
228
247
  const openedState = lib.checkoutState(pair.paneCwd, target);
229
248
  const openedReal = openedState.real !== null ? openedState.real : openedState.absolute;
230
249
  const inside = openedReal !== null && (openedReal === target || openedReal.startsWith(target + path.sep));
231
250
  if (!inside) {
232
- return `herdr session open failed: the pane '${pair.paneId}' '${openCall}' opened for ${target} has cwd ${pair.paneCwd}, outside ${target}; no session was started`;
251
+ return `herdr session open failed: the pane '${pair.paneId}' '${call}' opened for ${target} has cwd ${pair.paneCwd}, outside ${target}; no session was started`;
233
252
  }
234
253
  }
235
254
  return null;
@@ -271,10 +290,16 @@ async function executeSessionOpen(params, ctx, watcherOptions) {
271
290
  // it fails, one fresh list decides whether the workspace appeared anyway.
272
291
  // A worktree panel opens at the canonical checkout; a normal panel keeps the
273
292
  // spelling the caller asked for, which is what their shell will show.
274
- const opened = isWorktree
275
- ? await runHerdr("open", { path: target, noFocus: true }, 60000)
293
+ //
294
+ // The target travels as BOTH `--path` and `--cwd`: herdr resolves a
295
+ // worktree against the repository of the FOCUSED workspace unless `--cwd`
296
+ // names the resolution base, so only a target passed as `--cwd` can be
297
+ // resolved when its repository is not the focused one.
298
+ let reply = isWorktree
299
+ ? await runHerdr("open", { path: target, cwd: target, noFocus: true }, 60000)
276
300
  : await runHerdr("workspace-create", { cwd: requested, noFocus: true }, 60000);
277
- if (opened.status !== 0) {
301
+ let call = openCall;
302
+ if (reply.status !== 0) {
278
303
  if (isWorktree) {
279
304
  const relisted = await runHerdr("list", { cwd: target }, 60000);
280
305
  const retry = relisted.status === 0
@@ -283,17 +308,38 @@ async function executeSessionOpen(params, ctx, watcherOptions) {
283
308
  if (retry.id !== null) workspaceId = retry.id;
284
309
  }
285
310
  if (workspaceId === null) {
286
- return errorResult(
287
- `herdr session open failed: ${lib.herdrFailureText(openCall, opened.status, opened.stderr || opened.error)} for ${target}; no session was opened`,
288
- { path: target, kind, branch },
289
- );
311
+ // The ONE fallback (S3): herdr answered `worktree_not_found` for a path
312
+ // git still proves is a linked worktree, i.e. it could not resolve that
313
+ // worktree's repository. A normal panel at the same path still opens.
314
+ // Every other failure — and this code for a path that is no longer a
315
+ // linked worktree — keeps the abort below, so an unrelated error is
316
+ // never masked by a panel.
317
+ const code = isWorktree ? lib.herdrErrorCode(reply) : null;
318
+ if (code !== "worktree_not_found" || !(await lib.isLinkedWorktreePath(target))) {
319
+ return errorResult(
320
+ `herdr session open failed: ${lib.herdrFailureText(call, reply.status, reply.stderr || reply.error)} for ${target}; no session was opened`,
321
+ { path: target, kind, branch },
322
+ );
323
+ }
324
+ const fallback = await runHerdr("workspace-create", { cwd: target, noFocus: true }, 60000);
325
+ if (fallback.status !== 0) {
326
+ return errorResult(
327
+ `herdr session open failed: ${lib.herdrFailureText("herdr workspace create", fallback.status, fallback.stderr || fallback.error)} for ${target} after 'herdr worktree open' reported ${code}; no session was opened`,
328
+ { path: target, kind: "normal", branch, fallback: code },
329
+ );
330
+ }
331
+ reply = fallback;
332
+ call = "herdr workspace create";
333
+ openedKind = "normal";
334
+ fallbackCode = code;
290
335
  }
291
- } else {
292
- const pair = lib.openedWorkspace(opened.stdout);
293
- const refusal = verifyOpenedPair(pair);
336
+ }
337
+ if (reply.status === 0 && workspaceId === null) {
338
+ const pair = lib.openedWorkspace(reply.stdout);
339
+ const refusal = verifyOpenedPair(pair, call);
294
340
  if (refusal) {
295
341
  return errorResult(refusal, {
296
- path: target, kind, branch,
342
+ ...paneRefusalBase(),
297
343
  paneId: pair.paneId, workspaceId: pair.workspaceId,
298
344
  });
299
345
  }
@@ -303,7 +349,7 @@ async function executeSessionOpen(params, ctx, watcherOptions) {
303
349
  }
304
350
  if (paneId === null && workspaceId !== null) {
305
351
  const chosen = await choosePane(
306
- isWorktree
352
+ openedKind === "worktree"
307
353
  ? `; the workspace '${workspaceId}' was opened by this call and no session was started in it`
308
354
  : `; the workspace '${workspaceId}' was created by this call and no session was started in it`,
309
355
  );
@@ -320,7 +366,8 @@ async function executeSessionOpen(params, ctx, watcherOptions) {
320
366
  timeout: String(AGENT_START_TIMEOUT_MS), agentArgs: piArgs,
321
367
  }, AGENT_START_TIMEOUT_MS + 60000);
322
368
  const details = {
323
- path: target, kind, branch,
369
+ path: target, kind: openedKind, branch,
370
+ ...(fallbackCode === null ? {} : { fallback: fallbackCode }),
324
371
  paneId, workspaceId, sessionId, resumed, agentName, notify,
325
372
  };
326
373
  if (started.status !== 0) {
@@ -341,7 +388,7 @@ async function executeSessionOpen(params, ctx, watcherOptions) {
341
388
  try {
342
389
  notifications.startAgentSessionWatcher(
343
390
  {
344
- paneId, path: target, kind, branch, sessionId,
391
+ paneId, path: target, kind: openedKind, branch, sessionId,
345
392
  agentName, workspaceId, repoRoot: target,
346
393
  },
347
394
  watcherOptions,
@@ -28,14 +28,22 @@ const LEGACY_PLUGIN_ID = 'herdr-gentle-agents';
28
28
  // keeps the existing directory so upgrades keep their mode flag, marker
29
29
  // and installer state with no migration step.
30
30
  const STATE_PLUGIN_ID = 'herdr-gentle-agents';
31
- // Family of files proving a state dir is ours: when the Herdr-injected
32
- // dir (which changes with the plugin id) holds none of these while the
33
- // stored dir does, the stored dir wins so pre-rename flags stay readable.
34
- // This family is IDENTICAL in lib/perf-trace.js, herdr-plugin/bin/
35
- // gentle-status.js, herdr-plugin/lib/gentle-diagnostics.js and the state
36
- // extension, and every reader here must recognise every file any of them
37
- // writes: a family that omits a file splits the state across both dirs, and a
38
- // flag stored disabled then reads as missing (missing means enabled).
31
+ // Family of files proving a state dir is ours: the stored dir wins whenever it
32
+ // holds one of these, so pre-rename flags stay readable and one stray known
33
+ // file in the Herdr-injected dir (which changes with the plugin id) may never
34
+ // outrank the stored state — the daemon writes its pidfile into the dir it
35
+ // resolves, so that would make the split self-perpetuating. The active plugin id
36
+ // dir (`herdr-gentle-shell`) is a candidate in every context, because it is what
37
+ // Herdr injects and a legacy install may still keep its live flags only there;
38
+ // the stored canonical dir is the FINAL fallback, so a fresh install resolves the
39
+ // same directory in a context that receives the injected variable and one that
40
+ // never does. Selection order: stored if it holds a known file, else the
41
+ // active-id/injected dir if it holds one, else stored. This family is IDENTICAL
42
+ // in lib/perf-trace.js, herdr-plugin/bin/gentle-status.js,
43
+ // herdr-plugin/lib/gentle-diagnostics.js and the state extension, and every
44
+ // reader here must recognise every file any of them writes: a family that omits
45
+ // a file splits the state across both dirs, and a flag stored disabled then
46
+ // reads as missing (missing means enabled).
39
47
  const STATE_KNOWN_FILES = [
40
48
  'gentle-sidebar-mode.json',
41
49
  'gentle-moshi.json',
@@ -46,6 +54,14 @@ const STATE_KNOWN_FILES = [
46
54
  'gentle-worktree-mode.json',
47
55
  'gentle-plugin-tools.json',
48
56
  ];
57
+ // S1c: the only basenames an injected state dir may have to be honoured — the
58
+ // active plugin id Herdr injects today and the stored canonical segment — and
59
+ // the path must also BE the one this package derives for that name under the
60
+ // resolved state home. Any other injected path belongs to another plugin (or a
61
+ // stale/dev id) and is ignored, and so is an owned basename under another root,
62
+ // because the daemon receives the variable while this helper does not:
63
+ // honouring either is exactly what splits their state.
64
+ const OWNED_DIR_NAMES = [ACTIVE_PLUGIN_ID, STATE_PLUGIN_ID];
49
65
  // Backwards-compatible alias: the active plugin lookup identity.
50
66
  const PLUGIN_ID = ACTIVE_PLUGIN_ID;
51
67
  const MODE_VERSION = 1;
@@ -59,6 +75,62 @@ function storedStateDir(env = process.env) {
59
75
  : path.join(os.homedir(), '.local', 'state', 'herdr');
60
76
  return path.join(base, 'plugins', STATE_PLUGIN_ID);
61
77
  }
78
+
79
+ function dirHasKnownFiles(dir) {
80
+ for (const name of STATE_KNOWN_FILES) {
81
+ try {
82
+ if (fs.existsSync(path.join(dir, name))) return true;
83
+ } catch {
84
+ // A single unreadable entry never decides; keep scanning.
85
+ }
86
+ }
87
+ return false;
88
+ }
89
+
90
+ // Two spellings name the same directory when their canonical forms match.
91
+ // realpath resolves symlinks but throws for a path that does not exist yet, so
92
+ // walk up to the deepest existing ancestor and re-append the missing tail: that
93
+ // keeps a symlinked or relative spelling of the derived dir from being rejected
94
+ // as a different directory (S1c/T12 compares paths, never raw strings).
95
+ function canonicalStateDir(dir) {
96
+ const absolute = path.resolve(dir);
97
+ const tail = [];
98
+ let current = absolute;
99
+ for (;;) {
100
+ try {
101
+ const real = fs.realpathSync(current);
102
+ return tail.length ? path.join(real, ...tail) : real;
103
+ } catch {
104
+ const parent = path.dirname(current);
105
+ if (parent === current) return absolute;
106
+ // Prepended so the missing tail is re-appended in its original order.
107
+ tail.unshift(path.basename(current));
108
+ current = parent;
109
+ }
110
+ }
111
+ }
112
+
113
+ // The active-id dir: the Herdr-injected one only when it IS the directory this
114
+ // package derives for that name under the resolved state home, else the same
115
+ // sibling of the stored dir derived from the state home. S1c: an injected path
116
+ // with any other basename (a third plugin id, a stale or dev id) — or an owned
117
+ // basename under another root, which is exactly the case that splits the daemon
118
+ // (it receives the variable) from the producer (it derives its own) — is
119
+ // ignored rather than selected.
120
+ function activeStateDir(env = process.env) {
121
+ const pluginsDir = path.dirname(storedStateDir(env));
122
+ const injected = env.HERDR_PLUGIN_STATE_DIR;
123
+ if (typeof injected === 'string' && injected.length > 0) {
124
+ const name = path.basename(injected);
125
+ if (
126
+ OWNED_DIR_NAMES.includes(name) &&
127
+ canonicalStateDir(injected) === canonicalStateDir(path.join(pluginsDir, name))
128
+ ) {
129
+ return injected;
130
+ }
131
+ }
132
+ return path.join(pluginsDir, ACTIVE_PLUGIN_ID);
133
+ }
62
134
  const MODE_NAME = 'gentle-sidebar-mode.json';
63
135
  const MANAGED_BEGIN = '# BEGIN herdr-gentle-agents (managed; do not edit)';
64
136
  const MANAGED_END = '# END herdr-gentle-agents';
@@ -69,35 +141,17 @@ function stateDir(env = process.env) {
69
141
  const stored = storedStateDir(env);
70
142
  // HEAD parity: an explicit-but-empty (or otherwise invalid non-nullish)
71
143
  // value ignores every override and uses the stored default. Only an
72
- // omitted (null/undefined) explicit falls through to the injected dir.
144
+ // omitted (null/undefined) explicit falls through to the active-id dir.
73
145
  if (explicit !== undefined && explicit !== null) return stored;
74
- const injected = env.HERDR_PLUGIN_STATE_DIR;
75
- if (typeof injected !== 'string' || injected.length === 0) return stored;
76
- if (injected === stored) return injected;
146
+ const active = activeStateDir(env);
147
+ if (active === stored) return stored;
77
148
  try {
78
- let injectedHas = false;
79
- for (const name of STATE_KNOWN_FILES) {
80
- try {
81
- if (fs.existsSync(path.join(injected, name))) {
82
- injectedHas = true;
83
- break;
84
- }
85
- } catch {
86
- // A single unreadable entry never decides; keep scanning.
87
- }
88
- }
89
- if (injectedHas) return injected;
90
- for (const name of STATE_KNOWN_FILES) {
91
- try {
92
- if (fs.existsSync(path.join(stored, name))) return stored;
93
- } catch {
94
- // A single unreadable entry never decides; keep scanning.
95
- }
96
- }
149
+ if (dirHasKnownFiles(stored)) return stored;
150
+ if (dirHasKnownFiles(active)) return active;
97
151
  } catch {
98
- // Fall through to the injected dir on unexpected failure.
152
+ // Fall through to the stored canonical dir on unexpected failure.
99
153
  }
100
- return injected;
154
+ return stored;
101
155
  }
102
156
 
103
157
  function modePath(env) {
@@ -301,9 +301,16 @@ function agentNameForPath(target, options = {}) {
301
301
  // `--flag=value`. Unknown operations or flags throw, and `--trust-repository`
302
302
  // is absent everywhere: trusting a repository is a human decision this tool
303
303
  // never takes. `--focus` stays out too — panels open with `--no-focus`.
304
+ //
305
+ // `open` accepts `cwd` beside `path` because herdr resolves a worktree against
306
+ // the repository of the FOCUSED workspace, not against the process cwd
307
+ // (herdr 0.9.5: `herdr worktree list` reported the focused workspace's repo
308
+ // from three different cwds, while `--cwd <worktree>` reported the worktree's
309
+ // own repo). Passing the target as `--cwd` is what makes a worktree of
310
+ // another repository resolvable.
304
311
  const HERDR_ALLOWLIST = {
305
312
  list: ['cwd'],
306
- open: ['path', 'noFocus'],
313
+ open: ['cwd', 'path', 'noFocus'],
307
314
  'workspace-create': ['cwd', 'noFocus'],
308
315
  'pane-list': ['workspace'],
309
316
  'agent-start': ['name', 'kind', 'pane', 'timeout', 'agentArgs'],
@@ -444,6 +451,54 @@ function herdrFailureText(call, status, reason) {
444
451
  return `'${call}' exited ${status} (${detail})`;
445
452
  }
446
453
 
454
+ // The `error.code` a failed herdr reply names, or null when it names none.
455
+ // Herdr prints `{"error":{"code":"…","message":"…"}}`; only the CODE is read
456
+ // (a message is prose, never a decision), and a reply carrying anything else —
457
+ // plain text, or JSON without an error code — reads as no code at all.
458
+ function herdrErrorCode(reply) {
459
+ const source = reply && typeof reply === 'object' ? reply : {};
460
+ for (const raw of [source.stderr, source.stdout]) {
461
+ if (typeof raw !== 'string') continue;
462
+ const text = raw.trim();
463
+ if (text.length === 0) continue;
464
+ const candidates = [text];
465
+ const first = text.indexOf('{');
466
+ const last = text.lastIndexOf('}');
467
+ if (first !== -1 && last > first) candidates.push(text.slice(first, last + 1));
468
+ for (const candidate of candidates) {
469
+ let doc = null;
470
+ try {
471
+ doc = JSON.parse(candidate);
472
+ } catch {
473
+ continue;
474
+ }
475
+ const code = doc && typeof doc === 'object' && doc.error && typeof doc.error === 'object'
476
+ && typeof doc.error.code === 'string' && doc.error.code.length > 0
477
+ ? doc.error.code
478
+ : null;
479
+ if (code !== null) return code;
480
+ }
481
+ }
482
+ return null;
483
+ }
484
+
485
+ // Whether `target` is STILL the checkout root of an existing linked worktree,
486
+ // re-probed from git at the moment a failed open would fall back (never
487
+ // remembered from the earlier classification): a path that vanished, stopped
488
+ // being a worktree, or stopped being that worktree's ROOT keeps today's abort
489
+ // behaviour instead of falling back. Root identity matters on its own: a plain
490
+ // directory recreated inside another linked worktree resolves to the ENCLOSING
491
+ // checkout, whose kind says nothing about this path.
492
+ async function isLinkedWorktreePath(target, opts = {}) {
493
+ const state = checkoutState(target, null);
494
+ if (!state.exists || !state.isDirectory) return false;
495
+ const real = canonicalPath(target) || (state.real !== null ? state.real : state.absolute);
496
+ if (typeof real !== 'string' || real.length === 0) return false;
497
+ const probe = await repoProbe(real, opts);
498
+ if (probe.error !== null || probe.repo === null || probe.repo.isLinkedWorktree !== true) return false;
499
+ return identityOf(probe.repo.root) === identityOf(real);
500
+ }
501
+
447
502
  // ---------------------------------------------------------------------------
448
503
  // Herdr replies
449
504
  // ---------------------------------------------------------------------------
@@ -629,6 +684,10 @@ function sessionOpenRows(details) {
629
684
  const target = cleanValue(details.path);
630
685
  if (target.length > 0) rows.push(`path: ${target}`);
631
686
  rows.push(`panel: ${details.kind === 'worktree' ? 'worktree' : 'normal'}`);
687
+ // A fallback is never silent: a normal panel created because herdr refused
688
+ // the worktree says so, and names the error code that made it happen.
689
+ const fallback = cleanValue(details.fallback);
690
+ if (fallback.length > 0) rows.push(`fallback: normal panel after herdr reported ${fallback}`);
632
691
  const branch = cleanValue(details.branch);
633
692
  if (branch.length > 0) rows.push(`branch: ${branch}`);
634
693
  const session = cleanValue(details.sessionId);
@@ -657,6 +716,8 @@ module.exports = {
657
716
  resolveHerdrBinary,
658
717
  isHerdrRefusal,
659
718
  herdrFailureText,
719
+ herdrErrorCode,
720
+ isLinkedWorktreePath,
660
721
  worktreeWorkspaceId,
661
722
  selectSessionPane,
662
723
  openedWorkspace,
package/lib/perf-trace.js CHANGED
@@ -2,13 +2,22 @@
2
2
  // Writer half of the performance trace (S18/S24).
3
3
  //
4
4
  // Two plugin-owned files in the resolved plugin state directory:
5
- // GENTLE_STATUS_STATE_DIR (explicit override), else HERDR_PLUGIN_STATE_DIR
6
- // when it already holds one of our files, else
5
+ // GENTLE_STATUS_STATE_DIR (explicit override), else
7
6
  // $XDG_STATE_HOME/herdr/plugins/herdr-gentle-agents, else
8
- // ~/.local/state/herdr/plugins/herdr-gentle-agents. The resolution and its
9
- // known-file family are byte-for-byte the ones the sidebar switch, the Herdr
10
- // daemon and its diagnostics use, so all four read and write one directory per
11
- // install — which is why it lives here rather than in a worktree module.
7
+ // ~/.local/state/herdr/plugins/herdr-gentle-agents — the stored dir wins
8
+ // whenever it holds any of our files, and HERDR_PLUGIN_STATE_DIR is used only
9
+ // when the stored dir holds none while that one does; one stray known file in
10
+ // the injected dir may never outrank the stored state. The stored canonical dir
11
+ // is the FINAL fallback, so a fresh install resolves the same directory in a
12
+ // context that receives the injected variable and one that never does. An
13
+ // injected path is honoured only when it IS the directory this package derives
14
+ // for that name under the resolved state home (an owned basename under another
15
+ // root is ignored too); any other path is ignored (S1c), because the daemon
16
+ // receives that variable while this writer does not.
17
+ // The resolution and its known-file family are byte-for-byte the ones the sidebar
18
+ // switch, the Herdr daemon and its diagnostics use, so all four read and write
19
+ // one directory per install — which is why it lives here rather than in a
20
+ // worktree module.
12
21
  //
13
22
  // perf-trace.jsonl one JSON object per line — the trace
14
23
  // perf-trace.1.jsonl the single previous log, created on rotation
@@ -51,6 +60,18 @@ const { readHostValues } = require('./host-settings.js');
51
60
  // still carries them, and a family that differs between consumers splits the
52
61
  // state across two directories.
53
62
  const STATE_SEGMENT = 'herdr-gentle-agents';
63
+ // The active plugin lookup id: what Herdr injects as HERDR_PLUGIN_STATE_DIR, and
64
+ // where a legacy install may still keep its live flags. Every context resolves
65
+ // it, not only the daemon that receives the variable.
66
+ const ACTIVE_PLUGIN_ID = 'herdr-gentle-shell';
67
+ // S1c: the only basenames an injected state dir may have to be honoured — the
68
+ // active plugin id and the stored canonical segment — and the path must also BE
69
+ // the one this package derives for that name under the resolved state home. Any
70
+ // other injected path belongs to another plugin (a third id, a stale or dev id)
71
+ // and is ignored, and so is an owned basename under another root, because the
72
+ // daemon receives the variable while this writer usually does not: honouring
73
+ // either is exactly what splits the trace away from the rest of the state.
74
+ const OWNED_DIR_NAMES = [ACTIVE_PLUGIN_ID, STATE_SEGMENT];
54
75
  const STATE_KNOWN_FILES = [
55
76
  'gentle-sidebar-mode.json',
56
77
  'gentle-moshi.json',
@@ -80,24 +101,73 @@ function dirHasKnownFiles(dir) {
80
101
  return false;
81
102
  }
82
103
 
104
+ // Two spellings name the same directory when their canonical forms match.
105
+ // realpath resolves symlinks but throws for a path that does not exist yet, so
106
+ // walk up to the deepest existing ancestor and re-append the missing tail: that
107
+ // keeps a symlinked or relative spelling of the derived dir from being rejected
108
+ // as a different directory (S1c/T12 compares paths, never raw strings).
109
+ function canonicalStateDir(dir) {
110
+ const absolute = path.resolve(dir);
111
+ const tail = [];
112
+ let current = absolute;
113
+ for (;;) {
114
+ try {
115
+ const real = fs.realpathSync(current);
116
+ return tail.length ? path.join(real, ...tail) : real;
117
+ } catch {
118
+ const parent = path.dirname(current);
119
+ if (parent === current) return absolute;
120
+ // Prepended so the missing tail is re-appended in its original order.
121
+ tail.unshift(path.basename(current));
122
+ current = parent;
123
+ }
124
+ }
125
+ }
126
+
127
+ // The active-id dir: the injected one only when it IS the directory this package
128
+ // derives for that name under the resolved state home, else the same sibling of
129
+ // the stored dir derived from the state home (the segment is the only difference,
130
+ // so the parent of the stored dir is the plugins dir). S1c: an injected path with
131
+ // any other basename (a third plugin id, a stale or dev id) — or an owned basename
132
+ // under another root, which is exactly the case that splits this writer from the
133
+ // daemon — is ignored, not selected.
134
+ function activeStateDir(env) {
135
+ const pluginsDir = path.dirname(storedStateDir(env));
136
+ const injected = env.HERDR_PLUGIN_STATE_DIR;
137
+ if (typeof injected === 'string' && injected.length > 0) {
138
+ const name = path.basename(injected);
139
+ if (
140
+ OWNED_DIR_NAMES.includes(name) &&
141
+ canonicalStateDir(injected) === canonicalStateDir(path.join(pluginsDir, name))
142
+ ) {
143
+ return injected;
144
+ }
145
+ }
146
+ return path.join(pluginsDir, ACTIVE_PLUGIN_ID);
147
+ }
148
+
83
149
  // The explicit-but-empty (or non-string) override keeps using the stored
84
150
  // default, so a trace log written before the injected dir was introduced is
85
- // still the same file after an upgrade.
151
+ // still the same file after an upgrade. The stored dir wins over the active-id
152
+ // (injected) one whenever it holds a known file: the daemon writes its pidfile
153
+ // into the dir it resolves, so one stray known file there would make the split
154
+ // self-perpetuating. The active-id dir wins only when the stored dir holds no
155
+ // known file and it does; the stored canonical dir is the final fallback, so a
156
+ // fresh install resolves the same dir with or without the injected variable.
86
157
  function resolveStateDir(env) {
87
158
  const explicit = env.GENTLE_STATUS_STATE_DIR;
88
159
  if (typeof explicit === 'string' && explicit.length > 0) return explicit;
89
160
  const stored = storedStateDir(env);
90
161
  if (explicit !== undefined && explicit !== null) return stored;
91
- const injected = env.HERDR_PLUGIN_STATE_DIR;
92
- if (typeof injected !== 'string' || injected.length === 0) return stored;
93
- if (injected === stored) return injected;
162
+ const active = activeStateDir(env);
163
+ if (active === stored) return stored;
94
164
  try {
95
- if (dirHasKnownFiles(injected)) return injected;
96
165
  if (dirHasKnownFiles(stored)) return stored;
166
+ if (dirHasKnownFiles(active)) return active;
97
167
  } catch {
98
- // Fall through to the injected dir on unexpected failure.
168
+ // Fall through to the stored canonical dir on unexpected failure.
99
169
  }
100
- return injected;
170
+ return stored;
101
171
  }
102
172
 
103
173
  const LOG_NAME = 'perf-trace.jsonl';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herdr-gentle-shell",
3
- "version": "1.5.2",
3
+ "version": "1.6.1",
4
4
  "description": "Pi package for Herdr sidebar states: the Pi extension sidecar that publishes session facts as Herdr pane-metadata tokens, the optional Moshi notification channel, and the Pi-side helpers the Herdr Gentle Shell plugin drives.",
5
5
  "keywords": [
6
6
  "pi-package",