thinqos 3.2.0__tar.gz → 3.2.1__tar.gz

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 (136) hide show
  1. {thinqos-3.2.0 → thinqos-3.2.1}/CHANGELOG.md +7 -0
  2. {thinqos-3.2.0 → thinqos-3.2.1}/PKG-INFO +1 -1
  3. {thinqos-3.2.0 → thinqos-3.2.1}/pyproject.toml +1 -1
  4. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/hook.py +95 -12
  5. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/primecache.py +81 -0
  6. {thinqos-3.2.0 → thinqos-3.2.1}/tests/conftest.py +10 -0
  7. thinqos-3.2.1/tests/test_tos_4486_refresh_retry.py +296 -0
  8. {thinqos-3.2.0 → thinqos-3.2.1}/.gitignore +0 -0
  9. {thinqos-3.2.0 → thinqos-3.2.1}/README.md +0 -0
  10. {thinqos-3.2.0 → thinqos-3.2.1}/scripts/sync_cognitive_contract.py +0 -0
  11. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/__init__.py +0 -0
  12. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/__main__.py +0 -0
  13. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/accountscope.py +0 -0
  14. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/adapters/__init__.py +0 -0
  15. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/adapters/claude_code.py +0 -0
  16. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/adapters/cline.py +0 -0
  17. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/adapters/cline_tasks.py +0 -0
  18. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/adapters/codex.py +0 -0
  19. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/adapters/grok_build.py +0 -0
  20. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/adapters/vscode_chat_store.py +0 -0
  21. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/adapters/vscode_copilot.py +0 -0
  22. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/attribution.py +0 -0
  23. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/capture_history_policy.py +0 -0
  24. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/cli.py +0 -0
  25. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/client.py +0 -0
  26. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/cline_sweep.py +0 -0
  27. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/connections.py +0 -0
  28. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/denylist.py +0 -0
  29. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/discovery.py +0 -0
  30. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/filelock.py +0 -0
  31. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/importer.py +0 -0
  32. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/incremental.py +0 -0
  33. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/install_marker.py +0 -0
  34. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/installs.py +0 -0
  35. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/logsetup.py +0 -0
  36. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/mcp_transport.py +0 -0
  37. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/process.py +0 -0
  38. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/questionrecall.py +0 -0
  39. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/recovery.py +0 -0
  40. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/scheduler.py +0 -0
  41. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/secretstore.py +0 -0
  42. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/selfupdate.py +0 -0
  43. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/server_revision.py +0 -0
  44. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/shim.py +0 -0
  45. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/state.py +0 -0
  46. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/taskstate.py +0 -0
  47. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/tls.py +0 -0
  48. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/tool_turns.py +0 -0
  49. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/vscode_chat_sweep.py +0 -0
  50. {thinqos-3.2.0 → thinqos-3.2.1}/src/thinqos_capture/writeredirect.py +0 -0
  51. {thinqos-3.2.0 → thinqos-3.2.1}/tests/fixtures/claude_code_session.jsonl +0 -0
  52. {thinqos-3.2.0 → thinqos-3.2.1}/tests/fixtures/codex_session.jsonl +0 -0
  53. {thinqos-3.2.0 → thinqos-3.2.1}/tests/fixtures/grok_build_summary.json +0 -0
  54. {thinqos-3.2.0 → thinqos-3.2.1}/tests/fixtures/grok_build_updates.jsonl +0 -0
  55. {thinqos-3.2.0 → thinqos-3.2.1}/tests/fixtures/tos_6776_recovery_failures.json +0 -0
  56. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_attribution.py +0 -0
  57. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_capture_completeness.py +0 -0
  58. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_capture_incremental.py +0 -0
  59. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_claude_code_adapter.py +0 -0
  60. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_cli_drain.py +0 -0
  61. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_cli_install_hook.py +0 -0
  62. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_cli_list_forget.py +0 -0
  63. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_cli_run.py +0 -0
  64. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_client_limits.py +0 -0
  65. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_client_version_header.py +0 -0
  66. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_cline_adapter.py +0 -0
  67. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_cline_mcp_registration.py +0 -0
  68. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_cline_sweep.py +0 -0
  69. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_cline_tasks.py +0 -0
  70. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_codex_adapter.py +0 -0
  71. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_codex_capture_staleness.py +0 -0
  72. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_codex_hook_runtime_contract.py +0 -0
  73. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_codex_hook_trust.py +0 -0
  74. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_codex_plugin_setup.py +0 -0
  75. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_codex_rollout_memory.py +0 -0
  76. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_doctor.py +0 -0
  77. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_doctor_queue.py +0 -0
  78. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_drain_partition_split.py +0 -0
  79. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_drain_poison.py +0 -0
  80. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_drain_timeout.py +0 -0
  81. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_env_key_remnant.py +0 -0
  82. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_grok_build_adapter.py +0 -0
  83. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_hook.py +0 -0
  84. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_hook_autodrain.py +0 -0
  85. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_hook_prime.py +0 -0
  86. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_hook_secret_resolution.py +0 -0
  87. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_hook_self_update.py +0 -0
  88. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_hook_stdin.py +0 -0
  89. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_hook_task_state.py +0 -0
  90. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_importer.py +0 -0
  91. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_incremental.py +0 -0
  92. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_install.py +0 -0
  93. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_installer_hardening.py +0 -0
  94. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_liveness.py +0 -0
  95. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_logsetup.py +0 -0
  96. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_mcp_transport.py +0 -0
  97. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_no_retired_tool_names.py +0 -0
  98. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_plugin_autoupdate.py +0 -0
  99. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_plugin_mode.py +0 -0
  100. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_prime_cache.py +0 -0
  101. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_process.py +0 -0
  102. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_queue_policy.py +0 -0
  103. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_scheduler.py +0 -0
  104. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_secretstore.py +0 -0
  105. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_selfupdate.py +0 -0
  106. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_shim.py +0 -0
  107. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_state.py +0 -0
  108. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_state_migration.py +0 -0
  109. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_taskstate.py +0 -0
  110. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tls_cloud_proxy.py +0 -0
  111. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_token_economy.py +0 -0
  112. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tool_turns.py +0 -0
  113. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_2840_completion.py +0 -0
  114. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_2840_repair_round1.py +0 -0
  115. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_2840_repair_round2.py +0 -0
  116. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_4483_account_scope.py +0 -0
  117. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_4485_capture_history_policy.py +0 -0
  118. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_4485_doctor_update_state.py +0 -0
  119. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_4485_prime_refresh_coalescing.py +0 -0
  120. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_4486_question_recall.py +0 -0
  121. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_4487_install_marker.py +0 -0
  122. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_5043_connections.py +0 -0
  123. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_5043_discovery.py +0 -0
  124. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_5043_install_precedence.py +0 -0
  125. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_5100_key_prompt_links.py +0 -0
  126. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_5102_selfheal.py +0 -0
  127. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_5226_installs_registry.py +0 -0
  128. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_5369_mcp_revision.py +0 -0
  129. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_6776_recovery.py +0 -0
  130. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_6807_plugin_install.py +0 -0
  131. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_tos_7410_prime_refusals.py +0 -0
  132. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_verify.py +0 -0
  133. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_vscode_chat_store.py +0 -0
  134. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_vscode_copilot_adapter.py +0 -0
  135. {thinqos-3.2.0 → thinqos-3.2.1}/tests/test_writeredirect.py +0 -0
  136. {thinqos-3.2.0 → thinqos-3.2.1}/uv.lock +0 -0
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [3.2.1](https://github.com/AI4Outcomes/thinqos/compare/tools/thinqos-v3.2.0...tools/thinqos-v3.2.1) (2026-10-08)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **TOS-4486:** a failed prime refresh retries at 1 and 3 minutes when nothing is cached ([#8232](https://github.com/AI4Outcomes/thinqos/issues/8232)) ([d934de3](https://github.com/AI4Outcomes/thinqos/commit/d934de334ffc277bba2280f01faa8f659e8df366))
9
+
3
10
  ## [3.2.0](https://github.com/AI4Outcomes/thinqos/compare/tools/thinqos-v3.1.3...tools/thinqos-v3.2.0) (2026-10-08)
4
11
 
5
12
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: thinqos
3
- Version: 3.2.0
3
+ Version: 3.2.1
4
4
  Summary: Connect Claude Code, Codex, Grok Build, VS Code, and Cline to your thinqOS Mind.
5
5
  Project-URL: Homepage, https://thinqos.com
6
6
  Project-URL: Documentation, https://thinqos.com/mcp-memory-server
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "thinqos"
3
- version = "3.2.0"
3
+ version = "3.2.1"
4
4
  description = "Connect Claude Code, Codex, Grok Build, VS Code, and Cline to your thinqOS Mind."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -60,9 +60,13 @@ from thinqos_capture.incremental import record_attempt, should_capture
60
60
  from thinqos_capture.install_marker import build_marker, stamp_sessions
61
61
  from thinqos_capture.logsetup import configure_hook_logging
62
62
  from thinqos_capture.primecache import (
63
+ REFRESH_RETRY_OFFSETS_S,
64
+ claim_automatic_read,
63
65
  claim_refresh_slot,
64
66
  defer_refused_query,
65
67
  degradation_banner,
68
+ has_cached_block,
69
+ is_repeat_limit_refusal,
66
70
  load_cached_block,
67
71
  log_prime_latency,
68
72
  log_refresh_event,
@@ -2215,6 +2219,11 @@ def prime(query: str, limit: int) -> None:
2215
2219
  try:
2216
2220
  if query_is_deferred(cache_dir, query):
2217
2221
  raise _MCPToolRefusal("Automatic recall remains deferred after a tool refusal")
2222
+ # TOS-4486: every automatic prime read is counted, so the foreground
2223
+ # call and the background retries together stay inside the server's
2224
+ # identical-read allowance instead of earning a repeat-limit refusal.
2225
+ if not claim_automatic_read(cache_dir, query):
2226
+ raise _MCPToolRefusal(_READ_CAP_DETAIL)
2218
2227
  # Fast tier on the foreground path (TOS-1501): depth=quick skips the
2219
2228
  # conversation-corpus leg and attention reinforcement that made the
2220
2229
  # deep tier grow past the hook budget. The deep block still arrives
@@ -2241,7 +2250,8 @@ def prime(query: str, limit: int) -> None:
2241
2250
  except _MCPToolRefusal as exc:
2242
2251
  failure_detail = str(exc)
2243
2252
  # Keep the original deadline. Repeated prompts must not extend it.
2244
- if not query_is_deferred(cache_dir, query):
2253
+ # Only the repeat-limit refusal starts the cooldown (TOS-4486).
2254
+ if is_repeat_limit_refusal(failure_detail) and not query_is_deferred(cache_dir, query):
2245
2255
  defer_refused_query(cache_dir, query)
2246
2256
  logger.warning("hook.prime_refused", exc_info=True)
2247
2257
  outcome = "error"
@@ -2325,6 +2335,13 @@ def prime_refresh(query: str, limit: int, expected_scope: str, session_id: str)
2325
2335
  (server latency > 3s meant the refresher could never complete either).
2326
2336
  This is the one place that still uses ``recall`` at ``depth=deep`` -
2327
2337
  the generous budget is what pays for the corpus/aggregate evidence.
2338
+
2339
+ TOS-4486: when nothing is cached and the read fails, it retries about 1
2340
+ and 3 minutes after the failure (``REFRESH_RETRY_OFFSETS_S``), then
2341
+ exits and the normal ~10 minute cadence resumes. Every read is counted
2342
+ against the server's 3-per-10-minutes identical-read allowance, and no
2343
+ retry runs inside a repeat-limit cooldown. With a block cached, one read
2344
+ and exit, as before.
2328
2345
  """
2329
2346
  if expected_scope and not _expected_scope_is_current(DEFAULT_STATE_DIR, expected_scope):
2330
2347
  sys.exit(0)
@@ -2334,9 +2351,69 @@ def prime_refresh(query: str, limit: int, expected_scope: str, session_id: str)
2334
2351
  account = _account_scope(DEFAULT_STATE_DIR, base_url, token)
2335
2352
  if expected_scope and not scope_matches(base_url, token, expected_scope):
2336
2353
  sys.exit(0)
2354
+ state_dir = account.state_dir
2355
+ if query_is_deferred(state_dir, query):
2356
+ sys.exit(0)
2357
+
2358
+ def _attempt() -> str:
2359
+ return _refresh_prime_once(state_dir, base_url, token, query, limit, session_id=session_id)
2360
+
2361
+ if not claim_automatic_read(state_dir, query):
2362
+ log_refresh_event(state_dir, query=query, event="capped", detail=_READ_CAP_DETAIL)
2363
+ sys.exit(0)
2364
+ event = _attempt()
2365
+ # TOS-4486: with nothing cached, a failed refresh leaves every prompt
2366
+ # without Mind context until the next ~10 minute refresh. Retry about 1
2367
+ # and 3 minutes after the failure instead, never inside a repeat-limit
2368
+ # cooldown and never past the identical-read allowance. With a block
2369
+ # cached the turn is already served, so nothing changes.
2370
+ if event in _RETRYABLE_REFRESH_EVENTS and not has_cached_block(state_dir, query):
2371
+ failed_at = _refresh_clock()
2372
+ for offset in REFRESH_RETRY_OFFSETS_S:
2373
+ _refresh_sleep(max(0.0, failed_at + offset - _refresh_clock()))
2374
+ if query_is_deferred(state_dir, query):
2375
+ log_refresh_event(state_dir, query=query, event="retry_skipped_cooldown")
2376
+ break
2377
+ if expected_scope and not _expected_scope_is_current(DEFAULT_STATE_DIR, expected_scope):
2378
+ break
2379
+ if has_cached_block(state_dir, query):
2380
+ break
2381
+ if not claim_automatic_read(state_dir, query):
2382
+ log_refresh_event(
2383
+ state_dir, query=query, event="retry_skipped_cap", detail=_READ_CAP_DETAIL
2384
+ )
2385
+ continue
2386
+ log_refresh_event(state_dir, query=query, event="retry", detail=f"+{offset:g}s")
2387
+ event = _attempt()
2388
+ if event not in _RETRYABLE_REFRESH_EVENTS or has_cached_block(state_dir, query):
2389
+ break
2390
+ sys.exit(0)
2391
+
2392
+
2393
+ _READ_CAP_DETAIL = (
2394
+ "Automatic recall skipped: this prime was already read 3 times in the last 10 minutes."
2395
+ )
2396
+ #: Refresh outcomes worth retrying when nothing is cached. A repeat-limit
2397
+ #: refusal ("refused") is not: it starts its own cooldown.
2398
+ _RETRYABLE_REFRESH_EVENTS: frozenset[str] = frozenset(
2399
+ {"completed_empty", "degraded", "timeout", "error"}
2400
+ )
2401
+ # Indirection so tests can drive the retry schedule without real sleeps.
2402
+ _refresh_clock = time.monotonic
2403
+ _refresh_sleep = time.sleep
2404
+
2405
+
2406
+ def _refresh_prime_once(
2407
+ state_dir: Path,
2408
+ base_url: str,
2409
+ token: str,
2410
+ query: str,
2411
+ limit: int,
2412
+ *,
2413
+ session_id: str,
2414
+ ) -> str:
2415
+ """One background prime read. Logs and returns its event; never raises."""
2337
2416
  try:
2338
- if query_is_deferred(account.state_dir, query):
2339
- sys.exit(0)
2340
2417
  block = _fetch_memory_block(
2341
2418
  base_url,
2342
2419
  token,
@@ -2347,21 +2424,27 @@ def prime_refresh(query: str, limit: int, expected_scope: str, session_id: str)
2347
2424
  session_id=session_id,
2348
2425
  )
2349
2426
  if block:
2350
- save_cached_block(account.state_dir, query, block)
2351
- log_refresh_event(account.state_dir, query=query, event="completed")
2427
+ save_cached_block(state_dir, query, block)
2428
+ log_refresh_event(state_dir, query=query, event="completed")
2429
+ return "completed" if block else "completed_empty"
2352
2430
  except _DegradedRecall as exc:
2353
2431
  # Keep the last good block: a deadline-cut answer must never replace it.
2354
- log_refresh_event(account.state_dir, query=query, event="degraded", detail=str(exc))
2432
+ log_refresh_event(state_dir, query=query, event="degraded", detail=str(exc))
2433
+ return "degraded"
2355
2434
  except _MCPToolRefusal as exc:
2356
- defer_refused_query(account.state_dir, query)
2357
- log_refresh_event(account.state_dir, query=query, event="error", detail=str(exc))
2358
- logger.warning("hook.prime_refresh_refused", exc_info=True)
2435
+ log_refresh_event(state_dir, query=query, event="error", detail=str(exc))
2436
+ if is_repeat_limit_refusal(str(exc)):
2437
+ defer_refused_query(state_dir, query)
2438
+ logger.warning("hook.prime_refresh_refused", exc_info=True)
2439
+ return "refused"
2440
+ return "error"
2359
2441
  except httpx.TimeoutException as exc:
2360
- log_refresh_event(account.state_dir, query=query, event="timeout", detail=str(exc)[:200])
2442
+ log_refresh_event(state_dir, query=query, event="timeout", detail=str(exc)[:200])
2443
+ return "timeout"
2361
2444
  except Exception as exc:
2362
- log_refresh_event(account.state_dir, query=query, event="error", detail=str(exc)[:200])
2445
+ log_refresh_event(state_dir, query=query, event="error", detail=str(exc)[:200])
2363
2446
  logger.warning("hook.prime_refresh_failed", exc_info=True)
2364
- sys.exit(0)
2447
+ return "error"
2365
2448
 
2366
2449
 
2367
2450
  def _prime_block_from_recall_result(result: dict[str, object], *, limit: int) -> str:
@@ -62,6 +62,87 @@ def defer_refused_query(state_dir: Path, query: str) -> None:
62
62
  )
63
63
 
64
64
 
65
+ def is_repeat_limit_refusal(message: str) -> bool:
66
+ """Whether a tool refusal is the server's identical-read repeat limit.
67
+
68
+ Only this refusal starts the local cooldown. A read that timed out on the
69
+ server also comes back as a tool error, and treating it as a repeat-limit
70
+ refusal shut every automatic read off for ten minutes, so a failed prime
71
+ with nothing cached stayed empty for that whole window (TOS-4486).
72
+ """
73
+ return "loop_detected" in message or "repeat limit" in message
74
+
75
+
76
+ #: The server allows this many identical reads per window and counts failed
77
+ #: calls toward it (TOS-7410). Automatic prime reads never exceed it.
78
+ AUTOMATIC_READ_CAP: int = 3
79
+ AUTOMATIC_READ_WINDOW_S: float = 600.0
80
+ READ_LEDGER_NAME: str = "prime_read_ledger.json"
81
+ #: When nothing is cached, a failed refresh retries this long after the
82
+ #: failure, then the normal ~10 minute refresh cadence takes over (TOS-4486).
83
+ REFRESH_RETRY_OFFSETS_S: tuple[float, ...] = (60.0, 180.0)
84
+
85
+
86
+ def _read_ledger(path: Path) -> dict[str, Any]:
87
+ try:
88
+ data = json.loads(path.read_text(encoding="utf-8"))
89
+ except (OSError, json.JSONDecodeError):
90
+ return {}
91
+ return data if isinstance(data, dict) else {}
92
+
93
+
94
+ def _recent_reads(entry: object, now_ts: float) -> list[float]:
95
+ if not isinstance(entry, list):
96
+ return []
97
+ return [
98
+ float(ts)
99
+ for ts in entry
100
+ if isinstance(ts, int | float) and now_ts - float(ts) < AUTOMATIC_READ_WINDOW_S
101
+ ]
102
+
103
+
104
+ def claim_automatic_read(state_dir: Path, query: str, *, now: float | None = None) -> bool:
105
+ """Record one automatic prime read for ``query`` if the window allows it.
106
+
107
+ Returns False, recording nothing, when ``AUTOMATIC_READ_CAP`` reads of
108
+ this query already happened in the last ``AUTOMATIC_READ_WINDOW_S``.
109
+ Every automatic read of the prime (the foreground call on a miss and each
110
+ background refresh attempt) goes through here, so retries can never push
111
+ the client past the server's repeat limit. A ledger that cannot be read
112
+ counts as empty; one that cannot be written does not block the read.
113
+ """
114
+ now_ts = time.time() if now is None else now
115
+ path = state_dir / READ_LEDGER_NAME
116
+ try:
117
+ ensure_private_dir(state_dir)
118
+ fd = os.open(state_dir / ".prime_read_ledger.lock", os.O_RDWR | os.O_CREAT, 0o600)
119
+ with os.fdopen(fd, "a+") as handle:
120
+ lock_exclusive(handle)
121
+ try:
122
+ data = _read_ledger(path)
123
+ recent = _recent_reads(data.get(query), now_ts)
124
+ if len(recent) >= AUTOMATIC_READ_CAP:
125
+ return False
126
+ data = {
127
+ key: kept
128
+ for key, value in data.items()
129
+ if (kept := _recent_reads(value, now_ts))
130
+ }
131
+ data[query] = [*recent, now_ts]
132
+ write_private_json(path, data)
133
+ return True
134
+ finally:
135
+ unlock(handle)
136
+ except OSError:
137
+ logger.warning("primecache.read_ledger_failed", exc_info=True)
138
+ return True
139
+
140
+
141
+ def has_cached_block(state_dir: Path, query: str) -> bool:
142
+ """Whether any deliverable block exists for ``query``, fresh or stale."""
143
+ return load_cached_block(state_dir, query) is not None
144
+
145
+
65
146
  def query_is_deferred(state_dir: Path, query: str) -> bool:
66
147
  try:
67
148
  data = json.loads((state_dir / REFUSAL_COOLDOWN_NAME).read_text(encoding="utf-8"))
@@ -114,3 +114,13 @@ def _never_run_the_real_claude_cli(monkeypatch: pytest.MonkeyPatch) -> None:
114
114
  subprocess themselves.
115
115
  """
116
116
  monkeypatch.setattr(cli, "_claude_binary", lambda: None)
117
+
118
+
119
+ @pytest.fixture(autouse=True)
120
+ def _no_real_refresh_retry_waits(monkeypatch: pytest.MonkeyPatch) -> None:
121
+ """A failed background prime refresh retries after 1 and 3 minutes when
122
+ nothing is cached (TOS-4486). Off by default so no test sleeps for real;
123
+ the retry tests turn it back on with a fake clock."""
124
+ from thinqos_capture import hook
125
+
126
+ monkeypatch.setattr(hook, "REFRESH_RETRY_OFFSETS_S", ())
@@ -0,0 +1,296 @@
1
+ """TOS-4486: a failed prime refresh retries at ~1 and ~3 minutes when nothing is cached.
2
+
3
+ The server allows 3 identical reads per 10 minutes and counts failed calls, so
4
+ the retries never exceed that, never run inside a repeat-limit cooldown, and
5
+ nothing changes when a cached block exists.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from collections.abc import Callable
12
+ from pathlib import Path
13
+
14
+ import httpx
15
+ import pytest
16
+ from click.testing import CliRunner
17
+
18
+ from thinqos_capture import hook, primecache
19
+ from thinqos_capture.accountscope import activate_account_scope
20
+ from thinqos_capture.cli import main
21
+
22
+ GOOD = {"result": {"structuredContent": {"context": "# Mind\n- real context", "outcome": "ok"}}}
23
+ SERVER_TIMEOUT = {
24
+ "result": {
25
+ "isError": True,
26
+ "content": [
27
+ {
28
+ "type": "text",
29
+ "text": "recall (depth=quick) timed out while reading thinqOS Mind storage "
30
+ "(its 2s deadline passed). Nothing was written. Retry shortly, "
31
+ "or narrow the query.",
32
+ }
33
+ ],
34
+ }
35
+ }
36
+ REPEAT_LIMIT = {
37
+ "error": {
38
+ "code": -32603,
39
+ "message": "loop_detected: recall: This operation has already reached its repeat limit "
40
+ "in the last 10 minutes. Report the previous result or error to the user and stop. "
41
+ "Do not retry.",
42
+ }
43
+ }
44
+
45
+
46
+ class _Response:
47
+ def __init__(self, body: dict[str, object]) -> None:
48
+ self._body = body
49
+
50
+ def raise_for_status(self) -> None:
51
+ return None
52
+
53
+ def json(self) -> dict[str, object]:
54
+ return self._body
55
+
56
+
57
+ Step = dict[str, object] | type[Exception]
58
+
59
+
60
+ class _Clock:
61
+ def __init__(self) -> None:
62
+ self.now = 1000.0
63
+ self.sleeps: list[float] = []
64
+ self.on_sleep: Callable[[], None] | None = None
65
+
66
+ def clock(self) -> float:
67
+ return self.now
68
+
69
+ def sleep(self, seconds: float) -> None:
70
+ self.sleeps.append(seconds)
71
+ self.now += seconds
72
+ if self.on_sleep is not None:
73
+ self.on_sleep()
74
+
75
+
76
+ @pytest.fixture
77
+ def clock(monkeypatch: pytest.MonkeyPatch) -> _Clock:
78
+ fake = _Clock()
79
+ monkeypatch.setattr(hook, "REFRESH_RETRY_OFFSETS_S", primecache.REFRESH_RETRY_OFFSETS_S)
80
+ monkeypatch.setattr(hook, "_refresh_clock", fake.clock)
81
+ monkeypatch.setattr(hook, "_refresh_sleep", fake.sleep)
82
+ return fake
83
+
84
+
85
+ def _install(
86
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, steps: list[Step], clock: _Clock | None
87
+ ) -> list[float]:
88
+ """Script the server; return the fake-clock time of every call made."""
89
+ call_times: list[float] = []
90
+
91
+ def fake_post(*_a: object, **_k: object) -> _Response:
92
+ call_times.append(clock.now if clock else 0.0)
93
+ assert steps, "more server calls than scripted"
94
+ step = steps.pop(0)
95
+ if isinstance(step, type):
96
+ raise step("scripted")
97
+ return _Response(step)
98
+
99
+ monkeypatch.setattr("httpx.Client.post", fake_post)
100
+ monkeypatch.setattr("thinqos_capture.hook.DEFAULT_STATE_DIR", tmp_path)
101
+ monkeypatch.setattr("thinqos_capture.process.subprocess.Popen", lambda *_a, **_k: None)
102
+ monkeypatch.setenv("INGEST_API_KEY", "tq_test")
103
+ monkeypatch.setenv("THINQOS_BASE_URL", "http://example.test")
104
+ return call_times
105
+
106
+
107
+ def _state(tmp_path: Path) -> Path:
108
+ return activate_account_scope(tmp_path, "http://example.test", "tq_test").state_dir
109
+
110
+
111
+ def _events(state: Path) -> list[str]:
112
+ path = state / primecache.REFRESH_EVENT_LOG_NAME
113
+ if not path.exists():
114
+ return []
115
+ return [json.loads(line)["event"] for line in path.read_text(encoding="utf-8").splitlines()]
116
+
117
+
118
+ def _refresh() -> None:
119
+ result = CliRunner().invoke(main, ["hook", "prime-refresh", "--query", ""])
120
+ assert result.exit_code == 0, result.output
121
+
122
+
123
+ def test_retries_at_one_and_three_minutes_then_stops(
124
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, clock: _Clock
125
+ ) -> None:
126
+ times = _install(monkeypatch, tmp_path, [httpx.ReadTimeout, SERVER_TIMEOUT, GOOD], clock)
127
+
128
+ _refresh()
129
+
130
+ assert times == [1000.0, 1060.0, 1180.0]
131
+ state = _state(tmp_path)
132
+ cached = primecache.load_cached_block(state, "")
133
+ assert cached is not None and "real context" in cached[0]
134
+ assert _events(state) == ["timeout", "retry", "error", "retry", "completed"]
135
+
136
+
137
+ def test_a_successful_retry_ends_the_schedule(
138
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, clock: _Clock
139
+ ) -> None:
140
+ times = _install(monkeypatch, tmp_path, [SERVER_TIMEOUT, GOOD], clock)
141
+
142
+ _refresh()
143
+
144
+ assert times == [1000.0, 1060.0]
145
+ assert clock.sleeps == [60.0]
146
+
147
+
148
+ def test_falls_back_to_normal_cadence_after_two_retries(
149
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, clock: _Clock
150
+ ) -> None:
151
+ times = _install(monkeypatch, tmp_path, [SERVER_TIMEOUT, SERVER_TIMEOUT, SERVER_TIMEOUT], clock)
152
+
153
+ _refresh()
154
+
155
+ assert times == [1000.0, 1060.0, 1180.0]
156
+ assert primecache.load_cached_block(_state(tmp_path), "") is None
157
+
158
+
159
+ def test_never_more_than_three_reads_in_ten_minutes(
160
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, clock: _Clock
161
+ ) -> None:
162
+ """Two foreground reads already happened: one refresh read is left, no retries."""
163
+ state = _state(tmp_path)
164
+ assert primecache.claim_automatic_read(state, "")
165
+ assert primecache.claim_automatic_read(state, "")
166
+ times = _install(monkeypatch, tmp_path, [SERVER_TIMEOUT], clock)
167
+
168
+ _refresh()
169
+
170
+ assert len(times) == 1
171
+ assert _events(state).count("retry_skipped_cap") == 2
172
+
173
+
174
+ def test_refresh_with_the_allowance_spent_makes_no_call(
175
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, clock: _Clock
176
+ ) -> None:
177
+ state = _state(tmp_path)
178
+ for _ in range(3):
179
+ assert primecache.claim_automatic_read(state, "")
180
+ times = _install(monkeypatch, tmp_path, [], clock)
181
+
182
+ _refresh()
183
+
184
+ assert times == []
185
+ assert _events(state) == ["capped"]
186
+
187
+
188
+ def test_read_allowance_frees_after_the_window(tmp_path: Path) -> None:
189
+ for _ in range(3):
190
+ assert primecache.claim_automatic_read(tmp_path, "", now=100.0)
191
+ assert not primecache.claim_automatic_read(tmp_path, "", now=650.0)
192
+ assert primecache.claim_automatic_read(tmp_path, "", now=701.0)
193
+ # Another query has its own allowance.
194
+ assert primecache.claim_automatic_read(tmp_path, "other", now=650.0)
195
+
196
+
197
+ def test_repeat_limit_refusal_starts_cooldown_and_is_not_retried(
198
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, clock: _Clock
199
+ ) -> None:
200
+ times = _install(monkeypatch, tmp_path, [REPEAT_LIMIT], clock)
201
+
202
+ _refresh()
203
+
204
+ assert len(times) == 1
205
+ assert clock.sleeps == []
206
+ assert primecache.query_is_deferred(_state(tmp_path), "")
207
+
208
+
209
+ def test_no_retry_inside_a_cooldown_that_starts_while_waiting(
210
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, clock: _Clock
211
+ ) -> None:
212
+ state = _state(tmp_path)
213
+ times = _install(monkeypatch, tmp_path, [SERVER_TIMEOUT], clock)
214
+ clock.on_sleep = lambda: primecache.defer_refused_query(state, "")
215
+
216
+ _refresh()
217
+
218
+ assert len(times) == 1
219
+ assert _events(state)[-1] == "retry_skipped_cooldown"
220
+
221
+
222
+ def test_active_cooldown_means_no_refresh_at_all(
223
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, clock: _Clock
224
+ ) -> None:
225
+ primecache.defer_refused_query(_state(tmp_path), "")
226
+ times = _install(monkeypatch, tmp_path, [], clock)
227
+
228
+ _refresh()
229
+
230
+ assert times == []
231
+
232
+
233
+ def test_server_timeout_error_does_not_start_a_cooldown(
234
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, clock: _Clock
235
+ ) -> None:
236
+ """Before TOS-4486 any tool error deferred all automatic reads for 10 minutes."""
237
+ _install(monkeypatch, tmp_path, [SERVER_TIMEOUT, GOOD], clock)
238
+
239
+ _refresh()
240
+
241
+ assert not primecache.query_is_deferred(_state(tmp_path), "")
242
+
243
+
244
+ @pytest.mark.parametrize("failure", [SERVER_TIMEOUT, httpx.ReadTimeout])
245
+ def test_unchanged_when_a_block_exists(
246
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, clock: _Clock, failure: Step
247
+ ) -> None:
248
+ state = _state(tmp_path)
249
+ primecache.save_cached_block(state, "", "# Old\n- still good")
250
+ times = _install(monkeypatch, tmp_path, [failure], clock)
251
+
252
+ _refresh()
253
+
254
+ assert len(times) == 1
255
+ assert clock.sleeps == []
256
+ cached = primecache.load_cached_block(state, "")
257
+ assert cached is not None and cached[0] == "# Old\n- still good"
258
+
259
+
260
+ def test_retry_stops_when_another_process_fills_the_cache(
261
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, clock: _Clock
262
+ ) -> None:
263
+ state = _state(tmp_path)
264
+ times = _install(monkeypatch, tmp_path, [SERVER_TIMEOUT], clock)
265
+ clock.on_sleep = lambda: primecache.save_cached_block(state, "", "# From the foreground")
266
+
267
+ _refresh()
268
+
269
+ assert len(times) == 1
270
+
271
+
272
+ def test_foreground_prime_respects_the_read_allowance(
273
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
274
+ ) -> None:
275
+ state = _state(tmp_path)
276
+ for _ in range(3):
277
+ assert primecache.claim_automatic_read(state, "")
278
+ times = _install(monkeypatch, tmp_path, [], None)
279
+
280
+ result = CliRunner().invoke(main, ["hook", "prime"])
281
+
282
+ assert result.exit_code == 0, result.output
283
+ assert times == []
284
+ assert "thinqOS recall FAILED" in result.output
285
+ assert not primecache.query_is_deferred(state, "")
286
+
287
+
288
+ def test_foreground_read_is_counted(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
289
+ _install(monkeypatch, tmp_path, [GOOD], None)
290
+
291
+ CliRunner().invoke(main, ["hook", "prime"])
292
+
293
+ ledger = json.loads(
294
+ (_state(tmp_path) / primecache.READ_LEDGER_NAME).read_text(encoding="utf-8")
295
+ )
296
+ assert len(ledger[""]) == 1
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes