@iiiokojiadbi/shift 0.33.0 → 0.34.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.
@@ -39,7 +39,7 @@ export const NOTE_KINDS = {
39
39
  export type NoteKind = keyof typeof NOTE_KINDS
40
40
 
41
41
  export const OPENED = (name: string, line: string, track: string) =>
42
- `Opened ${TASKS}/${name}/ with task.md and track.md, and its line in ${TASK_LIST}:\n${line}\n${track === '' ? '' : `Its items, each changed with ${TRACK_TOOL} by its id:\n${track}`}Its decisions, dead ends and owner decisions say "none" until there are some; add items as you go with ${TRACK_TOOL}.`
42
+ `Opened ${TASKS}/${name}/ with ${NAMES.task} and ${NAMES.track}, and its line in ${TASK_LIST}:\n${line}\n${track === '' ? '' : `Its items, each changed with ${TRACK_TOOL} by its id:\n${track}`}Its decisions, dead ends and owner decisions say "none" until there are some; add items as you go with ${TRACK_TOOL}.`
43
43
 
44
44
  export const ARCHIVED = (name: string) =>
45
45
  `Archived to ${ARCHIVE}/${name}/, its line is in ${INDEX}, and ${TASK_LIST} no longer lists it: links to it now point into the archive. Lift to the board any of its decisions that still bind beyond it.`
@@ -212,9 +212,13 @@ export function waitContext(letter: string, back: HandedBack): string {
212
212
  return shiftMessage("You shifted and waited for the owner; the owner's message comes with this one.", letter, back, [GUIDE_KNOWN])
213
213
  }
214
214
 
215
- export function resumePrompt(letter: string, back: HandedBack): string {
215
+ export function resumePrompt(letter: string, back: HandedBack, outcome: string | null = null): string {
216
216
  return shiftMessage(
217
- 'You pick up the work from the last shift: this is a new session, you have no history of the previous one, only the records.',
217
+ `You pick up the work from the last shift: this is a new session, you have no history of the previous one, only the records.${
218
+ outcome === null
219
+ ? ''
220
+ : ` That shift did not finish — "${outcome}": its letter was written when it was accepted, the records below are as they are now; where they differ, the records are the later state.`
221
+ }`,
218
222
  letter,
219
223
  back,
220
224
  [
@@ -251,6 +255,16 @@ export const EXCLUDED = (file: string) =>
251
255
  export const SHIFT_TOO_EARLY = (why: string) =>
252
256
  `Nothing to shift yet: ${why} Nothing was written. Keep working with the records as they are, and shift once the history has grown — after the first hint.`
253
257
 
258
+ // A reason the harness gives, in the mod's words: it reaches the model, which reads only "shift" and "let go". A word
259
+ // inside a path or a file's name is left as it is, so the path still names the file.
260
+ const OUTSIDE_NAME = (word: string) => new RegExp(`(?<![\\w./-])(?:${word})(?![\\w/-]|\\.\\w)`, 'gi')
261
+ export function ourWords(why: string): string {
262
+ return why
263
+ .replace(OUTSIDE_NAME('compaction|summarization|compression'), 'let-go')
264
+ .replace(OUTSIDE_NAME('(?:compact|summari[sz]e|compress)(?:s|ed|ing)?'), 'let go')
265
+ .replace(OUTSIDE_NAME('summary'), 'digest')
266
+ }
267
+
254
268
  // A shift accepted and then not made: the agent was told it was accepted, so it is told it was not.
255
269
  export const NOT_MADE_NOTE = (name: string, why: string) =>
256
270
  `<${MOD} note="from the mod: the shift was not made">
@@ -260,7 +274,7 @@ Shift ${name} was not made — ${why}. Nothing was let go: your history is whole
260
274
  // A shift let go and its message not built: the agent has lost its history and got nothing back.
261
275
  export const UNSETTLED_NOTE = (name: string, why: string, dir: string) =>
262
276
  `<${MOD} note="from the mod: the history was let go, the records were not handed back">
263
- Shift ${name}: the history was let go, but the mod could not hand your records back — ${why}. Read ${LETTER} (a copy is in ${dir}/${NAMES.letter}), then ${BOARD} and ${TASK_LIST}, and continue from "${NEXT}".
277
+ Shift ${name}: the history was let go, but the mod could not hand your records back — ${why}. Read the letter of this shift, ${dir}/${NAMES.letter} — the one it accepted, whatever ${LETTER} holds now — then ${BOARD} and ${TASK_LIST}, and continue from "${NEXT}".
264
278
  </${MOD}>`
265
279
 
266
280
  // What the owner's row names when a failure's note went with their message.
@@ -20,7 +20,8 @@ export const UNSETTLED = (name: string, why: string) =>
20
20
 
21
21
  export const DELIVERED = (files: readonly string[], dir: string) => `went with your message: ${files.join(', ')} — ${dir}/${NAMES.letter}`
22
22
 
23
- export const NOT_CONTINUED = (why: string) => `the next turn did not start after the shift — ${why}; send any message to go on`
23
+ export const NOT_CONTINUED = (why: string, carried = 'the letter') =>
24
+ `the next turn did not start after the shift — ${why}; send any message to go on, ${carried} goes with it`
24
25
 
25
26
  // What /shift-tasks shows the owner: every open task, and under one in progress its items not closed yet. The harness
26
27
  // puts the plugin's name before the first line only, so a heading takes it and every task starts at the same column.
@@ -13,6 +13,7 @@ import {
13
13
  LETTER,
14
14
  MENTIONS_TOOL,
15
15
  NAME_RULE,
16
+ NAMES,
16
17
  OPEN_TOOL,
17
18
  OUTCOMES,
18
19
  OUTLINE_TOOL,
@@ -26,7 +27,7 @@ import {
26
27
  } from '../layout'
27
28
  import { quote } from '../markdown'
28
29
 
29
- export const TOOL_DESCRIPTION = `Make a shift: the stretch's history is let go, and you continue from your letter to yourself (after: continue) or wait for the owner (after: wait). Before the call the board, the tasks and the letter must be ready — how is in ${GUIDE_TOOL}, read once per project. After the call, end the turn: one line with continue; with wait, your whole answer to the owner — it is all they read.`
30
+ export const TOOL_DESCRIPTION = `Make a shift: the stretch's history is let go, and you continue from your letter to yourself (after: continue) or wait for the owner (after: wait). Before the call the board, the tasks and the letter must be ready — how is in ${GUIDE_TOOL}, read once per project. After the call, end the turn: one line with continue; with wait, your whole answer to the owner — it is all they read. Only the main agent shifts: a subagent's call is refused.`
30
31
 
31
32
  export const GUIDE_DESCRIPTION =
32
33
  'How to shift: the steps, the letter, when the mod refuses, the strict structure of about.md, then the rules of the board, the tasks, the archive and the other records a shift checks. Read it once, before your first shift in a project; after that only when a refusal sends you to it — the steps do not change between shifts.'
@@ -44,7 +45,7 @@ export const SETUP_SCHEMA = { type: 'object', properties: {} }
44
45
 
45
46
  export const HISTORY_DESCRIPTION = `Past shifts in brief, oldest first: time, outcome, description, what the stretch did, dropped and archived, and for the last one what is open. count — how many of the latest (default ${HISTORY_DEFAULT}).`
46
47
 
47
- export const OPEN_DESCRIPTION = `Open a task instead of creating its files by hand: writes ${TASKS}/<name>/task.md with its sections, track.md with the first items, and the task's line with its links in ${TASK_LIST}, all checked first — a refusal writes nothing. Decisions, dead ends and owner decisions start as "none".`
48
+ export const OPEN_DESCRIPTION = `Open a task instead of creating its files by hand: writes ${TASKS}/<name>/${NAMES.task} with its sections, ${NAMES.track} with the first items, and the task's line with its links in ${TASK_LIST}, all checked first — a refusal writes nothing. Decisions, dead ends and owner decisions start as "none".`
48
49
 
49
50
  const LINK_LINES = (what: string) => ({
50
51
  type: 'array',
@@ -70,7 +71,7 @@ export const OPEN_SCHEMA = {
70
71
  description: 'The first track items, each "item — what matters" or just "item"; all open.',
71
72
  },
72
73
  needs: LINK_LINES('open tasks this one cannot finish without'),
73
- after: LINK_LINES('archived tasks it stands on'),
74
+ after: LINK_LINES('archived tasks it stands on; an open one is "needs"'),
74
75
  continues: LINK_LINES('archived tasks it picks up'),
75
76
  },
76
77
  required: ['name', 'title', 'goal', 'done_when', 'about'],
@@ -78,7 +79,7 @@ export const OPEN_SCHEMA = {
78
79
 
79
80
  export const ARCHIVE_DESCRIPTION = `Archive a finished or dropped task: moves ${TASKS}/<name>/ to ${ARCHIVE}/<name>/ and adds its line to ${INDEX}. It also takes the task out of ${TASK_LIST}.`
80
81
 
81
- export const TRACK_DESCRIPTION = `Set a status instead of editing the records by hand. With id: the track item with that id, the number in its "#<id>". With item: a new item with that text, given the next id. Without either: the task's own status in ${TASK_LIST}. status — for an item ${quote(STATUSES)}; for a task ${quote(FOCUS)}. note — replaces what follows " — ": what matters, or the reason a task is deferred or waits (required then). Several items at once — when a stage closes one item and opens the next: items, a list of {id or item, status, note}, applied together or not at all; status beside items is then the task's own.`
82
+ export const TRACK_DESCRIPTION = `Set a status instead of editing the records by hand. With id: the track item with that id, the number in its "#<id>". With item: a new item with that text, given the next id; its text differs from every item's in the track, case aside. Without either: the task's own status in ${TASK_LIST}. status — for an item ${quote(STATUSES)}; for a task ${quote(FOCUS)}. note — replaces what follows " — ": what matters, or the reason a task is deferred or waits (required then). Several items at once — when a stage closes one item and opens the next: items, a list of {id or item, status, note}, applied together or not at all; status beside items is then the task's own.`
82
83
 
83
84
  export const TRACK_SCHEMA = {
84
85
  type: 'object',
package/core/types.ts CHANGED
@@ -126,4 +126,5 @@ export type PendingShift = {
126
126
  export type WaitNote = { context: string; dir: string; files: string[] }
127
127
 
128
128
  // What follows a let-go: the agent goes on from the prompt, or the note waits for the owner; the row tells the owner.
129
- export type Settled = { after: 'continue'; prompt: string; row: string } | { after: 'wait'; note: WaitNote; row: string }
129
+ // `note`, for a continue: the same letter as a wait note, kept for the owner's next message when the turn does not start.
130
+ export type Settled = { after: 'continue'; prompt: string; note: WaitNote; row: string } | { after: 'wait'; note: WaitNote; row: string }
package/index.ts CHANGED
@@ -2,7 +2,7 @@ import { resolve } from 'node:path'
2
2
  import type { CompactionEntry, CompactionResult, ExtensionAPI, ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-agent'
3
3
  import { estimateTokens, findCutPoint, SettingsManager } from '@earendil-works/pi-coding-agent'
4
4
  import type { TSchema } from 'typebox'
5
- import type { Courier, Gauge, GaugeKeeper, LetGoHarness, Looks, Loop, LoopState, Note, WaitNote } from './core/index'
5
+ import type { Courier, Gauge, GaugeKeeper, LetGoHarness, Looks, Loop, LoopState, Note, Project, WaitNote } from './core/index'
6
6
  import {
7
7
  addGrowth,
8
8
  afterTool,
@@ -12,6 +12,7 @@ import {
12
12
  beforeTool,
13
13
  contentChars,
14
14
  countGrowth,
15
+ dropWaiting,
15
16
  FRESH_GAUGE,
16
17
  FRESH_LOOKS,
17
18
  FRESH_LOOP,
@@ -24,12 +25,12 @@ import {
24
25
  resumeShift,
25
26
  SETTINGS,
26
27
  SHIFT_COMMAND,
27
- SHIFT_NOW,
28
28
  SHIFT_NOW_DESCRIPTION,
29
29
  SOURCES,
30
30
  sessionDoctrine,
31
31
  sessionFiles,
32
32
  shiftBase,
33
+ shiftNow,
33
34
  startSession,
34
35
  TASKS_COMMAND,
35
36
  TASKS_DESCRIPTION,
@@ -52,8 +53,8 @@ export default function shift(pi: ExtensionAPI): void {
52
53
  let ownerTyped = false
53
54
  // false when the project's settings turn the mod off; read at each session start.
54
55
  let enabled = true
55
- // The doctrine with the tools this project shows; read at each session start, built at the first run without one.
56
- let doctrine: string | null = null
56
+ // The documents' tocs and the map are refreshed at the first run of a session, before anything looks at them.
57
+ let refreshed = false
57
58
  // The records as last seen and the agent's tools running now; what changed before each tool began, by its call.
58
59
  let looks: Looks = FRESH_LOOKS
59
60
  const outside = new Map<string, Note[]>()
@@ -78,7 +79,7 @@ export default function shift(pi: ExtensionAPI): void {
78
79
  loop: loopOf(ctx),
79
80
  // pi reads the session's files anew before every run, so its copy is never older than them.
80
81
  loaded: async () => null,
81
- status: () => gaugeStatus(keeperOf(ctx)),
82
+ status: () => gaugeStatus(keeperOf(ctx, () => projectAt(ctx.cwd))),
82
83
  cannotLetGo: async () => cannotLetGo(ctx),
83
84
  })
84
85
  if ('deny' in done) throw new Error(done.deny)
@@ -98,7 +99,10 @@ export default function shift(pi: ExtensionAPI): void {
98
99
  handler: async (args, ctx) => {
99
100
  if (!enabled) return ctx.ui.notify(`${MOD} is off in this project: ${SETTINGS} has enabled = false.`, 'info')
100
101
  // Typed mid-run, it waits for the run to end, as Claude Code holds a command until the turn is over.
101
- pi.sendUserMessage(SHIFT_NOW(args.trim()), ctx.isIdle() ? undefined : { deliverAs: 'followUp' })
102
+ // The letter's clearing goes on the branch before the message that carries it, as `branchNote` reads them.
103
+ const now = await shiftNow(loopOf(ctx), args.trim())
104
+ await now.delivered()
105
+ pi.sendUserMessage(now.text, ctx.isIdle() ? undefined : { deliverAs: 'followUp' })
102
106
  },
103
107
  })
104
108
 
@@ -110,9 +114,14 @@ export default function shift(pi: ExtensionAPI): void {
110
114
  const resumed = await resumeShift(await projectAt(ctx.cwd))
111
115
  ctx.ui.notify(resumed.text, 'info')
112
116
  if (resumed.prompt === undefined) return
117
+ // The newest letter goes now: one waiting for the owner's message is not told again. Its clearing goes on the
118
+ // branch before the message, as `branchNote` reads them.
119
+ await dropWaiting(loopOf(ctx))
113
120
  const words = args.trim()
114
- pi.sendMessage({ customType: MOD, content: resumed.prompt, display: true }, { triggerTurn: words === '' })
115
- if (words !== '') pi.sendUserMessage(words)
121
+ // Typed mid-run, both wait for the run to end.
122
+ const busy = ctx.isIdle() ? {} : { deliverAs: 'followUp' as const }
123
+ pi.sendMessage({ customType: MOD, content: resumed.prompt, display: true }, { triggerTurn: words === '', ...busy })
124
+ if (words !== '') pi.sendUserMessage(words, ctx.isIdle() ? undefined : { deliverAs: 'followUp' })
116
125
  },
117
126
  })
118
127
 
@@ -121,42 +130,54 @@ export default function shift(pi: ExtensionAPI): void {
121
130
  pi.on('session_start', async (_event, ctx) => {
122
131
  const start = await startSession(await projectAt(ctx.cwd))
123
132
  enabled = start.enabled
124
- doctrine = start.doctrineBody
133
+ refreshed = false
125
134
  for (const row of start.rows) tell(ctx, row.text, row.level)
126
135
  const shown = start.tools.map(tool => tool.name)
127
136
  pi.setActiveTools([...pi.getActiveTools().filter(name => !OURS.has(name)), ...shown])
128
137
  if (!enabled) return
129
- const last = ctx.sessionManager
130
- .getBranch()
131
- .filter(entry => entry.type === 'custom' && entry.customType === WAIT_ENTRY)
132
- .at(-1)
133
- loop = { ...loop, note: last?.type === 'custom' ? ((last.data as { note: WaitNote | null } | undefined)?.note ?? null) : null }
138
+ loop = { ...loop, note: branchNote(ctx) }
134
139
  })
135
140
 
136
- // The owner's own input: only a message that starts a run takes the waiting letter with it.
141
+ // Another branch has its own wait note, or none: a letter of the branch left behind never goes with this one.
142
+ // Its history too: the gauge is counted anew from the branch.
143
+ pi.on('session_tree', async (_event, ctx) => {
144
+ if (!enabled) return
145
+ loop = { ...loop, note: branchNote(ctx) }
146
+ gauge = FRESH_GAUGE
147
+ })
148
+
149
+ // The owner's own input: only a message that starts a run takes the waiting letter with it. An extension's message
150
+ // comes after any owner input another extension took without a run, so it clears what that left.
137
151
  pi.on('input', async (event, _ctx) => {
138
- if (!enabled || event.source === 'extension') return
139
- if (event.streamingBehavior === undefined) ownerTyped = true
152
+ if (!enabled) return
153
+ if (event.source === 'extension') ownerTyped = false
154
+ else if (event.streamingBehavior === undefined) ownerTyped = true
140
155
  })
141
156
 
142
157
  // The doctrine every run; between turns a hint, and after a wait the letter, follow the owner's message.
143
158
  pi.on('before_agent_start', async (event, ctx) => {
144
159
  if (!enabled) return
145
- doctrine ??= sessionDoctrine((await projectAt(ctx.cwd)).settings).doctrineBody
146
- event.systemPromptOptions.sections[MOD] = doctrine
147
- // SHIFT.md, OWNER.md, GLOSSARY.md and TASKS.md go where pi puts AGENTS.md; the same paths are replaced, not added twice.
148
- const loaded = await sessionFiles(await projectAt(ctx.cwd))
160
+ const project = once(ctx)
161
+ const loading = project()
162
+ // The doctrine at the settings' places: a shift may have moved a record.
163
+ event.systemPromptOptions.sections[MOD] = sessionDoctrine((await loading).settings).doctrineBody
164
+ // A session's first run refreshes the tocs and the map before the documents' stamps are first looked at.
165
+ if (!refreshed) await sessionFiles(await loading)
166
+ refreshed = true
167
+ // Records changed between runs — by the owner's hand or another session — a hint, and after a wait the letter.
168
+ const owner = event.messageType === 'user' && ownerTyped
169
+ if (owner) ownerTyped = false
170
+ const told = await atPrompt(courierOf(ctx, project), { runStarts: true, owner })
171
+ if (told.notes.length > 0) await told.delivered()
172
+ // SHIFT.md, OWNER.md, GLOSSARY.md and TASKS.md go where pi puts AGENTS.md; the same paths are replaced, not added
173
+ // twice. Read after the notes: a toc a script left stale is written with its note, never silently before it.
174
+ const loaded = await sessionFiles(await loading, { refresh: false })
149
175
  const ours = new Set(loaded.map(file => file.path))
150
176
  event.systemPromptOptions.contextFiles = [
151
177
  ...event.systemPromptOptions.contextFiles.filter(file => !ours.has(file.path)),
152
178
  ...loaded.map(file => ({ path: file.path, content: file.text })),
153
179
  ]
154
- // Records changed between runs — by the owner's hand or another session — a hint, and after a wait the letter.
155
- const owner = event.messageType === 'user' && ownerTyped
156
- if (owner) ownerTyped = false
157
- const told = await atPrompt(courierOf(ctx), { runStarts: true, owner })
158
180
  if (told.notes.length === 0) return
159
- await told.delivered()
160
181
 
161
182
  return { message: { customType: MOD, content: told.notes.join('\n\n'), display: true } }
162
183
  })
@@ -165,27 +186,33 @@ export default function shift(pi: ExtensionAPI): void {
165
186
  pi.on('message_end', async (event, ctx) => {
166
187
  if (!enabled) return
167
188
  const source = growthSource(event.message)
168
- if (source !== null) await countGrowth(keeperOf(ctx), source, messageChars(event.message))
189
+ if (source !== null)
190
+ await countGrowth(
191
+ keeperOf(ctx, () => projectAt(ctx.cwd)),
192
+ source,
193
+ messageChars(event.message),
194
+ )
169
195
  })
170
196
 
171
197
  // Every note to the agent mid-run goes with a tool's result: what changed in the records around a tool of the agent,
172
198
  // the docs after a write, a hint. A nested tool's write gets only the docs.
173
199
  pi.on('tool_call', async (event, ctx) => {
174
200
  if (!enabled || event.parentToolCallId !== undefined) return
175
- outside.set(event.toolCallId, await beforeTool(courierOf(ctx)))
201
+ outside.set(event.toolCallId, await beforeTool(courierOf(ctx, once(ctx))))
176
202
  })
177
203
 
178
204
  pi.on('tool_result', async (event, ctx) => {
179
205
  if (!enabled) return
180
206
  const path = (event.toolName === 'edit' || event.toolName === 'write') && !event.isError ? event.input.path : undefined
181
207
  const written = typeof path === 'string' ? resolve(ctx.cwd, path) : undefined
208
+ const courier = courierOf(ctx, once(ctx))
182
209
  if (event.parentToolCallId !== undefined) {
183
- if (written !== undefined) await afterWrite(courierOf(ctx), written)
210
+ if (written !== undefined) await afterWrite(courier, written)
184
211
  return
185
212
  }
186
213
  const before = outside.get(event.toolCallId) ?? []
187
214
  outside.delete(event.toolCallId)
188
- const added = await afterTool(courierOf(ctx), before, { own: OURS.has(event.toolName), readOnly: READING.has(event.toolName), written })
215
+ const added = await afterTool(courier, before, { own: OURS.has(event.toolName), readOnly: READING.has(event.toolName), written })
189
216
  if (added.length === 0) return
190
217
 
191
218
  return {
@@ -194,6 +221,18 @@ export default function shift(pi: ExtensionAPI): void {
194
221
  }
195
222
  })
196
223
 
224
+ // A call blocked before it ran has no result: it ends here, so the tools after it still know what runs.
225
+ pi.on('tool_execution_end', async (event, ctx) => {
226
+ if (!enabled || !outside.has(event.toolCallId)) return
227
+ outside.delete(event.toolCallId)
228
+ await afterTool(courierOf(ctx), [], null)
229
+ })
230
+
231
+ // pi's own let-go at its threshold would go without the letter's Hold: an accepted shift lets go once the run settles.
232
+ pi.on('session_before_compact', async event => {
233
+ if (enabled && loop.pending !== null && event.reason === 'threshold') return { cancel: true }
234
+ })
235
+
197
236
  // The shift lets go once the run has settled: compacting aborts whatever runs, so never from inside the turn.
198
237
  pi.on('agent_settled', async (event, ctx) => {
199
238
  if (loop.pending === null) return
@@ -206,11 +245,11 @@ export default function shift(pi: ExtensionAPI): void {
206
245
  })
207
246
 
208
247
  // The notes to the agent over the extension's runtime: the looks at the records, the loop and the gauge.
209
- function courierOf(ctx: ExtensionContext): Courier {
248
+ function courierOf(ctx: ExtensionContext, project: () => Promise<Project> = once(ctx)): Courier {
210
249
  return {
211
250
  loop: loopOf(ctx),
212
- gauge: keeperOf(ctx),
213
- project: () => projectAt(ctx.cwd),
251
+ gauge: keeperOf(ctx, project),
252
+ project,
214
253
  looks: async () => looks,
215
254
  updateLooks: async change => {
216
255
  looks = change(looks)
@@ -256,7 +295,7 @@ export default function shift(pi: ExtensionAPI): void {
256
295
 
257
296
  // The gauge in the extension's runtime; the history and the base read from the session. pi compacts by itself once
258
297
  // the free room falls under `reserveTokens`.
259
- function keeperOf(ctx: ExtensionContext): GaugeKeeper {
298
+ function keeperOf(ctx: ExtensionContext, project: () => Promise<Project>): GaugeKeeper {
260
299
  return {
261
300
  read: async () => gauge,
262
301
  update: async change => {
@@ -271,7 +310,7 @@ export default function shift(pi: ExtensionAPI): void {
271
310
 
272
311
  return counted.growth
273
312
  },
274
- base: async () => shiftBase(await projectAt(ctx.cwd), ctx.sessionManager.getSessionId()),
313
+ base: async () => shiftBase(await project(), ctx.sessionManager.getSessionId()),
275
314
  reading: async () => {
276
315
  const usage = ctx.getContextUsage()
277
316
  const window = usage?.contextWindow ?? ctx.model?.contextWindow ?? 0
@@ -283,14 +322,30 @@ export default function shift(pi: ExtensionAPI): void {
283
322
  }
284
323
  }
285
324
 
286
- // pi lets go only of the messages before the cut it finds by keepRecentTokens, counted from the last let-go; with none
287
- // there — a history no bigger, the cut on its first message — it refuses as "session too small". The same cut is
288
- // found here, before the shift is accepted.
325
+ // The wait note of the branch the session stands on: its last wait entry, written whenever the note changes. A note
326
+ // cleared by a message rewound off this branch still waits on it: every clearing is followed by the message that
327
+ // carries the letter — the mod's, or the owner's /shift. The system prompt pi records as a message carries none.
328
+ function branchNote(ctx: ExtensionContext): WaitNote | null {
329
+ let followed = false
330
+ for (const entry of ctx.sessionManager.getBranch().toReversed()) {
331
+ if ((entry.type === 'custom_message' && entry.customType === MOD) || (entry.type === 'message' && entry.message.role !== 'system'))
332
+ followed = true
333
+ if (entry.type !== 'custom' || entry.customType !== WAIT_ENTRY) continue
334
+ const note = (entry.data as { note: WaitNote | null } | undefined)?.note ?? null
335
+ if (note !== null || followed) return note
336
+ }
337
+
338
+ return null
339
+ }
340
+
289
341
  // What a let-go summarizes: the conversation, not the system prompt pi records as a message of its own.
290
342
  function summarized(entry: SessionEntry): boolean {
291
343
  return entry.type === 'message' ? entry.message.role !== 'system' : entry.type === 'custom_message' || entry.type === 'branch_summary'
292
344
  }
293
345
 
346
+ // pi lets go only of the messages before the cut it finds by keepRecentTokens, counted from the last let-go; with none
347
+ // there — a history no bigger, the cut on its first message — it refuses as "session too small". The same cut is
348
+ // found here, before the shift is accepted.
294
349
  function cannotLetGo(ctx: ExtensionContext): string | null {
295
350
  const keep = SettingsManager.create(ctx.cwd).getCompactionSettings(ctx.model).keepRecentTokens
296
351
  const branch = ctx.sessionManager.getBranch()
@@ -304,6 +359,12 @@ function cannotLetGo(ctx: ExtensionContext): string | null {
304
359
  return `the history since the last let-go is about ${formatK(since)} tokens, and pi keeps its last ${formatK(keep)} whole, so it has nothing to let go.`
305
360
  }
306
361
 
362
+ // The project loaded once for the hook at hand.
363
+ function once(ctx: ExtensionContext): () => Promise<Project> {
364
+ const loading = projectAt(ctx.cwd)
365
+ return () => loading
366
+ }
367
+
307
368
  // A row for the owner; a context gone stale with its session has no one to tell.
308
369
  function tell(ctx: ExtensionContext, row: string, kind: 'info' | 'warning' | 'error'): void {
309
370
  try {
@@ -313,8 +374,10 @@ function tell(ctx: ExtensionContext, row: string, kind: 'info' | 'warning' | 'er
313
374
  }
314
375
  }
315
376
 
316
- // Who a message came from, as the hint names it; digests of earlier history are not counted.
317
- function growthSource(message: { role: string; toolName?: string }): string | null {
377
+ // Who a message came from, as the hint names it; digests of earlier history and a shell output the owner kept out of
378
+ // the context are not counted.
379
+ function growthSource(message: { role: string; toolName?: string; excludeFromContext?: boolean }): string | null {
380
+ if (message.excludeFromContext === true) return null
318
381
  if (message.role === 'assistant') return SOURCES.responses
319
382
  if (message.role === 'user' || message.role === 'bashExecution') return SOURCES.owner
320
383
  if (message.role === 'toolResult') return message.toolName ?? SOURCES.tools
@@ -323,10 +386,15 @@ function growthSource(message: { role: string; toolName?: string }): string | nu
323
386
  return SOURCES.attachments
324
387
  }
325
388
 
326
- // A shell command the owner ran has its command and output instead of content.
389
+ // A shell command the owner ran has its command and output instead of content; a change of the system prompt carries
390
+ // its text in sections.
327
391
  function messageChars(message: object): number {
328
- if ('content' in message) return contentChars(message.content)
392
+ const sections =
393
+ 'sections' in message && typeof message.sections === 'object' && message.sections !== null
394
+ ? Object.values(message.sections).reduce((sum: number, text) => sum + (typeof text === 'string' ? text.length : 0), 0)
395
+ : 0
396
+ if ('content' in message) return contentChars(message.content) + sections
329
397
  if ('output' in message && typeof message.output === 'string') return message.output.length
330
398
 
331
- return 0
399
+ return sections
332
400
  }
package/package.json CHANGED
@@ -1,9 +1,13 @@
1
1
  {
2
2
  "name": "@iiiokojiadbi/shift",
3
- "version": "0.33.0",
3
+ "version": "0.34.0",
4
4
  "description": "The agent decides by itself when to shift: it keeps a work board and task folders, writes a letter to itself, and continues from where it stopped.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
+ "homepage": "https://github.com/iiiokojiadbi/shift#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/iiiokojiadbi/shift/issues"
10
+ },
7
11
  "repository": {
8
12
  "type": "git",
9
13
  "url": "git+https://github.com/iiiokojiadbi/shift.git",
@@ -11,7 +15,13 @@
11
15
  },
12
16
  "keywords": [
13
17
  "pi-package",
14
- "opencode-plugin"
18
+ "opencode-plugin",
19
+ "pi",
20
+ "opencode",
21
+ "agent",
22
+ "context",
23
+ "memory",
24
+ "handoff"
15
25
  ],
16
26
  "files": [
17
27
  "index.ts",