pi-odd-worktree 3.12.4 → 3.14.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.
@@ -1,66 +1,82 @@
1
1
  'use strict';
2
- // Automatic session naming from the ODD document being written
3
- // (odd/tasks/session-auto-name.md, D2-D7).
2
+ // Automatic session naming from the ODD document being written.
4
3
  //
5
- // Pure derivation, no I/O: the caller passes what a tool call touched, a
6
- // reader for the touched document when it has one, and whether that call was
7
- // a write, and gets back either the label to write or `null` for "leave the
8
- // session alone".
4
+ // Pure derivation, no I/O: the caller passes what a tool call touched, whether that
5
+ // call was a write, and the names the session already wrote, and gets back either the
6
+ // label to write or `null` for "leave the session alone".
9
7
  //
10
- // The channel is the session NAME (`pi.setSessionName`), because Pi 1.3.0
11
- // exposes no subject/alias write (D7): the session record carries a single
12
- // `name`. The never-clobber guarantee (P3) therefore cannot come from a
13
- // channel choice, so it comes from PATTERN: the plugin may write only an
14
- // empty name or a name it can account for as its own (see
15
- // `isPluginSessionName`). Anything else was typed by a human and is
16
- // untouchable. The admitted consequence (D7) is that a human who names a
17
- // session exactly like a label the plugin would write owns a name the plugin
18
- // may later update.
8
+ // THE NAME IS THE ODD'S OWN NAME (D2). Writing `odd/tasks/prompt-card-fix.md` names
9
+ // the session `Prompt card fix`: the separators a feature name uses (`-`, `_`, and
10
+ // the `/` of a nested feature) become spaces, the first letter is capitalized, the
11
+ // rest of the name is left exactly as the document named it, and the result is cut
12
+ // at a word boundary when it is too long to read at a glance. Prose INSIDE the
13
+ // document never names the session: a document's own heading is its author's
14
+ // sentence, not the ODD's identity, and reading it made the name depend on a file
15
+ // read that a not-yet-created document does not have.
19
16
  //
20
- // The label head is the document's own first level-1 heading (D2: the honest
21
- // source for what the session is about), and the filename slug is only the
22
- // fallback for a document with no readable heading.
17
+ // EVERY WRITE RE-NAMES (D3): the label is derived on each `write`/`edit` that lands on
18
+ // an `odd/tasks/*.md` document, so a session that moves on to another ODD is renamed
19
+ // to that ODD. Reading is context gathering and never renames (D6).
20
+ //
21
+ // NEVER CLOBBER A HUMAN (D4). The channel is the session NAME (`setSessionName`); a
22
+ // name the plugin cannot account for was typed by a person and is untouchable. The
23
+ // plugin may write only an empty name, or one it can PROVE it produced:
24
+ // (a) the label this session already applied (in-memory, per session);
25
+ // (b) the label of the document being written right now;
26
+ // (c) the label of any ODD this session already wrote — the durable record of
27
+ // touches (`odd-worktree.odd-touch`) hands those names in, which is what makes
28
+ // the proof survive a resume (D5) without storing a second thing; or
29
+ // (d) a name an earlier version of this plugin wrote: the plain dashed slug
30
+ // (`prompt-card-fix`) or the same slug with a branch suffix
31
+ // (`prompt-card-fix @ feat/prompt-card-fix`).
32
+ // Anything else is a human's name. The admitted consequence is that a human who names
33
+ // a session exactly like an ODD they themselves wrote stops owning that name.
34
+ //
35
+ // There is no branch in the name (the user's decision): two forks of the same ODD
36
+ // share a label, and the session file, not the name, is what tells them apart.
23
37
  //
24
38
  // Input rels are the canonical `odd/<rel>` names the worktree capture already
25
- // produces, never raw filesystem paths: mapping a path to a document is path
26
- // logic that lives in one place already.
39
+ // produces, never raw filesystem paths: mapping a path to a document is path logic
40
+ // that lives in one place already.
27
41
 
