@yasaswy.nagavolu/agents 0.26.7 → 0.26.9

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 (28) hide show
  1. package/content/hooks/conclusion-scribe/conclusion_scribe_hook.py +1 -1
  2. package/content/hooks/conclusion-scribe/test_conclusion_scribe_hook.py +12 -0
  3. package/content/manifest.json +14 -6
  4. package/content/mods/handoff/README.md +2 -2
  5. package/content/mods/handoff/hooks/register.js +84 -2
  6. package/content/mods/handoff/lib/keepwarm.mjs +3 -2
  7. package/content/mods/handoff/lib/pending.mjs +100 -0
  8. package/content/mods/handoff/prompts/keepwarm-nudge.md +1 -1
  9. package/content/mods/handoff/tests/e2e/tui_dialog_e2e.py +253 -0
  10. package/content/mods/handoff/tests/e2e/tui_driver.py +160 -0
  11. package/content/mods/handoff/tests/e2e/tui_driver_smoke.py +174 -0
  12. package/content/mods/handoff/tests/keepwarm.test.mjs +12 -2
  13. package/content/mods/handoff/tests/pending.test.mjs +107 -0
  14. package/content/mods/handoff/tests/register-dialogs.test.mjs +295 -0
  15. package/content/mods/handoff/tests/register.test.mjs +8 -8
  16. package/content/mods/handoff/tests/template.test.mjs +1 -1
  17. package/content/mods/model-routing/README.md +6 -4
  18. package/content/mods/model-routing/hooks/register.js +36 -15
  19. package/content/mods/model-routing/lib/route.mjs +5 -2
  20. package/content/mods/model-routing/tests/e2e/run_routing_e2e.py +59 -4
  21. package/content/mods/model-routing/tests/register.test.mjs +65 -8
  22. package/content/mods/model-routing/tests/route.test.mjs +12 -3
  23. package/content/proxy/agent_model_guard.py +2 -2
  24. package/content/proxy/routing_audit.py +9 -0
  25. package/content/proxy/routing_log.py +79 -16
  26. package/content/proxy/routing_post_hook.py +28 -12
  27. package/lib/routingCheck.js +18 -5
  28. package/package.json +1 -1
@@ -182,7 +182,7 @@ SHIP_RE = re.compile(
182
182
  r"\b(shipped|fixed|live|pushed|committed|green|mandate|closed|deployed)\b", re.I
183
183
  )
184
184
  ISSUE_URL_RE = re.compile(r"gitlab\.com/[\w./-]+/(?:issues|work_items)/\d+")
185
- ISSUE_URL_PARTS_RE = re.compile(r"gitlab\.com/([\w./-]+)/(?:issues|work_items)/(\d+)")
185
+ ISSUE_URL_PARTS_RE = re.compile(r"gitlab\.com/([\w./-]+?)(?:/-)?/(?:issues|work_items)/(\d+)")
186
186
  ISSUE_REF_RE = re.compile(r"^([\w-]+)#(\d+)$")
