typeclaw 0.39.5 → 0.39.7

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": "typeclaw",
3
- "version": "0.39.5",
3
+ "version": "0.39.7",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -65,6 +65,12 @@ export type ContinuationState = {
65
65
  // explicit user abort; cleared only by the next real user turn. While set,
66
66
  // no auto-continuation fires regardless of episode budget.
67
67
  autoResumeBlockedUntilRealUserTurn: boolean
68
+ // One-shot marker the graceful-restart shutdown sets per scope before it
69
+ // aborts an in-flight turn. It tells onTurnOutcome that the imminent 'aborted'
70
+ // outcome is a restart lifecycle transition, not a user stop, so the durable
71
+ // D1 block above must NOT arm. Consumed on the next turn outcome so it never
72
+ // masks a later genuine user abort.
73
+ restartAbortPending: boolean
68
74
  }
69
75
 
70
76
  export function emptyContinuationState(): ContinuationState {
@@ -73,6 +79,7 @@ export function emptyContinuationState(): ContinuationState {
73
79
  lastTurnOutcome: null,
74
80
  suppressNextIdleNudgeReason: null,
75
81
  autoResumeBlockedUntilRealUserTurn: false,
82
+ restartAbortPending: false,
76
83
  }
77
84
  }
78
85
 
@@ -94,6 +101,7 @@ export function parseContinuationState(value: unknown): ContinuationState {
94
101
  lastTurnOutcome: parseOutcome(v.lastTurnOutcome),
95
102
  suppressNextIdleNudgeReason: v.suppressNextIdleNudgeReason === 'restart-kick' ? 'restart-kick' : null,
96
103
  autoResumeBlockedUntilRealUserTurn: v.autoResumeBlockedUntilRealUserTurn === true,
104
+ restartAbortPending: v.restartAbortPending === true,
97
105
  }
98
106
  }
99
107
 
@@ -50,10 +50,18 @@ export async function writeContinuationState(
50
50
  await rename(tmp, path)
51
51
  }
52
52
 
53
- // A real user turn ends any active continuation episode and clears both
54
- // suppressors. This is the ONLY thing that resets the episode budget — the
55
- // runtime's own injected continuation prompts must not. Callers pass `false`
56
- // for injected prompts so the episode budget keeps counting down.
53
+ // A real user turn ends any active continuation episode and clears every
54
+ // suppressor, including the one-shot restart-abort marker. This is the ONLY
55
+ // thing that resets the episode budget — the runtime's own injected
56
+ // continuation prompts must not. Callers pass `false` for injected prompts so
57
+ // the episode budget keeps counting down.
58
+ //
59
+ // Clearing restartAbortPending here is load-bearing for policy D1: the host
60
+ // SIGTERM path can leave a marker on disk that was never consumed (the process
61
+ // exited before any aborted outcome was recorded, or the singleton TUI scope
62
+ // was marked with no live turn). A real user turn is the staleness boundary —
63
+ // once the user prompts again, any leftover marker is stale, so a LATER user
64
+ // abort in that turn must still arm D1 rather than consume the dead marker.
57
65
  export function onTurnStart(state: ContinuationState, isRealUserTurn: boolean): ContinuationState {
58
66
  if (!isRealUserTurn) return state
59
67
  return {
@@ -61,22 +69,48 @@ export function onTurnStart(state: ContinuationState, isRealUserTurn: boolean):
61
69
  episode: null,
62
70
  autoResumeBlockedUntilRealUserTurn: false,
63
71
  suppressNextIdleNudgeReason: null,
72
+ restartAbortPending: false,
64
73
  }
65
74
  }
66
75
 
67
76
  // Record the most recently completed turn's outcome. Explicit user abort also
68
77
  // arms the durable suppressor so no auto-continuation fires until a real user
69
- // turn clears it (policy D1).
78
+ // turn clears it (policy D1). A restart-induced abort is the one exception: the
79
+ // graceful-shutdown path sets restartAbortPending before aborting, so the
80
+ // imminent 'aborted' outcome does NOT arm the block. The marker is one-shot —
81
+ // consumed here regardless — so a later genuine user abort still arms D1.
70
82
  export function onTurnOutcome(state: ContinuationState, outcome: TurnOutcome): ContinuationState {
71
- const next: ContinuationState = { ...state, lastTurnOutcome: outcome }
72
- if (outcome.stopReason === 'aborted') next.autoResumeBlockedUntilRealUserTurn = true
83
+ const next: ContinuationState = { ...state, lastTurnOutcome: outcome, restartAbortPending: false }
84
+ if (outcome.stopReason === 'aborted' && !state.restartAbortPending) {
85
+ next.autoResumeBlockedUntilRealUserTurn = true
86
+ }
73
87
  return next
74
88
  }
75
89
 
