typeclaw 0.43.1 → 0.44.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.
Files changed (56) hide show
  1. package/README.md +1 -1
  2. package/auth.schema.json +92 -0
  3. package/package.json +2 -2
  4. package/secrets.schema.json +92 -0
  5. package/src/agent/index.ts +14 -2
  6. package/src/agent/multimodal/look-at.ts +27 -9
  7. package/src/agent/plugin-tools.ts +9 -4
  8. package/src/agent/session-origin.ts +1 -0
  9. package/src/agent/tools/channel-fetch-attachment.ts +45 -3
  10. package/src/agent/tools/channel-reply.ts +41 -18
  11. package/src/agent/tools/channel-send.ts +82 -13
  12. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
  13. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
  14. package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
  15. package/src/bundled-plugins/memory/README.md +9 -9
  16. package/src/bundled-plugins/memory/index.ts +40 -9
  17. package/src/channels/adapters/github/inbound.ts +20 -14
  18. package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
  19. package/src/channels/adapters/teams-classify.ts +144 -0
  20. package/src/channels/adapters/teams-id-token.ts +112 -0
  21. package/src/channels/adapters/teams-key.ts +32 -0
  22. package/src/channels/adapters/teams.ts +519 -0
  23. package/src/channels/github-review-turn-ledger.ts +43 -0
  24. package/src/channels/index.ts +1 -1
  25. package/src/channels/manager.ts +54 -1
  26. package/src/channels/router.ts +302 -39
  27. package/src/channels/schema.ts +9 -0
  28. package/src/cli/channel.ts +92 -4
  29. package/src/cli/hostd.ts +41 -0
  30. package/src/cli/init.ts +58 -1
  31. package/src/config/channels-mutation.ts +9 -1
  32. package/src/cron/index.ts +16 -4
  33. package/src/cron/reloadable.ts +25 -7
  34. package/src/cron/scheduler.ts +4 -0
  35. package/src/cron/schema.ts +143 -35
  36. package/src/doctor/channel-checks.ts +27 -0
  37. package/src/hostd/daemon.ts +23 -3
  38. package/src/hostd/protocol.ts +2 -0
  39. package/src/hostd/teams-renewal-manager.ts +212 -0
  40. package/src/init/checkpoint.ts +1 -1
  41. package/src/init/index.ts +68 -1
  42. package/src/init/run-owner-claim.ts +1 -0
  43. package/src/init/teams-auth.ts +111 -0
  44. package/src/inspect/label.ts +4 -0
  45. package/src/permissions/match-rule.ts +11 -1
  46. package/src/permissions/resolve.ts +1 -0
  47. package/src/role-claim/match-rule.ts +2 -1
  48. package/src/run/index.ts +35 -8
  49. package/src/run/llm-fetch-observer.ts +27 -5
  50. package/src/sandbox/build.ts +12 -0
  51. package/src/sandbox/policy.ts +13 -0
  52. package/src/sandbox/writable-zones.ts +46 -10
  53. package/src/secrets/schema.ts +32 -0
  54. package/src/secrets/teams-renewal.ts +229 -0
  55. package/src/secrets/teams-store.ts +108 -0
  56. package/typeclaw.schema.json +163 -3
@@ -116,7 +116,8 @@ export function createChannelSendTool({
116
116
  'GitHub review threads ONLY — ignored on every other adapter and on a github send that has no `thread`. ' +
117
117
  'Set `true` to close out a review thread you authored once you have confirmed the new commits address your concern: pass the thread\'s root comment id as `thread`, an acknowledgement (e.g. "addressed in <sha> — resolving") as `text`, and this flag. ' +
118
118
  'This is the post-push close-out path: a `pull_request.synchronize` recheck lists your unresolved threads, and you call this once per addressed thread. ' +
119
- "Safe by default — the runtime resolves BEFORE posting and ONLY if the thread's root comment is yours, refusing (and blocking the send) on a human reviewer's thread. Leave it unset to keep the thread open (not addressed, partial fix, disagreement).",
119
+ "Safe by default — the runtime resolves BEFORE posting and ONLY if the thread's root comment is yours, refusing (and blocking the send) on a human reviewer's thread. " +
120
+ 'REQUIRED on a github PR review-thread send that has both a `thread` and `text`: pass `false` to post your reply while keeping the thread open (not addressed, partial fix, disagreement) — omitting it there is denied. Outside that scope (no `thread`, no `text`, or a non-github adapter) it may be left unset.',
120
121
  }),
121
122
  ),
122
123
  }),
@@ -162,6 +163,28 @@ export function createChannelSendTool({
162
163
  }
163
164
  }
164
165
 
166
+ // Required-choice guard (mirrors channel_reply): a github PR review-thread
167
+ // send with text must make an explicit resolve_review_thread choice. The
168
+ // `pull_request.synchronize` recheck routes the post-push close-out HERE
169
+ // via channel_send, and the model kept acknowledging "addressed" without
170
+ // the flag, stranding the thread — channel_reply forced the choice but
171
+ // channel_send did not, so the most-used resolve path was the least
172
+ // guarded. A send is always terminal, so there is no continue exemption.
173
+ const missingResolveChoice = missingReviewThreadResolveChoiceError({
174
+ adapter,
175
+ chat: params.chat,
176
+ thread: params.thread ?? null,
177
+ text: bodyText,
178
+ resolveReviewThread: params.resolve_review_thread,
179
+ })
180
+ if (missingResolveChoice) {
181
+ logger.warn(formatChannelToolFailure('channel_send', missingResolveChoice))
182
+ return {
183
+ content: [{ type: 'text' as const, text: `channel_send denied: ${missingResolveChoice}` }],
184
+ details: { ok: false, error: missingResolveChoice },
185
+ }
186
+ }
187
+
165
188
  const wantsResolve = params.resolve_review_thread === true