28
- // Document shape that names a session: `odd/tasks/<feature>.md`, where the
29
- // feature may be nested (`odd/tasks/perf/plan.md`).
42
+ // Document shape that names a session: `odd/tasks/<feature>.md`, where the feature
43
+ // may be nested (`odd/tasks/perf/plan.md`).
30
44
  const ODD_TASKS_PREFIX = 'odd/tasks/';
31
45
 
32
- // Separator between the label head and the branch discriminator (D4). The
33
- // spaces make it a shape a human hand-typing a name rarely produces, and
34
- // they are what distinguishes the label from a human `fix@home`.
35
- const BRANCH_SEPARATOR = ' @ ';
36
-
37
- // A heading-sized label beyond this loses the rest of the words, cut at the
38
- // last word boundary so the name stays readable at a glance.
46
+ // A label beyond this loses the rest of the words, cut at the last word boundary so
47
+ // the name stays readable at a glance.
39
48
  const LABEL_MAX_CHARS = 48;
40
49
 
41
- // gentle-pi's ODD phase tool (L3). Its result says WHICH phase the session
42
- // moved to, never WHICH feature it is about, so the phase trigger cannot
43
- // derive anything: it re-applies what the session last derived from a write.
44
- // It is observable only as a `tool_result`, not a host event.
50
+ // The separator the branch suffix of an EARLIER version used. It is never written any
51
+ // more; it is recognized so a resumed session renamed by that version is still
52
+ // adoptable (D4d).
53
+ const LEGACY_BRANCH_SEPARATOR = ' @ ';
54
+
55
+ // gentle-pi's ODD phase tool. Its result says WHICH phase the session moved to, never
56
+ // WHICH feature it is about, so the phase trigger cannot derive anything: it
57
+ // re-applies what the session last derived from a write. It is observable only as a
58
+ // `tool_result`, not a host event.
45
59
  const ODD_PHASE_TOOL_NAME = 'gentle_odd_phase';
46
60
 
47
- // A fallback feature is one or more `/`-separated segments using the
48
- // characters a document filename can carry, without whitespace. A branch is
49
- // any whitespace-free token — permissive on purpose, because a branch with an
50
- // unusual-but-legal character (say `#1`) must still be recognized as OUR
51
- // label on the next event, or a resumed session would freeze on it forever.
61
+ // A feature is one or more `/`-separated segments using the characters a document
62
+ // filename can carry, without whitespace. A branch is any whitespace-free token —
63
+ // permissive on purpose, because a branch of an earlier version's suffix may carry an
64
+ // unusual-but-legal character and must still be recognized as OUR label.
52
65
  const FEATURE_SEGMENT = /^[A-Za-z0-9._-]+$/;
53
66
  const BRANCH_TOKEN = /^\S+$/;
54
67
 
55
- // The tools whose call WRITES a document. Reading is context gathering: it
56
- // would make the name jump to whatever was opened last (P1), so `read` is
57
- // deliberately absent.
68
+ // The separators a feature name uses as word boundaries. `/` is the nested-feature
69
+ // separator and reads as a word break like the others.
70
+ const WORD_SEPARATORS = /[/_-]+/g;
71
+
72
+ // The tools whose call WRITES a document. Reading is context gathering: it would make
73
+ // the name jump to whatever was opened last (D6), so `read` is deliberately absent.
58
74
  const WRITE_TOOL_NAMES = new Set(['write', 'edit']);
59
75
 
60
- // The last ODD label each session applied, keyed by session id. In-module so
61
- // the phase trigger stays testable without the extension, and bounded so a
62
- // long-lived process that sees many sessions cannot grow without limit; only
63
- // the most recent sessions can still be alive and resumed.
76
+ // The last label each session applied, keyed by session id. In-module so the phase
77
+ // trigger stays testable without the extension, and bounded so a long-lived process
78
+ // that sees many sessions cannot grow without limit; only the most recent sessions
79
+ // can still be alive and resumed.
64
80
  const SESSION_MEMORY_LIMIT = 100;
65
81
  const lastLabelBySession = new Map();
66
82
 