187
187
  TESTS_RE = re.compile(
188
188
  r"\b\d+(?:/\d+)?\s*(?:tests?|specs?)\b[^.\n]{0,24}?"
@@ -257,6 +257,18 @@ def test_extract_facts_issue_ref_is_whitelist_only(monkeypatch):
257
257
  assert facts["issue"] is None
258
258
 
259
259
 
260
+ @pytest.mark.parametrize("url,ref", [
261
+ ("https://gitlab.com/group/my-agents/-/issues/692", "my-agents#692"),
262
+ ("https://gitlab.com/group/my-agents/-/work_items/693", "my-agents#693"),
263
+ ("https://gitlab.com/group/my-agents/issues/694", "my-agents#694"),
264
+ ("https://gitlab.com/group/sub/unmapped/-/issues/695", "unmapped#695"),
265
+ ("https://gitlab.com/group/unmapped/issues/696", "unmapped#696"),
266
+ ])
267
+ def test_extract_issue_ref_handles_gitlab_dash_routing_segment(url, ref):
268
+ merged = {"my-agents": "group%2Fmy-agents"}
269
+ assert hook._extract_issue_ref(f"closed {url} today", merged) == ref
270
+
271
+
260
272
  def test_extract_facts_no_git_info_degrades_to_none_fields(monkeypatch):
261
273
  monkeypatch.setattr(hook, "_merged_project_map", lambda: {})
262
274
  monkeypatch.setattr(hook, "_head_sha", lambda cwd: None)
@@ -1597,12 +1597,20 @@
1597
1597
  {
1598
1598
  "path": "proxy/routing_post_hook.py",
1599
1599
  "kind": "hook",
1600
- "wiring": {
1601
- "event": "PostToolUse",
1602
- "matcher": "Agent",
1603
- "type": "command",
1604
- "command": "python ~/.claude/proxy/routing_post_hook.py"
1605
- }
1600
+ "wiring": [
1601
+ {
1602
+ "event": "PostToolUse",
1603
+ "matcher": "Agent",
1604
+ "type": "command",
1605
+ "command": "python ~/.claude/proxy/routing_post_hook.py"
1606
+ },
1607
+ {
1608
+ "event": "PostToolUseFailure",
1609
+ "matcher": "Agent",
1610
+ "type": "command",
1611
+ "command": "python ~/.claude/proxy/routing_post_hook.py"
1612
+ }
1613
+ ]
1606
1614
  },
1607
1615
  {
1608
1616
  "path": "proxy/routing_escalation_hook.py",
@@ -60,7 +60,7 @@ an unattended session's prompt cache warm. Needs Claude Code 2.1.287 or later (m
60
60
 
61
61
  - On by default each session. `/keepwarm on|off|status`. No status-bar marker.
62
62
  - When the main chat is idle, no handoff runs, and the cache has 1 to 75 s left, the mod submits
63
- `prompts/keepwarm-nudge.md`. Max 6 in a row; a real user prompt resets the count. Each submitted nudge toasts `Keep-warm nudge sent (N of 6)`.
63
+ `prompts/keepwarm-nudge.md`. Max 12 in a row; a real user prompt resets the count. Each submitted nudge toasts `Keep-warm nudge sent (N of 12)`. Pending dialogs: an AskUserQuestion left open for the release time is answered for the model ("not answered yet, end your turn") and the dialog is re-hosted, never cancelled, so nudges keep the cache warm. While a dialog is pending, a blocked or idle nudge reply does not pause keep-warm. The founder's answer, or a dismissal or blank auto-resolve, arrives as a user message and resets the nudge count and any pause.
64
64
  - A nudge is never sent while a user prompt waits for its turn to start, within 3 s of any turn end,
65
65
  or while the prompt box holds text (checked again right before the submit).
66
66
  - The nudge reply is the turn whose start text carries the nudge marker; its turn id is the only turn
@@ -93,6 +93,6 @@ Windows, macOS, Linux. Only the optional clipboard copy differs, and a missing t
93
93
 
94
94
  ## Notes
95
95
 
96
- - Overrides: `HANDOFF_DIR`, `HANDOFF_AUTO_PERCENT` (auto threshold, test use), `KEEPWARM_CONFIG`, `KEEPWARM_CACHE_DIR`, `KEEPWARM_WINDOW_MS`, `KEEPWARM_TICK_MS`.
96
+ - Overrides: `HANDOFF_DIR`, `HANDOFF_AUTO_PERCENT` (auto threshold, test use), `KEEPWARM_CONFIG`, `KEEPWARM_CACHE_DIR`, `KEEPWARM_WINDOW_MS`, `KEEPWARM_TICK_MS`, `KEEPWARM_RELEASE_MS` (pending-dialog release time, default 20 minutes).
97
97
  - The loader checks statically: one hooks module, no `$` passed across files, literal names in env reads.
98
98
  - After a Claude Code upgrade: `claude plugin validate mods/handoff --strict`.
@@ -29,9 +29,27 @@ import {
29
29
  decide,
30
30
  statusText,
31
31
  parseCommandArgs,
32
+ parseStatus,
32
33
  PAUSE_TOASTS,
33
34
  applyVerdict,
34
35
  } from '../lib/keepwarm.mjs'
36
+ import {
37
+ RELEASE_MS_DEFAULT,
38
+ newPending,
39
+ clearPending,
40
+ hasPending,
41
+ questionKey,
42
+ isPending,
43
+ onRelease,
44
+ isCurrent,
45
+ onSettled,
46
+ releaseResult,
47
+ alreadyPendingResult,
48
+ askArgs,
49
+ isBlankAnswer,
50
+ answersMessage,
51
+ dismissedMessage,
52
+ } from '../lib/pending.mjs'
35
53
 
36
54
  const AUTO_STOPPED_TOAST = 'Auto-handoff stopped after a failed attempt. Use /handoff or the band button; /handoff auto on re-enables it'
37
55
  const REFRESH_MS = 30000
@@ -170,7 +188,8 @@ let warmTick = null
170
188
  let tickingSince = null
171
189
  let backgroundTasks = []
172
190
  let auto = newAuto(true)
173
- let settings = { windowMs: NUDGE_WINDOW_MS, tickMs: TICK_MS, cacheDir: '', autoPercent: AUTO_THRESHOLD_PERCENT }
191
+ let pending = newPending()
192
+ let settings = { windowMs: NUDGE_WINDOW_MS, tickMs: TICK_MS, cacheDir: '', autoPercent: AUTO_THRESHOLD_PERCENT, releaseMs: RELEASE_MS_DEFAULT }
174
193
 
175
194
  async function loadSettings($) {
176
195
  const home = (await $.env.get('USERPROFILE')) || (await $.env.get('HOME')) || ''
@@ -179,6 +198,7 @@ async function loadSettings($) {
179
198
  tickMs: positiveNumberOr(await $.env.get('KEEPWARM_TICK_MS'), TICK_MS),
180
199
  cacheDir: (await $.env.get('KEEPWARM_CACHE_DIR')) || claudeSubdir(home, '.cache_state'),
181
200
  autoPercent: positiveNumberOr(await $.env.get('HANDOFF_AUTO_PERCENT'), AUTO_THRESHOLD_PERCENT),
201
+ releaseMs: positiveNumberOr(await $.env.get('KEEPWARM_RELEASE_MS'), RELEASE_MS_DEFAULT),
182
202
  }
183
203
  const configPath = (await $.env.get('KEEPWARM_CONFIG')) || claudeSubdir(home, 'keepwarm.json')
184
204
  try {
@@ -217,6 +237,7 @@ async function sendNudge($, now) {
217
237
  return
218
238
  }
219
239
  if (state.nudgeSentAt !== now) return
240
+ if (hasPending(pending)) dialogLog($, 'nudge while ' + pending.records.length + ' dialog(s) pending')
220
241
  await $.prompt.submit({ text })
221
242
  $.ui.toast('Keep-warm nudge sent (' + sent + ' of ' + state.max + ')', { timeoutMs: TOAST_MS })
222
243
  } catch (err) {
@@ -306,19 +327,78 @@ async function runKeepwarmCommand($, e) {
306
327
  async function completeKeepwarmTurn($, e) {
307
328
  if (e.agentId) return
308
329
  const before = state
309
- const reply = { answer: e.answer, reason: e.reason, turnId: e.turnId, toolCount: undefined, activeCount: undefined }
330
+ const reply = { answer: e.answer, reason: e.reason, turnId: e.turnId, toolCount: undefined, activeCount: undefined, dialogPending: hasPending(pending) }
310
331
  if (isNudgeTurn(state, e.turnId)) {
311
332
  reply.toolCount = await nudgeToolCount($)
312
333
  reply.activeCount = (await activeWork($)).total
313
334
  }
314
335
  state = onTurnComplete(state, reply, await $.clock.now())
336
+ if (reply.dialogPending && isNudgeTurn(before, e.turnId)) dialogLog($, 'nudge reply ignored for pause while dialog pending, status=' + (parseStatus(e.answer) || 'none'))
315
337
  toastIfNewlyPaused($, before)
316
338
  }
317
339
 
340
+ const dialogLog = ($, text) => $.ui.log('keepwarm dialog: ' + text, { to: 'debug' })
341
+
342
+ function releaseTimer($, ms) {
343
+ let timer = null
344
+ const fired = new Promise((resolve) => {
345
+ timer = $.clock.after(ms, () => resolve(true))
346
+ })
347
+ return { fired, cancel: () => timer && timer.cancel && timer.cancel() }
348
+ }
349
+
350
+ async function rehostDialog($, record) {
351
+ const answers = []
352
+ let dismissed = false
353
+ for (const q of record.questions) {
354
+ try {
355
+ const answer = await $.ui.ask(...askArgs(q))
356
+ if (isBlankAnswer(answer)) {
357
+ dismissed = true
358
+ dialogLog($, 'dialog resolved without an answer')
359
+ break
360
+ }
361
+ answers.push(answer)
362
+ } catch (err) {
363
+ dismissed = true
364
+ dialogLog($, 'dialog dismissed: ' + err)
365
+ break
366
+ }
367
+ }
368
+ if (!isCurrent(pending, record)) return dialogLog($, 'answer dropped, session changed')
369
+ pending = onSettled(pending, record)
370
+ const text = dismissed ? dismissedMessage(record, answers) : answersMessage(record, answers)
371
+ dialogLog($, (dismissed ? 'delivering dismissal' : 'delivering ' + answers.length + ' answer(s)') + ', ' + pending.records.length + ' still pending')
372
+ state = onUserPrompt(state, await $.clock.now())
373
+ await tryOr($, 'dialog answer delivery', () => $.prompt.submit({ text, asUser: true }))
374
+ }
375
+
376
+ async function guardQuestion($, e, next) {
377
+ if (e.agentId) return next(e)
378
+ const key = questionKey(e.questions)
379
+ if (isPending(pending, key)) {
380
+ dialogLog($, 'identical question re-asked while pending, answered as already pending')
381
+ return alreadyPendingResult(e.questions)
382
+ }
383
+ const timer = releaseTimer($, settings.releaseMs)
384
+ const asked = next(e)
385
+ asked.catch(() => {})
386
+ const winner = await Promise.race([asked.then(() => false), timer.fired])
387
+ timer.cancel()
388
+ if (!winner) return asked
389
+ const made = onRelease(pending, e.questions, await $.clock.now())
390
+ pending = made.pending
391
+ dialogLog($, 'question released to the model after ' + settings.releaseMs + ' ms, dialog re-hosted, ' + pending.records.length + ' pending')
392
+ $.clock.after(0, () => rehostDialog($, made.record))
393
+ return releaseResult(e.questions)
394
+ }
395
+
318
396
  export function register(on) {
319
397
  on('session.start', async ($, e, next) => {
320
398
  const v = await tryOr($, 'session.version', () => $.session.version(), null)
321
399
  supported = Boolean(v) && versionAtLeast(v.version, MIN_CLAUDE_CODE_VERSION)
400
+ if (hasPending(pending)) dialogLog($, 'pending cleared on session start')
401
+ pending = clearPending(pending)
322
402
  await $.command.register({
323
403
  name: 'handoff',
324
404
  description: 'Prepare, verify and hand this session off to a fresh one',
@@ -345,6 +425,8 @@ export function register(on) {
345
425
  return next(e)
346
426
  })
347
427
 
428
+ on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => guardQuestion($, e, next))
429
+
348
430
  on('classic.Stop', async ($, e, next) => {
349
431
  if (!e.agent_id) backgroundTasks = Array.isArray(e.background_tasks) ? e.background_tasks : []
350
432
  return next(e)
@@ -2,7 +2,7 @@ import { cacheRemainingMs } from './cache.mjs'
2
2
 
3
3
  export const NUDGE_WINDOW_MS = 75 * 1000
4
4
  export const TICK_MS = 15 * 1000
5
- export const DEFAULT_MAX_CONSECUTIVE = 6
5
+ export const DEFAULT_MAX_CONSECUTIVE = 12
6
6
  export const CONTEXT_STOP_PERCENT = 90
7
7
  export const BUSY_STALE_MS = 30 * 60 * 1000
8
8
  export const PENDING_STALE_MS = 15 * 1000
@@ -85,10 +85,11 @@ export function toolUseCountSince(messages, marker) {
85
85
  .reduce((sum, m) => sum + (Array.isArray(m.toolUses) ? m.toolUses.length : 0), 0)
86
86
  }
87
87
 
88
- export function evaluateReply({ answer, reason, toolCount, activeCount }) {
88
+ export function evaluateReply({ answer, reason, toolCount, activeCount, dialogPending }) {
89
89
  if (reason === 'aborted') return 'interrupted'
90
90
  if (reason !== 'answer') return 'error'
91
91
  const status = parseStatus(answer)
92
+ if (dialogPending) return ''
92
93
  if (status === 'blocked') return 'blocked'
93
94
  if (status === 'working') return ''
94
95
  return toolCount === 0 && activeCount === 0 ? 'idle' : ''
@@ -0,0 +1,100 @@
1
+ export const RELEASE_MS_DEFAULT = 20 * 60 * 1000
2
+ export const MAX_QUESTIONS = 4
3
+ export const HEADER_MAX = 12
4
+
5
+ export const RELEASED_NOTE =
6
+ 'The user has not answered yet. Their answer will arrive later as their next message. End your turn now and do not ask again.'
7
+ export const ALREADY_PENDING_NOTE =
8
+ 'This question is already open in front of the user. Their answer will arrive as their next message. Do not ask again; continue other work or end your turn.'
9
+
10
+ export function newPending() {
11
+ return { epoch: 0, records: [] }
12
+ }
13
+
14
+ export function clearPending(p) {
15
+ return { epoch: p.epoch + 1, records: [] }
16
+ }
17
+
18
+ export function hasPending(p) {
19
+ return p.records.length > 0
20
+ }
21
+
22
+ function asQuestions(raw) {
23
+ return Array.isArray(raw) ? raw.filter((q) => q && typeof q.question === 'string').slice(0, MAX_QUESTIONS) : []
24
+ }
25
+
26
+ function labels(q) {
27
+ return Array.isArray(q.options) ? q.options.map((o) => (typeof o === 'string' ? o : String((o && o.label) || ''))).filter(Boolean) : []
28
+ }
29
+
30
+ export function questionKey(raw) {
31
+ return JSON.stringify(asQuestions(raw).map((q) => [q.question.trim(), labels(q), q.multiSelect === true]))
32
+ }
33
+
34
+ export function isPending(p, key) {
35
+ return p.records.some((r) => r.key === key)
36
+ }
37
+
38
+ export function onRelease(p, raw, now) {
39
+ const questions = asQuestions(raw)
40
+ const record = { key: questionKey(questions), questions, releasedAt: now, epoch: p.epoch }
41
+ return { pending: { ...p, records: [...p.records, record] }, record }
42
+ }
43
+
44
+ export function isCurrent(p, record) {
45
+ return record.epoch === p.epoch && p.records.includes(record)
46
+ }
47
+
48
+ export function onSettled(p, record) {
49
+ return { ...p, records: p.records.filter((r) => r !== record) }
50
+ }
51
+
52
+ function echo(raw) {
53
+ return asQuestions(raw).map((q) => ({
54
+ question: q.question,
55
+ header: typeof q.header === 'string' ? q.header : '',
56
+ options: Array.isArray(q.options) ? q.options : [],
57
+ multiSelect: q.multiSelect === true,
58
+ }))
59
+ }
60
+
61
+ function noteResult(raw, note) {
62
+ const answers = Object.fromEntries(asQuestions(raw).map((q) => [q.question, 'PENDING: ' + note]))
63
+ return { result: { questions: echo(raw), answers, response: note }, context: [note] }
64
+ }
65
+
66
+ export function releaseResult(raw) {
67
+ return noteResult(raw, RELEASED_NOTE)
68
+ }
69
+
70
+ export function alreadyPendingResult(raw) {
71
+ return noteResult(raw, ALREADY_PENDING_NOTE)
72
+ }
73
+
74
+ export function isBlankAnswer(answer) {
75
+ return typeof answer !== 'string' || answer.trim() === ''
76
+ }
77
+
78
+ export function askArgs(q) {
79
+ const options = labels(q)
80
+ const out = { options: options.slice(0, 4) }
81
+ const header = typeof q.header === 'string' ? q.header.trim().slice(0, HEADER_MAX) : ''
82
+ if (header) out.header = header
83
+ if (q.multiSelect === true) out.multiSelect = true
84
+ return [q.question, out]
85
+ }
86
+
87
+ function tag(q) {
88
+ return (typeof q.header === 'string' && q.header.trim()) || q.question
89
+ }
90
+
91
+ export function answersMessage(record, answers) {
92
+ const lines = record.questions.map((q, i) => '- ' + tag(q) + ': ' + answers[i])
93
+ return 'My answers to your open question' + (lines.length > 1 ? 's' : '') + ':\n' + lines.join('\n')
94
+ }
95
+
96
+ export function dismissedMessage(record, answers) {
97
+ const given = record.questions.slice(0, answers.length).map((q, i) => '- ' + tag(q) + ': ' + answers[i])
98
+ const head = 'I closed your open question' + (record.questions.length > 1 ? 's' : '') + ' without answering' + (given.length ? ' all of them' : '') + '.'
99
+ return given.length ? head + ' Answered so far:\n' + given.join('\n') : head + ' Decide for yourself or ask again.'
100
+ }
@@ -1 +1 @@
1
- Keep-warm check. What is the current progress? Finish all remaining tasks autonomously. Tasks that need the founder (decisions, real clicks, logins) go last: list them at the end and do not wait on them. Make sure the task list and the PRD issue are updated. End your reply with one final line: KEEPWARM_STATUS: working (more work to do), KEEPWARM_STATUS: idle (nothing left for you to do), or KEEPWARM_STATUS: blocked (only the founder can continue).
1
+ Keep-warm check. What is the current progress? Finish all remaining tasks autonomously. Tasks that need the founder (decisions, real clicks, logins) go last: list them at the end and do not wait on them. If you asked the founder a question earlier, it is still open as a dialog and the answer will arrive as a message: do not ask it again, and continue with other work. Make sure the task list and the PRD issue are updated. Only in your reply to this keep-warm message, end with one final line: KEEPWARM_STATUS: working (more work to do), KEEPWARM_STATUS: idle (nothing left for you to do), or KEEPWARM_STATUS: blocked (only the founder can continue). Never add that line to any later reply.
@@ -0,0 +1,253 @@
1
+ """Real-TUI scenarios for the keep-warm pending-dialog release (hidden, via tui_driver).
2
+
3
+ Run: python tui_dialog_e2e.py [T1 T3 T4 T5] (default: all; T1 includes T2)
4
+ Needs pywinpty, pyte, psutil (see tui_driver docstring). Uses the real mods/handoff with a stub nudge prompt.
5
+ """
6
+ import json
7
+ import re
8
+ import sys
9
+ import time
10
+ from pathlib import Path
11
+
12
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
13
+ import tui_driver as td # noqa: E402
14
+ from keepwarm_e2e import NUDGE_HEAD, STUB_TAIL # noqa: E402
15
+ from run_e2e import OBSERVER # noqa: E402
16
+
17
+ DIALOG = r"Enter to select|Esc to cancel"
18
+ QUESTION = "Which colour do you want?"
19
+ ASK = (
20
+ "Use the AskUserQuestion tool exactly once with the question '" + QUESTION + "', header 'Colour', "
21
+ "options Red and Blue, single select. Then wait for the answer."
22
+ )
23
+ RELEASE_MS = 8000
24
+ REPLY = re.compile(r"^● KEEPWARM_STATUS: blocked", re.M)
25
+ results = []
26
+
27
+
28
+ class Run:
29
+ def __init__(self, name, nudge_tail):
30
+ self.name = name
31
+ self.work = td.temp_workspace(f"tui-dialog-{name}-")
32
+ self.mod = td.copy_mod(self.work / "mod")
33
+ (self.mod / "prompts" / "keepwarm-nudge.md").write_text(NUDGE_HEAD + STUB_TAIL + nudge_tail, encoding="utf-8")
34
+ self.cwd = self.work / "cwd"
35
+ self.cwd.mkdir()
36
+ self.cache = self.work / "cache"
37
+ self.cache.mkdir()
38
+ self.debug = self.work / "debug.log"
39
+ self.obs = self.work / "observer.log"
40
+ env = dict(
41
+ OBSERVER_LOG=str(self.obs), HANDOFF_DIR=str(self.work / "handoffs"), KEEPWARM_CACHE_DIR=str(self.cache),
42
+ KEEPWARM_CONFIG=str(self.work / "none.json"), KEEPWARM_TICK_MS="2000", KEEPWARM_WINDOW_MS="300000",
43
+ KEEPWARM_RELEASE_MS=str(RELEASE_MS),
44
+ )
45
+ self.t = td.start([self.mod, OBSERVER], env, extra_args=["--permission-mode", "bypassPermissions", "--debug-file", str(self.debug)], cwd=self.cwd)
46
+ self.t0 = time.time()
47
+
48
+ def stamp(self):
49
+ return f"[{time.time() - self.t0:6.1f}s]"
50
+
51
+ def read(self, path):
52
+ return Path(path).read_text(encoding="utf-8", errors="replace") if Path(path).exists() else ""
53
+
54
+ def dialog_lines(self):
55
+ return [l.split("keepwarm dialog:", 1)[1].strip() for l in self.read(self.debug).splitlines() if "keepwarm dialog:" in l]
56
+
57
+ def debug_hits(self, needle):
58
+ return [l for l in self.read(self.debug).splitlines() if needle in l]
59
+
60
+ def obs_lines(self):
61
+ return self.read(self.obs).splitlines()
62
+
63
+ def nudges_submitted(self):
64
+ return len([l for l in self.obs_lines() if 'origin={"kind":"plugin"' in l and "Keep-warm check" in l])
65
+
66
+ def dialog_open(self):
67
+ return bool(re.search(DIALOG, self.t.screen_text()))
68
+
69
+ def show(self, label):
70
+ print(f"{self.stamp()} ---- screen: {label} ----\n{self.t.screen_text()}\n----------------")
71
+
72
+ def wait(self, pred, timeout, poll=0.5):
73
+ end = time.time() + timeout
74
+ while time.time() < end:
75
+ if pred():
76
+ return True
77
+ time.sleep(poll)
78
+ return pred()
79
+
80
+ def boot(self):
81
+ try:
82
+ return self._boot()
83
+ except EOFError:
84
+ print("boot: claude exited early; screen:\n" + self.t.screen_text())
85
+ return False
86
+
87
+ def _boot(self):
88
+ t = self.t
89
+ end = time.time() + 60
90
+ ok = False
91
+ while time.time() < end:
92
+ s = t.screen_text()
93
+ if re.search(r"Yes, I trust this folder", s) and "Enter to confirm" in s:
94
+ t.send_keys("{Down}{Enter}")
95
+ time.sleep(2)
96
+ if re.search(r"^\s*[>❯]", s, re.M) and re.search(r"\? for shortcuts|bypass permissions", s, re.I):
97
+ ok = True
98
+ break
99
+ time.sleep(1)
100
+ if not ok:
101
+ return False
102
+ ids = []
103
+
104
+ def have_id():
105
+ ids.extend(re.findall(r"session\.start id=(\S+)", self.read(self.obs)))
106
+ return bool(ids)
107
+
108
+ if not self.wait(have_id, 30):
109
+ return False
110
+ (self.cache / f"{ids[0]}.json").write_text(json.dumps({"ttl": "5m"}), encoding="utf-8")
111
+ time.sleep(3)
112
+ return True
113
+
114
+ def type_line(self, text):
115
+ self.t.send_keys(text)
116
+ self.t.send_keys("{Enter}")
117
+
118
+ def open_dialog(self):
119
+ self.type_line(ASK)
120
+ return self.wait(lambda: self.dialog_open() and "Red" in self.t.screen_text(), 60)
121
+
122
+ def close(self):
123
+ print(f"{self.stamp()} visible windows: {self.t.visible_windows()}")
124
+ self.t.stop()
125
+
126
+
127
+ def verdict(name, ok, note=""):
128
+ results.append((name, ok))
129
+ print(f"{name}: {'PASS' if ok else 'FAIL'} {note}")
130
+
131
+
132
+ def dump_logs(run):
133
+ print("---- debug 'keepwarm dialog:' lines ----\n" + "\n".join(run.dialog_lines()))
134
+ print("---- observer log ----\n" + run.read(run.obs))
135
+
136
+
137
+ def t1_t2():
138
+ run = Run("t1", "reply with the single line KEEPWARM_STATUS: blocked")
139
+ try:
140
+ if not run.boot():
141
+ return verdict("T1", False, "boot failed\n" + run.t.screen_text())
142
+ if not run.open_dialog():
143
+ run.show("no dialog")
144
+ return verdict("T1", False, "dialog not opened")
145
+ t_open = time.time()
146
+ print(f"{run.stamp()} dialog open")
147
+ released = run.wait(lambda: any("released" in l for l in run.dialog_lines()), 25)
148
+ print(f"{run.stamp()} released={released} after {time.time() - t_open:.1f}s")
149
+ time.sleep(4)
150
+ run.show("4 s after release")
151
+ still = run.dialog_open()
152
+ # key question: does the stub nudge get accepted while the re-hosted dialog is open
153
+ accepted = run.wait(lambda: run.nudges_submitted() >= 1 or "Keep-warm check" in run.t.screen_text(), 40)
154
+ print(f"{run.stamp()} nudge visible/submitted={accepted} observer_nudges={run.nudges_submitted()}")
155
+ replied = run.wait(lambda: "KEEPWARM_STATUS: blocked" in run.t.screen_text().replace("\n", " ") and run.nudges_submitted() >= 1, 30)
156
+ run.show("after first nudge")
157
+ print(f"{run.stamp()} nudge_reply_on_screen={replied} dialog_open={run.dialog_open()}")
158
+ time.sleep(25)
159
+ n2 = run.nudges_submitted()
160
+ replies = len(REPLY.findall(run.t.screen_text()))
161
+ run.show("25 s later")
162
+ print(f"{run.stamp()} nudges_submitted={n2} status_lines_on_screen={replies} dialog_open={run.dialog_open()}")
163
+ print("debug nudge-while-pending hits:", run.debug_hits("nudge while"))
164
+ verdict("T1 release+rehost", released and still, f"released={released} dialog_still_open_4s={still}")
165
+ verdict("T1 nudge accepted under re-hosted dialog", accepted and replied, f"nudges_submitted={n2} replies={replies}")
166
+ run.t.send_keys("/keepwarm status")
167
+ time.sleep(2)
168
+ run.show("after typing /keepwarm status (no Enter) into the open dialog")
169
+ print(f"{run.stamp()} dialog_open_after_status_keys={run.dialog_open()}")
170
+ # T2
171
+ run.t.send_keys("1")
172
+ got = run.wait(lambda: "My answers to your open question" in run.t.screen_text() or "My answers to your open question" in run.read(run.obs), 20)
173
+ time.sleep(8)
174
+ run.show("after answering with 1")
175
+ run.type_line("/keepwarm status")
176
+ time.sleep(4)
177
+ run.show("after /keepwarm status once the dialog is answered")
178
+ dump_logs(run)
179
+ verdict("T2 answer delivered as message", got, "")
180
+ finally:
181
+ run.close()
182
+
183
+
184
+ def t3():
185
+ run = Run("t3", "reply with the single line KEEPWARM_STATUS: idle")
186
+ try:
187
+ if not run.boot():
188
+ return verdict("T3", False, "boot failed")
189
+ if not run.open_dialog():
190
+ return verdict("T3", False, "dialog not opened")
191
+ t_open = time.time()
192
+ time.sleep(max(0, 2 - (time.time() - t_open)))
193
+ run.t.send_keys("1")
194
+ cont = run.wait(lambda: not run.dialog_open() and re.search(r"You chose|Red", run.t.screen_text()), 30)
195
+ time.sleep(12)
196
+ run.show("T3 after answer + 12 s")
197
+ released = [l for l in run.dialog_lines() if "released" in l]
198
+ dump_logs(run)
199
+ verdict("T3 fast answer", bool(cont) and not released, f"continued={bool(cont)} released_lines={released}")
200
+ finally:
201
+ run.close()
202
+
203
+
204
+ def t4():
205
+ run = Run("t4", "use the AskUserQuestion tool again with the identical question '" + QUESTION + "', header 'Colour', options Red and Blue, single select")
206
+ try:
207
+ if not run.boot():
208
+ return verdict("T4", False, "boot failed")
209
+ if not run.open_dialog():
210
+ return verdict("T4", False, "dialog not opened")
211
+ dedup = run.wait(lambda: any("answered as already pending" in l for l in run.dialog_lines()), 70)
212
+ time.sleep(5)
213
+ run.show("T4 after dedup wait")
214
+ dump_logs(run)
215
+ verdict("T4 dedup", dedup and run.dialog_open(), f"dedup_line={dedup} dialog_open={run.dialog_open()}")
216
+ finally:
217
+ run.close()
218
+
219
+
220
+ def t5():
221
+ run = Run("t5", "reply with the single line KEEPWARM_STATUS: blocked")
222
+ try:
223
+ if not run.boot():
224
+ return verdict("T5", False, "boot failed")
225
+ run.type_line("/keepwarm off")
226
+ time.sleep(4)
227
+ run.show("after /keepwarm off")
228
+ if not run.open_dialog():
229
+ return verdict("T5", False, "dialog not opened")
230
+ t_open = time.time()
231
+ released = run.wait(lambda: any("released" in l for l in run.dialog_lines()), 25)
232
+ print(f"{run.stamp()} released={released}")
233
+ ok = True
234
+ for i in range(8):
235
+ time.sleep(30)
236
+ open_now = run.dialog_open()
237
+ print(f"{run.stamp()} +{time.time() - t_open:.0f}s dialog_open={open_now} nudges={run.nudges_submitted()} dialog_lines={len(run.dialog_lines())}")
238
+ ok = ok and open_now
239
+ run.show("T5 end")
240
+ dump_logs(run)
241
+ bad = [l for l in run.dialog_lines() if "dismiss" in l or "delivering" in l]
242
+ verdict("T5 dialog survives 4 min", released and ok and not bad, f"dismiss_lines={bad}")
243
+ finally:
244
+ run.close()
245
+
246
+
247
+ SCENARIOS = {"T1": t1_t2, "T3": t3, "T4": t4, "T5": t5}
248
+
249
+
250
+ if __name__ == "__main__":
251
+ for name in (sys.argv[1:] or SCENARIOS):
252
+ SCENARIOS[name]()
253
+ print("\n".join(f"{n}: {'PASS' if ok else 'FAIL'}" for n, ok in results))