166
189
  const falseReceipt = checkFalseReceipt({
167
190
  sessionId,
@@ -207,21 +230,32 @@ export function createChannelSendTool({
207
230
  // block the acknowledgement so the bot never posts "addressed — resolving"
208
231
  // next to a still-open thread. The router enforces that only the bot's own
209
232
  // threads can be resolved.
233
+ let resolveMissNotice: string | null = null
210
234
  if (wantsResolve) {
211
- const resolveError = await resolveReviewThreadBeforeSend(router, {
235
+ const resolve = await resolveReviewThreadBeforeSend(router, {
212
236
  adapter,
213
237
  workspace: params.workspace,
214
238
  chat: params.chat,
215
239
  thread: params.thread ?? null,
216
240
  })
217
- if (resolveError !== null) {
218
- logger.warn(formatChannelToolFailure('channel_send', resolveError))
241
+ if (resolve.kind === 'block') {
242
+ logger.warn(formatChannelToolFailure('channel_send', resolve.error))
219
243
  return {
220
- content: [{ type: 'text' as const, text: `channel_send denied: ${resolveError}` }],
221
- details: { ok: false, error: resolveError },
244
+ content: [{ type: 'text' as const, text: `channel_send denied: ${resolve.error}` }],
245
+ details: { ok: false, error: resolve.error },
222
246
  }
223
247
  }
224
- recordResolvedThreadFromSend(sessionId, params.workspace, params.chat, params.thread ?? null)
248
+ // `no-match`: the thread listed cleanly but nothing is rooted at this
249
+ // comment (gone, or a mispaired id from the bare-id follow-up list). It
250
+ // stays non-blocking so a genuinely-deleted thread's ack still posts,
251
+ // but the resolve did NOT happen — surface it so the model re-targets,
252
+ // and skip the ledger so a phantom resolution can't suppress this
253
+ // thread on a later sweep.
254
+ if (resolve.kind === 'no-match') {
255
+ resolveMissNotice = resolveMissHint(params.thread ?? null)
256
+ } else {
257
+ recordResolvedThreadFromSend(sessionId, params.workspace, params.chat, params.thread ?? null)
258
+ }
225
259
  }
226
260
 
227
261
  const result = await router.send({
@@ -275,6 +309,8 @@ export function createChannelSendTool({
275
309
 
276
310
  if (falseReceiptNotice !== null) hints.push(fenceRuntimeNotice(falseReceiptNotice))
277
311
 
312
+ if (resolveMissNotice !== null) hints.push(resolveMissNotice)
313
+
278
314
  return {
279
315
  content: [{ type: 'text' as const, text: `${fenceToolResult(receipt)}${hints.join('')}` }],
280
316
  details,
@@ -288,15 +324,37 @@ export function createChannelSendTool({
288
324
  })
289
325
  }
290
326
 
327
+ function missingReviewThreadResolveChoiceError(input: {
328
+ adapter: AdapterId
329
+ chat: string
330
+ thread: string | null
331
+ text: string | undefined
332
+ resolveReviewThread: boolean | undefined
333
+ }): string {
334
+ const isGithubPrReviewThread = input.adapter === 'github' && /^pr:\d+$/.test(input.chat) && input.thread !== null
335
+ const hasText = input.text !== undefined && input.text.trim() !== ''
336
+ if (!isGithubPrReviewThread || !hasText || input.resolveReviewThread !== undefined) {
337
+ return ''
338
+ }
339
+ return (
340
+ 'This is a github PR review-thread send with text, so `resolve_review_thread` is required: ' +
341
+ 'set it to `true` when the concern is fixed and this bot-authored thread should be closed (the runtime ' +
342
+ 'resolves before posting and only on your own thread), or `false` to leave it open. You omitted it; ' +
343
+ 're-call channel_send with an explicit boolean.'
344
+ )
345
+ }
346
+
347
+ type ResolveOutcome = { kind: 'resolved' } | { kind: 'no-match' } | { kind: 'block'; error: string }
348
+
291
349
  async function resolveReviewThreadBeforeSend(
292
350
  router: ChannelRouter,
293
351
  target: { adapter: AdapterId; workspace: string; chat: string; thread: string | null },
294
- ): Promise<string | null> {
352
+ ): Promise<ResolveOutcome> {
295
353
  if (target.adapter !== 'github') {
296
- return 'resolve_review_thread is only supported on github sends.'
354
+ return { kind: 'block', error: 'resolve_review_thread is only supported on github sends.' }
297
355
  }
298
356
  if (target.thread === null) {
299
- return 'resolve_review_thread requires a `thread` (the review thread root comment id).'
357
+ return { kind: 'block', error: 'resolve_review_thread requires a `thread` (the review thread root comment id).' }
300
358
  }
301
359
  const result = await router.resolveReviewThread({
302
360
  adapter: target.adapter,
@@ -304,9 +362,20 @@ async function resolveReviewThreadBeforeSend(
304
362
  chat: target.chat,
305
363
  rootCommentId: target.thread,
306
364
  })
307
- if (result.ok) return null
308
- if (result.code === 'no-match') return null
309
- return `could not resolve review thread: ${result.error}`
365
+ if (result.ok) return { kind: 'resolved' }
366
+ if (result.code === 'no-match') return { kind: 'no-match' }
367
+ return { kind: 'block', error: `could not resolve review thread: ${result.error}` }
368
+ }
369
+
370
+ // The model asked to resolve but no thread was rooted at this comment. Fenced
371
+ // as a runtime notice (not chat prose) so a persona-rich model reads it as
372
+ // tool feedback and re-targets, rather than replying to it in-character.
373
+ function resolveMissHint(thread: string | null): string {
374
+ return fenceRuntimeNotice(
375
+ `you set resolve_review_thread but no unresolved review thread is rooted at comment ${JSON.stringify(thread)} — ` +
376
+ `your reply posted, but that thread was not resolved (it may be already gone, or you passed the wrong root ` +
377
+ `comment id). If a different thread should close, re-call channel_send with the correct \`thread\`.`,
378
+ )
310
379
  }
311
380
 
312
381
  function recordResolvedThreadFromSend(sessionId: string, workspace: string, chat: string, thread: string | null): void {
@@ -1,4 +1,4 @@
1
- import type { ReviewVerdict } from '@/channels/github-review-turn-ledger'
1
+ import type { ReviewOutputState, ReviewVerdict } from '@/channels/github-review-turn-ledger'
2
2
 
3
3
  // Extracts the formal-review verdict a successful `gh` command landed, so the
4
4
  // false-receipt ledger can credit it. Covers the three vectors the agent uses to
@@ -49,6 +49,106 @@ export function detectReviewSubmission(input: GhReviewDetectInput): DetectedRevi
49
49
  return null
50
50
  }
51
51
 
52
+ // A landed review of ANY state — the two decisive verdicts PLUS a COMMENT. Feeds
53
+ // the router's empty-turn guard (a COMMENT is real user-facing output, so an empty
54
+ // completion afterward must not fire the "I got stuck" fallback). Deliberately
55
+ // SEPARATE from detectReviewSubmission, which stays verdict-only for the
56
+ // false-receipt ledger: a COMMENT carries no verdict-claim risk and must never be
57
+ // credited there. A bare create-review with no event (a PENDING draft, not a
58
+ // submitted review) returns null — only a submitted state counts as output.
59
+ export type DetectedReviewOutput = {
60
+ workspace: string
61
+ prNumber: number
62
+ state: ReviewOutputState
63
+ source: 'api' | 'pr-review'
64
+ }
65
+
66
+ export function detectReviewOutput(input: GhReviewDetectInput): DetectedReviewOutput | null {
67
+ const fileContents = input.inputFileContents ?? null
68
+ for (const args of ghSegments(input.command)) {
69
+ const sub = args[1]
70
+ if (sub === 'api') {
71
+ const out = detectApiReviewOutput(args, fileContents)
72
+ if (out !== null) return out
73
+ } else if (sub === 'pr' && args[2] === 'review') {
74
+ const out = detectPrReviewOutput(args)
75
+ if (out !== null) return out
76
+ }
77
+ }
78
+ return null
79
+ }
80
+
81
+ function detectApiReviewOutput(args: readonly string[], fileContents: string | null): DetectedReviewOutput | null {
82
+ const endpoint = args.find((a) => REVIEWS_ENDPOINT.test(a))
83
+ if (endpoint === undefined) return null
84
+ const m = REVIEWS_ENDPOINT.exec(endpoint)
85
+ if (m === null) return null
86
+ const prNumber = Number(m[3])
87
+ if (!Number.isSafeInteger(prNumber)) return null
88
+ const state = reviewStateFromInlineFields(args) ?? reviewStateFromFile(fileContents)
89
+ if (state === null) return null
90
+ return { workspace: `${m[1]}/${m[2]}`, prNumber, state, source: 'api' }
91
+ }
92
+
93
+ function detectPrReviewOutput(args: readonly string[]): DetectedReviewOutput | null {
94
+ const state: ReviewOutputState | null = args.includes('--approve')
95
+ ? 'APPROVE'
96
+ : args.includes('--request-changes')
97
+ ? 'REQUEST_CHANGES'
98
+ : args.includes('--comment') || args.includes('-c')
99
+ ? 'COMMENT'
100
+ : null
101
+ if (state === null) return null
102
+ const workspace = repoFromFlag(args)
103
+ const prNumber = prNumberArg(args)
104
+ if (workspace === null || prNumber === null) return null
105
+ return { workspace, prNumber, state, source: 'pr-review' }
106
+ }
107
+
108
+ function reviewStateFromInlineFields(args: readonly string[]): ReviewOutputState | null {
109
+ for (let i = 0; i < args.length; i++) {
110
+ const a = args[i]
111
+ if (a === undefined) continue
112
+ if (a === '-f' || a === '-F' || a === '--field' || a === '--raw-field') {
113
+ const v = parseEventState(args[i + 1])
114
+ if (v !== null) return v
115
+ }
116
+ if (a.startsWith('-f=') || a.startsWith('-F=') || a.startsWith('--field=') || a.startsWith('--raw-field=')) {
117
+ const v = parseEventState(a.slice(a.indexOf('=') + 1))
118
+ if (v !== null) return v
119
+ }
120
+ }
121
+ return null
122
+ }
123
+
124
+ function parseEventState(token: string | undefined): ReviewOutputState | null {
125
+ if (token === undefined) return null
126
+ const eq = token.indexOf('=')
127
+ if (eq === -1) return null
128
+ if (token.slice(0, eq).trim().toLowerCase() !== 'event') return null
129
+ return normalizeReviewState(token.slice(eq + 1))
130
+ }
131
+
132
+ function reviewStateFromFile(contents: string | null): ReviewOutputState | null {
133
+ if (contents === null || contents === '') return null
134
+ try {
135
+ const parsed = JSON.parse(contents) as unknown
136
+ if (typeof parsed !== 'object' || parsed === null) return null
137
+ const event = (parsed as Record<string, unknown>).event
138
+ return typeof event === 'string' ? normalizeReviewState(event) : null
139
+ } catch {
140
+ return null
141
+ }
142
+ }
143
+
144
+ function normalizeReviewState(value: string): ReviewOutputState | null {
145
+ const v = value.trim().toUpperCase()
146
+ if (v === 'APPROVE') return 'APPROVE'
147
+ if (v === 'REQUEST_CHANGES') return 'REQUEST_CHANGES'
148
+ if (v === 'COMMENT') return 'COMMENT'
149
+ return null
150
+ }
151
+
52
152
  // Each segment is the argv of one `gh` invocation found anywhere in the command.
53
153
  function detectInGhSegment(args: readonly string[], fileContents: string | null): DetectedReview | null {
54
154
  const sub = args[1]
@@ -1,12 +1,14 @@
1
1
  import { readFile } from 'node:fs/promises'
2
2
 
3
- import { recordReview } from '@/channels/github-review-turn-ledger'
3
+ import { recordReview, recordReviewOutput } from '@/channels/github-review-turn-ledger'
4
4
  import type { ContentPart, ToolResult } from '@/plugin'
5
5
 
6
6
  import {
7
+ detectReviewOutput,
7
8
  detectReviewSubmission,
8
9
  detectReviewSubmissionAttempt,
9
10
  type DetectedReview,
11
+ type DetectedReviewOutput,
10
12
  type ReviewSubmissionAttempt,
11
13
  } from './gh-review-detect'
12
14
  import { detectReviewDump, type ReviewDumpDecision } from './gh-review-inline-detect'
@@ -29,6 +31,10 @@ import { detectReviewDump, type ReviewDumpDecision } from './gh-review-inline-de
29
31
 
30
32
  const pending = new Map<string, DetectedReview>()
31
33
  const submissionAttempts = new Map<string, ReviewSubmissionAttempt>()
34
+ // COMMENT-only submissions, stashed apart from `pending`: a decisive verdict is
35
+ // credited to the false-receipt ledger via recordReview (which also fans to the
36
+ // output observer), so only non-verdict COMMENTs need their own output credit.
37
+ const pendingCommentOutput = new Map<string, DetectedReviewOutput>()
32
38
 
33
39
  const MAX_INPUT_BYTES = 1_000_000
34
40
 
@@ -45,8 +51,19 @@ export async function noteReviewCommand(args: { callId: string; command: string
45
51
  // missed shape): only such a command may later arm the backstop, so a reviews
46
52
  // READ — which is not an attempt — can never be miscredited as a landed review.
47
53
  else {
48
- const attempt = detectReviewSubmissionAttempt(args.command)
49
- if (attempt !== null) submissionAttempts.set(args.callId, attempt)
54
+ // A COMMENT review carries no verdict, so it dodges `pending` above — stash it
55
+ // here so a successful COMMENT still credits review OUTPUT (not the verdict
56
+ // ledger) and suppresses the router's empty-turn fallback. It is stashed
57
+ // INSTEAD of a submission attempt: the backstop only ever credits a decisive
58
+ // verdict, so arming it for a COMMENT would just leave a stale attempt entry
59
+ // that `commitReviewIfSucceeded`'s COMMENT branch returns before clearing.
60
+ const output = detectReviewOutput({ command: args.command, inputFileContents })
61
+ if (output !== null && output.state === 'COMMENT') {
62
+ pendingCommentOutput.set(args.callId, output)
63
+ } else {
64
+ const attempt = detectReviewSubmissionAttempt(args.command)
65
+ if (attempt !== null) submissionAttempts.set(args.callId, attempt)
66
+ }
50
67
  }
51
68
  return { dump: detectReviewDump({ command: args.command, inputFileContents }), detected }
52
69
  }
@@ -79,6 +96,22 @@ export function commitReviewIfSucceeded(args: {
79
96
  return { committed: true, landedFromResult: null }
80
97
  }
81
98
 
99
+ // A COMMENT review credits review OUTPUT only (never the verdict ledger). Same
100
+ // fail-closed success bias as verdicts: an ambiguous result stays uncredited.
101
+ const comment = pendingCommentOutput.get(args.callId)
102
+ if (comment !== undefined) {
103
+ pendingCommentOutput.delete(args.callId)
104
+ if (commentReviewSucceeded(text)) {
105
+ recordReviewOutput({
106
+ sessionId: args.sessionId,
107
+ workspace: comment.workspace,
108
+ prNumber: comment.prNumber,
109
+ state: 'COMMENT',
110
+ })
111
+ }
112
+ return { committed: false, landedFromResult: null }
113
+ }
114
+
82
115
  // The backstop runs ONLY for a command that tool.before saw as a real
83
116
  // submission attempt (POST create-review) but whose verdict it could not
84
117
  // extract. This excludes a reviews-list READ outright, and the PR-match below
@@ -177,8 +210,16 @@ const API_SUCCESS_MARKERS = [
177
210
  '"state": "APPROVED"',
178
211
  ]
179
212
  const PR_REVIEW_SUCCESS_MARKERS = ['Approved pull request', 'Requested changes to pull request']
213
+ // COMMENT vectors: REST echoes `"state":"COMMENTED"`; the `gh pr review --comment`
214
+ // porcelain prints "Reviewed pull request …". Covers both spacings of the JSON.
215
+ const COMMENT_SUCCESS_MARKERS = ['"state":"COMMENTED"', '"state": "COMMENTED"', 'Reviewed pull request']
180
216
  const FAILURE_MARKERS = ['gh: ', 'HTTP 4', 'HTTP 5', 'Bad credentials', 'Not Found', 'Validation Failed']
181
217
 
218
+ function commentReviewSucceeded(text: string): boolean {
219
+ if (FAILURE_MARKERS.some((m) => text.includes(m))) return false
220
+ return COMMENT_SUCCESS_MARKERS.some((m) => text.includes(m))
221
+ }
222
+
182
223
  // Require a success marker AND no failure marker, so a partial/garbled capture
183
224
  // fails closed (uncredited).
184
225
  function looksSucceeded(detected: DetectedReview, text: string): boolean {
@@ -2,7 +2,7 @@ import { readFile, realpath } from 'node:fs/promises'
2
2
  import path from 'node:path'
3
3
 
4
4
  import { parseConfigJson } from '@/config'
5
- import { parseCronJson } from '@/cron'
5
+ import { validateCronEdit } from '@/cron'
6
6
 
7
7
  import type { GuardBlock } from '../policy'
8
8
 
@@ -30,7 +30,8 @@ export async function checkManagedConfigGuard(options: {
30
30
  const contentResult = await intendedContent(tool, args, targetPath)
31
31
  if ('block' in contentResult) return contentResult
32
32
 
33
- const validation = validateManagedContent(managed.file, contentResult.content)
33
+ const existing = await readExisting(targetPath)
34
+ const validation = validateManagedContent(managed.file, contentResult.content, existing)
34
35
  if (validation.ok) return undefined
35
36
 
36
37
  return {
@@ -66,15 +67,30 @@ async function resolveManagedTarget(agentDir: string, targetPath: string): Promi
66
67
  return undefined
67
68
  }
68
69
 
69
- function validateManagedContent(file: ManagedFile, content: string): { ok: true } | { ok: false; reason: string } {
70
+ function validateManagedContent(
71
+ file: ManagedFile,
72
+ content: string,
73
+ existing: string | undefined,
74
+ ): { ok: true } | { ok: false; reason: string } {
70
75
  if (file === 'typeclaw.json') {
71
76
  const result = parseConfigJson(content, { migrate: false })
72
77
  return result.ok ? { ok: true } : { ok: false, reason: result.reason }
73
78
  }
74
- const result = parseCronJson(content, { mode: 'edit' })
79
+ // Delta validation: a stale `at`/`until` on a job carried over unchanged from
80
+ // the existing file must not block the edit (esp. an edit that removes it),
81
+ // but a newly-added or re-timed past job is still rejected. See validateCronEdit.
82
+ const result = validateCronEdit(content, existing)
75
83
  return result.ok ? { ok: true } : { ok: false, reason: result.reason }
76
84
  }
77
85
 
86
+ async function readExisting(targetPath: string): Promise<string | undefined> {
87
+ try {
88
+ return await readFile(targetPath, 'utf8')
89
+ } catch {
90
+ return undefined
91
+ }
92
+ }
93
+
78
94
  async function intendedContent(
79
95
  tool: string,
80
96
  args: Record<string, unknown>,
@@ -12,19 +12,19 @@ Auto-loaded by every TypeClaw agent. No `plugins[]` entry to add and no opt-out.
12
12
  "idleMs": 60000,
13
13
  "bufferBytes": 500000,
14
14
  "injectionBudgetBytes": 16384,
15
- "minIdleDeltaLines": 3,
15
+ "minIdleDeltaLines": 20,
16
16
  "dreaming": { "schedule": "*/30 * * * *" }
17
17
  }
18
18
  }
19
19
  ```
20
20
 
21
- | Field | Default | Effect |
22
- | ----------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
23
- | `memory.idleMs` | `60000` | Debounce window before `memory-logger` spawns after a prompt completes. Minimum `1000`. |
24
- | `memory.bufferBytes` | `500000` | Size-based ceiling: spawns `memory-logger` when the transcript grows by this many bytes since the last run. `0` disables. Minimum `10000` when non-zero. |
25
- | `memory.injectionBudgetBytes` | `16384` | Total shard-body budget for direct-mode memory injection. Above this, per-turn retrieval switches to index mode and uses top-K hybrid search; channel turns always receive headings only. Minimum `4096`. |
26
- | `memory.minIdleDeltaLines` | `3` | Minimum JSONL line growth since the last `memory-logger` run required to fire an idle spawn. Below this, the idle timer ticks but no spawn fires. `0` disables (legacy always-fire-on-idle behavior). Independent of `bufferBytes`. |
27
- | `memory.dreaming.schedule` | `"*/30 * * * *"` | Five-field cron expression for the dreaming subagent. |
21
+ | Field | Default | Effect |
22
+ | ----------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
23
+ | `memory.idleMs` | `60000` | Debounce window before `memory-logger` spawns after a prompt completes. Minimum `1000`. |
24
+ | `memory.bufferBytes` | `500000` | Size-based ceiling: spawns `memory-logger` when the transcript grows by this many bytes since the last run. `0` disables. Minimum `10000` when non-zero. |
25
+ | `memory.injectionBudgetBytes` | `16384` | Total shard-body budget for direct-mode memory injection. Above this, per-turn retrieval switches to index mode and uses top-K hybrid search; channel turns always receive headings only. Minimum `4096`. |
26
+ | `memory.minIdleDeltaLines` | `20` | Minimum JSONL line growth since the last `memory-logger` run required to fire an idle spawn. Below this, the idle timer ticks but no spawn fires — the unread span is deferred to the next buffer-trip or `session.end` (which advances the watermark), so nothing is lost. Tuned for channel-native traffic (busy group chats where most exchanges aren't memorable). `0` disables (legacy always-fire-on-idle behavior). Independent of `bufferBytes`. |
27
+ | `memory.dreaming.schedule` | `"*/30 * * * *"` | Five-field cron expression for the dreaming subagent. |
28
28
 
29
29
  All fields are **restart-required** — the plugin reads them once at boot. The `memory` block is plugin-owned config that passes through core's schema (`.catchall`), so it is **outside the core `FIELD_EFFECTS` reload fence**: changing any `memory.*` field and running `typeclaw reload` silently no-ops with no "restart-required" warning. Restart the container to apply.
30
30
 
@@ -160,7 +160,7 @@ In busy channel sessions the agent rarely goes idle long enough to trip the time
160
160
 
161
161
  The `session.idle` hook fires after every prompt completion. A chatty channel session that briefly quiets four times in seven minutes would otherwise pay the per-spawn floor (system-prompt prefill + stream-file read + several decision-making turns) on each tick — even when only a handful of new transcript lines have arrived, almost certainly containing nothing memorable.
162
162
 
163
- `memory.minIdleDeltaLines` (default `3`) gates the idle-timer spawn: when the timer fires, if the transcript grew by fewer than this many JSONL lines since the last memory-logger run for the session, the spawn is skipped. The skip is logged as `memory-logger idle skip ses_X (delta below minIdleDeltaLines=N)`. The buffer-trip path is unaffected — sessions that grow `bufferBytes` of unread transcript still spawn regardless of line delta.
163
+ `memory.minIdleDeltaLines` (default `20`, tuned for channel-native traffic) gates the idle-timer spawn: when the timer fires, if the transcript grew by fewer than this many JSONL lines since the last memory-logger run for the session, the spawn is skipped. The skip is logged as `memory-logger idle skip ses_X (delta below minIdleDeltaLines=N)`. Skipping is **loss-free**: an idle skip does not advance the watermark, so the unread span stays unprocessed and is read in full by the next catch-all — a later non-skipped idle spawn, the buffer-trip ceiling, or `session.end` (which also fires on channel stale-rollover). The buffer-trip path is unaffected — sessions that grow `bufferBytes` of unread transcript still spawn regardless of line delta.
164
164
 
165
165
  ### Byte-equality skip (session.end)
166
166
 
@@ -35,20 +35,34 @@ const DEFAULT_BUFFER_BYTES = 500_000
35
35
  const MIN_BUFFER_BYTES = 10_000
36
36
  // Minimum JSONL line growth since the last memory-logger run required to spawn
37
37
  // on a plain `session.idle` tick. The hook fires after every prompt completion,
38
- // so a chatty channel session that goes briefly quiet 4 times in 7 minutes
39
- // would otherwise pay the full per-spawn floor (~50 KB context + 4-11 turns of
40
- // LLM decision-making) on each tick — even when the new transcript content is
41
- // a handful of lines almost certain to contain nothing memorable.
38
+ // so a chatty channel session that goes briefly quiet several times in a few
39
+ // minutes would otherwise pay the full per-spawn floor (~50 KB context + 4-11
40
+ // turns of LLM decision-making) on each tick — even when the new transcript
41
+ // content is a handful of lines almost certain to contain nothing memorable.
42
+ //
43
+ // TypeClaw is channel-native: nearly every real session is a group chat where
44
+ // most exchanges are banter and memory accrues rarely. Measured on a live
45
+ // agent, ~62% of memory-logger runs write zero fragments, concentrated in a few
46
+ // busy human channels re-distilled every idle tick. A default of `3` lines is a
47
+ // chat-message-sized bar, so it barely dampens that. `20` is tuned to the
48
+ // channel reality without changing the buffer-trip / session-end catch-alls.
49
+ //
50
+ // Raising this is loss-free by construction: an idle skip does NOT advance the
51
+ // watermark, so the skipped span stays unprocessed and is read in full by the
52
+ // next catch-all — a later non-skipped idle spawn, the buffer-trip ceiling, or
53
+ // `session.end` (which also fires on channel stale-rollover). Skipping delays
54
+ // capture; it never drops it. That is why the gate is idle-only.
42
55
  //
43
56
  // Gate semantics: skip the spawn when (currentLines - linesAtLastRun) < N AND
44
57
  // the transcript file actually exists with at least one line. A zero-line
45
58
  // transcript (test dummies, brand-new sessions) is NOT gated — the existing
46
59
  // "fire and let memory-logger decide" behavior is preserved.
47
60
  //
48
- // The buffer-trip path (size-based ceiling) is independent and unaffected:
49
- // busy sessions that grow `bufferBytes` of unread transcript still spawn
50
- // regardless of the idle delta.
51
- const DEFAULT_MIN_IDLE_DELTA_LINES = 3
61
+ // The buffer-trip path (size-based ceiling) and `session.end` are independent
62
+ // and unaffected: busy sessions that grow `bufferBytes` of unread transcript
63
+ // still spawn regardless of the idle delta, and session close/rollover always
64
+ // sweeps the unprocessed tail.
65
+ const DEFAULT_MIN_IDLE_DELTA_LINES = 20
52
66
  // 30-minute default. Fires short-circuit before any LLM call when nothing
53
67
  // sits past the watermark (`dreaming.ts` handler returns when
54
68
  // `snapshots.undreamed.length === 0`), so frequent no-op fires are cheap.
@@ -264,7 +278,17 @@ export function createMemoryPlugin(deps: MemoryPluginDeps = defaultDeps) {
264
278
 
265
279
  const idleTimers = new Map<string, ReturnType<typeof setTimeout>>()
266
280
  const lastIdleEvent = new Map<string, { parentTranscriptPath: string | undefined; origin?: SessionOrigin }>()
281
+ // Byte size at the last memory-logger observation. NOTE: this is seeded by
282
+ // `shouldTripBufferCeiling` on a session's FIRST idle WITHOUT a logger run
283
+ // (the buffer-ceiling needs an initial baseline to measure growth against).
284
+ // It is therefore a buffer-ceiling delta baseline, NOT a "drained up to
285
+ // here" watermark — do not use it to decide session.end can skip.
267
286
  const bytesAtLastRun = new Map<string, number>()
287
+ // Byte size at the last ACTUAL memory-logger spawn (set only inside the
288
+ // chained spawn body). This is the real drained watermark: session.end's
289
+ // byte-equality skip trusts THIS, so a buffer-seeded baseline can never
290
+ // masquerade as "already logged" and drop an un-distilled prefix.
291
+ const bytesAtLastSpawn = new Map<string, number>()
268
292
  const linesAtLastRun = new Map<string, number>()
269
293
  // Per-session stream-file cursor: the JSONL line count of the daily
270
294
  // stream file at the END of this session's most recent memory-logger
@@ -331,6 +355,9 @@ export function createMemoryPlugin(deps: MemoryPluginDeps = defaultDeps) {
331
355
  const currentSize = await readSize(parentTranscriptPath)
332
356
  const currentLines = await readLineCount(parentTranscriptPath)
333
357
  bytesAtLastRun.set(sessionId, currentSize)
358
+ // Real drained watermark — set only here, inside an actual spawn, so
359
+ // session.end's byte-equality skip never trusts a buffer-only seed.
360
+ bytesAtLastSpawn.set(sessionId, currentSize)
334
361
  // Monotonic: never regress below a baseline the idle gate already
335
362
  // reserved. readLineCount returns 0 on a read error or a
336
363
  // missing/truncated file, so an unconditional set could undo the
@@ -538,7 +565,10 @@ export function createMemoryPlugin(deps: MemoryPluginDeps = defaultDeps) {
538
565
  const last = lastIdleEvent.get(sessionId)
539
566
  let skip = false
540
567
  if (last?.parentTranscriptPath !== undefined) {
541
- const baseline = bytesAtLastRun.get(sessionId)
568
+ // Trust only a REAL drained watermark, not the buffer-ceiling
569
+ // seed — otherwise a session whose prefix was seeded but never
570
+ // logged would skip its final sweep and lose that prefix.
571
+ const baseline = bytesAtLastSpawn.get(sessionId)
542
572
  if (baseline !== undefined && baseline > 0) {
543
573
  const currentSize = await readSize(last.parentTranscriptPath)
544
574
  if (currentSize === baseline) {
@@ -552,6 +582,7 @@ export function createMemoryPlugin(deps: MemoryPluginDeps = defaultDeps) {
552
582
  if (!skip) void fireMemoryLogger(sessionId, 'session-end')
553
583
  lastIdleEvent.delete(sessionId)
554
584
  bytesAtLastRun.delete(sessionId)
585
+ bytesAtLastSpawn.delete(sessionId)
555
586
  linesAtLastRun.delete(sessionId)
556
587
  streamCursorAtLastRun.delete(sessionId)
557
588
  })()
@@ -10,7 +10,7 @@ import type { DeliveryDedup } from './dedup'
10
10
  import { isGithubEventAllowed } from './event-allowlist'
11
11
  import { encodeGithubReactionRef, type GithubReactionTarget } from './reactions'
12
12
  import { fetchSelfReviewBlocking } from './review-state'
13
- import { listUnresolvedSelfReviewThreads } from './review-thread-resolver'
13
+ import { listUnresolvedSelfReviewThreads, type UnresolvedSelfReviewThread } from './review-thread-resolver'
14
14
 
15
15
  export type GithubInboundLogger = { info: (m: string) => void; warn: (m: string) => void; error: (m: string) => void }
16
16
 
@@ -280,15 +280,14 @@ function scheduleReviewFollowup(input: {
280
280
  else options.logger.warn(`[github] review-state recheck failed for ${target}: ${blocking.error}`)
281
281
  }
282
282
 
283
- const rootCommentIds = threads.threads.map((t) => t.rootCommentId)
284
- if (rootCommentIds.length === 0 && !selfBlocking) return
283
+ if (threads.threads.length === 0 && !selfBlocking) return
285
284
  options.route(
286
285
  withApprovalPolicy(
287
286
  buildReviewFollowupInbound({
288
287
  repository,
289
288
  pullNumber,
290
289
  headSha,
291
- rootCommentIds,
290
+ threads: threads.threads,
292
291
  selfBlocking,
293
292
  title: readString(pr, 'title'),
294
293
  }),
@@ -307,15 +306,15 @@ function buildReviewFollowupInbound(input: {
307
306
  repository: { owner: string; name: string }
308
307
  pullNumber: number
309
308
  headSha: string
310
- rootCommentIds: readonly number[]
309
+ threads: readonly UnresolvedSelfReviewThread[]
311
310
  selfBlocking: boolean
312
311
  title: string | null
313
312
  }): InboundMessage {
314
- const { repository, pullNumber, headSha, rootCommentIds, selfBlocking, title } = input
313
+ const { repository, pullNumber, headSha, threads, selfBlocking, title } = input
315
314
  const titleSegment = title !== null && title.trim() !== '' ? `: "${title}"` : ''
316
315
  const text =
317
316
  `PR #${pullNumber}${titleSegment} received new commits (now at ${headSha.slice(0, 7)}). ` +
318
- followupInstruction(rootCommentIds, selfBlocking)
317
+ followupInstruction(threads, selfBlocking)
319
318
 
320
319
  return {
321
320
  adapter: 'github',
@@ -336,14 +335,15 @@ function buildReviewFollowupInbound(input: {
336
335
  }
337
336
  }
338
337
 
339
- function followupInstruction(rootCommentIds: readonly number[], selfBlocking: boolean): string {
338
+ function followupInstruction(threads: readonly UnresolvedSelfReviewThread[], selfBlocking: boolean): string {
340
339
  const threadPart =
341
- rootCommentIds.length > 0
342
- ? `You have ${rootCommentIds.length} unresolved review thread(s) you authored on this PR ` +
343
- `(root comment id(s): ${rootCommentIds.join(', ')}). For each, check whether the new commits ` +
344
- `addressed your concern. If addressed, reply on that thread via channel_send with a short ` +
345
- `acknowledgement and resolve_review_thread: true (the thread id is the root comment id); ` +
346
- `if not, leave it open. `
340
+ threads.length > 0
341
+ ? `You have ${threads.length} unresolved review thread(s) you authored on this PR. ` +
342
+ `For each, check whether the new commits addressed your concern, then act on THAT thread ` +
343
+ `by passing its root comment id as \`thread\` to channel_send: if addressed, reply with a short ` +
344
+ `acknowledgement and resolve_review_thread: true; if not, reply with resolve_review_thread: false ` +
345
+ `(or leave it). Use the id — not the file/line — as \`thread\`; the file/line is only to tell the ` +
346
+ `threads apart:\n${threads.map(renderThreadLine).join('\n')}\n`
347
347
  : ''
348
348
  // A held CHANGES_REQUESTED never clears itself: GitHub keeps the block until a
349
349
  // fresh APPROVE/COMMENT/dismiss, so a blocking follow-up must always end with a
@@ -360,6 +360,12 @@ function followupInstruction(rootCommentIds: readonly number[], selfBlocking: bo
360
360
  return `${threadPart}${blockingPart}${tail}`
361
361
  }
362
362
 
363
+ function renderThreadLine(thread: UnresolvedSelfReviewThread): string {
364
+ const where = thread.path !== null ? ` on ${thread.path}${thread.line !== null ? `:${thread.line}` : ''}` : ''
365
+ const concern = thread.snippet !== null ? ` — "${thread.snippet}"` : ''
366
+ return `- thread ${thread.rootCommentId}${where}${concern}`
367
+ }
368
+
363
369
  export async function verifySignature(body: string, secret: string, sigHeader: string): Promise<boolean> {
364
370
  const expected = `sha256=${createHmac('sha256', secret).update(body).digest('hex')}`
365
371
  const a = Buffer.from(expected)