@@ -68,13 +84,13 @@ function sessionKey(sessionId) {
68
84
  return typeof sessionId === 'string' && sessionId.length > 0 ? sessionId : null;
69
85
  }
70
86
 
71
- function rememberLabel(sessionId, entry) {
87
+ function rememberLabel(sessionId, label) {
72
88
  const key = sessionKey(sessionId);
73
89
  if (key === null) return;
74
- // Re-inserting moves the session to the young end of the insertion order,
75
- // so eviction always drops the least recently written session.
90
+ // Re-inserting moves the session to the young end of the insertion order, so
91
+ // eviction always drops the least recently written session.
76
92
  lastLabelBySession.delete(key);
77
- lastLabelBySession.set(key, entry);
93
+ lastLabelBySession.set(key, label);
78
94
  while (lastLabelBySession.size > SESSION_MEMORY_LIMIT) {
79
95
  const oldest = lastLabelBySession.keys().next().value;
80
96
  lastLabelBySession.delete(oldest);
@@ -91,9 +107,9 @@ function isWriteToolName(name) {
91
107
  return typeof name === 'string' && WRITE_TOOL_NAMES.has(name);
92
108
  }
93
109
 
94
- // `<feature>` for an `odd/tasks/<feature>.md` rel, else null. Rejects empty
95
- // segments, nested `.`/`..`, and any name carrying whitespace or characters a
96
- // feature document cannot have.
110
+ // `<feature>` for an `odd/tasks/<feature>.md` rel, else null. Rejects empty segments,
111
+ // nested `.`/`..`, and any name carrying whitespace or characters a feature document
112
+ // cannot have.
97
113
  function featureFromOddRel(rel) {
98
114
  if (typeof rel !== 'string' || rel.length === 0) return null;
99
115
  if (!rel.startsWith(ODD_TASKS_PREFIX)) return null;
@@ -108,8 +124,8 @@ function featureFromOddRel(rel) {
108
124
  return feature;
109
125
  }
110
126
 
111
- // The first `odd/tasks/<feature>.md` document of the call, or null. The
112
- // first one wins because a multi-document write has no natural order.
127
+ // The first `odd/tasks/<feature>.md` document of the call, or null. The first one wins
128
+ // because a multi-document write has no natural order.
113
129
  function firstTaskDocument(rels) {
114
130
  if (!Array.isArray(rels)) return null;
115
131
  for (const rel of rels) {
@@ -119,9 +135,9 @@ function firstTaskDocument(rels) {
119
135
  return null;
120
136
  }
121
137
 
122
- // Cut to `max` characters at the last word boundary inside the cut, so a
123
- // truncated label ends with a whole word. A single word longer than `max`
124
- // has no boundary and is cut hard; anything short stays untouched.
138
+ // Cut to `max` characters at the last word boundary inside the cut, so a truncated
139
+ // label ends with a whole word. A single word longer than `max` has no boundary and is
140
+ // cut hard; anything short stays untouched.
125
141
  function truncateLabel(text, max) {
126
142
  if (text.length <= max) return text;
127
143
  const slice = text.slice(0, max);
@@ -129,54 +145,30 @@ function truncateLabel(text, max) {
129
145
  return lastSpace > 0 ? slice.slice(0, lastSpace) : slice;
130
146
  }
131
147
 
132
- // The document's first level-1 ATX heading (`# ...`), trimmed with inner
133
- // whitespace collapsed and truncated for the label, or null when the text
134
- // carries none. A deeper heading (`## ...`) is a section title, not the
135
- // document's own heading, and never matches.
136
- function headingFromText(text) {
137
- if (typeof text !== 'string' || text.length === 0) return null;
138
- for (const rawLine of text.split(/\r?\n/)) {
139
- const line = rawLine.trim();
140
- // ATX level-1 needs whitespace after the `#`; `##` and deeper are
141
- // section titles, and `#hashtag` is prose, not a heading.
142
- if (!/^#[ \t]/.test(line)) continue;
143
- const body = line.slice(1).trim();
144
- if (body.length === 0) continue;
145
- return truncateLabel(body.replace(/\s+/g, ' '), LABEL_MAX_CHARS);
146
- }
147
- return null;
148
- }
149
-
150
- // The label head for a document: its heading when there is one, else the
151
- // filename slug. Deterministic for the same document, which is what keeps
152
- // repeated events idempotent.
153
- function labelHeadForDocument(feature, text) {
154
- const heading = headingFromText(text);
155
- return heading !== null ? heading : feature;
148
+ // The session label for an ODD feature name (D2): separators become spaces, the run
149
+ // of spaces collapses, the first letter is capitalized and the rest is left exactly
150
+ // as the document named it. `perf/plan` -> `Perf plan`, `prompt-card-fix` ->
151
+ // `Prompt card fix`. An empty name yields no label; nothing is invented.
152
+ function labelFromFeature(feature) {
153
+ if (typeof feature !== 'string' || feature.length === 0) return null;
154
+ const words = feature.replace(WORD_SEPARATORS, ' ').replace(/\s+/g, ' ').trim();
155
+ if (words.length === 0) return null;
156
+ const sentence = words.charAt(0).toUpperCase() + words.slice(1);
157
+ return truncateLabel(sentence, LABEL_MAX_CHARS);
156
158
  }
157
159
 
158
- // Read the touched document through the caller's reader. Any failure — a
159
- // reader that throws, a missing file, a non-string result — is "no heading"
160
- // and falls back to the slug, never an error the naming path must handle.
161
- function readDocumentText(readDocument, rel) {
162
- if (typeof readDocument !== 'function') return null;
163
- try {
164
- const text = readDocument(rel);
165
- return typeof text === 'string' ? text : null;
166
- } catch {
167
- return null;
168
- }
169
- }
170
-
171
- // D4: the branch suffix is what keeps two concurrent forks of the same
172
- // feature apart, since the worktree branch is already unique. A branch the
173
- // caller cannot supply (an odd registry entry without one) degrades to the
174
- // bare label head, which is still a label the plugin owns.
175
- function sessionNameForFeature(feature, branch) {
176
- if (typeof branch === 'string' && BRANCH_TOKEN.test(branch)) {
177
- return `${feature}${BRANCH_SEPARATOR}${branch}`;
160
+ // The labels of the ODDs this session already wrote, as handed in from the durable
161
+ // touch record (`oddSession.touched()` names). Malformed and unusable entries are
162
+ // skipped: a durable record that cannot be read leaves the ownership test with less
163
+ // evidence, never with a wrong answer.
164
+ function sessionLabelsFrom(touchedNames) {
165
+ if (!Array.isArray(touchedNames)) return [];
166
+ const out = [];
167
+ for (const name of touchedNames) {
168
+ const label = labelFromFeature(name);
169
+ if (label !== null && !out.includes(label)) out.push(label);
178
170
  }
179
- return feature;
171
+ return out;
180
172
  }
181
173
 
182
174
  function isFeatureName(name) {
@@ -185,108 +177,100 @@ function isFeatureName(name) {
185
177
  return segments.every((segment) => segment !== '.' && segment !== '..' && FEATURE_SEGMENT.test(segment));
186
178
  }
187
179
 
188
- // The ownership test (D7), widened for heading labels: a name counts as the
189
- // plugin's own when ANY of these holds.
190
- // (a) it is the label this session already applied (the memory below),
191
- // which is what lets the phase trigger reuse it;
192
- // (b) it ends with ` @ <branch>` for THIS worktree's branch — the property
193
- // that survives a resume without in-memory state, since the branch
194
- // suffix is applied on every write;
195
- // (c) it is the plain feature slug from the filename, i.e. what earlier
196
- // versions wrote before heading labels existed;
197
- // (d) it is the document's current heading.
198
- // Called with no context it keeps the original contract: exactly the two
199
- // shapes earlier versions wrote (`<feature>` and `<feature> @ <branch>`).
180
+ // The ownership test (D4). A name counts as the plugin's own when ANY of these holds:
181
+ // (a) it is the label this session already applied — what lets the phase trigger
182
+ // reuse it;
183
+ // (b) it is the label of the document being written;
184
+ // (c) it is the label of an ODD this session already wrote (the durable record);
185
+ // (d) an earlier version wrote it: the plain feature slug, or `<slug> @ <branch>`.
186
+ // Anything else was typed by a human. Called with no context it answers exactly what
187
+ // earlier versions of this test answered for those legacy shapes.
200
188
  function isPluginSessionName(name, context) {
201
189
  if (typeof name !== 'string' || name.length === 0) return false;
202
- const { branch, feature, documentLabel, appliedLabel } = context || {};
190
+ const { feature, appliedLabel, sessionLabels } = context || {};
203
191
  if (typeof appliedLabel === 'string' && appliedLabel.length > 0 && name === appliedLabel) return true;
204
- if (typeof documentLabel === 'string' && documentLabel.length > 0 && name === documentLabel) return true;
205
- const at = name.indexOf(BRANCH_SEPARATOR);
206
- if (at === -1) {
207
- if (typeof feature === 'string' && feature.length > 0 && name === feature) return true;
208
- return isFeatureName(name);
209
- }
192
+ if (typeof feature === 'string' && feature.length > 0 && name === labelFromFeature(feature)) return true;
193
+ if (Array.isArray(sessionLabels) && sessionLabels.includes(name)) return true;
194
+ const at = name.indexOf(LEGACY_BRANCH_SEPARATOR);
195
+ if (at === -1) return isFeatureName(name);
210
196
  const head = name.slice(0, at);
211
- const tail = name.slice(at + BRANCH_SEPARATOR.length);
197
+ const tail = name.slice(at + LEGACY_BRANCH_SEPARATOR.length);
212
198
  if (head.length === 0 || !BRANCH_TOKEN.test(tail)) return false;
213
- if (typeof branch === 'string' && branch.length > 0 && tail === branch) return true;
214
199
  return isFeatureName(head);
215
200
  }
216
201
 
217
- // May the plugin write over `name`? An unnamed session (empty, or no name
218
- // entry at all — `getSessionName()` returns undefined) is adoptable; every
219
- // other name must be the plugin's own.
202
+ // May the plugin write over `name`? An unnamed session (empty, or no name entry at
203
+ // all — `getSessionName()` returns undefined) is adoptable; every other name must be
204
+ // the plugin's own.
220
205
  function canAdoptSessionName(name, context) {
221
206
  if (name === undefined || name === null) return true;
222
207
  if (typeof name !== 'string') return false;
223
208
  return name.length === 0 || isPluginSessionName(name, context);
224
209
  }
225
210
 
226
- // The label for a tool call that touched `rels`, or null when the call is
227
- // not a WRITE to an `odd/tasks/<feature>.md` document. No ownership is
228
- // decided here; `planSessionRename` owns that.
229
- function autoNameForToolCall({ rels, isWrite, branch, readDocument } = {}) {
211
+ // The label for a tool call that touched `rels`, or null when the call is not a WRITE
212
+ // to an `odd/tasks/<feature>.md` document. No ownership is decided here;
213
+ // `planSessionRename` owns that.
214
+ function autoNameForToolCall({ rels, isWrite } = {}) {
230
215
  if (isWrite !== true) return null;
231
216
  const match = firstTaskDocument(rels);
232
217
  if (match === null) return null;
233
- const head = labelHeadForDocument(match.feature, readDocumentText(readDocument, match.rel));
234
- return sessionNameForFeature(head, branch);
218
+ return labelFromFeature(match.feature);
235
219
  }
236
220
 
237
- // The single decision the write wiring needs. Returns the name to write, or
238
- // null for "touch nothing", which covers three cases: the call did not write
239
- // an ODD task document, the current name was chosen by a human, and the
240
- // derived label is already the current name — the last one is what makes
241
- // running this on every pipeline event idempotent instead of a stream of host
242
- // writes. The derived label is remembered per session whether or not it was
243
- // written, so a later phase transition can re-apply it.
244
- function planSessionRename({ rels, isWrite, branch, currentName, sessionId, readDocument } = {}) {
221
+ // The single decision the write wiring needs. Returns the name to write, or null for
222
+ // "touch nothing", which covers three cases: the call did not write an ODD task
223
+ // document, the current name was chosen by a human, and the derived label is already
224
+ // the current name — the last one is what makes running this on every pipeline event
225
+ // idempotent instead of a stream of host writes. The derived label is remembered per
226
+ // session whether or not it was written, so a later phase transition can re-apply it.
227
+ function planSessionRename({ rels, isWrite, currentName, sessionId, touchedNames } = {}) {
245
228
  if (isWrite !== true) return null;
246
229
  const match = firstTaskDocument(rels);
247
230
  if (match === null) return null;
248
- const head = labelHeadForDocument(match.feature, readDocumentText(readDocument, match.rel));
249
- const label = sessionNameForFeature(head, branch);
231
+ const label = labelFromFeature(match.feature);
232
+ if (label === null) return null;
250
233
  const previous = rememberedLabel(sessionId);
251
234
  const adoptable = canAdoptSessionName(currentName, {
252
- branch,
253
235
  feature: match.feature,
254
- documentLabel: head,
255
- appliedLabel: previous === null ? undefined : previous.label,
236
+ appliedLabel: previous === null ? undefined : previous,
237
+ sessionLabels: sessionLabelsFrom(touchedNames),
256
238
  });
257
- rememberLabel(sessionId, { label, head, branch });
239
+ rememberLabel(sessionId, label);
258
240
  if (!adoptable || label === currentName) return null;
259
241
  return label;
260
242
  }
261
243
 
262
- // The phase trigger: an ODD phase transition with no feature of its own
263
- // re-applies the label this session last derived from a write. Returns null
264
- // for "touch nothing" when the session never wrote an ODD document, when the
265
- // current name is a human's, or when the label is already applied.
266
- function planPhaseSessionRename({ sessionId, branch, currentName } = {}) {
244
+ // The phase trigger: an ODD phase transition with no feature of its own re-applies the
245
+ // label this session last derived from a write. After a resume there is no in-memory
246
+ // memory, so the newest ODD of the durable touch record stands in — it is the same
247
+ // fact, read from where it survives. Returns null for "touch nothing" when the session
248
+ // never wrote an ODD document, when the current name is a human's, or when the label
249
+ // is already applied.
250
+ function planPhaseSessionRename({ sessionId, currentName, touchedNames } = {}) {
251
+ const sessionLabels = sessionLabelsFrom(touchedNames);
267
252
  const previous = rememberedLabel(sessionId);
268
- if (previous === null) return null;
269
- if (!canAdoptSessionName(currentName, { branch, appliedLabel: previous.label })) return null;
270
- const effectiveBranch = typeof branch === 'string' && branch.length > 0 ? branch : previous.branch;
271
- const label = sessionNameForFeature(previous.head, effectiveBranch);
253
+ const label = previous !== null ? previous : sessionLabels.length > 0 ? sessionLabels[0] : null;
254
+ if (label === null) return null;
255
+ if (!canAdoptSessionName(currentName, { appliedLabel: previous === null ? undefined : previous, sessionLabels })) {
256
+ return null;
257
+ }
272
258
  if (label === currentName) return null;
273
- rememberLabel(sessionId, { label, head: previous.head, branch: effectiveBranch });
259
+ rememberLabel(sessionId, label);
274
260
  return label;
275
261
  }
276
262
 
277
263
  module.exports = {
278
264
  ODD_TASKS_PREFIX,
279
- BRANCH_SEPARATOR,
280
265
  LABEL_MAX_CHARS,
266
+ LEGACY_BRANCH_SEPARATOR,
281
267
  ODD_PHASE_TOOL_NAME,
282
268
  autoNameForToolCall,
283
269
  featureFromOddRel,
284
- headingFromText,
285
270
  isPluginSessionName,
286
271
  canAdoptSessionName,
287
272
  isWriteToolName,
288
- labelHeadForDocument,
273
+ labelFromFeature,
289
274
  planSessionRename,
290
275
  planPhaseSessionRename,
291
- sessionNameForFeature,
292
276
  };