portable-agent-layer 0.118.0 → 0.119.0-canary.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "portable-agent-layer",
3
- "version": "0.118.0",
3
+ "version": "0.119.0-canary.1",
4
4
  "description": "PAL — Portable Agent Layer: persistent personal context for AI coding assistants",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,266 @@
1
+ /** The fields each bronze event type may carry; anything else is dropped before it is written. */
2
+
3
+ export const USAGE_FIELDS = [
4
+ "inputTokens",
5
+ "outputTokens",
6
+ "cacheWrite5m",
7
+ "cacheWrite1h",
8
+ "cacheRead",
9
+ "thinkingTokens",
10
+ "costUsd",
11
+ ] as const;
12
+
13
+ export const EVENT_FIELDS = {
14
+ turn: [
15
+ "hour",
16
+ "weekday",
17
+ "words",
18
+ "gapSec",
19
+ "afterBreak",
20
+ "skimmed",
21
+ "interrupted",
22
+ "repeated",
23
+ "corrected",
24
+ "reply",
25
+ "reaction",
26
+ "reactionRules",
27
+ "mood",
28
+ "hinted",
29
+ "complied",
30
+ "language",
31
+ "pastedChars",
32
+ "images",
33
+ "command",
34
+ "backAfterSec",
35
+ ],
36
+ reply: [
37
+ "words",
38
+ "listItems",
39
+ "headings",
40
+ "asked",
41
+ "mode",
42
+ "latencySec",
43
+ "turn",
44
+ "narrationBlocks",
45
+ "thinkingBlocks",
46
+ ],
47
+ session_start: [
48
+ "source",
49
+ "model",
50
+ "effort",
51
+ "entrypoint",
52
+ "branch",
53
+ "palVersion",
54
+ "tz",
55
+ "utcOffsetMin",
56
+ ],
57
+ session_end: ["reason", "durationSec", "turns", "messages", "status"],
58
+ sync: ["pushed", "pulled", "written", "quarantined", "refused"],
59
+ sync_account: ["action", "store"],
60
+ actor_adopted: ["from", "to"],
61
+ upstream_report: ["action", "report", "leaks", "via"],
62
+ doctor_run: ["failing", "warnings"],
63
+ pal_bug_signal: ["trigger", "surface", "verdict"],
64
+ compaction: ["trigger", "withInstructions", "contextTokens"],
65
+ context_injected: ["instructionsChars", "semiStaticChars", "dynamicChars"],
66
+ hook_timing: ["hook", "totalMs", "handlers"],
67
+ inference_call: [
68
+ "caller",
69
+ "route",
70
+ "model",
71
+ "tier",
72
+ "web",
73
+ "latencyMs",
74
+ "failure",
75
+ ...USAGE_FIELDS,
76
+ ],
77
+ judge_call: [
78
+ "caller",
79
+ "mode",
80
+ "route",
81
+ "provider",
82
+ "model",
83
+ "inputTokens",
84
+ "costUsd",
85
+ "latencyMs",
86
+ "failure",
87
+ "systemOneAnswers",
88
+ "fallbackAnswers",
89
+ ],
90
+ pal_update: ["outcome", "from", "to", "durationSec", "skipReason"],
91
+ memory_move: [
92
+ "migration",
93
+ "outcome",
94
+ "entries",
95
+ "files",
96
+ "bytes",
97
+ "manifest",
98
+ "reason",
99
+ "hashTotal",
100
+ "archive",
101
+ "lines",
102
+ "kept",
103
+ "differ",
104
+ ],
105
+ migration_run: [
106
+ "migration",
107
+ "outcome",
108
+ "migrated",
109
+ "skipped",
110
+ "dryRun",
111
+ "undo",
112
+ "sweep",
113
+ ],
114
+ pal_heartbeat: ["outcome", "payload", "status", "skipReason"],
115
+ commitment: ["iscProject", "isc", "outcome", "surface", "snoozeDays"],
116
+ ticket: ["iscProject", "ticket", "status", "at", "since", "was"],
117
+ entity_first_seen: ["domain", "entityType"],
118
+ discord_nag: ["stage", "kind", "responseSec"],
119
+ model_call: [
120
+ "billing",
121
+ "plan",
122
+ "extraUsage",
123
+ "model",
124
+ "requestedModel",
125
+ "provider",
126
+ "inputTokens",
127
+ "outputTokens",
128
+ "cacheWrite5m",
129
+ "cacheWrite1h",
130
+ "cacheRead",
131
+ "thinkingTokens",
132
+ "thinkingMs",
133
+ "webSearches",
134
+ "webFetches",
135
+ "serviceTier",
136
+ "speed",
137
+ "effort",
138
+ "stopReason",
139
+ "entrypoint",
140
+ "sidechain",
141
+ "costUsd",
142
+ "agent",
143
+ "mode",
144
+ "durationMs",
145
+ "ttftMs",
146
+ "aiu",
147
+ "initiator",
148
+ "host",
149
+ ],
150
+ conversation: ["steps", "status", "depth", "subagent", "killed"],
151
+ commit: [
152
+ "hash",
153
+ "committedAt",
154
+ "files",
155
+ "added",
156
+ "deleted",
157
+ "commitType",
158
+ "breaking",
159
+ "revert",
160
+ "merge",
161
+ "tags",
162
+ "coAuthors",
163
+ "aiCoAuthored",
164
+ ],
165
+ rating: ["rating", "source"],
166
+ forgotten: ["target", "undone"],
167
+ project: ["change", "status"],
168
+ setting: ["key", "change"],
169
+ rule_decision: ["rule", "decision"],
170
+ calibration_label: ["deck", "item", "answer"],
171
+ decision: ["words"],
172
+ promise: ["change", "dueInSec", "lateSec", "snoozes", "nags"],
173
+ action: [
174
+ "tool",
175
+ "outcome",
176
+ "fileExt",
177
+ "change",
178
+ "linesAdded",
179
+ "linesRemoved",
180
+ "beforeBytes",
181
+ "afterBytes",
182
+ ],
183
+ permission_prompt: ["tool"],
184
+ notification: ["kind"],
185
+ tool_call: [
186
+ "tool",
187
+ "outcome",
188
+ "denial",
189
+ "toolUseId",
190
+ "promptWaitSec",
191
+ "durationMs",
192
+ "inputChars",
193
+ "outputChars",
194
+ "fileExt",
195
+ "program",
196
+ "skill",
197
+ "subagent",
198
+ "subagentTokens",
199
+ "subagentTools",
200
+ "mcpServer",
201
+ "host",
202
+ ],
203
+ slurp_check: [
204
+ "mode",
205
+ "predicted",
206
+ "oom",
207
+ "hitCount",
208
+ "maxBytes",
209
+ "thresholdBytes",
210
+ "idioms",
211
+ ],
212
+ compaction_near: [
213
+ "mode",
214
+ "trigger",
215
+ "contextTokens",
216
+ "windowTokens",
217
+ "windowSource",
218
+ "compactAtTokens",
219
+ "tokensLeft",
220
+ "marginTokens",
221
+ "predicted",
222
+ "idleMinTokens",
223
+ ],
224
+ algorithm_run: [
225
+ "mode",
226
+ "change",
227
+ "run",
228
+ "node",
229
+ "turn",
230
+ "phases",
231
+ "header",
232
+ "headerFirst",
233
+ "startsNew",
234
+ "verdict",
235
+ "source",
236
+ "runType",
237
+ "wouldNudge",
238
+ "exempt",
239
+ ],
240
+ deadline_run: [
241
+ "kind",
242
+ "change",
243
+ "blocks",
244
+ "logEntries",
245
+ "minutesLeft",
246
+ "estimateMin",
247
+ "done",
248
+ ],
249
+ minimum_run: [
250
+ "change",
251
+ "lens",
252
+ "blocks",
253
+ "rounds",
254
+ "floorMin",
255
+ "minutesLeft",
256
+ "bar",
257
+ "early",
258
+ ],
259
+ worktree_pruned: ["branch"],
260
+ worktree_prune_failed: ["branch"],
261
+ git_state_injected: ["trigger", "source", "changed", "committedFiles", "chars"],
262
+ hook_run: ["hook", "event", "part", "durationMs", "exitCode"],
263
+ repo_state: ["head", "branch", "changed", "ahead", "behind"],
264
+ } as const satisfies Record<string, readonly string[]>;
265
+
266
+ export type EventType = keyof typeof EVENT_FIELDS;
@@ -12,256 +12,12 @@ import { logError } from "../core/log";
12
12
  import { boundProjectAt } from "../core/project-bindings";
