@staix/agent-hub 0.40.0 → 0.42.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.
package/src/cli/main.ts CHANGED
@@ -2857,7 +2857,8 @@ const commands: Record<string, () => Promise<void> | void> = {
2857
2857
  if (!result.ready) process.exitCode = 1;
2858
2858
  return;
2859
2859
  }
2860
- try { console.log(await memoryCommand(args, cwd, { person: caller.role === "console" })); } catch (e) { fail((e as Error).message); }
2860
+ // #1522: an agent shell runs this as itself; its peer id, not the person, is what amem records for a change.
2861
+ try { console.log(await memoryCommand(args, cwd, { person: caller.role === "console", ...(caller.role === "tools" ? { agent: caller.peer } : {}) })); } catch (e) { fail((e as Error).message); }
2861
2862
  },
2862
2863
  goal: async () => {
2863
2864
  // #258: long-term tasks; a link goes through the project's hub, so Tasks validates the board task.
package/src/cli/memory.ts CHANGED
@@ -12,7 +12,8 @@ import { foldSegment } from "../hub/permission-mode.ts";
12
12
  import { matchesPolicyLexically } from "../hub/path-policy.ts";
13
13
  import { memoryAnchorTaskIdentity, memoryStaleAnchors, unavailableMemoryStaleAnchors, type MemoryStaleAnchorReport, type MemoryTaskPrivacy } from "../hub/memory-stale-anchors.ts";
14
14
  import { MEMORY_SYMBOL_START_BUDGET_MS } from "../hub/memory-symbols.ts";
15
- import { detectCliIdentity } from "./identity.ts";
15
+ import { AGENT_MEMORY_RECORDING_SUBS, detectCliIdentity } from "./identity.ts";
16
+ import { withAgentAttribution } from "./agent-attribution.ts";
16
17
  import { createStalenessProbe } from "../hub/memory-staleness.ts";
17
18
  import { looksSecret, memoryHome, memoryProjectKey, pathCandidates, readProfileJSON, resolveShardProfile, type MemoryStore } from "@staix/agent-mem";
18
19
  import type { SyncOptions } from "@staix/agent-mem";
@@ -111,6 +112,9 @@ function commandStores(provided: MemoryStore | undefined, options: ProfileMemory
111
112
  try { return { ...(provided ? bindProfileMemory(provided, undefined, memoryProjectKey(cwd)) : openProfileMemory(options)), owned: !provided }; }
112
113
  catch (error) { throw new Error(error instanceof Error && error.message === MEMORY_SPLIT_INCOMPLETE ? error.message : MEMORY_PROFILE_UNAVAILABLE); }
113
114
  }
115
+ /** What a JSON receipt may carry for an agent (#1522): the kind, state and generation prefix, never the home path, selector, version or skip totals the person sees. */
116
+ const shownReceipt = (profile: MemoryProfileReceipt | undefined, person: boolean) =>
117
+ person || !profile ? profile : { profile: profile.profile, state: profile.state, ...(profile.generation ? { generation: profile.generation.slice(0, 8) } : {}) };
114
118
  function profileOutput(text: string, json: boolean, profile: MemoryProfileReceipt | undefined, person: boolean): string {
115
119
  if (!profile) return text;
116
120
  if (profile.state !== "ready") throw new Error(MEMORY_PROFILE_UNAVAILABLE);
@@ -119,12 +123,23 @@ function profileOutput(text: string, json: boolean, profile: MemoryProfileReceip
119
123
  }
120
124
 
121
125
  /** Hub wrapper: current project policy and TTL stay here; parsing and storage commands belong to the core. */
122
- export async function memoryCommand(args: string[], cwd: string, opts: { store?: MemoryStore; sync?: Omit<SyncOptions, "remote">; now?: () => number; person?: boolean } = {}): Promise<string> {
126
+ export async function memoryCommand(args: string[], cwd: string, opts: { store?: MemoryStore; sync?: Omit<SyncOptions, "remote">; now?: () => number; person?: boolean; /** The agent shell's peer id (#1522): its changes are recorded under this name. */ agent?: string } = {}): Promise<string> {
123
127
  const person = opts.person ?? detectCliIdentity(process.env).role === "console";
128
+ const sub = args.find(arg => arg !== "--json");
129
+ // #1522: an agent runs the family as itself. The recording commands run inside amem's agent attribution, so every writer stamps the agent (never "user")
130
+ // and amem applies its screened-visibility checks to each target; with no agent peer id, or no way to attribute, a change is refused rather than run as the person.
131
+ if (!person && sub !== undefined && AGENT_MEMORY_RECORDING_SUBS.includes(sub)) {
132
+ const peer = opts.agent ?? (() => { const identity = detectCliIdentity(process.env); return identity.role === "tools" ? identity.peer : undefined; })();
133
+ if (peer === undefined) fail(`memory ${sub} changes memory and needs an identified agent or the person; no agent identity was found, so nothing was run`);
134
+ return withAgentAttribution(peer!, cwd, () => memoryCommandBody(args, cwd, opts, person));
135
+ }
136
+ return memoryCommandBody(args, cwd, opts, person);
137
+ }
138
+
139
+ async function memoryCommandBody(args: string[], cwd: string, opts: { store?: MemoryStore; sync?: Omit<SyncOptions, "remote">; now?: () => number }, person: boolean): Promise<string> {
124
140
  const privatePaths = (): string[] => { try { return loadConfig(cwd).pii?.paths ?? []; } catch (e) { return fail(`the project's config does not load (${(e as Error).message}); fix it before reading hub memory`); } };
125
141
  const rest = args.filter(arg => arg !== "--json");
126
142
  if (rest[0] === "decay") {
127
- if (!person) fail("memory decay requires person authority");
128
143
  let days = 90;
129
144
  if (rest.length !== 1) {
130
145
  if (rest.length !== 3 || rest[1] !== "--days" || !/^[1-9][0-9]*$/.test(rest[2]!)) fail("usage: ahub memory decay [--days N] [--json] (N must be a positive integer)");
@@ -149,7 +164,8 @@ export async function memoryCommand(args: string[], cwd: string, opts: { store?:
149
164
  && !note.about.some(node => openGoals.has(node) || (node.startsWith("task:") && linkedTasks.has(node.slice(5))))), routing, cwd, paths);
150
165
  });
151
166
  const profile = context.binding.status(store);
152
- if (args.includes("--json")) return profileOutput(JSON.stringify({ days, cutoff, candidates, memoryProfile: profile }), true, profile, person);
167
+ // #1522: decay is open to an agent, so its JSON carries only the receipt an agent may see.
168
+ if (args.includes("--json")) return profileOutput(JSON.stringify({ days, cutoff, candidates, memoryProfile: shownReceipt(profile, person) }), true, profile, person);
153
169
  const text = candidates.length
154
170
  ? [`${candidates.length} decay candidate${candidates.length === 1 ? "" : "s"} older than ${days} days (review only):`, ...candidates.map(note => `mem:${note.id} ${note.at} ${note.kind}: ${note.title ?? note.text}`)].join("\n")
155
171
  : `no decay candidates older than ${days} days`;
@@ -157,7 +173,6 @@ export async function memoryCommand(args: string[], cwd: string, opts: { store?:
157
173
  } finally { if (context.owned) store.close(); }
158
174
  }
159
175
  if (rest[0] === "declined") {
160
- if (!person) fail("memory declined requires person authority");
161
176
  if (rest.length !== 1) fail("usage: ahub memory declined [--json]");
162
177
  const project = projectOf(cwd, opts.store);
163
178
  const context = commandStores(opts.store, { project, deferPromotions: true, now: opts.now }, cwd);
@@ -175,7 +190,7 @@ export async function memoryCommand(args: string[], cwd: string, opts: { store?:
175
190
  const profile = context.binding.status(context.store);
176
191
  if (hostSyncPolicyInputs(cwd, context.binding.home, project, profile).version !== boundPolicy.version)
177
192
  fail("memory declined policy changed during inspection; retry with stable privacy policy");
178
- if (args.includes("--json")) return JSON.stringify({ rows: result.rows, complete: result.complete, ...(result.reason ? { reason: result.reason } : {}), memoryProfile: profile });
193
+ if (args.includes("--json")) return JSON.stringify({ rows: result.rows, complete: result.complete, ...(result.reason ? { reason: result.reason } : {}), memoryProfile: shownReceipt(profile, person) });
179
194
  const text = result.complete
180
195
  ? result.rows.length
181
196
  ? [`${result.rows.length} declined physical outbound row${result.rows.length === 1 ? "" : "s"}:`, ...result.rows.map(row => `mem:${row.id} ${row.rule}`), "Review the source or approved policy, then run `ahub memory sync`. `forget` does not remove append-only physical rows."].join("\n")
@@ -0,0 +1,60 @@
1
+ import { PreEffectToolRefusal } from "./tool-refusal.ts";
2
+
3
+ /**
4
+ * #1331: the optional structured fields of `hub_checkpoint`, next to the free-text `summary` (kept for compatibility).
5
+ * The order below is the fixed order they render in, in the handoff prompt to the next owner and in the private context-checkpoint
6
+ * file. A field the caller left out is omitted, never invented. A field over its limit is refused with the limit named, never cut.
7
+ */
8
+ export const CHECKPOINT_FIELDS = ["done", "in_progress", "next", "verified_by", "traps"] as const;
9
+ export type CheckpointField = (typeof CHECKPOINT_FIELDS)[number];
10
+ export type CheckpointFields = Partial<Record<CheckpointField, string>>;
11
+
12
+ /** The heading each field renders under, and the heading the checkpoint request asks the agent to use in `.agenthub/checkpoint.md`. */
13
+ export const CHECKPOINT_HEADINGS: Record<CheckpointField, string> = { done: "Done", in_progress: "In progress", next: "Next", verified_by: "Verified by", traps: "Traps" };
14
+
15
+ /** Each field: at most this many lines of at most this many characters. */
16
+ export const CHECKPOINT_FIELD_MAX_LINES = 5;
17
+ export const CHECKPOINT_FIELD_MAX_LINE_CHARS = 200;
18
+ /**
19
+ * The rendered text (summary and fields together) stays within what a handoff keeps today: `Tasks.sendTask` slices the handoff context
20
+ * to 3000 characters, so a longer structured checkpoint would lose its last field (`traps`) silently. A summary-only call keeps its
21
+ * existing behavior and is not held to this number.
22
+ */
23
+ export const CHECKPOINT_TOTAL_MAX_CHARS = 3000;
24
+
25
+ const chars = (text: string): number => [...text].length;
26
+
27
+ /** The structured fields of one call, validated. Throws `PreEffectToolRefusal` (nothing is written yet) naming the field and the limit. */
28
+ export function parseCheckpointFields(args: Record<string, unknown>): CheckpointFields {
29
+ const out: CheckpointFields = {};
30
+ for (const name of CHECKPOINT_FIELDS) {
31
+ const raw = args[name];
32
+ if (raw === undefined || raw === null) continue;
33
+ if (typeof raw !== "string") throw new PreEffectToolRefusal(`checkpoint field ${name} must be a string`);
34
+ const value = raw.replace(/\r\n?/g, "\n").trim();
35
+ if (!value) continue;
36
+ const lines = value.split("\n");
37
+ if (lines.length > CHECKPOINT_FIELD_MAX_LINES) throw new PreEffectToolRefusal(`checkpoint field ${name} has ${lines.length} lines; the limit is ${CHECKPOINT_FIELD_MAX_LINES} lines`);
38
+ const long = lines.findIndex(line => chars(line) > CHECKPOINT_FIELD_MAX_LINE_CHARS);
39
+ if (long >= 0) throw new PreEffectToolRefusal(`checkpoint field ${name} line ${long + 1} has ${chars(lines[long]!)} characters; the limit is ${CHECKPOINT_FIELD_MAX_LINE_CHARS} characters per line`);
40
+ out[name] = value;
41
+ }
42
+ return out;
43
+ }
44
+
45
+ /** How many structured fields a checkpoint carried (0 for a summary-only call). */
46
+ export const checkpointFieldCount = (fields: CheckpointFields): number => CHECKPOINT_FIELDS.filter(name => fields[name] !== undefined).length;
47
+
48
+ /**
49
+ * The summary first, as written, then each present field in the fixed order under its heading. With no field the result is the summary
50
+ * unchanged, byte for byte. With fields, a total over `CHECKPOINT_TOTAL_MAX_CHARS` is refused (never truncated).
51
+ */
52
+ export function renderCheckpoint(summary: string, fields: CheckpointFields): string {
53
+ if (checkpointFieldCount(fields) === 0) return summary;
54
+ const text = [summary, ...CHECKPOINT_FIELDS.filter(name => fields[name] !== undefined).map(name => `${CHECKPOINT_HEADINGS[name]}:\n${fields[name]}`)].join("\n\n");
55
+ if (chars(text) > CHECKPOINT_TOTAL_MAX_CHARS) throw new PreEffectToolRefusal(`checkpoint is ${chars(text)} characters with its fields; the limit is ${CHECKPOINT_TOTAL_MAX_CHARS} characters in total`);
56
+ return text;
57
+ }
58
+
59
+ /** The sentence the checkpoint requests and the tool description use to name the fields, in the render order. */
60
+ export const CHECKPOINT_FIELDS_SENTENCE = `Optional structured fields, each at most ${CHECKPOINT_FIELD_MAX_LINES} lines of ${CHECKPOINT_FIELD_MAX_LINE_CHARS} characters: ${CHECKPOINT_FIELDS.map(name => `${name} (${CHECKPOINT_HEADINGS[name].toLowerCase()})`).join(", ")}. Use the same headings in .agenthub/checkpoint.md.`;
@@ -26,9 +26,23 @@ type Entry = { watch: CiWatch; timer?: ReturnType<typeof setTimeout>; reported?:
26
26
  */
27
27
  const DEFERRED_ON_DRAFT: readonly string[] = ["check (macos-latest)"];
28
28
 
29
+ /** A ready run's shards can appear before its aggregate; only later, same-workflow running shards fence the old deferred failure. */
30
+ function awaitingDeferredReplacement(check: Record<string, unknown>, rows: readonly Record<string, unknown>[]): boolean {
31
+ const name = check.name;
32
+ if (typeof name !== "string" || !DEFERRED_ON_DRAFT.includes(name) || check.conclusion !== "FAILURE") return false;
33
+ const workflow = check.workflowName, at = typeof check.startedAt === "string" ? Date.parse(check.startedAt) : NaN;
34
+ if (typeof workflow !== "string" || !workflow || !Number.isFinite(at)) return false;
35
+ const prefix = `${name} shard `;
36
+ return rows.some(row => typeof row.name === "string" && row.name.startsWith(prefix)
37
+ && /^\d+\/\d+$/.test(row.name.slice(prefix.length)) && row.workflowName === workflow
38
+ && (row.status === "QUEUED" || row.status === "IN_PROGRESS")
39
+ && typeof row.startedAt === "string" && Date.parse(row.startedAt) > at);
40
+ }
41
+
29
42
  /**
30
43
  * One read of the PR: the head, its state and the required checks of that head. A failed or unreadable read is `pending`; the deadline bounds the retries.
31
44
  * #1490: a cancelled check (a superseded run, or the draft run that `gh pr ready` replaces) and a draft PR's deferred macOS check are `pending`, never `failed`: nobody has to fix them.
45
+ * After a PR becomes ready, a later same-workflow macOS shard also keeps the older aggregate pending until the replacement aggregate appears.
32
46
  * A cancelled run of an older head never gets here (the head differs: `superseded`).
33
47
  */
34
48
  export async function pollCi(target: { repo: string; pr: number }, head: string, required: readonly string[], run: SdlcGh): Promise<CiPoll> {
@@ -42,9 +56,10 @@ export async function pollCi(target: { repo: string; pr: number }, head: string,
42
56
  if (body?.headRefOid !== head) return "superseded";
43
57
  if (body.state !== "OPEN") return "closed";
44
58
  const draft = body.isDraft === true;
45
- const rollup = Array.isArray(body.statusCheckRollup) ? latestCheckRuns(body.statusCheckRollup as Record<string, unknown>[]).map((check: Record<string, unknown>) => {
59
+ const allRows: Record<string, unknown>[] = Array.isArray(body.statusCheckRollup) ? body.statusCheckRollup : [];
60
+ const rollup = Array.isArray(body.statusCheckRollup) ? latestCheckRuns(allRows).map((check: Record<string, unknown>) => {
46
61
  const native = String(check?.conclusion ?? check?.state ?? "");
47
- return native === "CANCELLED" || draft && DEFERRED_ON_DRAFT.includes(String(check?.name ?? check?.context)) && native !== "SUCCESS" ? { ...check, status: "PENDING" } : check;
62
+ return native === "CANCELLED" || draft && DEFERRED_ON_DRAFT.includes(String(check?.name ?? check?.context)) && native !== "SUCCESS" || awaitingDeferredReplacement(check, allRows) ? { ...check, status: "PENDING" } : check;
48
63
  }) : body.statusCheckRollup;
49
64
  // The same check-state mapping as every other PR read; files are not requested here.
50
65
  const evidence = parsePrEvidence({ ...body, statusCheckRollup: rollup, files: [], changedFiles: 0 });
@@ -196,7 +196,7 @@ const schema: Record<string, Check> = {
196
196
  adapters: v => { createProjectAdapterCatalog(v); }, instances: v => { validateInstances(v, createProjectAdapterCatalog()); }, pet: validatePetConfig,
197
197
  batch_max: number(1, 100_000, true), batch_ms: number(0, 2_147_483_647), queue_cap: number(1, 1_000_000, true),
198
198
  memory: block({ enabled: bool, worker_url: text, inject_tokens: number(0, 1_000_000, true), brief_items: number(0, 10_000, true), native: bool,
199
- short_ttl_days: number(1, 3650, true), sync_interval_min: number(0, 1440, true), suggest_edges: bool }),
199
+ short_ttl_days: number(1, 3650, true), sync_interval_min: number(0, 1440, true), suggest_edges: bool, preface_unused_after: number(0, 100_000, true) }),
200
200
  roster: peerMap(bool), roles: map(strings), planner: words(PLANNER_PEERS), profile: words(["dev", "research", "writing", "general"]),
201
201
  profile_overrides: (v, k) => { map(() => {})(v, k); const fields = object(v, k); for (const name of ["classes", "role_text", "catalog_roles"]) if (fields[name] !== undefined) map(() => {})(fields[name], `${k}.${name}`); resolveProfile("dev", v); },
202
202
  catalog_roles: (v, k) => { map(() => {})(v, k); catalogAssignments(v); },
@@ -282,7 +282,7 @@ const restart: Record<string, string> = {
282
282
  text_projection: "Converter and cache ownership are bound at startup", corpus: "The corpus index is bound to its roots at startup", terminal: "Terminal provider is supplied by the daemon lifecycle", bench: "Benchmark execution environment is selected before work starts",
283
283
  };
284
284
  const live = new Set(["visuals", "action_policy", "permission", "roster", "roles", "planner", "conductor", "protect_instruction_files", "task_sweep", "capabilities", "invocation", "research", "snapshots", "worktrees", "tasks.wip_limits", "tasks.escalate_after", "tasks.auto_pull", "tasks.queue_backpressure", "schedules", "approvals.notify", "questions", "pet", "specs", "supervision"]);
285
- const nextMemory = new Set(["memory.inject_tokens", "memory.brief_items", "memory.suggest_edges"]);
285
+ const nextMemory = new Set(["memory.inject_tokens", "memory.brief_items", "memory.suggest_edges", "memory.preface_unused_after"]);
286
286
  /** Closed top-level schema; leaf overrides retain the existing session/runtime boundaries. */
287
287
  export function configApply(key: string, scopes: readonly ConfigIdentityScope[] = []): ApplyRule {
288
288
  const top = key.split(".")[0]!;
package/src/hub/daemon.ts CHANGED
@@ -153,6 +153,7 @@ import { PiToolReceipts, packPiShellResult } from "../pi/tool-receipts.ts";
153
153
  import { preparePiDependencies } from "../pi/task-dependencies.ts";
154
154
  import { publishPiDependencies } from "../pi/dependency-publish.ts";
155
155
  import { PreEffectToolRefusal } from "./tool-refusal.ts";
156
+ import { CHECKPOINT_FIELDS, CHECKPOINT_FIELDS_SENTENCE, checkpointFieldCount, parseCheckpointFields, renderCheckpoint } from "./checkpoint-fields.ts";
156
157
  import { ModelOverrides, ModelOverrideLatches, type RuntimeModelStatus, type ModelSource } from "./model-overrides.ts";
157
158
  import { isNativeModelToken } from "../adapters/model-token.ts";
158
159
  import { processSignature, processLiveness } from "../pi/process-signature.ts";
@@ -184,7 +185,7 @@ import { Board, isClosedTaskState, taskProposalAt, taskHasStarted, CLASSES, type
184
185
  import { UsageRollup, USAGE_GROUPS, LIMITS_MAX, type UsageGroup } from "./usage-rollup.ts";
185
186
  import { Budget, readNativeQuota, DEFAULT_BUDGET, type BudgetConfig } from "./budget.ts";
186
187
  import { remoteEnvelope, HUB } from "./envelope.ts";
187
- import { recallMemoryLines, trimToTokens } from "../memory/recall.ts";
188
+ import { recallMemoryLines, trimToTokens, aggregateUse, orderByUse } from "../memory/recall.ts";
188
189
  import { closeSync, constants as fsConstants, openSync, lstatSync, readSync, statSync } from "node:fs";
189
190
  import { basename, isAbsolute } from "node:path";
190
191
  import { fileURLToPath } from "node:url";
@@ -300,8 +301,8 @@ export interface HubConfig {
300
301
  model_relay?: ModelOperationalConfig["model_relay"];
301
302
  /** #489 H7: accepted presentation preferences read by a new console through settings_get. */
302
303
  console?: ConsoleOperationalConfig["console"];
303
- /** `native` (#258): the hub's own store in ~/.agenthub/memory, on with any project config; `short_ttl_days`: short-term lifetime after approval; `sync_interval_min`: machine sync while a remote is set (default 10, 0 off). */
304
- memory: { enabled: boolean; worker_url?: string; inject_tokens: number; brief_items: number; native?: boolean; short_ttl_days?: number; sync_interval_min?: number; suggest_edges?: boolean };
304
+ /** `native` (#258): the hub's own store in ~/.agenthub/memory, on with any project config; `short_ttl_days`: short-term lifetime after approval; `sync_interval_min`: machine sync while a remote is set (default 10, 0 off); `preface_unused_after` (#1330): a long-term preface line delivered at least this many times and never cited moves to the end of its section, so the cap cuts it first (default 20, 0 keeps the store order). */
305
+ memory: { enabled: boolean; worker_url?: string; inject_tokens: number; brief_items: number; native?: boolean; short_ttl_days?: number; sync_interval_min?: number; suggest_edges?: boolean; preface_unused_after?: number };
305
306
  roster: PeerRoster;
306
307
  roles: Record<string, string[]>;
307
308
  /** #455: the one peer that holds the planner role; unset, the `roles` planners stand, or the hub assigns one. */
@@ -396,7 +397,7 @@ export const DEFAULT_CONFIG: HubConfig = {
396
397
  queue_cap: 200,
397
398
  bus: { max_attempts: BUS_MAX_ATTEMPTS_SETTING.defaultValue, digest_max: BUS_DIGEST_MAX_SETTING.defaultValue, pull_budget_bytes: BUS_PULL_BUDGET_BYTES_SETTING.defaultValue, notes_kept: BUS_NOTES_KEPT_SETTING.defaultValue, terminal_history_limit: BUS_TERMINAL_HISTORY_LIMIT_SETTING.defaultValue, accepted_settle_ms: BUS_ACCEPTED_SETTLE_MS_SETTING.defaultValue },
398
399
  adapter_timing: { acp_tool_ceiling_min: ACP_TOOL_CEILING_SETTING.defaultValue, acp_activity_batch_ms: ACP_ACTIVITY_BATCH_SETTING.defaultValue, jcode_steer_timeout_s: JCODE_STEER_TIMEOUT_SETTING.defaultValue },
399
- memory: { enabled: true, inject_tokens: 2000, brief_items: 8 },
400
+ memory: { enabled: true, inject_tokens: 2000, brief_items: 8, preface_unused_after: 20 },
400
401
  roster: {},
401
402
  roles: DEFAULT_ROLES,
402
403
  conductor: { feed: "own", approval_wait_s: 30 },
@@ -2276,13 +2277,18 @@ export async function startDaemon(opts: DaemonOptions) {
2276
2277
  async function ensurePreface(peer: PeerId): Promise<void> {
2277
2278
  if ((!config.memory.enabled && !memoryStore) || recalled.has(peer) || reviewOnlyPeer(peer)) return; // #223 R2: no shared memory in a fresh review
2278
2279
  // The hub's own long-term decisions, contracts and fails lead; amem's curated short-term notes follow, each with half the budget.
2279
- let own: string | undefined;
2280
+ let own: string | undefined, orderedByUse = false;
2280
2281
  try {
2281
2282
  checkMemory();
2282
2283
  // This project's active long-term tasks lead, then its latest long-term decisions, contracts and fails.
2283
2284
  const goals = memoryStore ? screenMemory(memoryStore.goals(memoryProject).filter((g) => g.state !== "done" && g.state !== "dropped").map((g) => ({ ...g, text: "" }))).map(goalLine) : [];
2284
2285
  // Entries and titles are agents' words from any synced machine: one line each, and no forged message header.
2285
- own = memoryStore ? nativeRecall([...goals, ...recallMemoryLines(screenMemory(memoryStore.list({ project: memoryProject, tier: "long", limit: Number.MAX_SAFE_INTEGER }).filter((v) => v.kind !== "finding")), 30, staleness())], config.memory.enabled ? Math.floor(config.memory.inject_tokens / 2) : config.memory.inject_tokens, (line) => sanitize(line.replace(/\s+/g, " "))) : undefined;
2286
+ // #1330: order by observed use. Counter rows are per delivery, so they are summed per entry first; any read failure, a missing sidecar or a setting of 0 keeps the store order.
2287
+ let usage: ReturnType<typeof aggregateUse> | undefined;
2288
+ const unusedAfter = config.memory.preface_unused_after ?? 20;
2289
+ if (candidates && unusedAfter > 0) { try { usage = aggregateUse(candidates.counters(memoryProject)); } catch { usage = undefined; } }
2290
+ orderedByUse = usage !== undefined && usage.size > 0;
2291
+ own = memoryStore ? nativeRecall([...goals, ...recallMemoryLines(screenMemory(memoryStore.list({ project: memoryProject, tier: "long", limit: Number.MAX_SAFE_INTEGER }).filter((v) => v.kind !== "finding")), 30, staleness(), notes => orderByUse(notes, usage, unusedAfter))], config.memory.enabled ? Math.floor(config.memory.inject_tokens / 2) : config.memory.inject_tokens, (line) => sanitize(line.replace(/\s+/g, " "))) : undefined;
2286
2292
  }
2287
2293
  catch (e) { log(`hub memory recall failed: ${(e as Error).message}`); }
2288
2294
  const recordRecallTask: BriefTask = { owner: peer, title: "", refs: {} };
@@ -2297,6 +2303,8 @@ export async function startDaemon(opts: DaemonOptions) {
2297
2303
  if (!block || recalled.has(peer)) return; // nothing yet (worker down, no memory): the peer's next session tries again
2298
2304
  recalled.add(peer);
2299
2305
  bus.preface(peer, block);
2306
+ // #1330: the size of what was injected and whether use reordered it, as numbers only, so the preface can be measured before and after.
2307
+ event({ type: "preface", peer, bytes: Buffer.byteLength(block), lines: block.split("\n").filter(line => line.startsWith("mem:")).length, ordered: orderedByUse });
2300
2308
  log(`recall ${peer}: ${block.length} chars`);
2301
2309
  }
2302
2310
 
@@ -3961,8 +3969,8 @@ export async function startDaemon(opts: DaemonOptions) {
3961
3969
  if (previousRefusal) { clearTimeout(previousRefusal.timer); checkpointOwnershipRefusals.delete(peer); }
3962
3970
  const requestId = randomUUID();
3963
3971
  const body = reason === "quota"
3964
- ? "Checkpoint request: your quota window is almost used up and the hub is about to pause you. Finish the step you are on, write what you were doing, what is half done and what whoever continues must know to .agenthub/checkpoint.md, then call hub_checkpoint {summary} with the same text. Your open tasks will be handed to another peer; you will be resumed when the window resets."
3965
- : `Checkpoint request: your native context window is near the configured threshold. Finish the step you are on and call hub_checkpoint {summary, request_id: "${requestId}"} with what you were doing, what is half done and what a fresh session would need. This only saves a checkpoint; keep your tasks and session. The operator decides whether to continue or restart. Do not include private task text.`;
3972
+ ? `Checkpoint request: your quota window is almost used up and the hub is about to pause you. Finish the step you are on, write what you were doing, what is half done and what whoever continues must know to .agenthub/checkpoint.md, then call hub_checkpoint {summary} with the same text. Your open tasks will be handed to another peer; you will be resumed when the window resets. ${CHECKPOINT_FIELDS_SENTENCE}`
3973
+ : `Checkpoint request: your native context window is near the configured threshold. Finish the step you are on and call hub_checkpoint {summary, request_id: "${requestId}"} with what you were doing, what is half done and what a fresh session would need. This only saves a checkpoint; keep your tasks and session. The operator decides whether to continue or restart. ${CHECKPOINT_FIELDS_SENTENCE} Do not include private task text.`;
3966
3974
  const ask = newEnvelope(HUB, body, { to: [peer], kind: "budget", priority: "important" });
3967
3975
  return new Promise((resolve) => {
3968
3976
  const identityCurrent = () => !stopping && !recoveryActive() && bus.peers.get(peer) === owner && (!generationFenced || owner.sessionGeneration === generation) && contextSession(peer) === session;
@@ -6132,8 +6140,12 @@ export async function startDaemon(opts: DaemonOptions) {
6132
6140
  return saved;
6133
6141
  }
6134
6142
  case "hub_checkpoint": {
6135
- const summary = String(a.summary ?? "").trim();
6136
- if (!summary) throw new Error("summary is required");
6143
+ const written = String(a.summary ?? "").trim();
6144
+ if (!written) throw new Error("summary is required");
6145
+ // #1331: the structured fields are validated before anything is saved, so an over-length field leaves the request open for a corrected call.
6146
+ const checkpointFields = parseCheckpointFields(a);
6147
+ const summary = renderCheckpoint(written, checkpointFields);
6148
+ const checkpointNames = CHECKPOINT_FIELDS.filter(name => checkpointFields[name] !== undefined);
6137
6149
  const pending = checkpointWaits.get(by);
6138
6150
  if (!pending) {
6139
6151
  const refusal = checkpointOwnershipRefusals.get(by);
@@ -6156,11 +6168,13 @@ export async function startDaemon(opts: DaemonOptions) {
6156
6168
  renameSync(`${file}.tmp`, file);
6157
6169
  pending.done(summary);
6158
6170
  if (config.memory.enabled) await memory.save({ text: summary, title: `agent-hub ${by} context checkpoint`, project: memoryProject, metadata: { peer: by, kind: "handover" } }).catch(() => undefined);
6171
+ event({ type: "checkpoint", peer: by, reason: "context", fields: [...checkpointNames] });
6159
6172
  notify(`context: ${by} checkpoint saved locally; no tasks or session changed`);
6160
6173
  return "context checkpoint saved locally; keep your tasks and session, the operator decides the next step";
6161
6174
  }
6162
6175
  if (a.request_id && a.request_id !== pending.requestId) throw new Error("checkpoint request_id does not match");
6163
6176
  budget.checkpointed(by, summary);
6177
+ event({ type: "checkpoint", peer: by, reason: "quota", fields: [...checkpointNames] });
6164
6178
  pending.done(summary);
6165
6179
  return "checkpoint received; you will be paused now and resumed when your window resets";
6166
6180
  }
package/src/hub/events.ts CHANGED
@@ -71,6 +71,8 @@ export type HubEvent =
71
71
  | { type: "tooling"; peer: string; addons: import("./tooling.ts").Addon[] }
72
72
  /** #258: a task brief handed to its owner: how many hub-memory items (and fails among them) and supplemental items (legacy claudeMem field), never their text. New local-library records identify source amem. */
73
73
  | { type: "memory_brief"; source?: "amem"; peer: string; task: number; native: number; fails: number; claudeMem: number }
74
+ /** #1330: the session preface a peer was given: its size in bytes, the number of memory lines in it, and whether observed use reordered the long-term section. Numbers and a boolean only, never a line. */
75
+ | { type: "preface"; peer: string; bytes: number; lines: number; ordered: boolean }
74
76
  | { type: "split"; task: number; where?: "routing" | "cohort"; verdict: "split" | "single" | "unknown"; single?: string; splitS?: number; singleS?: number; reason?: string; trace?: string[] }
75
77
  | { type: "state"; peer: string; state: string }
76
78
  | { type: "turn_start"; peer: string; turn: string }
@@ -99,6 +101,8 @@ export type HubEvent =
99
101
  | ({ type: "pii_screen" } & ScreenRecord)
100
102
  | { type: "conflict"; peer: string; task?: number; other: number; owner: string; paths: string[]; concurrent: boolean; turns?: [string, string] }
101
103
  | { type: "context_pressure"; peer: string; source: string; measuredAt: number; used: number; window: number | null }
104
+ /** #1331: a saved checkpoint and which structured fields it carried (names from a closed list, never text), so field use is countable. */
105
+ | { type: "checkpoint"; peer: string; reason: "quota" | "context"; fields: string[] }
102
106
  | { type: "quota"; peer: string; windows: { id: string; used: number; resetsAt?: number }[]; hard: boolean; measuredAt?: string }
103
107
  /**
104
108
  * The limit ledger (#683 U1): additive, ids and numbers only, no PROTOCOL bump (a reader that does not know a type ignores it).
@@ -1,4 +1,5 @@
1
1
  import { EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
2
+ import { CHECKPOINT_FIELDS, CHECKPOINT_FIELDS_SENTENCE, CHECKPOINT_FIELD_MAX_LINES, CHECKPOINT_FIELD_MAX_LINE_CHARS, CHECKPOINT_HEADINGS } from "./checkpoint-fields.ts";
2
3
  import { MILESTONE_LIMITS, MILESTONE_STATES, MILESTONE_HORIZONS, MILESTONE_LINK_KINDS } from "./roadmap.ts";
3
4
  import { EXECUTION_LINK_LIMITS } from "./execution-links.ts";
4
5
  import { GUIDANCE_ROLE_MAX_BYTES, GUIDANCE_RECORD_MAX_BYTES, GUIDANCE_RATIONALE_MAX_BYTES, GUIDANCE_EVIDENCE_MAX_REFS, GUIDANCE_CURSOR_MAX_BYTES, GUIDANCE_HASH_HEX_LENGTH } from "./guidance-variants.ts";
@@ -289,7 +290,7 @@ export const TASK_TOOLS: HubTool[] = [
289
290
  tool("hub_task_list", "The task board, newest updated first, 50 compact rows (id, state, owner, reviewer, title) per call. The reply is {tasks, total, next?}: pass next as cursor for the following page. Use ids for full rows of specific tasks, or detail: true for full rows of a page. PII tasks show as [pii].", { state: { type: "string", enum: ["proposed", "in_progress", "in_review", "approved", "changes_requested", "cancelled"] }, ready: { type: "boolean", description: "only proposed tasks with nothing left to wait for" }, limit: { type: "integer", minimum: 1, maximum: 200, description: "rows per page, default 50" }, cursor: { type: "string", description: "the next value from the previous reply, unchanged" }, ids: { type: "array", minItems: 1, maxItems: 200, items: { type: "integer", minimum: 1 }, description: "full rows for exactly these task numbers; no paging" }, detail: { type: "boolean", description: "full rows instead of compact rows" } }),
290
291
  tool("hub_specs", "Read the project's design-spec checks or find specs covering repository-relative paths. Read-only; at most 20 result items are returned. Does not reveal private task data.", { action: { type: "string", enum: ["check", "covers"] }, paths: { type: "array", maxItems: 32, items: { type: "string", minLength: 1, maxLength: 2000 } } }, ["action"]),
291
292
  tool("hub_review", "Give your verdict on a task you were asked to review: map the changed signatures and call sites to the task's plan or detail, read the check result (hub_task_show has it, with the done summary), and list what is unmet. The verdict notifies the task owner; no duplicate hub_send chat is needed. Consecutive changes_requested verdicts (three by default, `tasks.escalate_after`) move the task to another peer.", { id, head: { type: "string", description: "full SHA actually reviewed; enforce binds approval to the current PR head" }, findings: reviewFindings, verdict: { type: "string", enum: ["approved", "changes_requested"] }, note: str, unmet: { type: "array", items: str, description: "each requirement of the plan or detail that the change does not meet; when the review request lists acceptance criteria, start an item with its id (\"AC1: what is missing\") so the verdict names it" }, coverage: { type: "object", description: "the review brief's reviewable paths you read (reviewed) and any you did not (skipped, each with a reason); in enforce an approval must account for every one", properties: { reviewed: { type: "array", items: str }, skipped: { type: "array", items: { type: "object", properties: { path: str, reason: str }, required: ["path", "reason"] } } } } }, ["id", "verdict"]),
292
- tool("hub_checkpoint", "Answer a checkpoint request from the hub (quota or context window pressure): what you were doing, what is half done, what whoever continues must know. Write the same to .agenthub/checkpoint.md first if you can.", { summary: str, request_id: { type: "string", description: "The request id supplied by a context checkpoint request; required for context checkpoints" } }, ["summary"]),
293
+ tool("hub_checkpoint", `Answer a checkpoint request from the hub (quota or context window pressure): what you were doing, what is half done, what whoever continues must know. Write the same to .agenthub/checkpoint.md first if you can. ${CHECKPOINT_FIELDS_SENTENCE} A field over its limit is refused, never cut; summary stays required.`, { summary: str, ...Object.fromEntries(CHECKPOINT_FIELDS.map(name => [name, { type: "string", description: `${CHECKPOINT_HEADINGS[name]}: at most ${CHECKPOINT_FIELD_MAX_LINES} lines of ${CHECKPOINT_FIELD_MAX_LINE_CHARS} characters` }])), request_id: { type: "string", description: "The request id supplied by a context checkpoint request; required for context checkpoints" } }, ["summary"]),
293
294
  tool("hub_source_read", "Read a registered source snapshot. Unicode character range, at most 32 KiB of sanitized UTF-8 text with next character offset. Private sources return only id, kind and private unless called by the on-prem worker inside a PII task. Excluded from capture.", { id: { type: "string", pattern: "^src:[0-9a-f]{16}$" }, range: { type: "object", properties: { offset: { type: "integer", minimum: 0 }, length: { type: "integer", minimum: 1 } }, required: ["offset", "length"], additionalProperties: false } }, ["id"]),
294
295
  tool("hub_memory_search", "Search daemon-scoped visible memory, fails first. Query <=200 UTF-8 bytes; default 8, max 20 lines; whole output <=4 KB. Incomplete excerpts are marked. No project argument.", { query: { type: "string", maxLength: 200, description: "At most 200 UTF-8 bytes, enforced by the daemon" }, limit: { type: "integer", minimum: 1, maximum: 20 } }, ["query"]),
295
296
  tool("hub_memory_show", "Read up to 8 visible memory ids or unique prefixes (6..64 UTF-8 bytes each). Original ids redirect; unavailable ids share one refusal. Whole output <=8 KB.", { ids: { type: "array", minItems: 1, maxItems: 8, items: { type: "string", minLength: 6, maxLength: 64, description: "6 to 64 UTF-8 bytes" } } }, ["ids"]),
@@ -23,13 +23,13 @@ const EVENT_FIELDS: Record<string,readonly string[]>={
23
23
  pii_screen:["task","item","label","source","category","miss","ms"],
24
24
  overflow:["id","from","peer"],undeliverable:["id","from","peer"],stale:["id","from","peer","task"],quiet:["id","from","peers"],
25
25
  envelope:["id","from","to","priority","hop","kind","task","bytes","private","dropped"],
26
- memory_brief:["source","peer","task","native","fails","claudeMem"],
26
+ memory_brief:["source","peer","task","native","fails","claudeMem"],preface:["peer","bytes","lines","ordered"],
27
27
  fact:["peer","id","files","plans","unknown","named","bytes","via","ms","hookMs","rttMs","accepted","unanswered","probe","coverage"],
28
28
  fact_ack:["peer","id","via","ms"],permission_mode:["peer","from","to"],
29
29
  permission:["id","peer","event","latencyMs","surface","option"],
30
30
  supervision_turn:["peer","turn","tokens","ms"],hook_stats:["peer","n","startupMs","hubMs","maxStartupMs"],
31
31
  capability:["peer","state","via"],cohort:["id","event","silent","tasks","owners"],
32
- planning:["by","task","release","fields","revision"],context_pressure:["peer","source","measuredAt","used","window"],
32
+ planning:["by","task","release","fields","revision"],context_pressure:["peer","source","measuredAt","used","window"],checkpoint:["peer","reason","fields"],
33
33
  budget_pause:["peer","reason","window","resetsAt","by"],budget_resume:["peer","reason","window","resetsAt","by"],
34
34
  quota_reset:["peer","window","cause","resetsAt","used","previousUsed","previousResetsAt","measuredAt"],
35
35
  };
@@ -38,13 +38,13 @@ const EVENT_REQUIRED:Record<string,readonly string[]>={
38
38
  task:["id","event","by","state","owner","reviewer","class","pii"],tokens:["peer","n"],usage:["peer","source","id"],turn_end:["peer","turn","ms"],
39
39
  conduct:["peer","action"],agent_cli:["peer","command","refused"],pii_screen:["item","label","source"],
40
40
  overflow:["id","from","peer"],undeliverable:["id","from","peer"],stale:["id","from","peer"],quiet:["id","from","peers"],envelope:["id","from","priority","hop"],
41
- memory_brief:["peer","task","native","fails","claudeMem"],fact:["peer","id","files","plans","unknown","named","bytes","via"],fact_ack:["peer","id","via","ms"],
41
+ memory_brief:["peer","task","native","fails","claudeMem"],preface:["peer","bytes","lines","ordered"],fact:["peer","id","files","plans","unknown","named","bytes","via"],fact_ack:["peer","id","via","ms"],
42
42
  permission_mode:["peer","from","to"],permission:["id","peer","event"],supervision_turn:["peer","turn"],hook_stats:["peer","n","startupMs","hubMs","maxStartupMs"],
43
- capability:["peer","state"],cohort:["id","event","silent","tasks","owners"],planning:["by","fields","revision"],context_pressure:["peer","source","measuredAt","used","window"],
43
+ capability:["peer","state"],cohort:["id","event","silent","tasks","owners"],planning:["by","fields","revision"],context_pressure:["peer","source","measuredAt","used","window"],checkpoint:["peer","reason","fields"],
44
44
  budget_pause:["peer","reason","window","resetsAt","by"],budget_resume:["peer","reason","window","resetsAt","by"],quota_reset:["peer","window","cause","used","previousUsed"],
45
45
  };
46
- const NUMBERS=new Set(["n","ms","tokens","files","snapshotMs","reasoningTokens","inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","totalTokens","hop","bytes","native","fails","claudeMem","plans","unknown","named","hookMs","rttMs","latencyMs","startupMs","hubMs","maxStartupMs","used","previousUsed","previousResetsAt","resetsAt","plannedStart","due","revision"]);
47
- const BOOLEANS=new Set(["pii","private","fresh","refused","delegated","accepted","unanswered","probe","coverage","silent"]);
46
+ const NUMBERS=new Set(["n","ms","tokens","files","snapshotMs","reasoningTokens","inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","totalTokens","hop","bytes","lines","native","fails","claudeMem","plans","unknown","named","hookMs","rttMs","latencyMs","startupMs","hubMs","maxStartupMs","used","previousUsed","previousResetsAt","resetsAt","plannedStart","due","revision"]);
47
+ const BOOLEANS=new Set(["pii","private","fresh","refused","delegated","accepted","unanswered","probe","coverage","silent","ordered"]);
48
48
  const TASK_EVENTS=new Set(["proposed","backlogged","backlog pulled","backlog returned","accepted","assigned","reassigned","unassigned","reserved","ready","blocked","declined","escalated","done","approved","changes_requested","cancelled","lifecycle"]);
49
49
  const identifier=(value:unknown):value is string=>typeof value==="string" && /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}$/.test(value);
50
50
  const peerId=(value:unknown):value is string=>typeof value==="string" && /^[a-z][a-z0-9-]{0,63}$/.test(value);
@@ -1,6 +1,7 @@
1
1
  import type { StampedEvent } from "./events.ts";
2
2
  import { familyOf as builtinFamilyOf } from "../adapters/registry.ts";
3
3
  import { nearestRank } from "./research-record.ts";
4
+ import { CHECKPOINT_FIELDS } from "./checkpoint-fields.ts";
4
5
  import { latestTaskRecords, type ResearchRecord, type TaskRecord } from "./research.ts";
5
6
 
6
7
  /**
@@ -30,13 +31,14 @@ export interface QualityReport {
30
31
  budget: { pauses: number; resumes: number; handoffs: number | null; byFamily: Record<string, { pauses: number; resumes: number }> };
31
32
  /** Task and review outcomes per (peer family, class), by the family of the task's last owner. */
32
33
  outcomes: Record<string, Record<string, OutcomeCounts>>;
33
- /** Every event type seen in the window with its count, and the types this report knows that did not occur. */
34
- events: { present: Record<string, number>; absent: string[] };
34
+ /** Every event type seen in the window with its count, and the types this report knows that did not occur. `preface` (#1330): the session prefaces injected in the window, their total bytes and memory lines, and how many were reordered by observed use; null when none was recorded. `checkpoints` (#1331): saved checkpoints in the window, by how many structured fields each carried and by field name; null when none was saved. */
35
+ events: { present: Record<string, number>; absent: string[]; preface: { prefaces: number; bytes: number; lines: number; ordered: number } | null; checkpoints: { total: number; byFieldCount: Record<string, number>; byField: Record<string, number> } | null };
35
36
  /** The share of attributed token increments by the attribution rule (#200) and the total; null when no tokens were counted. */
36
37
  tokenAttribution: { total: number; share: Record<"delivery" | "single_open" | "unattributed", number | null> };
37
38
  }
38
39
 
39
40
  const FAMILY_FALLBACK = "unknown";
41
+ const sortedRecord = (r: Record<string, number>): Record<string, number> => Object.fromEntries(Object.entries(r).sort(([a], [b]) => a.localeCompare(b)));
40
42
  /** The event types the report reasons about: the ones whose absence in a window means something. */
41
43
  export const EXPECTED_EVENTS = ["task", "tokens", "usage", "turn_end", "quota", "budget_pause", "budget_resume", "envelope", "memory_brief", "hub_start"] as const;
42
44
 
@@ -77,6 +79,8 @@ export function buildResearchQuality(records: readonly ResearchRecord[], events:
77
79
  const quota: Record<string, { times: number[]; measured: number; event: number }> = {};
78
80
  const budget: QualityReport["budget"] = { pauses: 0, resumes: 0, handoffs: null, byFamily: {} };
79
81
  const attribution: Record<string, number> = { delivery: 0, single_open: 0, unattributed: 0 };
82
+ let preface: NonNullable<QualityReport["events"]["preface"]> | null = null;
83
+ let checkpoints: NonNullable<QualityReport["events"]["checkpoints"]> | null = null;
80
84
  let tokenTotal = 0;
81
85
  for (const e of windowEvents) {
82
86
  present[e.type] = (present[e.type] ?? 0) + 1;
@@ -90,6 +94,17 @@ export function buildResearchQuality(records: readonly ResearchRecord[], events:
90
94
  } else if (e.type === "budget_pause" || e.type === "budget_resume") {
91
95
  const fam = family(e.peer), row = budget.byFamily[fam] ??= { pauses: 0, resumes: 0 };
92
96
  if (e.type === "budget_pause") { budget.pauses++; row.pauses++; } else { budget.resumes++; row.resumes++; }
97
+ } else if (e.type === "preface") {
98
+ if (Number.isSafeInteger(e.bytes) && e.bytes >= 0 && Number.isSafeInteger(e.lines) && e.lines >= 0) {
99
+ preface ??= { prefaces: 0, bytes: 0, lines: 0, ordered: 0 };
100
+ preface.prefaces++; preface.bytes += e.bytes; preface.lines += e.lines; if (e.ordered === true) preface.ordered++;
101
+ }
102
+ } else if (e.type === "checkpoint") {
103
+ const names = [...new Set((Array.isArray(e.fields) ? e.fields : []).filter((n): n is string => CHECKPOINT_FIELDS.includes(n as never)))];
104
+ checkpoints ??= { total: 0, byFieldCount: {}, byField: {} };
105
+ checkpoints.total++;
106
+ checkpoints.byFieldCount[String(names.length)] = (checkpoints.byFieldCount[String(names.length)] ?? 0) + 1;
107
+ for (const name of names) checkpoints.byField[name] = (checkpoints.byField[name] ?? 0) + 1;
93
108
  } else if (e.type === "tokens" && Number.isFinite(e.n) && e.n > 0) {
94
109
  tokenTotal += e.n; const rule = e.attribution === "delivery" || e.attribution === "single_open" ? e.attribution : "unattributed"; attribution[rule]! += e.n;
95
110
  }
@@ -112,7 +127,7 @@ export function buildResearchQuality(records: readonly ResearchRecord[], events:
112
127
  window: { since: window.since !== undefined ? new Date(window.since).toISOString() : null, until: window.until !== undefined && Number.isFinite(window.until) ? new Date(window.until).toISOString() : null },
113
128
  records: tasks.length, fields: Object.fromEntries(Object.entries(fields).sort(([a], [b]) => a.localeCompare(b))),
114
129
  quota: Object.fromEntries(Object.entries(quotaOut).sort(([a], [b]) => a.localeCompare(b))), budget, outcomes,
115
- events: { present: Object.fromEntries(Object.entries(present).sort(([a], [b]) => a.localeCompare(b))), absent: EXPECTED_EVENTS.filter(type => !(type in present)) },
130
+ events: { present: Object.fromEntries(Object.entries(present).sort(([a], [b]) => a.localeCompare(b))), absent: EXPECTED_EVENTS.filter(type => !(type in present)), preface, checkpoints: checkpoints && { total: checkpoints.total, byFieldCount: sortedRecord(checkpoints.byFieldCount), byField: sortedRecord(checkpoints.byField) } },
116
131
  tokenAttribution: { total: tokenTotal, share: { delivery: share(attribution.delivery!), single_open: share(attribution.single_open!), unattributed: share(attribution.unattributed!) } },
117
132
  };
118
133
  }
package/src/hub/tasks.ts CHANGED
@@ -3649,7 +3649,7 @@ export class Tasks {
3649
3649
  repo: string; apply: boolean; partial: boolean; milestones: { number: number; title: string; milestone: number | null; action: "create" | "exists"; issues: string[]; newLinks: number }[]; created: number; linked: number; withheld: number;
3650
3650
  }> {
3651
3651
  const current = this.roadmapWriteAuthority(by);
3652
- if (!this.personOrConductor(by)) throw new PreEffectToolRefusal("GitHub milestone import is a console command; ask the person to run ahub roadmap import-github");
3652
+ if (by !== USER) throw new PreEffectToolRefusal("GitHub milestone import is a console command; ask the person to run ahub roadmap import-github");
3653
3653
  if (input.apply !== undefined && typeof input.apply !== "boolean") throw new PreEffectToolRefusal("roadmap import apply must be true or false; omit it for a dry run");
3654
3654
  const apply = input.apply === true, gh = this.roadmapGh(run), repoInput = this.roadmapRepo(input.repo);
3655
3655
  const milestonePages = await readGitHubMilestonePages({ ...(repoInput === undefined ? {} : { repo: repoInput }) }, gh);
@@ -105,8 +105,50 @@ export function recallMemoryLine(note: RecallNote, idChars = 8, stale = false):
105
105
  return header + (whole ? `${whole} ...` : "...");
106
106
  }
107
107
 
108
- /** Filter before the display cap, so outcome noise cannot displace an older relevant contract or fail. */
109
- export function recallMemoryLines(notes: readonly RecallNote[], limit = 30, stale: (about: readonly string[]) => boolean = () => false): string[] {
108
+ /**
109
+ * #1330: counter rows are keyed per delivery (`{ entryId, task, deliveryId }`), so one entry has many rows. The use of an entry is
110
+ * the sum of its rows. A row whose `delivered` and `cited` are both null observed nothing and adds nothing, so an entry with no
111
+ * observed row has no figure at all: unknown is never read as zero.
112
+ */
113
+ export interface MemoryUse { delivered: number; cited: number }
114
+ interface CounterRow { key: { entryId: string }; delivered?: number | null; cited?: number | null }
115
+ const count = (n: number | null | undefined): number | undefined => typeof n === "number" && Number.isSafeInteger(n) && n >= 0 ? n : undefined;
116
+ export function aggregateUse(rows: readonly CounterRow[]): Map<string, MemoryUse> {
117
+ const use = new Map<string, MemoryUse>();
118
+ for (const row of rows) {
119
+ const delivered = count(row.delivered), cited = count(row.cited);
120
+ if (delivered === undefined && cited === undefined) continue;
121
+ const entry = use.get(row.key.entryId) ?? { delivered: 0, cited: 0 };
122
+ entry.delivered += delivered ?? 0; entry.cited += cited ?? 0;
123
+ use.set(row.key.entryId, entry);
124
+ }
125
+ return use;
126
+ }
127
+
128
+ /**
129
+ * Orders one preface section by observed use, keeping the caller's order inside each tier (a stable sort, so fixed counters give one
130
+ * result). Tier 0: entries with a cited/delivered ratio above zero, highest ratio first. Tier 1: everything else, including every entry
131
+ * with no observed use (unknown is not zero) and entries delivered fewer than `unusedAfter` times. Tier 2: entries delivered at least
132
+ * `unusedAfter` times and never cited, so the display cap cuts them first. The section's own kind order is the caller's and is not
133
+ * regrouped here: today the long-term section is the store's newest-first order across decisions, contracts and fails.
134
+ * `unusedAfter` of 0, or no usage at all, returns the input unchanged.
135
+ */
136
+ export function orderByUse<T extends { id: string }>(notes: readonly T[], usage: ReadonlyMap<string, MemoryUse> | undefined, unusedAfter: number): T[] {
137
+ if (!usage || usage.size === 0 || !(unusedAfter > 0)) return [...notes];
138
+ const rank = (note: T): { tier: 0 | 1 | 2; ratio: number } => {
139
+ const use = usage.get(note.id);
140
+ if (!use) return { tier: 1, ratio: 0 };
141
+ if (use.cited === 0 && use.delivered >= unusedAfter) return { tier: 2, ratio: 0 };
142
+ return use.cited > 0 && use.delivered > 0 ? { tier: 0, ratio: Math.min(1, use.cited / use.delivered) } : { tier: 1, ratio: 0 };
143
+ };
144
+ return notes.map((note, index) => ({ note, index, ...rank(note) }))
145
+ .sort((a, b) => a.tier - b.tier || (a.tier === 0 ? b.ratio - a.ratio : 0) || a.index - b.index)
146
+ .map(row => row.note);
147
+ }
148
+
149
+ /** Filter before the display cap, so outcome noise cannot displace an older relevant contract or fail. `order` runs before the cap, so a re-ordering decides what the cap cuts. */
150
+ export function recallMemoryLines<N extends RecallNote>(notes: readonly N[], limit = 30, stale: (about: readonly string[]) => boolean = () => false, order?: (notes: readonly N[]) => readonly N[]): string[] {
151
+ notes = order ? order(notes) : notes;
110
152
  const prefixes = new Map<string, string | null>();
111
153
  for (const note of notes) {
112
154
  const prefix = note.id.slice(0, 8), previous = prefixes.get(prefix);