typeclaw 0.38.1 → 0.39.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/README.md CHANGED
@@ -5,6 +5,10 @@
5
5
  <h3 align="center">TypeClaw: The agent for perfectionists</h3>
6
6
  <p align="center">Crafted in every detail – it behaves in your team's chat and<br />gets sharper the longer it runs. Sandboxed and self-managing.</p>
7
7
 
8
+ <p align="center">
9
+ <a href="https://discord.gg/V4NQnbXpr"><img src="https://img.shields.io/badge/Discord-Chat%20with%20Typeey-5865F2?logo=discord&logoColor=white" alt="Chat with Typeey on Discord" /></a>
10
+ </p>
11
+
8
12
  <br />
9
13
  <br />
10
14
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.38.1",
3
+ "version": "0.39.0",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -50,7 +50,7 @@
50
50
  "@mariozechner/pi-tui": "^0.67.3",
51
51
  "@modelcontextprotocol/sdk": "^1.29.0",
52
52
  "@mozilla/readability": "^0.6.0",
53
- "agent-messenger": "2.23.4",
53
+ "agent-messenger": "2.23.6",
54
54
  "cheerio": "^1.2.0",
55
55
  "citty": "^0.2.2",
56
56
  "cron-parser": "^5.5.0",
@@ -562,9 +562,10 @@ export function detectAttentionEscalation(text: string): boolean {
562
562
  return MORPHEME_PATTERNS.some((pattern) => pattern.test(normalized))
563
563
  }
564
564
 
565
- // Not `xhigh`: that level is OpenAI-family-only. `high` is universal and
566
- // `setThinkingLevel` clamps it down per-model, so it's safe to pass unconditionally.
567
- const ESCALATED_LEVEL: ThinkingLevel = 'high'
565
+ // `xhigh` is the strongest level. It's OpenAI-family-only, but `setThinkingLevel`
566
+ // clamps it per-model (down to `high` on non-OpenAI), so it's safe to pass
567
+ // unconditionally and gives OpenAI models maximum effort on escalation turns.
568
+ const ESCALATED_LEVEL: ThinkingLevel = 'xhigh'
568
569
 
