@iiiokojiadbi/shift 0.33.0 → 0.34.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.
package/core/flows.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
- import { OUTCOME, renderAbout, shiftFill } from './about'
2
+ import { OUTCOME, readAbout, renderAbout, shiftFill } from './about'
3
3
  import { addToIndex, checkArchive, indexLine } from './archive'
4
4
  import { docsReport, refreshDocs } from './docs'
5
5
  import { renderHistory, renderSummary, segment, shiftDir } from './history'
@@ -29,7 +29,7 @@ import { formatItem, formatK, itemsOf, sections } from './markdown'
29
29
  import { basename, dirname, join, resolvePath } from './paths'
30
30
  import type { Project } from './project'
31
31
  import { checkLetter, checkTask, checkWork, checkWritten, listedTasks } from './records'
32
- import { lastShifts, previousShift, readRecords, readSnapshot, readTask, recentShifts, shiftNames, writeSnapshot } from './store'
32
+ import { lastShifts, readRecords, readSnapshot, readTask, recentShifts, shiftNames, writeSnapshot } from './store'
33
33
  import { archiveInList, checkTaskList, formatTaskLine, parseTaskList, withTask } from './tasks'
34
34
  import {
35
35
  ACCEPTED,
@@ -150,7 +150,7 @@ export async function acceptShift(project: Project, call: ShiftCall): Promise<{
150
150
  await numberTracks(project)
151
151
  const work = await readRecords(project)
152
152
  if (work === null) return { deny: `No board: create ${BOARD} by the sections in ${GUIDE_TOOL} and call again.` }
153
- const previousDir = await previousShift(project)
153
+ const previousDir = await lastMadeShift(project)
154
154
  const previous = previousDir === null ? null : await readSnapshot(store, previousDir, `${previousDir}/${NAMES.index}`)
155
155
  const workProblem = checkWork(work, previous?.work ?? null, project)
156
156
  if (workProblem !== null) return { deny: workProblem }
@@ -158,7 +158,7 @@ export async function acceptShift(project: Project, call: ShiftCall): Promise<{
158
158
  if ('deny' in kept) return kept
159
159
 
160
160
  const index = await store.read(`${root}/${INDEX}`)
161
- const dir = shiftDir(root, call.at)
161
+ const dir = await freeShiftDir(project, shiftDir(root, call.at))
162
162
  const shift: PendingShift = {
163
163
  after: input.after,
164
164
  letter,
@@ -172,9 +172,11 @@ export async function acceptShift(project: Project, call: ShiftCall): Promise<{
172
172
  segment: segment({ work, index }, previous),
173
173
  focus: focusOf(work),
174
174
  }
175
- await writeSnapshot(store, dir, { work, letter, index, settings: project.settingsText })
176
- // Rewritten with the outcome once the turn ends; `pending` stays if the session dies first.
175
+ // Written first, it takes the folder as soon as the store can: no harness's file API creates a file only if it is not
176
+ // there, so two sessions accepting in the same second may still meet. Rewritten with the outcome once the turn ends;
177
+ // `pending` stays if the session dies first.
177
178
  await store.write(`${dir}/${NAMES.about}`, renderAbout({ ...shift, result: OUTCOME.pending }))
179
+ await writeSnapshot(store, dir, { work, letter, index, settings: project.settingsText })
178
180
 
179
181
  // Knowledge is rarely written: a stretch that added none is asked once, while its history is still whole.
180
182
  const learned = previous === null || knowledgeText(work) !== knowledgeText(previous.work)
@@ -183,6 +185,29 @@ export async function acceptShift(project: Project, call: ShiftCall): Promise<{
183
185
  return { shift, result: kept.excluded === null ? accepted : `${EXCLUDED(kept.excluded)}\n\n${accepted}` }
184
186
  }
185
187
 
188
+ // The newest shift that let the history go, or may have: one not shifted left the records as they were, so an unchanged
189
+ // retry is no empty shift.
190
+ async function lastMadeShift(project: Project): Promise<string | null> {
191
+ const names = await shiftNames(project)
192
+ for (const name of names.toReversed()) {
193
+ const dir = `${project.root}/${SHIFTS}/${name}`
194
+ const about = await project.store.read(`${dir}/${NAMES.about}`)
195
+ if (!(readAbout(about ?? '').result ?? '').startsWith(OUTCOME.notShifted(''))) return dir
196
+ }
197
+
198
+ return null
199
+ }
200
+
201
+ // Another session may shift in the same second: its folder is never shared, the next free name is taken.
202
+ async function freeShiftDir(project: Project, dir: string): Promise<string> {
203
+ const taken = new Set(await shiftNames(project))
204
+ const name = basename(dir)
205
+ let free = name
206
+ for (let n = 2; taken.has(free); n++) free = `${name}-${n}`
207
+
208
+ return `${dirname(dir)}/${free}`
209
+ }
210
+
186
211
  // The tasks in progress, each with the names of its items in progress.
187
212
  function focusOf(work: Work): string[] {
188
213
  return listedTasks(work)
@@ -266,13 +291,26 @@ export async function shiftHistory(project: Project, count: number): Promise<str
266
291
  }
267
292
 
268
293
  // The last shift picked up in a session that has not seen it: the text for the owner, and the prompt when there is one.
294
+ // The newest shift with a letter, whatever became of it: its letter is the freshest state. A folder whose letter was
295
+ // never written — a session that died while accepting — is passed over. Its outcome goes with it unless it shifted.
269
296
  export async function resumeShift(project: Project): Promise<{ text: string; prompt?: string }> {
270
- const dir = await previousShift(project)
271
- if (dir === null) return { text: `No shifts in this project: ${SHIFTS}/ is empty.` }
272
- const letter = await project.store.read(`${dir}/${NAMES.letter}`)
273
- if (letter === null) return { text: `No letter.md in ${dir}/ — nothing to pick up.` }
297
+ const { store, root } = project
298
+ const names = await shiftNames(project)
299
+ if (names.length === 0) return { text: `No shifts in this project: ${SHIFTS}/ is empty.` }
300
+ for (const name of names.toReversed()) {
301
+ const dir = `${root}/${SHIFTS}/${name}`
302
+ const letter = await store.read(`${dir}/${NAMES.letter}`)
303
+ if (letter === null) continue
304
+ const about = readAbout((await store.read(`${dir}/${NAMES.about}`)) ?? '')
305
+ const outcome = about.shifted || about.result === null ? null : about.result
306
+
307
+ return {
308
+ text: `Picking up shift ${name}${outcome === null ? '' : ` (${outcome})`}.`,
309
+ prompt: resumePrompt(letter, await handBack(project, dir), outcome),
310
+ }
311
+ }
274
312
 
275
- return { text: `Picking up shift ${basename(dir)}.`, prompt: resumePrompt(letter, await handBack(project, dir)) }
313
+ return { text: `No letter.md in any folder of ${SHIFTS}/ — nothing to pick up.` }
276
314
  }
277
315
 
278
316
  // The records, the last shifts and the documents' remarks as they are now, for the message after a shift.
@@ -367,28 +405,33 @@ export async function settleShift(project: Project, letGo: LetGo): Promise<Settl
367
405
  const back = await handBack(project, shift.dir)
368
406
  const name = basename(shift.dir)
369
407
 
408
+ const files = deliveredFiles(back.work)
370
409
  if (shift.after === 'continue') {
371
410
  await outcome(OUTCOME.continuing(shrank))
411
+ const prompt = continuePrompt(shift.letter, back)
372
412
 
373
- return {
374
- after: 'continue',
375
- prompt: continuePrompt(shift.letter, back),
376
- row: CONTINUING(name, shrank, shift.dir),
377
- }
413
+ return { after: 'continue', prompt, note: { context: prompt, dir: shift.dir, files }, row: CONTINUING(name, shrank, shift.dir) }
378
414
  }
379
415
 
380
416
  await outcome(OUTCOME.waiting(shrank, 'waiting for the owner'))
381
- const note = { context: waitContext(shift.letter, back), dir: shift.dir, files: deliveredFiles(back.work) }
417
+ const note = { context: waitContext(shift.letter, back), dir: shift.dir, files }
382
418
 
383
419
  return { after: 'wait', note, row: WAITING(name, shrank) }
384
420
  }
385
421
 
386
- // The fill the stretch started from, if the last shift was this session's: a fresh process counts from there.
422
+ // The fill the stretch started from, if the last shift that let the history go was this session's: a fresh process
423
+ // counts from there. A shift not made, or still pending, left the history as it was and is passed over.
387
424
  export async function shiftBase(project: Project, sessionId: string): Promise<number | null> {
388
- const dir = await previousShift(project)
389
- const about = dir === null ? null : await project.store.read(`${dir}/${NAMES.about}`)
425
+ for (const name of (await shiftNames(project)).toReversed()) {
426
+ const about = await project.store.read(`${project.root}/${SHIFTS}/${name}/${NAMES.about}`)
427
+ if (about === null) continue
428
+ const { result } = readAbout(about)
429
+ if (result === OUTCOME.pending || (result ?? '').startsWith(OUTCOME.notShifted(''))) continue
390
430
 
391
- return about === null ? null : shiftFill(about, sessionId)
431
+ return shiftFill(about, sessionId)
432
+ }
433
+
434
+ return null
392
435
  }
393
436
 
394
437
  // Unless the owner lets the project commit them, the records stay out of its git: when they are not ignored, the mod
@@ -411,11 +454,11 @@ export async function keepRecordsOut(project: Project): Promise<{ excluded: stri
411
454
  }
412
455
 
413
456
  // What comes into every session: SHIFT.md with a fresh map of the docs, OWNER.md, GLOSSARY.md and TASKS.md, with
414
- // paths from the project's root; none when the mod is off here.
415
- export async function sessionFiles(project: Project): Promise<SessionFile[]> {
457
+ // paths from the project's root; none when the mod is off here. `refresh: false` reads them as they are, writing nothing.
458
+ export async function sessionFiles(project: Project, { refresh = true }: { refresh?: boolean } = {}): Promise<SessionFile[]> {
416
459
  const { store, root, settings } = project
417
460
  if (!settings.enabled || (await staleLayout(project)) !== null) return []
418
- await refreshDocs(project)
461
+ if (refresh) await refreshDocs(project)
419
462
  const paths = [settings.files.shift, settings.files.owner, settings.files.glossary, TASK_LIST, ...settings.files.always]
420
463
  const files = await Promise.all(paths.map(async path => ({ path, text: await store.read(`${root}/${path}`) })))
421
464
 
package/core/glossary.ts CHANGED
@@ -48,8 +48,12 @@ export function checkGlossary(text: string | null, where: string): string | null
48
48
  const seen = new Map<string, string>()
49
49
  for (const article of articles) {
50
50
  if (!article.fields.Means) return `${where}, "${article.term}" has no "Means:" — what it is, in one or two sentences.`
51
+ // Spellings of one term that differ only in case are one name: only another article clashes, even one of the same title.
52
+ const own = new Set<string>()
51
53
  for (const name of [article.term, ...words(article.fields.Variants)]) {
52
54
  const key = name.toLowerCase()
55
+ if (own.has(key)) continue
56
+ own.add(key)
53
57
  const earlier = seen.get(key)
54
58
  if (earlier !== undefined) return `${where}: "${name}" is in both "${earlier}" and "${article.term}". One word, one article.`
55
59
  seen.set(key, article.term)
package/core/hint.ts CHANGED
@@ -140,13 +140,14 @@ export function renderStatus(current: Gauge, { tokens, window, threshold }: Read
140
140
  const limit = threshold ?? window
141
141
  const final = finalAt(limit)
142
142
  const lines = [
143
- `Used: ${formatK(tokens)} of ${formatK(window)} window; ${threshold === undefined ? 'the harness threshold is not read yet, the window stands for it' : `the harness lets the history go by itself at ${formatK(threshold)}`}.`,
143
+ `Used: ${formatK(tokens)} of ${formatK(window)} window; ${threshold === undefined ? 'the harness lets nothing go by itself, or its threshold is not read yet: the window stands for it' : `the harness lets the history go by itself at ${formatK(threshold)}`}.`,
144
144
  ]
145
145
  if (gauge.base !== null) lines.push(`Since the last shift: +${formatK(Math.max(0, tokens - gauge.base))}.`)
146
146
  if (tokens >= final) lines.push(`Past the final hint at ${formatK(final)}: shift at the nearest stage boundary.`)
147
147
  else {
148
- const soft = (gauge.hinted ?? gauge.base ?? tokens) + softStep(limit)
149
- const next = soft + softStep(limit) / 2 <= final ? `next soft hint at ${formatK(soft)}` : 'no soft hint before the final'
148
+ const step = softStep(limit)
149
+ const soft = Math.max(tokens, (gauge.hinted ?? gauge.base ?? tokens) + step)
150
+ const next = soft + step / 2 <= final ? `next soft hint at ${formatK(soft)}` : 'no soft hint before the final'
150
151
  lines.push(`Hints: ${next}; final at ${formatK(final)}.`)
151
152
  }
152
153
  const shares = growthShares(gauge.growth)
@@ -178,7 +179,8 @@ export function letGoGauge(unassisted: boolean): Gauge {
178
179
  return { ...FRESH_GAUGE, unassisted, whole: true }
179
180
  }
180
181
 
181
- // A hint for the agent if the fill since the last shift calls for one.
182
+ // A hint for the agent if the fill since the last shift calls for one, given in the same change that finds it: tools
183
+ // ending together never both carry it.
182
184
  export async function takeHint(keeper: GaugeKeeper): Promise<string | null> {
183
185
  await restore(keeper)
184
186
  const reading = await keeper.reading()
@@ -193,6 +195,46 @@ export async function takeHint(keeper: GaugeKeeper): Promise<string | null> {
193
195
  return text
194
196
  }
195
197
 
198
+ // A hint offered with the next prompt, which may not go: the gauge keeps everything else at once and marks the hint
199
+ // given only at `take`, so a hint whose prompt failed comes again with the next one. One prompt at a time asks.
200
+ export async function offerHint(keeper: GaugeKeeper): Promise<{ text: string; take(): Promise<void> } | null> {
201
+ await restore(keeper)
202
+ const reading = await keeper.reading()
203
+ const offered: { gauge?: Gauge; text?: string; seen?: Gauge } = {}
204
+ await keeper.update(current => {
205
+ // A harness may run the change again on a newer gauge: only the last run's hint is offered.
206
+ delete offered.gauge
207
+ delete offered.text
208
+ delete offered.seen
209
+ const now = complete(current)
210
+ const hint = shiftHint(now, reading)
211
+ if (hint.text === null) return hint.gauge
212
+ offered.gauge = hint.gauge
213
+ offered.text = hint.text
214
+ offered.seen = now
215
+
216
+ return now
217
+ })
218
+ const { gauge: given, text, seen } = offered
219
+ if (given === undefined || text === undefined || seen === undefined) return null
220
+
221
+ return {
222
+ text,
223
+ // Never over a newer count: a tool's hint given meanwhile, or a stretch begun since, stands.
224
+ take: () =>
225
+ keeper.update(current =>
226
+ !sameStretch(seen, current)
227
+ ? current
228
+ : {
229
+ ...current,
230
+ base: current.base ?? given.base,
231
+ hinted: current.hinted !== null && current.hinted >= (given.hinted ?? 0) ? current.hinted : given.hinted,
232
+ unassisted: current.unassisted && given.unassisted,
233
+ },
234
+ ),
235
+ }
236
+ }
237
+
196
238
  // What a row added to the stretch's history, by where it came from.
197
239
  export async function countGrowth(keeper: GaugeKeeper, source: string, chars: number): Promise<void> {
198
240
  await restore(keeper)
@@ -207,17 +249,29 @@ export async function gaugeStatus(keeper: GaugeKeeper): Promise<string> {
207
249
  return renderStatus(complete(await keeper.read()), reading)
208
250
  }
209
251
 
252
+ // Whether `later` is still the stretch `earlier` was: a let-go since starts the count anew — its own base, no hint
253
+ // given, the agent told if the harness let go by itself.
254
+ function sameStretch(earlier: Gauge, later: Gauge): boolean {
255
+ return (
256
+ later.base === earlier.base &&
257
+ (later.hinted ?? 0) >= (earlier.hinted ?? 0) &&
258
+ (later.unassisted === earlier.unassisted || !later.unassisted)
259
+ )
260
+ }
261
+
210
262
  function complete(current: Gauge | null): Gauge {
211
263
  return { ...FRESH_GAUGE, ...current }
212
264
  }
213
265
 
214
266
  // The base from the last shift of this session, the growth from the history plus whatever this process counted before
215
267
  // the restore finished, and the last hint as given before. Once; a let-go marks the count whole itself.
268
+ // Not before the first reading: the last hint is placed by the fill, and one placed at none would come again.
216
269
  async function restore(keeper: GaugeKeeper): Promise<void> {
217
270
  if (complete(await keeper.read()).whole) return
271
+ const reading = await keeper.reading()
272
+ if (reading.tokens === undefined) return
218
273
  const base = await keeper.base()
219
274
  const growth = await keeper.history()
220
- const reading = await keeper.reading()
221
275
  await keeper.update(current => {
222
276
  const now = complete(current)
223
277
  if (now.whole) return now
@@ -229,12 +283,13 @@ async function restore(keeper: GaugeKeeper): Promise<void> {
229
283
  }
230
284
 
231
285
  // The last step the history has passed since the base: its hint was given before the restart, so it is not repeated,
232
- // and the next step still hints.
286
+ // and the next step still hints. Past the final the hint is taken as given now: the final repeats every 5%, and a step
287
+ // placed below the real one would repeat it at once.
233
288
  export function lastStep(base: number | null, { tokens, window, threshold }: Reading): number | null {
234
289
  if (base === null || tokens === undefined || tokens < base) return null
235
290
  const limit = threshold ?? window
236
291
  const final = finalAt(limit)
237
- if (tokens >= final) return final + Math.floor((tokens - final) / finalStep(limit)) * finalStep(limit)
292
+ if (tokens >= final) return tokens
238
293
  const step = softStep(limit)
239
294
  const passed = Math.floor((tokens - base) / step)
240
295
 
package/core/history.ts CHANGED
@@ -3,7 +3,7 @@ import { readAbout } from './about'
3
3
  import { CLOSED, SHIFTS } from './layout'
4
4
  import { itemsOf } from './markdown'
5
5
  import { listedTasks } from './records'
6
- import type { HistoryEntry, Segment, Snapshot } from './types'
6
+ import type { HistoryEntry, Item, Segment, Snapshot } from './types'
7
7
 
8
8
  export function stamp(ms: number): string {
9
9
  const d = new Date(ms)
@@ -16,35 +16,44 @@ export function shiftDir(root: string, ms: number): string {
16
16
  return `${root}/${SHIFTS}/${stamp(ms)}`
17
17
  }
18
18
 
19
+ // What the stretch closed and archived, against the previous shift's snapshot. An item is the same item by its id, a
20
+ // line of the index the same task by its folder: a closed item renamed, or an archived task's line reworded, is no
21
+ // new work.
19
22
  export function segment(now: Snapshot, previous: Snapshot | null): Segment {
20
- const closedBefore = new Map<string, Set<string>>()
23
+ const closedBefore = new Map<string, Item[]>()
21
24
  for (const task of previous?.work.tasks ?? []) {
22
25
  closedBefore.set(
23
26
  task.name,
24
- new Set(
25
- itemsOf(task.track ?? '')
26
- .filter(i => CLOSED.has(i.status))
27
- .map(i => i.name),
28
- ),
27
+ itemsOf(task.track ?? '').filter(i => CLOSED.has(i.status)),
29
28
  )
30
29
  }
31
30
  const fresh = now.work.tasks.flatMap(task =>
32
31
  itemsOf(task.track ?? '')
33
- .filter(item => CLOSED.has(item.status) && !(closedBefore.get(task.name)?.has(item.name) ?? false))
32
+ .filter(item => CLOSED.has(item.status) && !(closedBefore.get(task.name) ?? []).some(before => sameItem(before, item)))
34
33
  .map(item => ({ status: item.status, text: `${task.name}: ${item.rest}` })),
35
34
  )
36
- const indexed = new Set(itemsOf(previous?.index ?? '').map(i => i.line))
35
+ const indexed = new Set(itemsOf(previous?.index ?? '').map(archivedKey))
37
36
 
38
37
  return {
39
38
  done: fresh.filter(f => f.status === 'done').map(f => f.text),
40
39
  dropped: fresh.filter(f => f.status === 'dropped').map(f => f.text),
41
40
  archived: itemsOf(now.index ?? '')
42
- .filter(i => !indexed.has(i.line))
41
+ .filter(i => !indexed.has(archivedKey(i)))
43
42
  .map(i => i.line.slice(2)),
44
43
  open: listedTasks(now.work).map(t => t.line.slice(2)),
45
44
  }
46
45
  }
47
46
 
47
+ // An item is known by its id; by its name only where one of the two has none — a track numbered since.
48
+ function sameItem(before: Item, now: Item): boolean {
49
+ return before.id !== null && now.id !== null ? before.id === now.id : before.name === now.name
50
+ }
51
+
52
+ // An index line by its task's folder, `[title](name/)`; the whole line when it links none.
53
+ function archivedKey(item: Item): string {
54
+ return /\]\(([^)]+?)\/?\)/.exec(item.line)?.[1] ?? item.line
55
+ }
56
+
48
57
  export function renderSummary(messages: readonly { role: string; text: string }[]): string {
49
58
  return `${messages.map(m => `## ${m.role}\n\n${m.text}`).join('\n\n')}\n`
50
59
  }
package/core/layout.ts CHANGED
@@ -46,6 +46,10 @@ export const DOCS_MAP_MAX_CHARS = 100000
46
46
  // The pinned blocks of the docs, in characters; past it the map says so, and shows them all still.
47
47
  export const DOCS_PINNED_MAX_CHARS = 4000
48
48
 
49
+ // How many folders deep a docs folder is walked: a store may follow a link to a folder, and a link back up must not make
50
+ // a walk endless. A document deeper is not mapped.
51
+ export const DOCS_MAX_DEPTH = 8
52
+
49
53
  // A knowledge file past this is split by topic.
50
54
  export const KNOWLEDGE_MAX_LINES = 400
51
55
 
@@ -169,4 +173,4 @@ export const STUCK_SHIFTS = 5
169
173
  export const STUCK_LOOKBACK = 30
170
174
 
171
175
  export const NAME = /^[a-z0-9][a-z0-9-]*$/
172
- export const NAME_RULE = 'lowercase latin, digits and dashes'
176
+ export const NAME_RULE = 'lowercase latin, digits and dashes, starting with a letter or a digit'
package/core/loop.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
2
  import { settleShift, shiftNotMade, shiftUnsettled } from './flows'
3
- import { type GaugeKeeper, takeHint } from './hint'
3
+ import { type GaugeKeeper, offerHint, takeHint } from './hint'
4
4
  import { basename } from './paths'
5
5
  import type { Project } from './project'
6
- import { compactInstructions, FAILURE_NOTE, NOT_MADE_NOTE, UNSETTLED_NOTE } from './texts/prompts'
6
+ import { compactInstructions, FAILURE_NOTE, NOT_MADE_NOTE, ourWords, SHIFT_NOW, UNSETTLED_NOTE } from './texts/prompts'
7
7
  import { DELIVERED, NOT_CONTINUED } from './texts/rows'
8
8
  import type { PendingShift, Settled, WaitNote } from './types'
9
9
 
@@ -16,6 +16,9 @@ export type LoopState = {
16
16
  pending: PendingShift | null
17
17
  // The letter and the records waiting for the owner's next message.
18
18
  note: WaitNote | null
19
+ // A let-go in flight, and whether the owner spoke during it: their message found no letter yet, so the one the
20
+ // shift then leaves for them is sent after it rather than kept for a message they already sent.
21
+ letting?: { heard: boolean } | null
19
22
  }
20
23
 
21
24
  export type Level = 'info' | 'warning' | 'error'
@@ -48,20 +51,42 @@ export async function holdShift(loop: Loop, shift: PendingShift): Promise<void>
48
51
  await loop.update(state => ({ ...state, pending: shift }))
49
52
  }
50
53
 
51
- // A hint for the agent if the fill calls for one; none while a shift is pending.
54
+ // A hint for the agent if the fill calls for one, given at once; none while a shift is pending.
52
55
  export async function loopHint(loop: Loop, gauge: GaugeKeeper): Promise<string | null> {
53
56
  if ((await loop.read()).pending !== null) return null
54
57
 
55
58
  return takeHint(gauge)
56
59
  }
57
60
 
61
+ // The same, offered with the next prompt and given once `take` says it went.
62
+ export async function loopOffer(loop: Loop, gauge: GaugeKeeper): Promise<{ text: string; take(): Promise<void> } | null> {
63
+ if ((await loop.read()).pending !== null) return null
64
+
65
+ return offerHint(gauge)
66
+ }
67
+
58
68
  // Once the turn has ended: a pending shift lets the history go, unless the turn was aborted. Every outcome is written
59
69
  // to the shift's about.md and told to the owner; nothing is lost silently.
60
70
  export async function afterTurn(project: Project, loop: Loop, harness: LetGoHarness, aborted: boolean): Promise<void> {
61
- const shift = (await loop.read()).pending
62
- if (shift === null) return
63
- await loop.update(current => ({ ...current, pending: null }))
64
- const before = await harness.fill()
71
+ // The let-go is marked before the shift is claimed, so an owner's message never falls between the two: a harness may
72
+ // keep them apart. Claimed in the change that clears it: two ends of a turn never let go twice.
73
+ await loop.update(current => (current.pending === null ? current : { ...current, letting: { heard: current.letting?.heard === true } }))
74
+ const claim: { shift?: PendingShift | null } = {}
75
+ await loop.update(current => {
76
+ claim.shift = current.pending
77
+ return current.pending === null ? current : { ...current, pending: null, letting: { heard: current.letting?.heard === true } }
78
+ })
79
+ const { shift } = claim
80
+ if (shift === undefined || shift === null) return
81
+ try {
82
+ await letGoShift(project, loop, harness, shift, aborted)
83
+ } finally {
84
+ await loop.update(current => (current.letting == null ? current : { ...current, letting: null }))
85
+ }
86
+ }
87
+
88
+ async function letGoShift(project: Project, loop: Loop, harness: LetGoHarness, shift: PendingShift, aborted: boolean): Promise<void> {
89
+ const before = await harness.fill().catch(() => undefined)
65
90
  const name = basename(shift.dir)
66
91
  if (aborted) {
67
92
  const why = 'the turn was aborted'
@@ -72,8 +97,10 @@ export async function afterTurn(project: Project, loop: Loop, harness: LetGoHarn
72
97
 
73
98
  const done = await harness.letGo(compactInstructions(shift)).catch((error: unknown) => ({ skip: `the let-go failed: ${String(error)}` }))
74
99
  if ('skip' in done) {
75
- loop.tell(await shiftNotMade(project, shift, done.skip, before), 'error')
76
- await tellAgent(loop, harness, shift, NOT_MADE_NOTE(name, done.skip), true)
100
+ // The harness's reason, in the mod's words wherever it goes: the note, the row and about.md.
101
+ const why = ourWords(done.skip)
102
+ loop.tell(await shiftNotMade(project, shift, why, before), 'error')
103
+ await tellAgent(loop, harness, shift, NOT_MADE_NOTE(name, why), true)
77
104
  return
78
105
  }
79
106
  let settled: Settled
@@ -86,43 +113,89 @@ export async function afterTurn(project: Project, loop: Loop, harness: LetGoHarn
86
113
  after: done.after ?? (await harness.fill()) ?? 0,
87
114
  })
88
115
  } catch (error) {
89
- const why = String(error)
116
+ const why = ourWords(String(error))
90
117
  loop.tell(await shiftUnsettled(project, shift, why, done.before ?? before), 'error')
91
118
  await tellAgent(loop, harness, shift, UNSETTLED_NOTE(name, why, shift.dir), true)
92
119
  return
93
120
  }
94
121
  if (settled.after === 'wait') {
95
- const { note } = settled
96
- await loop.update(current => ({ ...current, note }))
97
122
  loop.tell(settled.row, 'info')
123
+ await leave(loop, harness, settled.note)
98
124
  return
99
125
  }
100
126
  loop.tell(settled.row, 'info')
101
- // The shift is settled and written; a turn that does not start is told, not recorded against it.
102
- await harness.continueWith(settled.prompt).catch((error: unknown) => loop.tell(NOT_CONTINUED(String(error)), 'error'))
127
+ // The shift is settled and written; a turn that does not start is told, not recorded against it, and its letter
128
+ // waits for the owner's next message as after a wait. A letter an earlier shift left waiting is older than this one.
129
+ await dropWaiting(loop).catch(() => undefined)
130
+ await harness.continueWith(settled.prompt).catch(async (error: unknown) => {
131
+ await loop.update(current => ({ ...current, note: settled.note }))
132
+ loop.tell(NOT_CONTINUED(String(error)), 'error')
133
+ })
103
134
  }
104
135
 
105
136
  // A failed shift is told to the agent, who was told it was accepted: at once when it was to continue and may go on,
106
137
  // otherwise with the owner's next message.
107
138
  async function tellAgent(loop: Loop, harness: LetGoHarness, shift: PendingShift, context: string, goOn: boolean): Promise<void> {
108
139
  if (goOn && shift.after === 'continue') {
109
- await harness.continueWith(context).catch((error: unknown) => loop.tell(NOT_CONTINUED(String(error)), 'error'))
140
+ await harness.continueWith(context).catch(async (error: unknown) => {
141
+ await loop.update(current => ({ ...current, note: { context, dir: shift.dir, files: [FAILURE_NOTE] } }))
142
+ loop.tell(NOT_CONTINUED(String(error), FAILURE_NOTE), 'error')
143
+ })
110
144
  return
111
145
  }
112
- await loop.update(current => ({ ...current, note: { context, dir: shift.dir, files: [FAILURE_NOTE] } }))
146
+ await leave(loop, harness, { context, dir: shift.dir, files: [FAILURE_NOTE] })
147
+ }
148
+
149
+ // A note for the owner's next message — or, when the owner already spoke while the history was let go, sent after
150
+ // that message at once; kept for the next one if it does not go.
151
+ async function leave(loop: Loop, harness: LetGoHarness, note: WaitNote): Promise<void> {
152
+ const heard: { now?: boolean } = {}
153
+ await loop.update(current => {
154
+ heard.now = current.letting?.heard === true
155
+ return heard.now ? { ...current, letting: null } : { ...current, note, letting: null }
156
+ })
157
+ if (heard.now !== true) return
158
+ await harness.continueWith(note.context).catch(async (error: unknown) => {
159
+ await loop.update(current => ({ ...current, note }))
160
+ loop.tell(NOT_CONTINUED(String(error), note.files.includes(FAILURE_NOTE) ? FAILURE_NOTE : undefined), 'error')
161
+ })
113
162
  }
114
163
 
115
164
  // The note waiting for the owner's message, if any, and what clears it once it went with that message: a failed
116
165
  // delivery keeps it for the next one.
117
166
  export async function waitingNote(loop: Loop): Promise<{ context: string; delivered: () => Promise<void> } | null> {
118
- const { note } = await loop.read()
167
+ const { note, pending, letting } = await loop.read()
168
+ // The owner spoke while a shift waits to let the history go or lets it go: what it leaves for them follows their
169
+ // message, whether an older letter goes with this one or not.
170
+ if (pending !== null || letting != null)
171
+ await loop.update(current => (current.pending === null && current.letting == null ? current : { ...current, letting: { heard: true } }))
119
172
  if (note === null) return null
120
173
 
121
174
  return {
122
175
  context: note.context,
123
176
  delivered: async () => {
124
- await loop.update(state => ({ ...state, note: null }))
177
+ // Only this note: one parked since is newer, and waits for the next message.
178
+ await loop.update(state => (sameNote(state.note, note) ? { ...state, note: null } : state))
125
179
  loop.tell(DELIVERED(note.files, note.dir), 'info')
126
180
  },
127
181
  }
128
182
  }
183
+
184
+ // A waiting letter delivered another way — by /unshift, or by a newer shift's — is not delivered again.
185
+ export async function dropWaiting(loop: Loop): Promise<void> {
186
+ await loop.update(current => (current.note === null ? current : { ...current, note: null }))
187
+ }
188
+
189
+ // Notes compared by value: a harness may keep them serialized.
190
+ function sameNote(a: WaitNote | null, b: WaitNote): boolean {
191
+ return a !== null && a.dir === b.dir && a.context === b.context
192
+ }
193
+
194
+ // The owner's /shift: the ask to shift, after a letter still waiting for them, which goes with it — the agent shifts
195
+ // from its records, never past a letter it has not read.
196
+ export async function shiftNow(loop: Loop, words: string): Promise<{ text: string; delivered: () => Promise<void> }> {
197
+ const letter = await waitingNote(loop)
198
+ const ask = SHIFT_NOW(words)
199
+
200
+ return letter === null ? { text: ask, delivered: async () => {} } : { text: `${letter.context}\n\n${ask}`, delivered: letter.delivered }
201
+ }