13
13
  import { storeDir } from "./bronze";
14
14
  import { currentChannel } from "./channel";
15
+ import { EVENT_FIELDS, type EventType } from "./event-fields";
15
16
 
16
17
  export const EVENT_SCHEMA_VERSION = 1;
17
18
  const MAX_STRING = 64;
18
19
  const MAX_ARRAY = 50;
19
20
 
20
- export const USAGE_FIELDS = [
21
- "inputTokens",
22
- "outputTokens",
23
- "cacheWrite5m",
24
- "cacheWrite1h",
25
- "cacheRead",
26
- "thinkingTokens",
27
- "costUsd",
28
- ] as const;
29
-
30
- export const EVENT_FIELDS = {
31
- turn: [
32
- "hour",
33
- "weekday",
34
- "words",
35
- "gapSec",
36
- "afterBreak",
37
- "skimmed",
38
- "interrupted",
39
- "repeated",
40
- "corrected",
41
- "reply",
42
- "reaction",
43
- "reactionRules",
44
- "mood",
45
- "hinted",
46
- "complied",
47
- "language",
48
- "pastedChars",
49
- "images",
50
- "command",
51
- "backAfterSec",
52
- ],
53
- reply: ["words", "listItems", "headings", "asked", "mode", "latencySec", "turn"],
54
- session_start: [
55
- "source",
56
- "model",
57
- "effort",
58
- "entrypoint",
59
- "branch",
60
- "palVersion",
61
- "tz",
62
- "utcOffsetMin",
63
- ],
64
- session_end: ["reason", "durationSec", "turns", "messages", "status"],
65
- sync: ["pushed", "pulled", "written", "quarantined", "refused"],
66
- sync_account: ["action", "store"],
67
- actor_adopted: ["from", "to"],
68
- upstream_report: ["action", "report", "leaks", "via"],
69
- doctor_run: ["failing", "warnings"],
70
- pal_bug_signal: ["trigger", "surface", "verdict"],
71
- compaction: ["trigger", "withInstructions", "contextTokens"],
72
- context_injected: ["instructionsChars", "semiStaticChars", "dynamicChars"],
73
- hook_timing: ["hook", "totalMs", "handlers"],
74
- inference_call: [
75
- "caller",
76
- "route",
77
- "model",
78
- "tier",
79
- "web",
80
- "latencyMs",
81
- "failure",
82
- ...USAGE_FIELDS,
83
- ],
84
- judge_call: [
85
- "caller",
86
- "mode",
87
- "route",
88
- "provider",
89
- "model",
90
- "inputTokens",
91
- "costUsd",
92
- "latencyMs",
93
- "failure",
94
- "systemOneAnswers",
95
- "fallbackAnswers",
96
- ],
97
- pal_update: ["outcome", "from", "to", "durationSec", "skipReason"],
98
- memory_move: [
99
- "migration",
100
- "outcome",
101
- "entries",
102
- "files",
103
- "bytes",
104
- "manifest",
105
- "reason",
106
- "hashTotal",
107
- "archive",
108
- "lines",
109
- "kept",
110
- "differ",
111
- ],
112
- migration_run: [
113
- "migration",
114
- "outcome",
115
- "migrated",
116
- "skipped",
117
- "dryRun",
118
- "undo",
119
- "sweep",
120
- ],
121
- pal_heartbeat: ["outcome", "payload", "status", "skipReason"],
122
- commitment: ["iscProject", "isc", "outcome", "surface", "snoozeDays"],
123
- ticket: ["iscProject", "ticket", "status", "at", "since", "was"],
124
- entity_first_seen: ["domain", "entityType"],
125
- discord_nag: ["stage", "kind", "responseSec"],
126
- model_call: [
127
- "billing",
128
- "plan",
129
- "extraUsage",
130
- "model",
131
- "requestedModel",
132
- "provider",
133
- "inputTokens",
134
- "outputTokens",
135
- "cacheWrite5m",
136
- "cacheWrite1h",
137
- "cacheRead",
138
- "thinkingTokens",
139
- "thinkingMs",
140
- "webSearches",
141
- "webFetches",
142
- "serviceTier",
143
- "speed",
144
- "effort",
145
- "stopReason",
146
- "entrypoint",
147
- "sidechain",
148
- "costUsd",
149
- "agent",
150
- "mode",
151
- "durationMs",
152
- "ttftMs",
153
- "aiu",
154
- "initiator",
155
- "host",
156
- ],
157
- conversation: ["steps", "status", "depth", "subagent", "killed"],
158
- commit: [
159
- "hash",
160
- "committedAt",
161
- "files",
162
- "added",
163
- "deleted",
164
- "commitType",
165
- "breaking",
166
- "revert",
167
- "merge",
168
- "tags",
169
- "coAuthors",
170
- "aiCoAuthored",
171
- ],
172
- rating: ["rating", "source"],
173
- forgotten: ["target", "undone"],
174
- project: ["change", "status"],
175
- setting: ["key", "change"],
176
- rule_decision: ["rule", "decision"],
177
- calibration_label: ["deck", "item", "answer"],
178
- decision: ["words"],
179
- promise: ["change", "dueInSec", "lateSec", "snoozes", "nags"],
180
- action: [
181
- "tool",
182
- "outcome",
183
- "fileExt",
184
- "change",
185
- "linesAdded",
186
- "linesRemoved",
187
- "beforeBytes",
188
- "afterBytes",
189
- ],
190
- permission_prompt: ["tool"],
191
- notification: ["kind"],
192
- tool_call: [
193
- "tool",
194
- "outcome",
195
- "denial",
196
- "toolUseId",
197
- "promptWaitSec",
198
- "durationMs",
199
- "inputChars",
200
- "outputChars",
201
- "fileExt",
202
- "program",
203
- "skill",
204
- "subagent",
205
- "subagentTokens",
206
- "subagentTools",
207
- "mcpServer",
208
- "host",
209
- ],
210
- slurp_check: [
211
- "mode",
212
- "predicted",
213
- "oom",
214
- "hitCount",
215
- "maxBytes",
216
- "thresholdBytes",
217
- "idioms",
218
- ],
219
- compaction_near: [
220
- "mode",
221
- "trigger",
222
- "contextTokens",
223
- "windowTokens",
224
- "windowSource",
225
- "compactAtTokens",
226
- "tokensLeft",
227
- "marginTokens",
228
- "predicted",
229
- "idleMinTokens",
230
- ],
231
- algorithm_run: [
232
- "mode",
233
- "change",
234
- "run",
235
- "node",
236
- "turn",
237
- "phases",
238
- "header",
239
- "headerFirst",
240
- "startsNew",
241
- "verdict",
242
- "source",
243
- "runType",
244
- "wouldNudge",
245
- "exempt",
246
- ],
247
- minimum_run: [
248
- "change",
249
- "lens",
250
- "blocks",
251
- "rounds",
252
- "floorMin",
253
- "minutesLeft",
254
- "bar",
255
- "early",
256
- ],
257
- worktree_pruned: ["branch"],
258
- worktree_prune_failed: ["branch"],
259
- git_state_injected: ["trigger", "source", "changed", "committedFiles", "chars"],
260
- hook_run: ["hook", "event", "part", "durationMs", "exitCode"],
261
- repo_state: ["head", "branch", "changed", "ahead", "behind"],
262
- } as const satisfies Record<string, readonly string[]>;
263
-
264
- export type EventType = keyof typeof EVENT_FIELDS;
265
21
  // answers keep their probabilities: question → answer → probabilities
266
22
  const NESTING_DEPTH: Partial<Record<EventType, number>> = { judge_call: 2 };
267
23
  type EventValue =
@@ -6,11 +6,11 @@
6
6
 
7
7
  import { readdirSync } from "node:fs";
8
8
  import { resolve } from "node:path";
9
+ import type { EventType } from "./event-fields";
9
10
  import {
10
11
  allEventsSince,
11
12
  appendEvent,
12
13
  contentDir,
13
- type EventType,
14
14
  eventsSince,
15
15
  type LoggedEvent,
16
16
  parseLines,
@@ -27,7 +27,14 @@ export interface EvidenceTurn {
27
27
  project: string | null;
28
28
  text: string | null;
29
29
  pastedChars: number | null;
30
- reply: { id: string; text: string | null } | null;
30
+ reply: EvidenceReply | null;
31
+ }
32
+
33
+ interface EvidenceReply {
34
+ id: string;
35
+ text: string | null;
36
+ narration: string[];
37
+ thinking: string[];
31
38
  }
32
39
 
33
40
  export interface Exclusion {
@@ -50,6 +57,21 @@ export function contentById(): Map<string, ContentRow> {
50
57
  const textOf = (row: ContentRow | undefined, field: string): string | null =>
51
58
  typeof row?.[field] === "string" ? (row[field] as string) : null;
52
59
 
60
+ const textsOf = (row: ContentRow | undefined, field: string): string[] => {
61
+ const texts = row?.[field];
62
+
63
+ return Array.isArray(texts) ? texts.filter((t) => typeof t === "string") : [];
64
+ };
65
+
66
+ function replyOf(row: ContentRow | undefined, id: string): EvidenceReply {
67
+ return {
68
+ id,
69
+ text: textOf(row, "reply"),
70
+ narration: textsOf(row, "narration"),
71
+ thinking: textsOf(row, "thinking"),
72
+ };
73
+ }
74
+
53
75
  export function contentFor(id: string): ContentRow | null {
54
76
  return contentById().get(id) ?? null;
55
77
  }
@@ -80,6 +102,8 @@ export function userTurnsSince(since: Date): EvidenceTurn[] {
80
102
  const excluded = new Set(exclusions().map((e) => e.id));
81
103
  const textIfKept = (id: string, field: string) =>
82
104
  excluded.has(id) ? null : textOf(content.get(id), field);
105
+ const replyIfKept = (id: string) =>
106
+ replyOf(excluded.has(id) ? undefined : content.get(id), id);
83
107
 
84
108
  return ofType(events, "turn")
85
109
  .filter((e) => e.authority === "user" && !excluded.has(e.id))
@@ -95,7 +119,7 @@ export function userTurnsSince(since: Date): EvidenceTurn[] {
95
119
  project: turn.project,
96
120
  text: textIfKept(turn.id, "prompt"),
97
121
  pastedChars: typeof turn.pastedChars === "number" ? turn.pastedChars : null,
98
- reply: reply ? { id: reply.id, text: textIfKept(reply.id, "reply") } : null,
122
+ reply: reply ? replyIfKept(reply.id) : null,
99
123
  };
100
124
  });
101
125
  }
@@ -118,7 +118,7 @@ function entryId(entry: EntryIds): string | undefined {
118
118
  return id === undefined ? undefined : String(id);
119
119
  }
120
120
 
121
- function messageOfLine(line: string): Message | null {
121
+ export function messageOfLine(line: string): Message | null {
122
122
  try {
123
123
  const entry = JSON.parse(line);
124
124
  const message = parseTranscriptEntry(entry);
@@ -112,6 +112,9 @@ export function loginExpiryFindings(
112
112
  const MOVES_EXPLAINED =
113
113
  "they move your data, so they run only when you start them: PAL must be idle, a verified backup is taken first, every file is hash-checked, and pal cli migrate --undo <id> puts it back. PAL reads the old folders until then. PAL 1.0 needs every one of them";
114
114
 
115
+ const PLAIN_TERMINAL_ONLY =
116
+ "Close every agent session and the control room, wait 20 seconds, then run each one below from a plain terminal: an agent's own hooks keep PAL busy, so a move it starts is refused";
117
+
115
118
  function ownerMovesFinding(pending: PendingMigration[]): Finding[] {
116
119
  const count = pending.filter((migration) => migration.ownerRun).length;
117
120
  if (count === 0) return [];
@@ -122,7 +125,7 @@ function ownerMovesFinding(pending: PendingMigration[]): Finding[] {
122
125
  ...warning(
123
126
  "owner-migrations",
124
127
  `${moves} for you, required before PAL 1.0 — ${MOVES_EXPLAINED}`,
125
- { say: "Close your other agent sessions, then run each one below" }
128
+ { say: PLAIN_TERMINAL_ONLY }
126
129
  ),
127
130
  notice: `${moves} for you, required before PAL 1.0`,
128
131
  },
@@ -143,7 +146,11 @@ function pendingMigrationFindings(pending: PendingMigration[]): Finding[] {
143
146
  return warning(
144
147
  `owner-migration.${migration.id}`,
145
148
  `Waiting for you to run it: ${migration.description}`,
146
- { say: "Run it", command: `pal cli migrate ${migration.id}`, external: false }
149
+ {
150
+ say: "Run it from a plain terminal",
151
+ command: `pal cli migrate ${migration.id}`,
152
+ external: false,
153
+ }
147
154
  );
148
155
 
149
156
  return warning(
@@ -258,6 +258,21 @@ export function bindingFinding(issue: BindingIssue): Finding {
258
258
  return warning(`binding.${project}`, title, { say, command, external: false });
259
259
  }
260
260
 
261
+ /** Rebuild drops every binding the history lacks, so it is offered only when the file merely lost some. */
262
+ function driftFix(drift: BindingChange[]) {
263
+ const onlyInFile = drift.filter((d) => d.change === "bound").map((d) => d.project);
264
+ if (onlyInFile.length > 0)
265
+ return {
266
+ say: `Record the file's bindings in the history; a rebuild would drop ${onlyInFile.join(", ")}`,
267
+ command: "pal cli project bindings adopt",
268
+ };
269
+
270
+ return {
271
+ say: "Restore it from the history, or run `pal cli project bindings adopt` if you removed it on purpose",
272
+ command: "pal cli project bindings rebuild",
273
+ };
274
+ }
275
+
261
276
  /** A write that bypassed writeBindings left the file and its history apart; the history is what PAL itself wrote. */
262
277
  export function bindingDriftFinding(drift: BindingChange[]): Finding | null {
263
278
  if (drift.length === 0) return null;
@@ -266,11 +281,7 @@ export function bindingDriftFinding(drift: BindingChange[]): Finding | null {
266
281
  return warning(
267
282
  "bindings.drift",
268
283
  `bindings.json differs from its history in ${drift.length} binding(s): ${names}`,
269
- {
270
- say: "Rewrite it from the history, or run `pal cli project bindings adopt` if you changed it on purpose",
271
- command: "pal cli project bindings rebuild",
272
- external: false,
273
- }
284
+ { ...driftFix(drift), external: false }
274
285
  );
275
286
  }
276
287
 
@@ -12,7 +12,7 @@
12
12
 
13
13
  import { appendEvent, logQuietly } from "../bronze/events";
14
14
  import { LEFTOVERS, type Leftover } from "./leftovers";
15
- import type { Migration, MigrationResult } from "./migrations/migration";
15
+ import type { Migration, MigrationResult, RunOptions } from "./migrations/migration";
16
16
  import { v1Projects } from "./migrations/v1-projects";
17
17
  import { v2ThreadsToIsc } from "./migrations/v2-threads-to-isc";
18
18
  import { v3EntitiesToKnowledge } from "./migrations/v3-entities-to-knowledge";
@@ -145,7 +145,7 @@ function recorded(
145
145
  export function runRecorded(
146
146
  migration: Migration,
147
147
  dryRun: boolean,
148
- options: { force?: boolean } = {}
148
+ options: RunOptions = {}
149
149
  ): MigrationResult {
150
150
  return recorded(migration, { dryRun, undo: false }, () =>
151
151
  migration.run(dryRun, options)
@@ -299,7 +299,9 @@ function runNamed(id: string, dryRun: boolean, force: boolean): void {
299
299
  if (dryRun) console.log(" Dry run — no files will be written.\n");
300
300
  console.log(` Running: ${id} — ${migration.description}`);
301
301
 
302
- for (const line of runRecorded(migration, dryRun, { force }).results)
302
+ const printStep = (step: string) => console.log(` … ${step}`);
303
+
304
+ for (const line of runRecorded(migration, dryRun, { force, onStep: printStep }).results)
303
305
  console.log(` ${line}`);
304
306
  console.log("");
305
307
  }
@@ -2,17 +2,22 @@ import { existsSync } from "node:fs";
2
2
  import { paths } from "../../core/paths";
3
3
  import { type BackupReport, backupDataVerified } from "./data-backup";
4
4
  import { sweepLateWrites } from "./late-write-sweep";
5
- import type { MigrationResult } from "./migration";
6
- import { type GuardSeams, moveGuardRefusal } from "./move-guards";
5
+ import type { MigrationResult, RunOptions } from "./migration";
6
+ import { dataBytes, type GuardSeams, moveGuardRefusal } from "./move-guards";
7
7
  import { newestManifest, type PlannedMove } from "./move-manifest";
8
8
  import { moveVerified, previewMoves, undoVerifiedMove } from "./verified-move";
9
9
 
10
- export interface LayoutMoveOptions {
11
- force?: boolean;
10
+ export interface LayoutMoveOptions extends RunOptions {
12
11
  guardSeams?: Partial<GuardSeams>;
13
12
  backup?: () => BackupReport;
14
13
  }
15
14
 
15
+ const megabytes = (bytes: number) => `${Math.ceil(bytes / 1_000_000)} MB`;
16
+
17
+ function backupStep(): string {
18
+ return `Backing up ${megabytes(dataBytes())} of PAL data to ${paths.backups()} and checking every file in the copy; this can take a few minutes`;
19
+ }
20
+
16
21
  /** Moves whose source is still there and whose target is not: the work left to do. */
17
22
  export function movesLeft(moves: PlannedMove[]): PlannedMove[] {
18
23
  return moves.filter((move) => existsSync(move.from) && !existsSync(move.to));
@@ -69,12 +74,16 @@ export function runLayoutMove(
69
74
  if (dryRun)
70
75
  return { migrated: left.length, skipped: 0, results: [previewMoves(left).trim()] };
71
76
 
77
+ const step = options.onStep ?? (() => {});
78
+ step("Checking that PAL is idle and the disk has room");
72
79
  const guard = moveGuardRefusal(id, { force: options.force, seams: options.guardSeams });
73
80
  if (guard) return refusal([`refused: ${guard}`], left.length);
74
81
 
82
+ step(backupStep());
75
83
  const backup = (options.backup ?? backupDataVerified)();
76
84
  if (!backup.ok) return refusal(backupRefusal(backup), left.length);
77
85
 
86
+ step(`Moving ${left.length} path(s) and hash-checking every moved file`);
78
87
  const report = moveVerified(id, left);
79
88
  if (report.outcome !== "moved")
80
89
  return refusal(
@@ -6,11 +6,16 @@ export interface MigrationResult {
6
6
  results: string[];
7
7
  }
8
8
 
9
+ export interface RunOptions {
10
+ force?: boolean;
11
+ onStep?: (step: string) => void;
12
+ }
13
+
9
14
  export interface Migration {
10
15
  id: string;
11
16
  description: string;
12
17
  check(): { pending: boolean; detail?: string };
13
- run(dryRun?: boolean, options?: { force?: boolean }): MigrationResult;
18
+ run(dryRun?: boolean, options?: RunOptions): MigrationResult;
14
19
  /** Moves its sources rather than copying them, so there is nothing left to delete. */
15
20
  movesSources?: true;
16
21
  /** Moves recorded data: install never runs it; the owner names it to `pal cli migrate`. */
@@ -23,6 +23,7 @@ export interface GuardSeams {
23
23
  const BUSY_WINDOW_MS = 20_000;
24
24
  const TAIL_BYTES = 256 * 1024;
25
25
  const OWN_EVENT_TYPES = new Set(["memory_move", "migration_run"]);
26
+ const CLOSE_EVERYTHING = `Close every agent session and the control room, wait ${BUSY_WINDOW_MS / 1000} seconds, then run it again from a plain terminal; a move an agent starts is always refused, because its own hooks write to bronze`;
26
27
 
27
28
  function processIsAlive(pid: number): boolean {
28
29
  try {
@@ -85,11 +86,10 @@ function newestOutsideEvent(since: number): number | null {
85
86
  }
86
87
 
87
88
  function recentEventReason(seams: GuardSeams): string[] {
88
- const now = seams.now();
89
- const newest = newestOutsideEvent(now - BUSY_WINDOW_MS);
89
+ const newest = newestOutsideEvent(seams.now() - BUSY_WINDOW_MS);
90
90
  if (newest === null) return [];
91
91
 
92
- return [`a bronze event was written ${Math.round((now - newest) / 1000)}s ago`];
92
+ return [`PAL wrote to bronze in the last ${BUSY_WINDOW_MS / 1000} seconds`];
93
93
  }
94
94
 
95
95
  function pidIn(file: string): number | null {
@@ -132,10 +132,14 @@ export function sizeOf(dir: string): number {
132
132
  return filesUnder(dir).reduce((sum, file) => sum + statSync(file).size, 0);
133
133
  }
134
134
 
135
+ export function dataBytes(): number {
136
+ return paths.dataRoots().reduce((sum, root) => sum + sizeOf(root), 0);
137
+ }
138
+
135
139
  /** Why the filesystem holding the PAL home is too full for a backup plus its verify copy, or null. */
136
140
  export function diskShortfall(seams: Partial<GuardSeams> = {}): string | null {
137
141
  const all = { ...realSeams, ...seams };
138
- const needed = 2 * paths.dataRoots().reduce((sum, root) => sum + sizeOf(root), 0);
142
+ const needed = 2 * dataBytes();
139
143
  const free = all.freeBytes(palHome());
140
144
 
141
145
  return free < needed
@@ -152,7 +156,7 @@ export function moveGuardRefusal(
152
156
  if (busy.length > 0) {
153
157
  recordMemoryMove(name, { outcome: "refused", reason: "busy" }, { busy });
154
158
 
155
- return `PAL is in use: ${busy.join("; ")}`;
159
+ return `PAL is in use: ${busy.join("; ")}. ${CLOSE_EVERYTHING}`;
156
160
  }
157
161
 
158
162
  const shortfall = diskShortfall(options.seams);
@@ -1,15 +1,17 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { storeLocation } from "../../bronze/bronze";
4
- import { readBindings } from "../../core/project-bindings";
5
- import { adoptBindingsFile, hasBindingHistory } from "../../progress/binding-history";
4
+ import {
5
+ adoptUnrecordedBindings,
6
+ unrecordedBindings as bindingsWithNoEvent,
7
+ } from "../../progress/binding-history";
6
8
  import type { Migration, MigrationResult } from "./migration";
7
9
 
8
10
  /** Until the owner moves the stores into records/, install must not start that folder. */
9
11
  const recordsLayoutAdopted = () => existsSync(dirname(storeLocation("events")));
10
12
 
11
13
  const unrecordedBindings = () =>
12
- !recordsLayoutAdopted() || hasBindingHistory() ? 0 : Object.keys(readBindings()).length;
14
+ recordsLayoutAdopted() ? bindingsWithNoEvent().length : 0;
13
15
 
14
16
  export const v20BindingsIntoBronze: Migration = {
15
17
  id: "v20-bindings-into-bronze",
@@ -35,7 +37,7 @@ export const v20BindingsIntoBronze: Migration = {
35
37
  return {
36
38
  migrated: 1,
37
39
  skipped: 0,
38
- results: [`recorded ${adoptBindingsFile().length} binding(s)`],
40
+ results: [`recorded ${adoptUnrecordedBindings().length} binding(s)`],
39
41
  };
40
42
  },
41
43
  };
@@ -5,6 +5,7 @@
5
5
 
6
6
  import { progressSession } from "../progress/progress-session";
7
7
  import { scopeOf } from "../progress/progress-tree";
8
+ import { logDeadlineRun, logRunStarted } from "../safety/deadline-events";
8
9
  import { logMinimum } from "../safety/minimum-events";
9
10
  import { recordRunEstimate } from "../safety/run-estimates";
10
11
  import {
@@ -116,6 +117,7 @@ function endRun(kind: RunKind): number {
116
117
  const run = runOf(kind);
117
118
  if (!run) return noRun(kind);
118
119
  recordIfEndedUnfinished(run);
120
+ logDeadlineRun("ended", run);
119
121
  clearRun(run.scope);
120
122
  console.log(`Ended the ${kind} run that was due at ${untilLabel(run)}.`);
121
123
 
@@ -137,6 +139,7 @@ function startTimebox(values: {
137
139
  report: values.report,
138
140
  });
139
141
  writeRun(run);
142
+ logRunStarted(run);
140
143
  console.log(
141
144
  `Time box set: ends at ${untilLabel(run)}. After that only \`pal cli\` and report edits run.`
142
145
  );
@@ -180,6 +183,7 @@ function startUnattended(values: {
180
183
  rules: unattendedRules(isInGitRepo(process.cwd()), values.rule),
181
184
  });
182
185
  writeRun(withCurrentSession(run));
186
+ logRunStarted(run);
183
187
  console.log(describeRun(run));
184
188
 
185
189
  return 0;
@@ -189,8 +193,11 @@ function logEntry(text: string): number {
189
193
  const found = runOf("unattended");
190
194
  if (!found) return noRun("unattended");
191
195
  const run = withCurrentSession(found);
192
- writeRun({ ...run, log: [...run.log, { at: new Date().toISOString(), entry: text }] });
193
- console.log(`Logged (${run.log.length + 1} entries).`);
196
+ const now = new Date();
197
+ const logged = { ...run, log: [...run.log, { at: now.toISOString(), entry: text }] };
198
+ writeRun(logged);
199
+ logDeadlineRun("logged", logged, now, { entry: text });
200
+ console.log(`Logged (${logged.log.length} entries).`);
194
201
 
195
202
  return 0;
196
203
  }
@@ -200,7 +207,9 @@ function markDone(): number {
200
207
  if (!found) return noRun("unattended");
201
208
  const run = withCurrentSession(found);
202
209
  if (!run.done) recordFinished(run);
203
- writeRun({ ...run, done: true });
210
+ const finished = { ...run, done: true };
211
+ writeRun(finished);
212
+ logDeadlineRun("done", finished);
204
213
  console.log("Marked done: the agent may stop. The run ends when the user is back.");
205
214
 
206
215
  return 0;
@@ -33,6 +33,7 @@ import { assets, ensureDir, paths } from "../../core/paths";
33
33
  import { spawnDetachedInference } from "../../inference/detached-inference";
34
34
  import { transcriptLines } from "../../opinions/claim-log";
35
35
  import { recordReply } from "../../opinions/interaction";
36
+ import { messagesNarration, turnNarration } from "../../opinions/turn-narration";
36
37
  import {
37
38
  recordAlgorithmTurnQuietly,
38
39
  type TurnLines,
@@ -182,13 +183,15 @@ export async function runStopHandlers(
182
183
  // Cache last assistant response (session-scoped)
183
184
  cacheLastResponse(messages, options.lastAssistantMessage, options.sessionId);
184
185
 
185
- if (options.sessionId) recordFinalReply(messages, options.sessionId);
186
+ const turnLines = readOnce(options.turnLines);
187
+
188
+ if (options.sessionId) recordFinalReply(messages, options.sessionId, turnLines);
186
189
 
187
190
  recordAlgorithmTurnQuietly(
188
191
  options.sessionId,
189
192
  turnTexts(messages),
190
193
  "transcript",
191
- options.turnLines
194
+ turnLines
192
195
  );
193
196
 
194
197
  // Always persist last exchange — drives CompactRecover + "Pick Up Where You Left Off"
@@ -297,10 +300,31 @@ function cacheLastResponse(
297
300
  }
298
301
  }
299
302
 
300
- function recordFinalReply(messages: Message[], sessionId: string): void {
303
+ /** The transcript tail is read at most once per stop, by whichever handler asks first. */
304
+ function readOnce(turnLines: TurnLines | undefined): TurnLines {
305
+ let read: { lines: readonly string[] | null } | undefined;
306
+
307
+ return () => {
308
+ read ??= { lines: turnLines?.() ?? null };
309
+
310
+ return read.lines;
311
+ };
312
+ }
313
+
314
+ function recordFinalReply(
315
+ messages: Message[],
316
+ sessionId: string,
317
+ turnLines: TurnLines
318
+ ): void {
301
319
  try {
302
320
  const reply = extractContent(extractLastAssistant(messages));
303
- recordReply(sessionId, reply);
321
+ const lines = turnLines();
322
+ recordReply(
323
+ sessionId,
324
+ reply,
325
+ new Date(),
326
+ lines ? turnNarration(lines, reply) : messagesNarration(messages, reply)
327
+ );
304
328
  acknowledgeMentioned(reply);
305
329
  } catch (err) {
306
330
  logError("runStopHandlers:recordReply", err);
@@ -3,7 +3,8 @@
3
3
  * model answered, how long it took and how it ended.
4
4
  */
5
5
 
6
- import { appendEvent, logQuietly, USAGE_FIELDS } from "../bronze/events";
6
+ import { USAGE_FIELDS } from "../bronze/event-fields";
7
+ import { appendEvent, logQuietly } from "../bronze/events";
7
8
  import type { InferenceUsage } from "./inference-usage";
8
9
 
9
10
  interface InferenceCall {
@@ -45,6 +45,7 @@ import {
45
45
  } from "./interaction-reaction";
46
46
  import { keepSample, replyEnd } from "./interaction-samples";
47
47
  import { responseModeOf, turnExtras } from "./turn-extras";
48
+ import { NO_NARRATION, type TurnNarration } from "./turn-narration";
48
49
 
49
50
  interface ReplyShape {
50
51
  at: string;
@@ -183,7 +184,8 @@ function logReply(
183
184
  session: string,
184
185
  reply: string,
185
186
  shape: ReplyShape,
186
- track: SessionTrack
187
+ track: SessionTrack,
188
+ { narration, thinking }: TurnNarration
187
189
  ) {
188
190
  const { at, ...features } = shape;
189
191
  logQuietly("reply", () =>
@@ -194,8 +196,10 @@ function logReply(
194
196
  mode: responseModeOf(reply),
195
197
  latencySec: secondsBetween(track.lastPromptAt, new Date(at)),
196
198
  turn: track.lastTurnId ?? null,
199
+ narrationBlocks: narration.length,
200
+ thinkingBlocks: thinking.length,
197
201
  },
198
- { ts: at, session, content: { reply } }
202
+ { ts: at, session, content: { reply, narration, thinking } }
199
203
  )
200
204
  );
201
205
  }
@@ -324,12 +328,13 @@ export function lastTurnIdOf(session: string): string | null {
324
328
  export function recordReply(
325
329
  session: string,
326
330
  reply: string,
327
- now: Date = new Date()
331
+ now: Date = new Date(),
332
+ working: TurnNarration = NO_NARRATION
328
333
  ): void {
329
334
  if (!session || !reply.trim() || !isEnabled("interactionAwareness")) return;
330
335
  const track = trackOf(session);
331
336
  const shape = replyShape(reply, now);
332
- logReply(session, reply, shape, track);
337
+ logReply(session, reply, shape, track, working);
333
338
  writeTrack(session, {
334
339
  ...track,
335
340
  updated: now.toISOString(),
@@ -0,0 +1,88 @@
1
+ /**
2
+ * What an agent wrote while it worked on a turn: its text between tool calls and
3
+ * its non-empty thinking summaries, read from the turn's own transcript lines.
4
+ * The final reply is recorded on its own, so it is left out here.
5
+ */
6
+
7
+ import { extractContent, type Message, messageOfLine } from "../bronze/transcript";
8
+ import { isPromptLine } from "./claim-check";
9
+
10
+ export interface TurnNarration {
11
+ narration: string[];
12
+ thinking: string[];
13
+ }
14
+
15
+ export const NO_NARRATION: TurnNarration = { narration: [], thinking: [] };
16
+
17
+ interface WorkingEntry {
18
+ type?: string;
19
+ isSidechain?: boolean;
20
+ message?: { content?: unknown };
21
+ payload?: { summary?: { text?: unknown }[] };
22
+ }
23
+
24
+ function entryOf(line: string): WorkingEntry | null {
25
+ try {
26
+ return JSON.parse(line);
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ const stringsIn = (field: string, items: unknown): string[] =>
33
+ Array.isArray(items)
34
+ ? items.flatMap((item) => (typeof item?.[field] === "string" ? [item[field]] : []))
35
+ : [];
36
+
37
+ /** Only Claude's thinking blocks carry `thinking`, and only Codex's reasoning items a `summary`. */
38
+ function thinkingOf(entry: WorkingEntry): string[] {
39
+ return [
40
+ ...stringsIn("thinking", entry.message?.content),
41
+ ...stringsIn("text", entry.payload?.summary),
42
+ ];
43
+ }
44
+
45
+ function assistantTextOf(line: string): string[] {
46
+ const message = messageOfLine(line);
47
+
48
+ return message?.role === "assistant" ? [extractContent(message)] : [];
49
+ }
50
+
51
+ const nonEmpty = (texts: string[]) => texts.filter((text) => text.trim().length > 0);
52
+
53
+ /** The main agent's lines after the turn's prompt; a subagent's lines are its own work. */
54
+ function turnOf(lines: readonly string[]): string[] {
55
+ const start = lines.findLastIndex(isPromptLine);
56
+
57
+ return lines.slice(start + 1).filter((line) => entryOf(line)?.isSidechain !== true);
58
+ }
59
+
60
+ function withoutFinalReply(texts: string[], finalReply: string): string[] {
61
+ return texts.at(-1)?.trim() === finalReply.trim() ? texts.slice(0, -1) : texts;
62
+ }
63
+
64
+ /** For an agent that hands over only parsed messages (opencode): no thinking, text alone. */
65
+ export function messagesNarration(
66
+ messages: Message[],
67
+ finalReply: string
68
+ ): TurnNarration {
69
+ const prompt = messages.findLastIndex((m) => m.role === "user");
70
+ const texts = messages
71
+ .slice(prompt + 1)
72
+ .filter((m) => m.role === "assistant")
73
+ .map(extractContent);
74
+
75
+ return { narration: withoutFinalReply(nonEmpty(texts), finalReply), thinking: [] };
76
+ }
77
+
78
+ export function turnNarration(
79
+ lines: readonly string[],
80
+ finalReply: string
81
+ ): TurnNarration {
82
+ const turn = turnOf(lines);
83
+
84
+ return {
85
+ narration: withoutFinalReply(nonEmpty(turn.flatMap(assistantTextOf)), finalReply),
86
+ thinking: nonEmpty(turn.flatMap((line) => thinkingOf(entryOf(line) ?? {}))),
87
+ };
88
+ }
@@ -31,6 +31,22 @@ export function hasBindingHistory(home: string = palHome()): boolean {
31
31
  return bindingEventsOfThisMachine(home).length > 0;
32
32
  }
33
33
 
34
+ /** Bindings in the file for projects no event on this machine mentions; a project with history is drift, not this. */
35
+ export function unrecordedBindings(home: string = palHome()): BindingChange[] {
36
+ const recorded = new Set(bindingEventsOfThisMachine(home).map((e) => e.project));
37
+
38
+ return Object.entries(readBindings(home))
39
+ .filter(([project]) => !recorded.has(project))
40
+ .map(([project, path]): BindingChange => ({ project, change: "bound", path }));
41
+ }
42
+
43
+ export function adoptUnrecordedBindings(home: string = palHome()): BindingChange[] {
44
+ const unrecorded = unrecordedBindings(home);
45
+ logBindingChanges(unrecorded);
46
+
47
+ return unrecorded;
48
+ }
49
+
34
50
  /** The bindings this machine's events leave behind, oldest event first. */
35
51
  export function replayedBindings(home: string = palHome()): Bindings {
36
52
  const text = contentById();
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Each step of a time box or an unattended run, as one `deadline_run` event:
3
+ * the start, every log entry, every stop it sent back, done and the end. The
4
+ * task, tasks, rules and log text go to the content store, so the run file is
5
+ * only a cache once the run ends.
6
+ */
7
+
8
+ import { appendEvent, logQuietly } from "../bronze/events";
9
+ import { minutesLeft, type Run } from "./run-mode";
10
+
11
+ export type DeadlineChange = "started" | "logged" | "blocked" | "done" | "ended";
12
+
13
+ export function logDeadlineRun(
14
+ change: DeadlineChange,
15
+ run: Run,
16
+ now: Date = new Date(),
17
+ content?: Record<string, unknown>
18
+ ): void {
19
+ logQuietly("deadline_run", () =>
20
+ appendEvent(
21
+ "deadline_run",
22
+ {
23
+ kind: run.kind,
24
+ change,
25
+ blocks: run.stopBlocks,
26
+ logEntries: run.log.length,
27
+ minutesLeft: minutesLeft(run, now),
28
+ estimateMin: run.estimateMinutes ?? null,
29
+ done: run.done,
30
+ },
31
+ { ts: now.toISOString(), ...(content && { content }) }
32
+ )
33
+ );
34
+ }
35
+
36
+ export function logRunStarted(run: Run, now: Date = new Date()): void {
37
+ const { task, report, tasks, fallbacks, rules, until } = run;
38
+ logDeadlineRun("started", run, now, { task, report, tasks, fallbacks, rules, until });
39
+ }
@@ -8,6 +8,7 @@
8
8
  import { resolve } from "node:path";
9
9
  import { replyAsks } from "../opinions/interaction";
10
10
  import { scopeOf } from "../progress/progress-tree";
11
+ import { logDeadlineRun } from "./deadline-events";
11
12
  import { logMinimum } from "./minimum-events";
12
13
  import { floorReachedMessage, minimumStopReason, nextLensName } from "./minimum-prompt";
13
14
  import {
@@ -131,7 +132,9 @@ export function unattendedStopReason(cwd: string, now: Date = new Date()): strin
131
132
  if (run?.kind !== "unattended" || run.done) return null;
132
133
 
133
134
  if (run.stopBlocks >= MAX_STOP_BLOCKS) return null;
134
- writeRun({ ...run, stopBlocks: run.stopBlocks + 1 });
135
+ const blocked = { ...run, stopBlocks: run.stopBlocks + 1 };
136
+ writeRun(blocked);
137
+ logDeadlineRun("blocked", blocked, now);
135
138
 
136
139
  return stopMessage(run, now);
137
140
  }
@@ -1,5 +1,6 @@
1
1
  import { existsSync } from "node:fs";
2
- import { type EventType, eventMonthFile } from "../../../bronze/events";
2
+ import type { EventType } from "../../../bronze/event-fields";
3
+ import { eventMonthFile } from "../../../bronze/events";
3
4
  import { transcriptLines } from "../../../bronze/transcript-lines";
4
5
 
5
6
  type KeyOf = (event: Record<string, unknown>) => string;
@@ -4,12 +4,8 @@
4
4
  * API-price cost.
5
5
  */
6
6
 
7
- import {
8
- allEventsSince,
9
- type EventType,
10
- type LoggedEvent,
11
- loggedEventIds,
12
- } from "../../bronze/events";
7
+ import type { EventType } from "../../bronze/event-fields";
8
+ import { allEventsSince, type LoggedEvent, loggedEventIds } from "../../bronze/events";
13
9
  import { collectInChildProcess } from "../../hooks/lib/collect-trigger";
14
10
  import { scopeOf } from "../../progress/progress-tree";
15
11
  import { backfillGit } from "./backfill/git";
@@ -1,4 +1,5 @@
1
- import { allEventsSince, type EventType, type LoggedEvent } from "../../../bronze/events";
1
+ import type { EventType } from "../../../bronze/event-fields";
2
+ import { allEventsSince, type LoggedEvent } from "../../../bronze/events";
2
3
  import { localDay } from "../../../core/wall-clock";
3
4
 
4
5
  export function dayOf(event: LoggedEvent): string {