typeclaw 0.43.1 → 0.45.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 (86) hide show
  1. package/README.md +1 -1
  2. package/auth.schema.json +92 -0
  3. package/package.json +7 -6
  4. package/secrets.schema.json +92 -0
  5. package/src/agent/index.ts +25 -2
  6. package/src/agent/model-fallback.ts +59 -40
  7. package/src/agent/multimodal/look-at.ts +29 -10
  8. package/src/agent/plugin-tools.ts +9 -4
  9. package/src/agent/provider-error.ts +71 -18
  10. package/src/agent/retry-same-ref.ts +139 -0
  11. package/src/agent/session-origin.ts +1 -0
  12. package/src/agent/subagents.ts +6 -2
  13. package/src/agent/tools/channel-edit.ts +144 -0
  14. package/src/agent/tools/channel-fetch-attachment.ts +51 -8
  15. package/src/agent/tools/channel-reply.ts +41 -18
  16. package/src/agent/tools/channel-send.ts +82 -13
  17. package/src/agent/tools/curl-impersonate.ts +40 -1
  18. package/src/agent/tools/webfetch/fetch.ts +86 -3
  19. package/src/agent/tools/webfetch/tool.ts +26 -3
  20. package/src/agent/tools/webfetch/types.ts +8 -0
  21. package/src/agent/turn-runner.ts +65 -36
  22. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +28 -11
  23. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
  24. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
  25. package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
  26. package/src/bundled-plugins/memory/README.md +9 -9
  27. package/src/bundled-plugins/memory/index.ts +40 -9
  28. package/src/bundled-plugins/reviewer/skills/code-review.ts +22 -2
  29. package/src/channels/adapters/discord-bot-edit.ts +49 -0
  30. package/src/channels/adapters/discord-bot.ts +5 -0
  31. package/src/channels/adapters/discord-edit.ts +51 -0
  32. package/src/channels/adapters/discord.ts +4 -0
  33. package/src/channels/adapters/github/inbound.ts +20 -14
  34. package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
  35. package/src/channels/adapters/slack-bot-edit.ts +58 -0
  36. package/src/channels/adapters/slack-bot.ts +18 -6
  37. package/src/channels/adapters/slack-edit.ts +47 -0
  38. package/src/channels/adapters/slack.ts +5 -0
  39. package/src/channels/adapters/teams-classify.ts +144 -0
  40. package/src/channels/adapters/teams-edit.ts +61 -0
  41. package/src/channels/adapters/teams-id-token.ts +112 -0
  42. package/src/channels/adapters/teams-key.ts +32 -0
  43. package/src/channels/adapters/teams.ts +523 -0
  44. package/src/channels/adapters/telegram-bot-edit.ts +51 -0
  45. package/src/channels/adapters/telegram-bot.ts +5 -0
  46. package/src/channels/adapters/webex-bot.ts +5 -0
  47. package/src/channels/adapters/webex-edit.ts +47 -0
  48. package/src/channels/adapters/webex.ts +5 -0
  49. package/src/channels/continuation-willingness.ts +227 -35
  50. package/src/channels/github-review-turn-ledger.ts +43 -0
  51. package/src/channels/index.ts +1 -1
  52. package/src/channels/manager.ts +54 -1
  53. package/src/channels/router.ts +482 -53
  54. package/src/channels/schema.ts +33 -0
  55. package/src/channels/types.ts +36 -0
  56. package/src/cli/channel.ts +92 -4
  57. package/src/cli/hostd.ts +41 -0
  58. package/src/cli/init.ts +58 -1
  59. package/src/config/channels-mutation.ts +9 -1
  60. package/src/cron/index.ts +16 -4
  61. package/src/cron/reloadable.ts +25 -7
  62. package/src/cron/scheduler.ts +4 -0
  63. package/src/cron/schema.ts +143 -35
  64. package/src/doctor/channel-checks.ts +27 -0
  65. package/src/hostd/daemon.ts +23 -3
  66. package/src/hostd/protocol.ts +2 -0
  67. package/src/hostd/teams-renewal-manager.ts +212 -0
  68. package/src/init/checkpoint.ts +1 -1
  69. package/src/init/index.ts +68 -1
  70. package/src/init/run-owner-claim.ts +1 -0
  71. package/src/init/teams-auth.ts +111 -0
  72. package/src/inspect/label.ts +4 -0
  73. package/src/permissions/match-rule.ts +11 -1
  74. package/src/permissions/resolve.ts +1 -0
  75. package/src/role-claim/match-rule.ts +2 -1
  76. package/src/run/index.ts +35 -8
  77. package/src/run/llm-fetch-observer.ts +27 -5
  78. package/src/sandbox/build.ts +12 -0
  79. package/src/sandbox/policy.ts +13 -0
  80. package/src/sandbox/writable-zones.ts +46 -10
  81. package/src/secrets/schema.ts +32 -0
  82. package/src/secrets/teams-renewal.ts +229 -0
  83. package/src/secrets/teams-store.ts +108 -0
  84. package/src/server/command-runner.ts +2 -1
  85. package/src/server/index.ts +2 -1
  86. package/typeclaw.schema.json +163 -3