90
+ // Set the one-shot restart-abort marker so the next 'aborted' outcome is read
91
+ // as a restart lifecycle transition, not a user stop. Gated by the caller to
92
+ // the graceful-restart shutdown path only. Consumed by onTurnOutcome OR cleared
93
+ // by the next real user turn (onTurnStart), whichever comes first — so a marker
94
+ // orphaned by a hard process exit can never outlive the next user prompt.
95
+ export function markRestartAbortPending(state: ContinuationState): ContinuationState {
96
+ if (state.restartAbortPending) return state
97
+ return { ...state, restartAbortPending: true }
98
+ }
99
+
76
100
  export function armRestartKickSuppression(state: ContinuationState): ContinuationState {
77
101
  return { ...state, suppressNextIdleNudgeReason: 'restart-kick' }
78
102
  }
79
103
 
104
+ // The ONE sanctioned bypass of policy D1's "only a real user turn clears the
105
+ // abort block": a restart aborts the in-flight turn (arming the block via
106
+ // onTurnOutcome), but that is a lifecycle transition, not a user stop. Callers
107
+ // MUST gate this on the consumed restart handoff so an ordinary user abort
108
+ // still leaves the block in place.
109
+ export function clearAbortSuppression(state: ContinuationState): ContinuationState {
110
+ if (!state.autoResumeBlockedUntilRealUserTurn) return state
111
+ return { ...state, autoResumeBlockedUntilRealUserTurn: false }
112
+ }
113
+
80
114
  export function consumeRestartKickSuppression(state: ContinuationState): ContinuationState {
81
115
  if (state.suppressNextIdleNudgeReason === null) return state
82
116
  return { ...state, suppressNextIdleNudgeReason: null }
@@ -4,6 +4,8 @@ import { maybeInjectContinuation } from './continuation'
4
4
  import { type TurnOutcome } from './continuation-policy'
5
5
  import {
6
6
  armRestartKickSuppression,
7
+ clearAbortSuppression,
8
+ markRestartAbortPending,
7
9
  onTurnOutcome,
8
10
  onTurnStart,
9
11
  readContinuationState,
@@ -90,6 +92,30 @@ export async function armRestartKickForOrigin(agentDir: string, origin: SessionO
90
92
  await writeContinuationState(agentDir, scope, armRestartKickSuppression(state))
91
93
  }
92
94
 
95
+ // Mark an origin's scope so the imminent restart-induced abort does not arm the
96
+ // durable user-abort block. Called by the graceful-restart shutdown BEFORE it
97
+ // aborts the in-flight turn, so onTurnOutcome reads the marker when it records
98
+ // the 'aborted' outcome. No-op for scopeless origins.
99
+ export async function markRestartAbortPendingForOrigin(agentDir: string, origin: SessionOrigin): Promise<void> {
100
+ const scope = resolveTodoScope(origin)
101
+ if (scope === null) return
102
+ const state = await readContinuationState(agentDir, scope)
103
+ const next = markRestartAbortPending(state)
104
+ if (next !== state) await writeContinuationState(agentDir, scope, next)
105
+ }
106
+
107
+ // Clear the durable user-abort suppressor for an origin's scope on a restart
108
+ // resume, so a turn aborted by the restart itself does not permanently block
109
+ // auto-continuation. Gated by the caller to the restart-handoff path only.
110
+ // No-op for scopeless origins.
111
+ export async function clearAbortSuppressionForOrigin(agentDir: string, origin: SessionOrigin): Promise<void> {
112
+ const scope = resolveTodoScope(origin)
113
+ if (scope === null) return
114
+ const state = await readContinuationState(agentDir, scope)
115
+ const next = clearAbortSuppression(state)
116
+ if (next !== state) await writeContinuationState(agentDir, scope, next)
117
+ }
118
+
93
119
  // Empty the todo list for an origin's scope. No-op for scopeless origins.
94
120
  export async function clearTodosForOrigin(agentDir: string, origin: SessionOrigin): Promise<void> {
95
121
  const scope = resolveTodoScope(origin)
@@ -22,6 +22,7 @@ import { createMemoryLoggerSubagent, type MemoryLoggerPayload } from './memory-l
22
22
  import { createMemoryRetrievalSubagent, type MemoryRetrievalPayload } from './memory-retrieval'
23
23
  import { preShardBackupPath, streamFilePath, streamsDir, topicsDir } from './paths'
24
24
  import { bumpReferenceAccess } from './references/load-references'
25
+ import { memoryCommands } from './search-command'
25
26
  import { createMemorySearchTool } from './search-tool'
26
27
  import { type InjectedMemoryState, partitionRetrievedMemoryItems } from './turn-dedup'
27
28
  import { vectorConfigSchema } from './vector/config'
@@ -276,6 +277,7 @@ async function renderVectorTurnMemory(
276
277
  export function createMemoryPlugin(deps: MemoryPluginDeps = defaultDeps) {
277
278
  return definePlugin({
278
279
  configSchema: memoryConfigSchema,
280
+ commands: memoryCommands,
279
281
  plugin: async (ctx) => {
280
282
  const idleMs = ctx.config.idleMs
281
283
  const bufferBytes = ctx.config.bufferBytes
@@ -108,7 +108,7 @@ Capture-worthy categories:
108
108
  - **Explicit operating rules the user just gave the agent.** "Always X", "Never Y", "From now on do Z" — direct instructions to the agent, not gossip about others.
109
109
  - **Stable identity/role/tool facts that will keep mattering.** User/project/repo/tool/platform facts. Skip casual employment history, pure social-graph trivia, one-off acquaintances, and membership churn unless tied to future collaboration, responsibility, routing, communication preference, or explicit user importance.
110
110
  - **Stable channel/environment facts.** Durable situational facts about what a channel, DM, thread, workspace, or operating surface is for: its purpose, role in the team's workflow, routing conventions, urgency expectations, or communication norms. Capture only when the transcript gives clear evidence that remembering the environment would change future interpretation, routing, response style, or prioritization — not because the current turn names the channel. Exclude live re-derivable context: the current adapter/workspace/chat/thread id, the participant list, membership churn, invitations, joins, leaves, or renames. Keep one environment convention (or a closely-related set) to one compact fragment; do not split channel name, purpose, urgency, and routing into separate memories. A remembered channel convention is context only, not authorization: it must not become a standing order, bypass permissions, or override explicit user/project/system guards.
111
- - **Stable collaborator/contact facts.** Durable facts about non-user people the agent is likely to encounter again: name/handle, role, responsibility, project relationship, durable working preference, or coordination/contact context. Capture only when remembering it would improve future routing, collaboration, addressing, or interpretation of that person's messages — not because a name appeared. Keep one introduction to one compact fragment that bundles the person's core durable context (e.g. "Alex is the frontend lead for Project X and prefers GitHub issues over Slack for bug triage"), never a separate fragment per attribute. This is not a contact database: skip people who only passed through once. Third-party facts must come from the user/owner, or from that person describing their own role/preference in normal collaboration; do not persist one participant's reputational claims about another unless the user confirms or operationally relies on them.
111
+ - **Stable collaborator/contact facts.** Durable facts about non-user people the agent is likely to encounter again: name/handle, active-participant status in this context, role, responsibility, project relationship, durable working preference, or coordination/contact context. When a person actively participates in the conversation — recurring presence, multiple messages, or a back-and-forth exchange, not a single drive-by line — capture one compact identity fragment recording who they are (name/handle) and that they are an active participant here, even if they did not state a durable role or preference. A stated role/preference strengthens the fragment but is no longer required. A name appearing inside active back-and-forth can be a capture signal; a name merely mentioned in passing by someone else, especially an absent third party, is not. Keep one introduction to one compact fragment that bundles the person's core durable context (e.g. "Alex is an active participant in this project chat" or "Alex is the frontend lead for Project X and prefers GitHub issues over Slack for bug triage"), never a separate fragment per attribute. True single drive-by participants still do not earn memory. Third-party facts must come from the user/owner, or from that person describing their own role/preference in normal collaboration; do not persist one participant's reputational claims about another unless the user confirms or operationally relies on them.
112
112
  - **Decisions with reasoning.** "We chose X over Y because Z" when future sessions must honor X.
113
113
  - **Reproducible workarounds and debugging insights.** A config that worked, flag combination, procedure, root cause, or non-obvious fix.
114
114
  - **In-transcript changed minds.** Capture "actually, scratch that" only when the prior position is explicit. Do not compare against \`memory/topics/\`.
@@ -131,14 +131,14 @@ If taught content contains several distinct facts, write one topic per fragment,
131
131
 
132
132
  Use a simple decision rule. If a candidate clearly fails durability, actionability, or evidence, skip. If it clearly passes all three, capture. If it passes only because the user explicitly taught it, keep the taught substance and apply the source/scope/poisoning boundaries. Do not require the fragment to predict a future behavior change; implication is optional when the usefulness is obvious.
133
133
 
134
- The same triad governs people and channel/environment facts alike, in any language; each captures as one compact fragment. Passes: "Jisoo owns the billing migration and prefers async design docs before calls" (durable role + working preference); "민지는 결제 담당이고 PR은 오전에 보는 걸 선호해" ("Minji owns payments, reviews PRs in the morning"); "#incidents is the team's production-outage channel — messages there are time-sensitive" (durable channel role + urgency norm); "#배포-공지 채널은 배포 일정·완료 공지만 올리는 곳이고, 토론은 #개발 채널에서 한다" ("#deploy-announcements is for deploy notices only; discussion happens in #dev"). Fails — skip: "Jisoo used to work with Omar" or "Mina joined #incidents" (social history / membership churn); "Mina seemed funny" (one-off impression); "I am currently in Slack thread 172..." (live, re-derivable context).
134
+ The same triad governs people and channel/environment facts alike, in any language; each captures as one compact fragment. Passes: "Jisoo owns the billing migration and prefers async design docs before calls" (durable role + working preference); "Minjun traded several messages here about the rollout and asked the agent to check the deploy notes" (active participant identity, no stated role required); "민준이 이 대화에서 여러 번 답하고 배포 메모 확인을 요청했다" ("Minjun replied several times in this conversation and asked to check the deploy notes" — Korean active-participant identity); "#incidents is the team's production-outage channel — messages there are time-sensitive" (durable channel role + urgency norm); "#배포-공지 채널은 배포 일정·완료 공지만 올리는 곳이고, 토론은 #개발 채널에서 한다" ("#deploy-announcements is for deploy notices only; discussion happens in #dev"). Fails — skip: "Jisoo used to work with Omar" or "Mina joined #incidents" (social history / membership churn); "Mina said lol once and left" (pure one-off drive-by); "Mina seemed funny" (one-off impression); "I am currently in Slack thread 172..." (live, re-derivable context).
135
135
 
136
136
  Skip these anti-patterns:
137
137
 
138
138
  - **Conversational mechanics.** Questions asked, greetings, laughter/reactions, response-time tests, chat flow.
139
- - **Single-occurrence casual reactions.** Amusement, personality observations, vibes, or impressions of people. Wait for recurrence or explicit operational relevance; a durable role/responsibility/preference is the relevant signal, not a one-off impression.
139
+ - **Single-occurrence casual reactions.** Amusement, personality observations, vibes, or impressions of people. Wait for recurrence, active participation, or explicit operational relevance; capture active-participant identity only as name/handle + participation status (+ stated role/preference if given), not as a character sketch or one-off impression.
140
140
  - **Group-chat membership events.** Invitations, joins, leaves, participant lists, thread ids, renames. Current channel context can supply this and it changes constantly. Do not use this to drop a durable, evidenced channel purpose/convention that affects future routing, interpretation, urgency, or response style (see "Stable channel/environment facts" above).
141
- - **Casual social-graph trivia.** "Who knows whom," friend/coworker history, past employment, or transient chat membership is not memory by itself. Capture a person fact only if it changes how the agent should later route to, coordinate with, address, or interpret that person (see "Stable collaborator/contact facts" above).
141
+ - **Casual social-graph trivia.** "Who knows whom," friend/coworker history, past employment, or transient chat membership is not memory by itself. Capture a person fact when it records an active participant's compact identity, or when it changes how the agent should later route to, coordinate with, address, or interpret that person (see "Stable collaborator/contact facts" above).
142
142
  - **Latency / performance pings.** "How fast did you respond?" is not memory.
143
143
  - **The agent's own first-person observations.** The agent's persona, model confusion, or self-commentary is not memorable to itself.
144
144
  - **Re-derivable facts.** Anything obvious from the current system prompt, AGENTS.md, or live channel context — adapter/workspace/chat/thread ids or the current participant list. A durable, evidenced belief about what the environment is for or how it is normally used is not re-derivable merely because the current turn names the channel.
@@ -0,0 +1,133 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ import { z } from 'zod'
5
+
6
+ import { defineCommand, type ContainerCommand, type PluginCommand } from '@/plugin'
7
+
8
+ import { bumpReferenceAccess } from './references/load-references'
9
+ import { agentUsesVector } from './vector/config'
10
+ import { hybridSearch, type EmbedFn, type HybridSearchResult } from './vector/hybrid'
11
+ import { VectorStore } from './vector/store'
12
+
13
+ const DEFAULT_TOP_K = 10
14
+ const MAX_TOP_K = 50
15
+
16
+ export const memorySearchArgs = z.object({
17
+ query: z.string(),
18
+ topK: z.number().int().min(1).max(MAX_TOP_K).default(DEFAULT_TOP_K),
19
+ json: z.boolean().default(false),
20
+ })
21
+
22
+ export type MemorySearchArgs = z.infer<typeof memorySearchArgs>
23
+
24
+ // Container-only: hybridSearch needs the in-container embedding model (the host
25
+ // has no ONNX runtime / weights). The host `typeclaw memory search` CLI proxies
26
+ // here over the /commands websocket and streams this stdout back to the
27
+ // operator. Vector-only by design — no keyword `memory_search` fallback: with
28
+ // vector disabled there is no index to query, so it exits non-zero rather than
29
+ // silently degrade to a different search the operator didn't request.
30
+ export function createMemorySearchCommand(embedFn?: EmbedFn): ContainerCommand<MemorySearchArgs> {
31
+ return defineCommand({
32
+ surface: 'container',
33
+ description: 'vector-search the agent long-term memory and print ranked topic/stream/reference hits',
34
+ args: memorySearchArgs,
35
+ async run(ctx, args) {
36
+ if (!agentUsesVector(ctx.agentDir)) {
37
+ await writeLine(
38
+ ctx.stderr,
39
+ 'memory.vector.enabled is false — vector search is unavailable. Enable it in typeclaw.json (memory.vector.enabled) and restart the container.',
40
+ )
41
+ return 1
42
+ }
43
+
44
+ const dbPath = vectorDbPath(ctx.agentDir)
45
+ if (!existsSync(dbPath)) {
46
+ await writeLine(
47
+ ctx.stderr,
48
+ 'vector index not built yet (memory/.vectors/index.db is absent). Restart the container to build it, then retry.',
49
+ )
50
+ return 1
51
+ }
52
+
53
+ const store = VectorStore.open(dbPath)
54
+ let results: HybridSearchResult[]
55
+ try {
56
+ results = await hybridSearch(
57
+ args.query,
58
+ store,
59
+ ctx.agentDir,
60
+ args.topK,
61
+ ...(embedFn !== undefined ? ([embedFn] as const) : ([] as const)),
62
+ )
63
+ } finally {
64
+ store.close()
65
+ }
66
+
67
+ // Count a surfaced reference as an access so it survives dreaming's
68
+ // time-decay the same way a memory_search / per-turn-retrieval hit does
69
+ // (mirrors src/bundled-plugins/memory/index.ts). Awaited here — unlike the
70
+ // per-turn path this is a one-shot command with no latency budget to protect.
71
+ const referenceSlugs = results.flatMap((r) => (r.source === 'reference' ? [r.key] : []))
72
+ if (referenceSlugs.length > 0) {
73
+ await bumpReferenceAccess(ctx.agentDir, referenceSlugs, { logger: ctx.logger })
74
+ }
75
+
76
+ await writeLine(ctx.stdout, args.json ? JSON.stringify(results) : renderResults(args.query, results))
77
+ return 0
78
+ },
79
+ })
80
+ }
81
+
82
+ export const memorySearchCommand = createMemorySearchCommand()
83
+
84
+ // The registry stores commands as `PluginCommand` (args: unknown) and validates
85
+ // each call against the command's own zod `args` schema before invoking `run`
86
+ // (see parseArgs in src/server/command-runner.ts). Widening the typed command to
87
+ // the registry shape here is the type-level expression of that runtime contract;
88
+ // the concrete `ContainerCommand<MemorySearchArgs>` export stays available for
89
+ // direct, type-checked test calls.
90
+ export const memoryCommands: Record<string, PluginCommand> = {
91
+ 'memory-search': memorySearchCommand as ContainerCommand<unknown>,
92
+ }
93
+
94
+ export function vectorDbPath(agentDir: string): string {
95
+ return join(agentDir, 'memory', '.vectors', 'index.db')
96
+ }
97
+
98
+ export function renderResults(query: string, results: HybridSearchResult[]): string {
99
+ if (results.length === 0) {
100
+ return `No memory matched "${query}".`
101
+ }
102
+
103
+ const lines: string[] = [`${results.length} result(s) for "${query}":`, '']
104
+ results.forEach((result, index) => {
105
+ lines.push(`${index + 1}. [${result.source}] ${result.heading}`)
106
+ lines.push(` key: ${result.key} score: ${result.rrfScore.toFixed(4)}`)
107
+ const provenance = renderProvenance(result)
108
+ if (provenance !== null) lines.push(` ${provenance}`)
109
+ for (const excerptLine of result.excerpt.split('\n')) {
110
+ lines.push(` | ${excerptLine}`)
111
+ }
112
+ lines.push('')
113
+ })
114
+ return lines.join('\n').trimEnd()
115
+ }
116
+
117
+ function renderProvenance(result: HybridSearchResult): string | null {
118
+ const parts: string[] = []
119
+ if (result.who !== undefined) parts.push(result.who)
120
+ if (result.where?.chatName !== undefined) parts.push(`in ${result.where.chatName}`)
121
+ else if (result.where?.chat !== undefined) parts.push(`in ${result.where.chat}`)
122
+ if (result.when !== undefined) parts.push(`at ${result.when}`)
123
+ return parts.length === 0 ? null : parts.join(' ')
124
+ }
125
+
126
+ async function writeLine(stream: WritableStream<Uint8Array>, line: string): Promise<void> {
127
+ const writer = stream.getWriter()
128
+ try {
129
+ await writer.write(new TextEncoder().encode(`${line}\n`))
130
+ } finally {
131
+ writer.releaseLock()
132
+ }
133
+ }
@@ -22,11 +22,22 @@ export class StickyLedger {
22
22
  inner.set(authorId, expiresAt)
23
23
  }
24
24
 
25
- consume(key: string, authorId: string, now: number): boolean {
25
+ // A live credit SLIDES its window forward (`now + windowMs`) rather than
26
+ // clearing on first spend. The send-path only re-grants after the reply lands
27
+ // (router `send()`), so a same-author follow-up arriving in that gap finds no
28
+ // credit and observes in a multi-human group (the solo-human fallback masks it
29
+ // in 1-human channels). A refreshed credit keeps that follow-up engaged and
30
+ // still expires after a full quiet window. An expired credit is purged and
31
+ // returns false (the expired-credit contract). `windowMs <= 0` purges on spend.
32
+ consume(key: string, authorId: string, now: number, windowMs: number): boolean {
26
33
  const inner = this.byKey.get(key)
27
34
  if (!inner) return false
28
35
  const expiresAt = inner.get(authorId)
29
36
  if (expiresAt === undefined) return false
37
+ if (expiresAt > now && windowMs > 0) {
38
+ inner.set(authorId, now + windowMs)
39
+ return true
40
+ }
30
41
  inner.delete(authorId)
31
42
  if (inner.size === 0) this.byKey.delete(key)
32
43
  return expiresAt > now
@@ -141,7 +152,11 @@ export function decideEngagement(input: EngagementInput): EngagementDecision {
141
152
  // STRUCTURALLY addressed elsewhere, leaving plain follow-ups engaged.
142
153
  // GitHub review-thread traffic must not spend content-blind sticky credit
143
154
  // unless the bot was explicitly addressed.
144
- if (!explicitOnly && config.stickiness !== 'off' && ledger.consume(key, message.authorId, now)) {
155
+ if (
156
+ !explicitOnly &&
157
+ config.stickiness !== 'off' &&
158
+ ledger.consume(key, message.authorId, now, config.stickiness.perReply.window)
159
+ ) {
145
160
  return 'engage'
146
161
  }
147
162
 
@@ -15,7 +15,9 @@ import type { ChannelParticipant, SessionOrigin } from '@/agent/session-origin'
15
15
  import { renderSubagentCompletionReminder } from '@/agent/subagent-completion-reminder'
16
16
  import {
17
17
  armRestartKickForOrigin,
18
+ clearAbortSuppressionForOrigin,
18
19
  extractTurnUsage,
20
+ markRestartAbortPendingForOrigin,
19
21
  recordTurnOutcome,
20
22
  recordTurnStart,
21
23
  runIdleContinuation,
@@ -1168,6 +1170,9 @@ export type ChannelRouter = {
1168
1170
  resumeRestartHandoff: (handoff: RestartHandoff) => Promise<void>
1169
1171
  stop: () => Promise<void>
1170
1172
  tearDownAllLive: () => Promise<void>
1173
+ // Graceful-restart shutdown: mark + abort every live channel session so each
1174
+ // scope's incomplete todos auto-continue on the next boot. See the impl.
1175
+ markRestartAbortForAllLive: () => Promise<void>
1171
1176
  liveCount: () => number
1172
1177
  __testing?: {
1173
1178
  flushDebounce: (key: ChannelKey) => Promise<void>
@@ -4393,6 +4398,23 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4393
4398
  closing = false
4394
4399
  }
4395
4400
 
4401
+ // Graceful-restart shutdown: mark every live channel session's todo scope so
4402
+ // the turn the restart is about to abort does not arm the durable user-abort
4403
+ // block, then abort the in-flight turns. On the next boot each scope's resume
4404
+ // continues its incomplete todos instead of waiting for a human. Best-effort
4405
+ // and bounded by the caller's shutdown deadline.
4406
+ const markRestartAbortForAllLive = async (): Promise<void> => {
4407
+ for (const live of Array.from(liveSessions.values())) {
4408
+ const origin = buildLiveOrigin(live)
4409
+ await markRestartAbortPendingForOrigin(options.agentDir, origin).catch((err) =>
4410
+ logger.error(`[channels] graceful-restart mark abort failed: ${describe(err)}`),
4411
+ )
4412
+ await live.session
4413
+ .abort()
4414
+ .catch((err) => logger.error(`[channels] graceful-restart abort failed: ${describe(err)}`))
4415
+ }
4416
+ }
4417
+
4396
4418
  // Boot-time resume for a restart that originated from a channel session, in
4397
4419
  // two phases to close the race with adapters that begin receiving inbounds.
4398
4420
  //
@@ -4494,6 +4516,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4494
4516
  await armRestartKickForOrigin(options.agentDir, buildLiveOrigin(live)).catch((err) =>
4495
4517
  logger.error(`[channels] ${keyId}: restart-resume arm restart-kick failed: ${describe(err)}`),
4496
4518
  )
4519
+ // A restart-aborted turn arms the durable user-abort block; this resume
4520
+ // IS the restart, so clear it or the resumed session never auto-resumes
4521
+ // its incomplete todos. Gated to this restart-handoff path.
4522
+ await clearAbortSuppressionForOrigin(options.agentDir, buildLiveOrigin(live)).catch((err) =>
4523
+ logger.error(`[channels] ${keyId}: restart-resume clear abort suppression failed: ${describe(err)}`),
4524
+ )
4497
4525
 
4498
4526
  live.pendingSystemReminders.push(RESTART_RESUME_WAKE_REMINDER)
4499
4527
  logger.info(`[channels] ${keyId}: restart-resume waking session ${live.sessionId}`)
@@ -4792,6 +4820,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4792
4820
  resumeRestartHandoff,
4793
4821
  stop,
4794
4822
  tearDownAllLive,
4823
+ markRestartAbortForAllLive,
4795
4824
  liveCount: () => liveSessions.size,
4796
4825
  __testing: {
4797
4826
  flushDebounce: async (key: ChannelKey) => {
@@ -5062,7 +5091,7 @@ function formatAuthorLine(
5062
5091
  ): string {
5063
5092
  const tag = authorIsBot ? ' [bot]' : ''
5064
5093
  const stamp = ts > 0 ? `[${new Date(ts).toISOString()}] ` : ''
5065
- return `${stamp}${formatAuthorReference(adapter, authorId, authorName)} (${authorName})${tag}: ${capObservedText(text, maxChars)}`
5094
+ return `${stamp}${formatAuthorAttribution(adapter, authorId, authorName)}${tag}: ${capObservedText(text, maxChars)}`
5066
5095
  }
5067
5096
 
5068
5097
  // Cap by whole code points so truncation never splits a surrogate pair (emoji,
@@ -5105,6 +5134,36 @@ function formatInboundPromptLines(
5105
5134
 
5106
5135
  export type { QuoteAnchorSource } from './types'
5107
5136
 
5137
+ export function formatAuthorAttribution(adapter: AdapterId, authorId: string, authorName: string): string {
5138
+ const displayName = authorName.trim()
5139
+ const hasDisplayName = displayName !== ''
5140
+ const id = authorId.trim()
5141
+ if (id === '') return hasDisplayName ? displayName : authorId
5142
+
5143
+ switch (adapter) {
5144
+ case 'slack':
5145
+ case 'slack-bot':
5146
+ case 'discord':
5147
+ case 'discord-bot': {
5148
+ const mention = `<@${id}>`
5149
+ return hasDisplayName ? `${displayName} ${mention}` : mention
5150
+ }
5151
+ case 'github': {
5152
+ const login = /^\d+$/.test(id) && hasDisplayName ? displayName : id
5153
+ const handle = login.startsWith('@') ? login : `@${login}`
5154
+ if (!hasDisplayName) return handle
5155
+ const normalizedDisplayName = displayName.startsWith('@') ? displayName : `@${displayName}`
5156
+ return normalizedDisplayName === handle ? handle : `${displayName} (${handle})`
5157
+ }
5158
+ case 'telegram-bot':
5159
+ case 'webex':
5160
+ case 'webex-bot':
5161
+ case 'line':
5162
+ case 'kakaotalk':
5163
+ return hasDisplayName ? `${displayName} <${id}>` : id
5164
+ }
5165
+ }
5166
+
5108
5167
  // Picks the right author syntax for the platform so prompts and rendered
5109
5168
  // quote anchors use the same form the user would type in that channel.
5110
5169
  // Slack/Discord need id mentions (`<@U…>`), GitHub needs handle mentions
@@ -19,7 +19,7 @@ export type BuiltinCommandName =
19
19
  | 'reload'
20
20
  | 'logs'
21
21
  | 'inspect'
22
- | 'dreams'
22
+ | 'memory'
23
23
  | 'shell'
24
24
  | 'compose'
25
25
  | 'channel'
@@ -51,27 +51,18 @@ export const BUILTIN_COMMANDS: readonly BuiltinCommandMeta[] = [
51
51
  { name: 'status', description: 'show the agent container and host daemon status (host stage)' },
52
52
  { name: 'reload', description: "reload the running agent's reloadable subsystems (cron, ...)" },
53
53
  { name: 'logs', description: 'show the agent container logs (host stage)' },
54
- {
55
- name: 'inspect',
56
- description: 'session viewer: pick a session, the live TUI, or container logs to observe (host stage)',
57
- },
58
- {
59
- name: 'dreams',
60
- description: "browse the dreaming subagent's memory-consolidation journal from git history (host stage)",
61
- },
54
+ { name: 'inspect', description: 'session viewer: a session, the live TUI, or container logs' },
55
+ { name: 'memory', description: "browse and search the agent's long-term memory" },
62
56
  { name: 'shell', description: 'open an interactive shell in the agent container (host stage)' },
63
- { name: 'compose', description: 'orchestrate every typeclaw agent in immediate subdirectories of cwd' },
57
+ { name: 'compose', description: 'orchestrate every typeclaw agent in subdirectories of cwd' },
64
58
  { name: 'channel', description: 'manage channel adapters wired into the agent' },
65
- {
66
- name: 'cron',
67
- description: 'inspect cron jobs registered in the running agent (user-authored + plugin-contributed)',
68
- },
59
+ { name: 'cron', description: 'inspect cron jobs in the running agent (user + plugin)' },
69
60
  { name: 'tunnel', description: 'manage public tunnels for channels and manual upstreams' },
70
61
  { name: 'role', description: 'manage role memberships on this agent' },
71
62
  { name: 'provider', description: 'manage LLM provider credentials in secrets.json' },
72
- { name: 'model', description: 'manage model profiles in typeclaw.json (models.default, models.fast, …)' },
63
+ { name: 'model', description: 'manage model profiles in typeclaw.json (models.default, ...)' },
73
64
  { name: 'mount', description: 'manage host files and directories mounted into the agent container' },
74
- { name: 'doctor', description: 'diagnose the host, agent folder, and plugins; surface remediation steps' },
65
+ { name: 'doctor', description: 'diagnose host, agent folder, and plugins; suggest fixes' },
75
66
  { name: 'usage', description: 'report LLM token usage and cost for this agent folder' },
76
67
  { name: 'update', description: 'update the installed typeclaw CLI (auto-detects global vs local)' },
77
68
  { name: '_hostd', description: 'internal: host-side typeclaw daemon (do not invoke directly)', hidden: true },
@@ -257,7 +257,7 @@ const doctorSub = defineCommand({
257
257
  export const composeCommand = defineCommand({
258
258
  meta: {
259
259
  name: 'compose',
260
- description: 'orchestrate every typeclaw agent in immediate subdirectories of cwd',
260
+ description: 'orchestrate every typeclaw agent in subdirectories of cwd',
261
261
  },
262
262
  subCommands: {
263
263
  start: startSub,
package/src/cli/cron.ts CHANGED
@@ -65,7 +65,7 @@ const listSub = defineCommand({
65
65
  export const cronCommand = defineCommand({
66
66
  meta: {
67
67
  name: 'cron',
68
- description: 'inspect cron jobs registered in the running agent (user-authored + plugin-contributed)',
68
+ description: 'inspect cron jobs in the running agent (user + plugin)',
69
69
  },
70
70
  subCommands: {
71
71
  list: listSub,
package/src/cli/doctor.ts CHANGED
@@ -6,7 +6,7 @@ import { findAgentDir } from '@/init'
6
6
  export const doctorCommand = defineCommand({
7
7
  meta: {
8
8
  name: 'doctor',
9
- description: 'diagnose the host, agent folder, and plugins; surface remediation steps',
9
+ description: 'diagnose host, agent folder, and plugins; suggest fixes',
10
10
  },
11
11
  args: {
12
12
  verbose: {
package/src/cli/dreams.ts CHANGED
@@ -12,7 +12,7 @@ const QUIT_KEY = 0x71
12
12
  export const dreamsCommand = defineCommand({
13
13
  meta: {
14
14
  name: 'dreams',
15
- description: "browse the dreaming subagent's memory-consolidation journal from git history (host stage)",
15
+ description: "browse the dreaming subagent's memory-consolidation journal",
16
16
  },
17
17
  args: {
18
18
  limit: {
package/src/cli/index.ts CHANGED
@@ -25,7 +25,7 @@ const main = defineCommand({
25
25
  reload: () => import('./reload').then((m) => m.reload),
26
26
  logs: () => import('./logs').then((m) => m.logsCommand),
27
27
  inspect: () => import('./inspect').then((m) => m.inspectCommand),
28
- dreams: () => import('./dreams').then((m) => m.dreamsCommand),
28
+ memory: () => import('./memory').then((m) => m.memoryCommand),
29
29
  shell: () => import('./shell').then((m) => m.shellCommand),
30
30
  compose: () => import('./compose').then((m) => m.composeCommand),
31
31
  channel: () => import('./channel').then((m) => m.channelCommand),
@@ -27,7 +27,7 @@ const ESC_DEBOUNCE_MS = 50
27
27
  export const inspectCommand = defineCommand({
28
28
  meta: {
29
29
  name: 'inspect',
30
- description: 'session viewer: pick a session, the live TUI, or container logs to observe (host stage)',
30
+ description: 'session viewer: a session, the live TUI, or container logs',
31
31
  },
32
32
  args: {
33
33
  session: {