569
570
  export function resolveTurnThinkingLevel(
570
571
  text: string,
package/src/agent/auth.ts CHANGED
@@ -86,7 +86,7 @@ export function getAuthFor(providerId: KnownProviderId): Auth {
86
86
  // Uses the head of the fallback chain; auth for the rest of the chain is
87
87
  // resolved lazily when fallback actually fires.
88
88
  export function getAuth(): Auth {
89
- const defaultRef = getConfig().models.default[0]!
89
+ const defaultRef = getConfig().models.default.refs[0]!
90
90
  return getAuthFor(providerForModelRef(defaultRef))
91
91
  }
92
92
 
@@ -100,7 +100,7 @@ function hasAnyCredentialInEnv(apiKeyEnv: string | null): boolean {
100
100
 
101
101
  function missingCredentialMessage(providerId: KnownProviderId): string {
102
102
  const provider = KNOWN_PROVIDERS[providerId]
103
- const defaultRef = getConfig().models.default[0]!
103
+ const defaultRef = getConfig().models.default.refs[0]!
104
104
  const defaultProviderId = providerForModelRef(defaultRef)
105
105
  // For the `default` profile, name the model in the error message (matches
106
106
  // pre-multi-model behavior). For any other profile, the user is mixing
@@ -14,7 +14,14 @@ import type { AgentSession, ToolDefinition } from '@mariozechner/pi-coding-agent
14
14
  import { loadMemory } from '@/bundled-plugins/memory/load-memory'
15
15
  import type { ChannelRouter } from '@/channels/router'
16
16
  import type { ReactionRef } from '@/channels/types'
17
- import { getConfig, resolveModel, resolveProfile } from '@/config'
17
+ import {
18
+ getConfig,
19
+ resolveModel,
20
+ resolveProfile,
21
+ type Models,
22
+ type ResolvedProfile,
23
+ type ThinkingLevel,
24
+ } from '@/config'
18
25
  import { defaultThinkingLevelForRef, isOpenAiFamilyRef, providerForModelRef, type ModelRef } from '@/config/providers'
19
26
  import { renderMcpCatalog } from '@/mcp/catalog'
20
27
  import type { McpManager } from '@/mcp/manager'
@@ -235,6 +242,20 @@ export type CreateSessionResult = {
235
242
  dispose: () => Promise<void>
236
243
  }
237
244
 
245
+ // A session's reasoning effort layers like the model does: the resolved
246
+ // profile's own `thinkingLevel` → the `default` profile's `thinkingLevel`
247
+ // (the de-facto global default, mirroring how `models.default` is the default
248
+ // model) → the per-provider/SDK default for the active ref. When the requested
249
+ // profile was unknown, `resolved` is already the `default` profile, so the
250
+ // first two terms coincide and the expression still does the right thing.
251
+ export function resolveSessionThinkingLevel(
252
+ models: Models,
253
+ resolved: Pick<ResolvedProfile, 'thinkingLevel'>,
254
+ activeRef: ModelRef,
255
+ ): ThinkingLevel | undefined {
256
+ return resolved.thinkingLevel ?? models.default.thinkingLevel ?? defaultThinkingLevelForRef(activeRef)
257
+ }
258
+
238
259
  export async function createSession(options: CreateSessionOptions = {}): Promise<AgentSession> {
239
260
  const { session } = await createSessionWithDispose(options)
240
261
  return session
@@ -439,7 +460,9 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
439
460
  : customToolsPreBudget
440
461
 
441
462
  const model = applyModelRuntimeOverrides(resolveModel(activeRef), activeRef)
442
- const thinkingLevel = defaultThinkingLevelForRef(activeRef)
463
+ // Read live so a reloaded `models` lands on the next session without a
464
+ // container restart.
465
+ const thinkingLevel = resolveSessionThinkingLevel(getConfig().models, resolved, activeRef)
443
466
  const { session } = await createAgentSession({
444
467
  model,
445
468
  sessionManager,
@@ -1,8 +1,7 @@
1
1
  import { basename } from 'node:path'
2
2
 
3
3
  import { type RestartHandoffOrigin, writeRestartHandoff } from '@/agent/restart-handoff'
4
- import { send, sendHttp } from '@/hostd/client'
5
- import { containerSocketPath } from '@/hostd/paths'
4
+ import { sendHttp } from '@/hostd/client'
6
5
  import type { Stream } from '@/stream'
7
6
 
8
7
  const ACK_TIMEOUT_MS = 5_000
@@ -16,7 +15,6 @@ export type ContainerRestartingBroadcast = {
16
15
  export type RequestContainerRestartOptions = {
17
16
  containerName: string
18
17
  build?: boolean
19
- socketPath?: string
20
18
  hostdUrl?: string
21
19
  hostdToken?: string
22
20
  ackTimeoutMs?: number
@@ -49,7 +47,6 @@ export type RequestContainerRestartResult =
49
47
  export async function requestContainerRestart({
50
48
  containerName,
51
49
  build,
52
- socketPath,
53
50
  hostdUrl,
54
51
  hostdToken,
55
52
  ackTimeoutMs,
@@ -65,10 +62,22 @@ export async function requestContainerRestart({
65
62
  const httpUrl = hostdUrl ?? process.env.TYPECLAW_HOSTD_URL
66
63
  const httpToken = hostdToken ?? process.env.TYPECLAW_HOSTD_TOKEN
67
64
  const ackBudget = ackTimeoutMs ?? ACK_TIMEOUT_MS
68
- const reply =
69
- httpUrl && httpToken
70
- ? await sendHttp(request, { timeoutMs: ackBudget, url: httpUrl, token: httpToken })
71
- : await send(request, { timeoutMs: ackBudget, socket: socketPath ?? containerSocketPath() })
65
+
66
+ // HTTP/TCP is the only container->hostd transport (TYPECLAW_HOSTD_URL/TOKEN,
67
+ // injected by start.ts via host.docker.internal). There is no Unix-socket
68
+ // fallback: the host run dir is never bind-mounted, so the old
69
+ // `/run/typeclaw-host/hostd.sock` dial always silently failed — and on native
70
+ // Windows the host transport is a named pipe, not a socket. Fail loud here
71
+ // when the control env is absent (hostd unregistered/disabled).
72
+ if (!httpUrl || !httpToken) {
73
+ return {
74
+ ok: false,
75
+ containerName,
76
+ reason:
77
+ 'host daemon control endpoint unavailable (TYPECLAW_HOSTD_URL/TYPECLAW_HOSTD_TOKEN not set); cannot request restart',
78
+ }
79
+ }
80
+ const reply = await sendHttp(request, { timeoutMs: ackBudget, url: httpUrl, token: httpToken })
72
81
 
73
82
  if (!reply.ok) return { ok: false, containerName, reason: reply.reason }
74
83
 
@@ -130,6 +130,24 @@ function describePayload(payload: unknown): string {
130
130
  return typeof payload
131
131
  }
132
132
 
133
+ // Per-spawn override wins over the subagent's declared profile; absent override
134
+ // keeps the declared profile. Both may be undefined (no profile → createSession
135
+ // resolves `default`).
136
+ export function resolveSubagentProfile(
137
+ subagent: SubagentShared<any>,
138
+ options: CreateSessionForSubagentOptions | undefined,
139
+ ): string | undefined {
140
+ return options?.profileOverride ?? subagent.profile
141
+ }
142
+
143
+ function profileFromPayload(payload: unknown): string | undefined {
144
+ if (payload !== null && typeof payload === 'object') {
145
+ const value = (payload as { profile?: unknown }).profile
146
+ if (typeof value === 'string' && value !== '') return value
147
+ }
148
+ return undefined
149
+ }
150
+
133
151
  export type CreateSessionForSubagentResult = {
134
152
  session: AgentSession
135
153
  dispose?: () => Promise<void>
@@ -160,6 +178,12 @@ export type CreateSessionForSubagentOptions = {
160
178
  // wiring hooks without permissions would inject the GitHub token yet leave the
161
179
  // sandbox OFF — strictly weaker than the plugin-subagent branch this matches.
162
180
  permissions?: PermissionService
181
+ // Per-spawn model-profile override, resolved by `invokeSubagent` from the
182
+ // validated payload's `profile` field. Wins over the subagent's declared
183
+ // `profile`, letting a single spawn run a worker on a different model tier
184
+ // (e.g. operator on `deep`) without a second subagent. Unknown profile names
185
+ // fall back to `default` via resolveProfile, the same as a declared profile.
186
+ profileOverride?: string
163
187
  }
164
188
  export type CreateSessionForSubagent = (
165
189
  subagent: Subagent<any>,
@@ -180,7 +204,9 @@ export const defaultCreateSessionForSubagent: CreateSessionForSubagent = (subage
180
204
  customTools: subagent.customTools ?? [],
181
205
  ...(options?.plugins !== undefined ? { plugins: options.plugins } : {}),
182
206
  ...(options?.permissions !== undefined ? { permissions: options.permissions } : {}),
183
- ...(subagent.profile !== undefined ? { profile: subagent.profile } : {}),
207
+ ...(resolveSubagentProfile(subagent, options) !== undefined
208
+ ? { profile: resolveSubagentProfile(subagent, options) }
209
+ : {}),
184
210
  ...(subagent.toolResultBudget !== undefined ? { toolResultBudget: subagent.toolResultBudget } : {}),
185
211
  ...(subagent.bashPolicy !== undefined ? { bashPolicy: subagent.bashPolicy } : {}),
186
212
  })
@@ -255,11 +281,13 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
255
281
 
256
282
  const validatedPayload = validateSubagentPayload(name, subagent, options.payload)
257
283
  const createSessionForSubagent = options.createSessionForSubagent ?? defaultCreateSessionForSubagent
284
+ const profileOverride = profileFromPayload(validatedPayload)
258
285
  const sessionOptions: CreateSessionForSubagentOptions = {
259
286
  name,
260
287
  ...(options.parentSessionId !== undefined ? { parentSessionId: options.parentSessionId } : {}),
261
288
  ...(options.spawnedByRole !== undefined ? { spawnedByRole: options.spawnedByRole } : {}),
262
289
  ...(options.spawnedByOrigin !== undefined ? { spawnedByOrigin: options.spawnedByOrigin } : {}),
290
+ ...(profileOverride !== undefined ? { profileOverride } : {}),
263
291
  }
264
292
 
265
293
  const runSession: RunSession = async (override) => {
@@ -48,9 +48,23 @@ If it describes how you sound, use SOUL.md; how you work, AGENTS.md. **Edit disc
48
48
  - **\`typeclaw.json\`** — runtime config. Read when needed.
49
49
  - **\`secrets.json\`** — canonical gitignored secrets store. \`.env\` is legacy/env override. Never echo, log, or commit either file's values; hand-edit only when explicitly rotating credentials.
50
50
 
51
- ## Execution bias
51
+ ## Understanding the request
52
52
 
53
- Start work in the same turn when the next action is clear; do not answer with only a plan. For multi-step work, give one short progress update, not narration.
53
+ When the next action is clear, start work in the same turn — don't answer with only a plan, and for multi-step work give one short progress update, not narration.
54
+
55
+ Read for the practical task behind the wording, not the literal speech act: a status question ("is the build red?") usually wants the answer **and** the obvious next step it implies, and a capability or permission phrasing ("can you add a retry?", "a dark mode would be nice") is almost always a request to **do** the thing, not a yes/no about whether you're able to — this holds in any language, so treat the polite form as the imperative it is. Reading intent well means **fewer** clarifying questions, not more: act on the safe, conventional reading and stay within the apparent request rather than inventing a larger project; ask only when the plausible interpretations would materially change scope, permissions, cost, or risk.
56
+
57
+ Recognizing the task also means recognizing **who** should do it. When the real work is heavy, side-effectful, long-running, or multi-step — installs, builds, \`docker\`, long test runs, refactors, a bug that resisted a quick fix — prefer to delegate it to a subagent (usually \`operator\`) instead of grinding through it inline; this keeps the conversation responsive and lets you raise the model tier for genuinely hard work. Keep quick, single-shot answers inline. See \`## Subagent orchestration\` for the mechanics.
58
+
59
+ ## Finishing the job
60
+
61
+ When the user asks you to build, run, fix, or verify something, the deliverable is a working artifact backed by real tool output — not a description of one. Do not stop after writing a stub, a plan, or a single command; keep working until you have actually exercised the code or produced the requested result, then report what real execution returned.
62
+
63
+ If a tool, install, or network call fails and blocks the real path, say so directly and try an alternative (different approach, different package, ask the user). Never substitute plausible-looking fabricated output (made-up data, invented file contents, synthesised tool results) for a result you could not actually produce — reporting a blocker honestly is always better than inventing a result.
64
+
65
+ ## Parallel tool calls
66
+
67
+ When you need several pieces of information that don't depend on each other, request them in a single response instead of one tool call per turn. Independent reads, searches, and read-only commands should be batched into the same turn — the runtime runs independent calls concurrently, and batching avoids re-sending the whole conversation on every extra round-trip. Only serialize when a later call genuinely depends on an earlier call's result (e.g. read a file before patching it).
54
68
 
55
69
  ## Tracking your work
56
70
 
@@ -96,7 +110,6 @@ Commits to your agent folder (your own state):
96
110
  - Match the user's register. If SOUL.md specifies a voice, use it; otherwise be concise and direct.
97
111
  - Read files/memory before guessing. Follow AGENTS.md under your IDENTITY.md role; suggest AGENTS.md additions for repeatable gaps.
98
112
  - Answer questions, do work, and avoid over-explaining unless asked.
99
- - Ask one clarifying question only when ambiguity would materially change the work; otherwise choose a reasonable default.
100
113
  - Never suppress errors to make things "work", and never fabricate results. Report failures clearly.
101
114
 
102
115
  ## Subagent orchestration
@@ -107,9 +120,9 @@ Pick one of three modes:
107
120
 
108
121
  **Mode A — Research fan-out.** Broad search: spawn 2-5 \`explorer\`/\`scout\` workers in parallel with \`run_in_background: true\`, end your response, then collect each completion once via \`subagent_output\`. Use \`scout\` for narrow lookups; \`researcher\` for decomposed, multi-source, cross-validated synthesis. When the user *explicitly* says "research"/"investigate" (or equivalent), you MUST spawn \`researcher\` — answering from training memory or a single inline \`web_search\` does not satisfy the request, even if you think you know the answer. (Fanning out \`scout\`/\`explorer\` underneath is fine, but it does not replace \`researcher\`.)
109
122
 
110
- **Mode B — Delegate-and-converse.** For >~30s side-effectful/noisy work (installs, builds, \`docker\`, scrapes, long tests, multi-host loops, fetch-and-synthesize chains), spawn one background subagent and stay responsive: \`operator\` for side effects, \`scout\` quick lookup, \`researcher\` deep investigation, \`planner\` risk-aware sequencing. Keep single fast calls inline. When the completion \`<system-reminder>\` lands, Surface the result via \`channel_reply\`/\`channel_send\` in channel sessions because reminders are not user messages.
123
+ **Mode B — Delegate-and-converse.** For >~30s side-effectful/noisy work (installs, builds, \`docker\`, scrapes, long tests, multi-host loops, fetch-and-synthesize chains), spawn one background subagent and stay responsive: \`operator\` for side effects, \`scout\` quick lookup, \`researcher\` deep investigation, \`planner\` risk-aware sequencing. Keep single fast calls inline. For hard execution work that needs stronger reasoning than the default tier — gnarly bugs, non-obvious refactors, failures that resisted a quick fix — pass \`profile: "deep"\` to run that one spawn on a stronger model; leave it off for routine work. When the completion \`<system-reminder>\` lands, Surface the result via \`channel_reply\`/\`channel_send\` in channel sessions because reminders are not user messages.
111
124
 
112
- **Mode C — Troubleshooting.** After ~3 non-converging attempts at the same failure, stop and hand the loop to \`operator\` with \`run_in_background: true\`, symptom, attempts, and success condition. Read \`typeclaw-troubleshooting\` before spawning.
125
+ **Mode C — Troubleshooting.** After ~3 non-converging attempts at the same failure, stop and hand the loop to \`operator\` with \`run_in_background: true\` (and \`profile: "deep"\` when the failure is genuinely hard), symptom, attempts, and success condition. Read \`typeclaw-troubleshooting\` before spawning.
113
126
 
114
127
  **Status queries.** If the user asks "status?" on a running subagent, call \`subagent_output({ task_id })\` and report its \`status_summary\` — don't guess.
115
128
 
@@ -10,7 +10,6 @@ const EXIT_DELAY_MS = 500
10
10
  export type CreateRestartToolOptions = {
11
11
  containerName: string
12
12
  exit?: (code: number) => void
13
- socketPath?: string
14
13
  hostdUrl?: string
15
14
  hostdToken?: string
16
15
  // Optional so unit tests and ad-hoc tool construction keep working without
@@ -72,7 +71,6 @@ export type { ContainerRestartingBroadcast } from '@/agent/restart'
72
71
  export function createRestartTool({
73
72
  containerName,
74
73
  exit,
75
- socketPath,
76
74
  hostdUrl,
77
75
  hostdToken,
78
76
  stream,
@@ -121,7 +119,6 @@ export function createRestartTool({
121
119
  containerName,
122
120
  build,
123
121
  originatingSessionId,
124
- ...(socketPath !== undefined ? { socketPath } : {}),
125
122
  ...(hostdUrl !== undefined ? { hostdUrl } : {}),
126
123
  ...(hostdToken !== undefined ? { hostdToken } : {}),
127
124
  ...(ackTimeoutMs !== undefined ? { ackTimeoutMs } : {}),
@@ -88,6 +88,12 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
88
88
  'NOTE: background mode from subagents is only available when that subagent is explicitly enabled to drain child results; otherwise use sync spawns batched in one turn instead.',
89
89
  }),
90
90
  ),
91
+ profile: Type.Optional(
92
+ Type.String({
93
+ description:
94
+ 'Model profile to run this spawn on, overriding the subagent\'s default tier for this one task. Use "deep" for hard work that needs stronger reasoning (gnarly bugs, non-obvious refactors, failures that resisted a quick fix); omit (or "default") for routine work. Resolves against the configured model profiles; an unknown name falls back to default. Most useful on `operator` — leave it off unless the task clearly warrants a heavier model.',
95
+ }),
96
+ ),
91
97
  }),
92
98
 
93
99
  async execute(_toolCallId, params): Promise<ToolReturn> {
@@ -122,6 +128,7 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
122
128
  const background = params.run_in_background === true
123
129
  const payload: Record<string, unknown> = { requestId: taskId, prompt: params.prompt }
124
130
  if (params.description !== undefined) payload.description = params.description
131
+ if (params.profile !== undefined) payload.profile = params.profile
125
132
 
126
133
  const startedAt = now()
127
134
  const spawnedByRole = permissions?.resolveRole(origin)
@@ -353,7 +353,11 @@ export function createMemoryPlugin(deps: MemoryPluginDeps = defaultDeps) {
353
353
  const currentSize = await readSize(parentTranscriptPath)
354
354
  const currentLines = await readLineCount(parentTranscriptPath)
355
355
  bytesAtLastRun.set(sessionId, currentSize)
356
- linesAtLastRun.set(sessionId, currentLines)
356
+ // Monotonic: never regress below a baseline the idle gate already
357
+ // reserved. readLineCount returns 0 on a read error or a
358
+ // missing/truncated file, so an unconditional set could undo the
359
+ // eager reservation and reopen the over-fire window this fix closes.
360
+ linesAtLastRun.set(sessionId, Math.max(linesAtLastRun.get(sessionId) ?? 0, currentLines))
357
361
  ctx.logger.info(`memory-logger spawn ${sessionId} reason=${reason} transcript_bytes=${currentSize}`)
358
362
  try {
359
363
  await raceSpawn(ctx.spawnSubagent('memory-logger', payload, spawnOptions), spawnTimeoutMs)
@@ -392,12 +396,22 @@ export function createMemoryPlugin(deps: MemoryPluginDeps = defaultDeps) {
392
396
  return currentSize - baseline >= bufferBytes
393
397
  }
394
398
 
395
- const shouldSkipIdleSpawn = async (sessionId: string, transcriptPath: string): Promise<boolean> => {
396
- if (minIdleDeltaLines === 0) return false
399
+ // Reserves the new baseline ATOMICALLY with the gate read — the
400
+ // read-decide-reserve sequence has no await between reading
401
+ // linesAtLastRun and writing it back, so two idle timers whose
402
+ // readLineCount awaits settle close together cannot both observe the same
403
+ // stale baseline and both accept a spawn. The gate awaits real fs reads,
404
+ // so without this in-continuation reservation the second timer over-fires
405
+ // memory-logger. The deferred (monotonic) set in fireMemoryLogger stays
406
+ // the final exact baseline.
407
+ const decideIdleSpawn = async (sessionId: string, transcriptPath: string): Promise<{ skip: boolean }> => {
408
+ if (minIdleDeltaLines === 0) return { skip: false }
397
409
  const currentLines = await readLineCount(transcriptPath)
398
- if (currentLines === 0) return false
410
+ if (currentLines === 0) return { skip: false }
399
411
  const baseline = linesAtLastRun.get(sessionId) ?? 0
400
- return currentLines - baseline < minIdleDeltaLines
412
+ if (currentLines - baseline < minIdleDeltaLines) return { skip: true }
413
+ linesAtLastRun.set(sessionId, Math.max(baseline, currentLines))
414
+ return { skip: false }
401
415
  }
402
416
 
403
417
  const runMemoryRetrieval = async (event: {
@@ -508,7 +522,11 @@ export function createMemoryPlugin(deps: MemoryPluginDeps = defaultDeps) {
508
522
  const timer = setTimeout(() => {
509
523
  idleTimers.delete(sessionId)
510
524
  void (async () => {
511
- if (transcriptPath !== undefined && (await shouldSkipIdleSpawn(sessionId, transcriptPath))) {
525
+ const decision =
526
+ transcriptPath !== undefined
527
+ ? await decideIdleSpawn(sessionId, transcriptPath)
528
+ : { skip: false as const }
529
+ if (decision.skip) {
512
530
  ctx.logger.info(
513
531
  `memory-logger idle skip ${sessionId} (delta below minIdleDeltaLines=${minIdleDeltaLines})`,
514
532
  )
@@ -105,7 +105,9 @@ The evidence can be the user's exact words, a command/output pair, a file diff t
105
105
  Capture-worthy categories:
106
106
 
107
107
  - **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.
108
- - **Stable identity/role/tool facts that will keep mattering.** User/project/repo/tool/platform facts. Skip casual employment history, social-graph trivia, and membership churn unless the user says it matters.
108
+ - **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.
109
+ - **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.
110
+ - **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.
109
111
  - **Decisions with reasoning.** "We chose X over Y because Z" when future sessions must honor X.
110
112
  - **Reproducible workarounds and debugging insights.** A config that worked, flag combination, procedure, root cause, or non-obvious fix.
111
113
  - **In-transcript changed minds.** Capture "actually, scratch that" only when the prior position is explicit. Do not compare against \`memory/topics/\`.
@@ -128,17 +130,19 @@ If taught content contains several distinct facts, write one topic per fragment,
128
130
 
129
131
  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.
130
132
 
133
+ 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
+
131
135
  Skip these anti-patterns:
132
136
 
133
137
  - **Conversational mechanics.** Questions asked, greetings, laughter/reactions, response-time tests, chat flow.
134
- - **Single-occurrence casual reactions.** Amusement, personality observations, vibes. Wait for recurrence; if it never recurs, it was never memory.
135
- - **Group-chat membership events.** Invitations, joins, leaves, renames. Current channel context can supply this and it changes constantly.
136
- - **Casual social-graph trivia.** Friend/coworker history unless explicitly tied to future work.
138
+ - **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
+ - **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).
140
+ - **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).
137
141
  - **Latency / performance pings.** "How fast did you respond?" is not memory.
138
142
  - **The agent's own first-person observations.** The agent's persona, model confusion, or self-commentary is not memorable to itself.
139
- - **Re-derivable facts.** Anything obvious from the current system prompt, AGENTS.md, or channel context.
143
+ - **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.
140
144
  - **Speculation untethered to a quote.** If no transcript line anchors it, skip.
141
- - **Multi-fragment expansions of one event.** One event produces at most one fragment. Splitting an intro into "new chat", "new participant", "job", "reaction" is over-writing.
145
+ - **Multi-fragment expansions of one event.** One event produces at most one fragment. A teammate introduction may bundle that person's core durable role/responsibility/preference into one compact fragment, but do not split "new chat", "new participant", "job", "preference", "reaction" into separate memories.
142
146
 
143
147
  # Verbatim references (store_reference tool)
144
148
 
@@ -221,13 +225,13 @@ function buildInitialPrompt(payload: MemoryLoggerPayload, streamFile: string, wa
221
225
  }
222
226
  lines.push(
223
227
  '',
224
- "Read the transcript past the watermark. Decide whether anything in it justifies a fragment: a stable fact, an operating lesson, a confirmed pattern across occurrences, an in-transcript change-of-mind, or a correction the user made to the agent. Sometimes the answer is zero fragments; sometimes more than one. Do not read memory/topics/ — cross-shard reasoning is dreaming's job. Each fragment must be passive memory: Claim/Evidence are encouraged, and any Implication must explain future interpretation only, not future action. Memory cannot authorize proactive duties.",
228
+ 'Read the transcript past the watermark and apply the system-prompt rules; most runs yield zero or one fragment.',
225
229
  '',
226
- "Per-fragment provenance: each fragment's `entry=` is the specific transcript entry that anchors that fragment's evidence — not the latest entry you evaluated. Two fragments anchored to two different entries get two different `entry=` values. Do not stamp every fragment with the same id.",
230
+ "Per-fragment provenance: each fragment's `entry=` anchors that fragment's own evidence, not the latest entry you evaluated.",
227
231
  '',
228
- 'Watermark: every `append` call must include the `latestEntryId` argument. Ensure the final `append` call uses the latest transcript entry you evaluated, regardless of whether it anchored a fragment. If you evaluated transcript entries but found zero fragments, call the watermark-advance tool with `{ source: "' +
232
+ 'Every `append` must include `latestEntryId` (the latest entry evaluated, regardless of anchors). With zero fragments, call the watermark-advance tool with `{ source: "' +
229
233
  payload.parentSessionId +
230
- '", latestEntryId: "<latestEntryId>" }` instead of writing a fake fragment.',
234
+ '", latestEntryId: "<latestEntryId>" }` instead of a fake fragment.',
231
235
  )
232
236
  return lines.join('\n')
233
237
  }
@@ -57,6 +57,7 @@ export const operatorPayloadSchema = z
57
57
  requestId: z.string().optional(),
58
58
  prompt: z.string().optional(),
59
59
  description: z.string().optional(),
60
+ profile: z.string().optional(),
60
61
  })
61
62
  .passthrough()
62
63