@@ -1,7 +1,8 @@
1
1
  import type { ModelRef } from '@/config/providers'
2
2
 
3
3
  import type { AgentSession } from './index'
4
- import { detectProviderError, subscribeProviderErrors } from './provider-error'
4
+ import { detectProviderError, isRetryableSameRef, subscribeProviderErrors } from './provider-error'
5
+ import { RETRIES_PER_REF, retryTurnOnPersistentSession } from './retry-same-ref'
5
6
  import { modelThrottleCircuit, type ThrottleCircuit } from './throttle-circuit'
6
7
 
7
8
  export type PersistentTurnAttempt = {
@@ -73,44 +74,57 @@ export async function promptPersistentTurnWithFallback(opts: {
73
74
  if (softError === undefined) softError = new Error(err.message)
74
75
  })
75
76
  try {
76
- try {
77
- await opts.session.prompt(opts.text)
78
- } catch (err) {
79
- const error = err instanceof Error ? err : new Error(String(err))
80
- const attempt: PersistentTurnAttempt = { ref, outcome: 'hard', errorMessage: error.message }
81
- attempts.push(attempt)
82
- lastError = error
83
- if (opts.shouldFailover(error)) circuit.recordThrottle({ profile: opts.profile, ref })
84
- if (isLast || !canAdvance(error, activity, opts.shouldFailover)) throw error
85
- opts.onAttemptFailed?.(attempt)
86
- continue
87
- }
88
- if (softError !== undefined) {
89
- const attempt: PersistentTurnAttempt = { ref, outcome: 'soft', errorMessage: softError.message }
90
- attempts.push(attempt)
91
- lastError = softError
92
- if (opts.shouldFailover(softError)) circuit.recordThrottle({ profile: opts.profile, ref })
93
- if (isLast || !canAdvance(softError, activity, opts.shouldFailover)) {
94
- return { success: false, refUsed: ref, attempts, lastError }
77
+ // Same-ref retry loop: replay this ref on a transient failure before
78
+ // advancing the chain. `retry === 0` is the first, prompt()-driven attempt;
79
+ // later iterations resume via agent.continue() (no user-message re-append).
80
+ let outcome: AttemptOutcome | undefined
81
+ for (let retry = 0; ; retry++) {
82
+ softError = undefined
83
+ let outcomeThisAttempt: AttemptOutcome | undefined
84
+ try {
85
+ if (retry === 0) {
86
+ await opts.session.prompt(opts.text)
87
+ } else {
88
+ const retried = await retryTurnOnPersistentSession(opts.session, { attempt: retry - 1 })
89
+ // The safe continue-recipe couldn't apply: keep the PREVIOUS failure
90
+ // outcome (never cleared) and let it drive the advance/return below.
91
+ if (!retried) break
92
+ }
93
+ outcomeThisAttempt = classifySoftOutcome(softError, opts)
94
+ } catch (err) {
95
+ outcomeThisAttempt = { kind: 'hard', error: err instanceof Error ? err : new Error(String(err)) }
95
96
  }
96
- opts.onAttemptFailed?.(attempt)
97
- continue
97
+ outcome = outcomeThisAttempt
98
+ if (outcome === undefined) break
99
+ // Only keep retrying while the failure is same-ref retryable, the turn
100
+ // stayed idempotent (no output/tool-exec yet), and budget remains.
101
+ const mayRetry =
102
+ retry < RETRIES_PER_REF &&
103
+ isRetryableSameRef(outcome.error.message) &&
104
+ !activity.producedAssistantOutput &&
105
+ !activity.startedToolExecution
106
+ if (!mayRetry) break
98
107
  }
99
- const leafSoftError = opts.detectSoftErrorFromLeaf ? detectLeafSoftError(opts.session) : undefined
100
- if (leafSoftError !== undefined) {
101
- const attempt: PersistentTurnAttempt = { ref, outcome: 'soft', errorMessage: leafSoftError.message }
102
- attempts.push(attempt)
103
- lastError = leafSoftError
104
- if (opts.shouldFailover(leafSoftError)) circuit.recordThrottle({ profile: opts.profile, ref })
105
- if (isLast || !canAdvance(leafSoftError, activity, opts.shouldFailover)) {
106
- return { success: false, refUsed: ref, attempts, lastError }
107
- }
108
- opts.onAttemptFailed?.(attempt)
109
- continue
108
+
109
+ if (outcome === undefined) {
110
+ attempts.push({ ref, outcome: 'success' })
111
+ circuit.recordSuccess({ profile: opts.profile, ref })
112
+ return { success: true, refUsed: ref, attempts }
113
+ }
114
+
115
+ // Ref abandoned after exhausting same-ref retries. Record throttle ONCE
116
+ // here (not per internal retry) so a single turn can't self-trip the
117
+ // circuit breaker.
118
+ const attempt: PersistentTurnAttempt = { ref, outcome: outcome.kind, errorMessage: outcome.error.message }
119
+ attempts.push(attempt)
120
+ lastError = outcome.error
121
+ if (opts.shouldFailover(outcome.error)) circuit.recordThrottle({ profile: opts.profile, ref })
122
+ if (isLast || !canAdvance(outcome.error, activity, opts.shouldFailover)) {
123
+ if (outcome.kind === 'hard') throw outcome.error
124
+ return { success: false, refUsed: ref, attempts, lastError }
110
125
  }
111
- attempts.push({ ref, outcome: 'success' })
112
- circuit.recordSuccess({ profile: opts.profile, ref })
113
- return { success: true, refUsed: ref, attempts }
126
+ opts.onAttemptFailed?.(attempt)
127
+ continue
114
128
  } finally {
115
129
  unsubProvider()
116
130
  unsubActivity()
@@ -119,6 +133,21 @@ export async function promptPersistentTurnWithFallback(opts: {
119
133
  return { success: false, refUsed: opts.refs[opts.refs.length - 1]!, attempts, lastError }
120
134
  }
121
135
 
136
+ type AttemptOutcome = { kind: 'hard' | 'soft'; error: Error }
137
+
138
+ // Classify a completed (non-throwing) attempt: a captured soft error, else a
139
+ // leaf soft error (subagent path), else success (undefined). Mirrors the two
140
+ // soft-error sources the loop handled inline before the retry refactor.
141
+ function classifySoftOutcome(
142
+ softError: Error | undefined,
143
+ opts: { session: AgentSession; detectSoftErrorFromLeaf?: boolean },
144
+ ): AttemptOutcome | undefined {
145
+ if (softError !== undefined) return { kind: 'soft', error: softError }
146
+ const leafSoftError = opts.detectSoftErrorFromLeaf ? detectLeafSoftError(opts.session) : undefined
147
+ if (leafSoftError !== undefined) return { kind: 'soft', error: leafSoftError }
148
+ return undefined
149
+ }
150
+
122
151
  function canAdvance(error: Error, activity: AttemptActivity, shouldFailover: (err: Error) => boolean): boolean {
123
152
  return shouldFailover(error) && !activity.producedAssistantOutput && !activity.startedToolExecution
124
153
  }
@@ -15,10 +15,12 @@ already downloaded, so the CLI is ready to use out of the box.
15
15
 
16
16
  ## Human-in-the-loop via the dashboard
17
17
 
18
- You run inside a Docker container with no display, no clipboard, and no way to
19
- hand the keyboard over directly. The **dashboard is your only path to bring a
20
- human into a browser session** — it streams every session's live viewport,
21
- console, and command activity to a web UI the user opens on their host machine.
18
+ You run inside a Docker container. Chrome renders to the in-container virtual X
19
+ display (Xvfb, `DISPLAY=:99`), but there is no human-accessible display or
20
+ clipboard and no way to hand the keyboard over directly. The **dashboard is your
21
+ only path to bring a human into a browser session** — it streams every session's
22
+ live viewport, console, and command activity to a web UI the user opens on their
23
+ host machine.
22
24
 
23
25
  **Start the dashboard _before_ the step that needs a human, not after it fails.**
24
26
  The dashboard takes a moment to come up and the user needs time to open the URL.
@@ -91,13 +93,28 @@ you just want to show the user a single page or a captured state:
91
93
  Reserve the dashboard for cases that genuinely need live interaction or
92
94
  watching a multi-step flow unfold.
93
95
 
94
- ### Headless only
95
-
96
- Never pass `--headed` to any `agent-browser` command — the container has no X
97
- server or `$DISPLAY`, and a headed launch fails with `Missing X server or
98
- $DISPLAY / The platform failed to initialize.` The dashboard is the substitute
99
- for a headed browser. Use the default headless mode for everything, including
100
- dogfooding and Electron flows.
96
+ ### Headed vs headless
97
+
98
+ By default the container ships a virtual X server: the entrypoint spawns Xvfb
99
+ and exports `DISPLAY=:99`, so `--headed` (or `AGENT_BROWSER_HEADED=1`) launches a
100
+ real headed Chrome. Headless is fine for ordinary automation — dogfooding, form
101
+ filling, Electron flows, capturing a page you can already reach.
102
+
103
+ Prefer `--headed` when a site is guarded by a WAF/anti-bot layer (Akamai Bot
104
+ Manager, Cloudflare, PerimeterX — common on large e-commerce and portal sites).
105
+ Chrome's `--headless`/`--headless=new` modes are fingerprinted by these stacks
106
+ via signals no UA spoof can patch, so a headless launch draws a `403 Access
107
+ Denied` / CAPTCHA where a headed one under Xvfb passes. This is the whole reason
108
+ the container runs Xvfb. For a hard case, combine headed mode with a persistent
109
+ `--profile` and warm the session (land on the homepage, then navigate
110
+ organically) so the site's trust cookie is issued before you hit the target
111
+ page.
112
+
113
+ The one exception: if the agent folder sets `docker.file.xvfb: false`, there is
114
+ no `DISPLAY` and a headed launch fails with `Missing X server or $DISPLAY / The
115
+ platform failed to initialize.` In that configuration, stay headless and use the
116
+ dashboard for anything that needs a human. If a `--headed` command ever returns
117
+ that error, the toggle is off — fall back to headless rather than retrying.
101
118
 
102
119
  ## Start here
103
120
 
@@ -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
  })()
@@ -3,7 +3,7 @@ import type { LoadableSkill } from '@/plugin'
3
3
  export const CODE_REVIEW_SKILL_NAME = 'code-review'
4
4
 
5
5
  export const CODE_REVIEW_SKILL_DESCRIPTION =
6
- 'Review code: a pull request, a commit, a single file, or a module. Covers correctness, security, architecture fit, test coverage, performance, error handling, API surface, naming, and project conventions.'
6
+ 'Review code: a pull request, a commit, a single file, or a module. Covers correctness, security, architecture fit, test coverage, performance, error handling, API surface, naming, project conventions, and the PR title/body itself as a record — whether it captures the why behind each change for future readers.'
7
7
 
8
8
  export const CODE_REVIEW_SKILL_CONTENT = `# code-review
9
9
 
@@ -55,6 +55,26 @@ A finding without context is noise. Before forming findings:
55
55
  3. **Read the project's conventions.** \`AGENTS.md\`, \`CONTRIBUTING.md\`, \`CLAUDE.md\`, \`README.md\`, the test layout, the linter config. Deviation from established convention is a finding worth raising; following convention is not worth praising.
56
56
  4. **Read the tests.** Existing tests show what the project considers important to verify. New tests show what the author considers important to lock in. The gap between them is often where the bugs hide.
57
57
 
58
+ ## Review the PR title and body as an artifact, not just as context
59
+
60
+ Steps above use the PR title and body as *input* — the author's stated intent, which you check the code against. But the description is also a **deliverable in its own right, and it is part of your review scope.** Most harnesses only diff code and never review the prose; you are the one pass that can, so treat the title and body as a first-class review target alongside the diff.
61
+
62
+ Why this matters — the frame that decides your findings here:
63
+
64
+ - **A PR is a record, not a showcase.** Its dominant purpose is not to display the code or even to solicit code review — it is to **record the translation from the business need into the code change**: *why* this change became necessary, what business or product context forced it, what decision was made and what was rejected. The code shows *what* changed; the body is the only place *why* survives. When the why is absent, it is gone the moment the author forgets it.
65
+ - **The audience is the reviewer and future-self, who do NOT share the author's context.** The current reviewer, a teammate six months from now, or the author themselves later, all read this record under real cognitive load, missing the context that was obvious the day it was written. A good body exists to *lower that load*. Judge the body by whether a reader without the author's head can reconstruct why each change was made.
66
+ - **The concrete failure is a change whose context is silently dropped.** A large task drags in incidental side changes; the low-importance ones lose their rationale first, and later someone does redundant or wrong work because the record never explained the earlier decision (e.g. a field added in one PR with no note that it duplicates an existing one, so a later PR "fixes" a problem that was actually intentional). This is the highest-value thing to catch: a change in the diff that the body leaves **unexplained or unconnected to its reason**.
67
+
68
+ What to look for in the title and body:
69
+
70
+ 1. **Rationale for every meaningful change, not just the headline one.** The primary change is usually explained. The finding is the *secondary* change — a schema tweak, a config flip, a "while I was here" refactor, a new field — that appears in the diff with no corresponding why in the body. Anchor the finding to the diff hunk whose rationale is missing, and name what a future reader would fail to reconstruct.
71
+ 2. **Title accuracy and scope match.** Does the title name what the change actually does? Does the body's described scope match the diff — nothing significant in the diff that the body never mentions, and nothing promised in the body that the diff never delivers? A title that says A while the diff also does B is a scope/record defect: the B change is now unfindable by anyone searching the history for it.
72
+ 3. **Meaning-unit separation.** When the diff bundles several unrelated logical changes under one description, the context for each is harder to recover and the record is degraded even if every line is correct. Flag it as a record problem — the fix may be to split the PR, or at minimum to give each logical unit its own explained section in the body — not as a code defect.
73
+ 4. **Decision and trade-off capture.** For a change that chose one approach over an obvious alternative, or that is a deliberate one-way door (schema, public API, migration), does the body record the decision and why? A silent irreversible decision is a record gap worth raising even when the code is correct.
74
+ 5. **Linked context integrity.** Referenced issues/tickets/prior PRs actually correspond to this change; a load-bearing claim in the body ("as decided in #123") points where it says it does. A dangling or wrong reference breaks the record's chain.
75
+
76
+ Keep the anti-noise line from below firmly in view: **do not confuse restating the description with reviewing it.** Summarizing what the PR does back to the author is noise (see "What NOT to find"). The review work here is the *gap* — a change with no recorded reason, a title that misleads, a bundled scope that buries context, a decision left unexplained. Anchor these to the specific diff hunk or the quoted body passage; use \`location="general"\` only for a whole-description defect (e.g. an empty body on a non-trivial change) and say why in the \`<issue>\`. Calibrate severity to consequence, not to prose taste: an unexplained behavior-changing hunk or a title that hides a real change is a \`concern\` (a \`blocker\` when the missing context is what stops a future reader from avoiding a concrete mistake); a thin-but-adequate body is at most a \`nit\`. A body's writing quality is not the target — its function as a record is.
77
+
58
78
  ## What to look for
59
79
 
60
80
  Prioritize in this order:
@@ -77,7 +97,7 @@ Prioritize in this order:
77
97
  - **Settled convention objections.** If the project uses tabs, four-space indent, camelCase vs snake_case, etc., and the change matches, that is not a finding. Only the deviation is.
78
98
  - **Generic best-practice essays.** "Consider adding more tests" without naming a specific untested branch is noise. "Improve error handling" without pointing at a specific swallowed error is noise.
79
99
  - **Restating the code.** "This function reads the file and returns its contents" is not a finding.
80
- - **Restating the change description.** Summarizing what the PR does back to its author — "this PR adds caching to the user lookup" — is not a review. They wrote the description; they know.
100
+ - **Restating the change description.** Summarizing what the PR does back to its author — "this PR adds caching to the user lookup" — is not a review. They wrote the description; they know. (This forbids *echoing* the body, not *reviewing* it: judging whether the body records the why, matches the diff, and separates its meaning units is in scope — see "Review the PR title and body as an artifact". The line is echo vs. evaluate.)
81
101
  - **Already-acknowledged gaps.** A weakness the author already flagged with a \`TODO\`/\`FIXME\` in the diff, or named in the PR body as out of scope, is not a finding — they're already aware. Only raise it if you have new information: the gap is worse than they think, or it's a blocker they've mislabeled as deferrable. Say which.
82
102
 
83
103
  ## Severity hints specific to code