pdm-memory 0.2.4__tar.gz → 0.2.6__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 (186) hide show
  1. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/PKG-INFO +548 -23
  2. pdm_memory-0.2.6/README.md +1179 -0
  3. pdm_memory-0.2.6/pdm_memory/__init__.py +105 -0
  4. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/bench/correctability/ablation.py +7 -6
  5. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/bench/correctability/harness.py +3 -4
  6. pdm_memory-0.2.6/pdm_memory/claims.py +156 -0
  7. pdm_memory-0.2.6/pdm_memory/connector/__init__.py +10 -0
  8. pdm_memory-0.2.6/pdm_memory/connector/__main__.py +3 -0
  9. pdm_memory-0.2.6/pdm_memory/connector/server.py +145 -0
  10. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/core/alignment.py +12 -0
  11. pdm_memory-0.2.6/pdm_memory/core/field_scoped_retrieval.py +180 -0
  12. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/core/math.py +188 -16
  13. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/core/retrieval.py +27 -31
  14. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/core/signature.py +118 -6
  15. pdm_memory-0.2.6/pdm_memory/event_log.py +904 -0
  16. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/examples/README.md +14 -0
  17. pdm_memory-0.2.6/pdm_memory/examples/field_state_demo.py +213 -0
  18. pdm_memory-0.2.6/pdm_memory/examples/goal_loop_watch_price.py +147 -0
  19. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/examples/guarded_agent_logic.py +1 -1
  20. pdm_memory-0.2.6/pdm_memory/examples/guarded_effects.py +104 -0
  21. pdm_memory-0.2.6/pdm_memory/examples/guarded_pdm_write.py +125 -0
  22. pdm_memory-0.2.6/pdm_memory/filters/__init__.py +10 -0
  23. pdm_memory-0.2.6/pdm_memory/filters/base.py +50 -0
  24. pdm_memory-0.2.6/pdm_memory/filters/noun_probe.py +35 -0
  25. pdm_memory-0.2.6/pdm_memory/geopass.py +279 -0
  26. pdm_memory-0.2.6/pdm_memory/goal_loop/__init__.py +93 -0
  27. pdm_memory-0.2.6/pdm_memory/goal_loop/_json.py +134 -0
  28. pdm_memory-0.2.6/pdm_memory/goal_loop/checker.py +112 -0
  29. pdm_memory-0.2.6/pdm_memory/goal_loop/contract.py +649 -0
  30. pdm_memory-0.2.6/pdm_memory/goal_loop/controller.py +1288 -0
  31. pdm_memory-0.2.6/pdm_memory/goal_loop/executor.py +57 -0
  32. pdm_memory-0.2.6/pdm_memory/goal_loop/guard.py +93 -0
  33. pdm_memory-0.2.6/pdm_memory/goal_loop/job.py +329 -0
  34. pdm_memory-0.2.6/pdm_memory/goal_loop/receipts.py +115 -0
  35. pdm_memory-0.2.6/pdm_memory/goal_loop/states.py +111 -0
  36. pdm_memory-0.2.6/pdm_memory/goal_loop/store.py +367 -0
  37. pdm_memory-0.2.6/pdm_memory/goal_loop/testing.py +203 -0
  38. pdm_memory-0.2.6/pdm_memory/goal_loop/triggers.py +80 -0
  39. pdm_memory-0.2.6/pdm_memory/guarded_effects.py +1090 -0
  40. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/ingest/batch.py +2 -3
  41. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/ingest/ingester.py +17 -1
  42. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/io/json_transfer.py +18 -0
  43. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/memory.py +1320 -325
  44. pdm_memory-0.2.6/pdm_memory/models.py +778 -0
  45. pdm_memory-0.2.6/pdm_memory/noun_probe/__init__.py +94 -0
  46. pdm_memory-0.2.6/pdm_memory/noun_probe/boundary.py +77 -0
  47. pdm_memory-0.2.6/pdm_memory/noun_probe/config.py +58 -0
  48. pdm_memory-0.2.6/pdm_memory/noun_probe/contracts.py +308 -0
  49. pdm_memory-0.2.6/pdm_memory/noun_probe/detector.py +141 -0
  50. pdm_memory-0.2.6/pdm_memory/noun_probe/drift_veto.py +92 -0
  51. pdm_memory-0.2.6/pdm_memory/noun_probe/extraction.py +113 -0
  52. pdm_memory-0.2.6/pdm_memory/noun_probe/invariance.py +113 -0
  53. pdm_memory-0.2.6/pdm_memory/noun_probe/lexicon.py +577 -0
  54. pdm_memory-0.2.6/pdm_memory/noun_probe/perturbation.py +120 -0
  55. pdm_memory-0.2.6/pdm_memory/noun_probe/pipeline.py +222 -0
  56. pdm_memory-0.2.6/pdm_memory/noun_probe/relock.py +69 -0
  57. pdm_memory-0.2.6/pdm_memory/noun_probe/report.py +132 -0
  58. pdm_memory-0.2.6/pdm_memory/noun_probe/service.py +106 -0
  59. pdm_memory-0.2.6/pdm_memory/noun_probe/verb_coupling.py +147 -0
  60. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/storage/base.py +86 -1
  61. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/storage/cloud_driver.py +850 -15
  62. pdm_memory-0.2.6/pdm_memory/storage/errors.py +54 -0
  63. pdm_memory-0.2.6/pdm_memory/storage/event_hash.py +347 -0
  64. pdm_memory-0.2.6/pdm_memory/storage/event_store.py +863 -0
  65. pdm_memory-0.2.6/pdm_memory/storage/event_sync.py +333 -0
  66. pdm_memory-0.2.6/pdm_memory/storage/eventful_postgres.py +39 -0
  67. pdm_memory-0.2.6/pdm_memory/storage/eventful_sqlite.py +99 -0
  68. pdm_memory-0.2.6/pdm_memory/storage/events.py +991 -0
  69. pdm_memory-0.2.6/pdm_memory/storage/field_store.py +1053 -0
  70. pdm_memory-0.2.6/pdm_memory/storage/fields.py +581 -0
  71. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/storage/postgres_driver.py +154 -56
  72. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/storage/schema.py +296 -6
  73. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/storage/sqlite_driver.py +162 -15
  74. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/tools/cli.py +52 -29
  75. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/tools/explorer_actions.py +18 -20
  76. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/tools/server.py +5 -4
  77. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory.egg-info/PKG-INFO +548 -23
  78. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory.egg-info/SOURCES.txt +89 -1
  79. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory.egg-info/entry_points.txt +1 -0
  80. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory.egg-info/requires.txt +5 -0
  81. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pyproject.toml +7 -1
  82. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_alignment.py +21 -1
  83. pdm_memory-0.2.6/tests/test_carried.py +63 -0
  84. pdm_memory-0.2.6/tests/test_claims.py +148 -0
  85. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_cli.py +7 -2
  86. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_cloud_driver.py +13 -3
  87. pdm_memory-0.2.6/tests/test_cloud_events.py +292 -0
  88. pdm_memory-0.2.6/tests/test_cloud_fields.py +583 -0
  89. pdm_memory-0.2.6/tests/test_cloud_v19.py +178 -0
  90. pdm_memory-0.2.6/tests/test_connector.py +222 -0
  91. pdm_memory-0.2.6/tests/test_contrary_evidence.py +144 -0
  92. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_correctability.py +14 -17
  93. pdm_memory-0.2.6/tests/test_count_silent.py +86 -0
  94. pdm_memory-0.2.6/tests/test_current_resolution.py +120 -0
  95. pdm_memory-0.2.6/tests/test_event_layer_parity.py +423 -0
  96. pdm_memory-0.2.6/tests/test_evidence_layer_regressions.py +672 -0
  97. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_explorer_console.py +5 -3
  98. pdm_memory-0.2.6/tests/test_extract_signatures.py +146 -0
  99. pdm_memory-0.2.6/tests/test_field_memberships.py +662 -0
  100. pdm_memory-0.2.6/tests/test_field_state.py +221 -0
  101. pdm_memory-0.2.6/tests/test_geopass.py +242 -0
  102. pdm_memory-0.2.6/tests/test_goal_contract.py +440 -0
  103. pdm_memory-0.2.6/tests/test_goal_loop_controller.py +1337 -0
  104. pdm_memory-0.2.6/tests/test_goal_loop_store.py +140 -0
  105. pdm_memory-0.2.6/tests/test_goal_loop_triggers.py +138 -0
  106. pdm_memory-0.2.6/tests/test_guarded_effects.py +559 -0
  107. pdm_memory-0.2.6/tests/test_guarded_pdm_write.py +16 -0
  108. pdm_memory-0.2.6/tests/test_link_store.py +81 -0
  109. pdm_memory-0.2.6/tests/test_links.py +136 -0
  110. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_math.py +128 -2
  111. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_memory.py +149 -11
  112. pdm_memory-0.2.6/tests/test_noun_probe_engine.py +645 -0
  113. pdm_memory-0.2.6/tests/test_noun_probe_filter.py +55 -0
  114. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_pdm_concurrency.py +7 -7
  115. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_pdm_physics.py +4 -29
  116. pdm_memory-0.2.6/tests/test_postgres_live.py +230 -0
  117. pdm_memory-0.2.6/tests/test_projection.py +301 -0
  118. pdm_memory-0.2.6/tests/test_relationship_state.py +192 -0
  119. pdm_memory-0.2.6/tests/test_retrieve_v19.py +207 -0
  120. pdm_memory-0.2.6/tests/test_review24_followup.py +339 -0
  121. pdm_memory-0.2.6/tests/test_save_filters.py +267 -0
  122. pdm_memory-0.2.6/tests/test_settlement.py +256 -0
  123. pdm_memory-0.2.6/tests/test_source_events.py +772 -0
  124. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_storage_factory.py +1 -1
  125. pdm_memory-0.2.6/tests/test_tag_table.py +98 -0
  126. pdm_memory-0.2.6/tests/test_three_writers.py +147 -0
  127. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_tier2.py +3 -3
  128. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_torsion.py +14 -15
  129. pdm_memory-0.2.6/tests/test_trajectory.py +247 -0
  130. pdm_memory-0.2.6/tests/test_weight_law.py +75 -0
  131. pdm_memory-0.2.4/README.md +0 -658
  132. pdm_memory-0.2.4/pdm_memory/__init__.py +0 -44
  133. pdm_memory-0.2.4/pdm_memory/models.py +0 -128
  134. pdm_memory-0.2.4/pdm_memory/storage/errors.py +0 -26
  135. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/LICENSE +0 -0
  136. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/auth/__init__.py +0 -0
  137. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/auth/jwt_handler.py +0 -0
  138. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/bench/__init__.py +0 -0
  139. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/bench/__main__.py +0 -0
  140. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/bench/correctability/__init__.py +0 -0
  141. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/bench/correctability/baselines.py +0 -0
  142. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/bench/correctability/metrics.py +0 -0
  143. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/bench/correctability/scenarios.py +0 -0
  144. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/bench.py +0 -0
  145. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/core/__init__.py +0 -0
  146. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/core/constraints.py +0 -0
  147. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/examples/__init__.py +0 -0
  148. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/examples/handling_contradictions.py +0 -0
  149. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/examples/hello_pdm.py +0 -0
  150. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/examples/industrial_safety_gate.py +0 -0
  151. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/examples/standalone_guard.py +0 -0
  152. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/examples/temporal_recall_demo.py +0 -0
  153. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/ingest/__init__.py +0 -0
  154. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/ingest/auto_signature.py +0 -0
  155. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/integrations/__init__.py +0 -0
  156. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/integrations/anthropic_adapter.py +0 -0
  157. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/integrations/context_manager.py +0 -0
  158. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/integrations/gemini_adapter.py +0 -0
  159. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/integrations/groq_adapter.py +0 -0
  160. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/integrations/ollama_adapter.py +0 -0
  161. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/integrations/openai_adapter.py +0 -0
  162. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/io/__init__.py +0 -0
  163. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/io/csv_transfer.py +0 -0
  164. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/storage/__init__.py +0 -0
  165. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/storage/factory.py +0 -0
  166. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/sync.py +0 -0
  167. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/tools/__init__.py +0 -0
  168. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/tools/bench.py +0 -0
  169. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/tools/static/index.html +0 -0
  170. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory/types.py +0 -0
  171. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory.egg-info/dependency_links.txt +0 -0
  172. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/pdm_memory.egg-info/top_level.txt +0 -0
  173. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/setup.cfg +0 -0
  174. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_bench.py +0 -0
  175. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_constraints.py +0 -0
  176. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_explorer_ui.py +0 -0
  177. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_gemini_adapter.py +0 -0
  178. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_groq_adapter.py +0 -0
  179. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_jwt_auth.py +0 -0
  180. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_memory_hooks.py +0 -0
  181. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_ollama_adapter.py +0 -0
  182. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_postgres_driver.py +0 -0
  183. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_retrieval_diversity.py +0 -0
  184. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_sqlite_driver.py +0 -0
  185. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_tier3.py +0 -0
  186. {pdm_memory-0.2.4 → pdm_memory-0.2.6}/tests/test_verify_live.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pdm-memory
3
- Version: 0.2.4
3
+ Version: 0.2.6
4
4
  Summary: Pressure-Driven Memory (PDM) — persistent, resonance-based memory for AI apps.
5
5
  Author: Westfield Innovations LLC
6
6
  License: Elastic License 2.0 (ELv2)
@@ -156,6 +156,8 @@ Requires-Dist: fastapi>=0.110; extra == "ui"
156
156
  Requires-Dist: uvicorn[standard]>=0.27; extra == "ui"
157
157
  Provides-Extra: postgres
158
158
  Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
159
+ Provides-Extra: connector
160
+ Requires-Dist: mcp>=1.8; extra == "connector"
159
161
  Provides-Extra: dev
160
162
  Requires-Dist: pytest>=8.0; extra == "dev"
161
163
  Requires-Dist: pytest-cov>=5.0; extra == "dev"
@@ -168,6 +170,8 @@ Requires-Dist: ollama>=0.2.0; extra == "dev"
168
170
  Requires-Dist: groq>=0.9.0; extra == "dev"
169
171
  Requires-Dist: fastapi>=0.110; extra == "dev"
170
172
  Requires-Dist: uvicorn[standard]>=0.27; extra == "dev"
173
+ Requires-Dist: psycopg[binary]>=3.1; extra == "dev"
174
+ Requires-Dist: mcp>=1.8; extra == "dev"
171
175
  Dynamic: license-file
172
176
 
173
177
  # PDM — Memory for AI Apps That Works Like Memory
@@ -228,38 +232,198 @@ pip install "pdm-memory[all]"
228
232
  from pdm_memory import Memory
229
233
 
230
234
  # One line to start. The .db file is created automatically.
231
- mem = Memory(store="./my_app_memory.db")
235
+ mem = Memory(store="./my_app_memory.db", user="alice")
232
236
 
233
237
  # Write: PDM assigns pressure and stores a signature.
234
- mem.save("User prefers metric units and short answers", source="chat",
235
- tags=["units", "formatting", "preferences"], p_magnitude=85)
238
+ # Optional shape: ephemeral (2h) / behavioral (90d) / structural (∞).
239
+ mem.save("User prefers metric units and short answers", source="manual",
240
+ tags=["units", "formatting", "preferences"], p_magnitude=85,
241
+ shape="behavioral")
236
242
 
237
243
  # Read: resonance retrieval — surfaces what's relevant, not just what matches.
244
+ # Reading writes nothing.
238
245
  hits = mem.recall("how should I format the answer?", k=5)
239
246
 
240
247
  for h in hits:
241
- print(h.text, h.pressure, h.last_reinforced)
248
+ print(h.text, h.pressure, h.action_status)
242
249
 
243
- # Reinforce a memory manually (recall() does this automatically).
250
+ # Use: tell the memory what you acted on. This resets its fade, nothing more.
251
+ mem.touch([hits[0].id])
252
+
253
+ # Grade: when the world answers. reinforce() counts a correct prediction,
254
+ # penalize() a wrong one. Only V moves; P is fixed when a memory is saved.
244
255
  mem.reinforce(hits[0].id)
245
256
 
257
+ # Contrary evidence: lower V without rewriting the stored fact.
258
+ result = mem.apply_contrary_evidence(
259
+ hits[0].id,
260
+ "User prefers imperial units",
261
+ evidence_tags=["units", "formatting", "preferences"],
262
+ )
263
+ print(result.v_before, "→", result.v_after) # P stays; V falls
264
+
246
265
  # Inspect why a memory surfaced.
247
266
  report = mem.explain(hits[0].id, query="how should I format the answer?")
248
267
  print(report.render())
249
268
 
250
- # Decay runs automatically on each recall(). Manual trigger:
251
- counts = mem.decay()
252
- print(f"Decayed: {counts['decayed']}, Deleted: {counts['deleted']}")
269
+ # Live decay snapshot for one memory (read-only):
270
+ snap = mem.decay_at(hits[0].id)
271
+ print(snap.shape, snap.half_life_days, snap.p_effective)
272
+
273
+ # Nothing is deleted for fading: count the silent memories instead.
274
+ print(mem.count_silent()) # weight under 30 (0.3 of full)
275
+ ```
276
+
277
+ ### Retrieve, use, grade (PDM v1.9)
278
+
279
+ `retrieve()` is `recall()` with everything the call covered. It walks the tag
280
+ index, gates on the carried number (P × V), weighs each candidate at one fixed
281
+ time while its budget lasts, and flags what it returns:
282
+
283
+ ```python
284
+ from datetime import datetime, timedelta, timezone
285
+ from pdm_memory import Claim
286
+
287
+ # Weight = P × V × fade; with no verdicts V = 0.5, so P 80 weighs 40 (gate: 30).
288
+ sensor = mem.save("North flare sensor read 9 bar", tags=["north", "flare", "sensor"],
289
+ p_magnitude=80)
290
+ claim = mem.save(
291
+ "North flare igniter fails by Friday",
292
+ tags=["north", "flare", "igniter"],
293
+ p_magnitude=80,
294
+ rests_on=[sensor], # support: a correction to the sensor re-opens this
295
+ claim=Claim("occurs", datetime.now(timezone.utc) + timedelta(days=4),
296
+ outcome_source="failure-feed"),
297
+ )
298
+
299
+ result = mem.retrieve("north flare", k=5) # min_p=30 by default
300
+ for h in result.hits:
301
+ print(h.text, h.p_effective, h.validation_status, h.context,
302
+ h.support_in_doubt, h.owl, h.duck, h.action_status)
303
+ print(result.routes, result.theta, result.as_of, result.completed)
304
+
305
+ # Ran out of budget? Resume under the same as-of time and order.
306
+ if not result.completed:
307
+ more = mem.retrieve("north flare", continuation=result.continuation)
308
+
309
+ # A search lowers only the weight gate (never under 10 without a named area).
310
+ quiet = mem.search("north flare", min_p_lowered=12)
311
+
312
+ mem.touch([h.id for h in result.hits]) # what you used
313
+ mem.reinforce(sensor) # the sensor was checked: VALIDATED
314
+ mem.penalize(sensor) # later found stuck: a correction, returns the ids it re-opened
315
+ now = datetime.now(timezone.utc)
316
+ mem.report_coverage_gap("failure-feed", now - timedelta(hours=6), now) # a feed that was down
253
317
  ```
254
318
 
319
+ `action_status` is `UNVALIDATED` when the hit stands alone (`STANDALONE`), when
320
+ something it rests on is in doubt, or when it is a safety claim nobody has
321
+ checked (a duck). The memory returns qualified hits; the caller decides.
322
+
323
+ ### Settle claims (PDM v1.9)
324
+
325
+ A claim holds one verdict: `on_time`, `late`, `observed_absent`, `not_by_due`
326
+ or `expired_unobserved`. Amending it moves its one count in V; it never adds a
327
+ second. Run the settlement pass once per cycle; nothing runs it for you.
328
+
329
+ ```python
330
+ # Each cycle: every open claim whose due has come gets its verdict.
331
+ # Bound to a source with nothing reported: not_by_due (graded).
332
+ # Unbound, or a reported gap touches its interval: expired_unobserved (V unchanged).
333
+ report = mem.settle_due_claims()
334
+ print(report.settled, report.reopened, report.failed)
335
+
336
+ # An observation arrives: settle the claim, or amend its verdict while the
337
+ # watch window is open. "occurred", "observed_absent" or "unknown".
338
+ result = mem.validate_claim(claim, "occurred", event_time=now)
339
+ if result: # None when the observation changes nothing
340
+ print(result.verdict, result.reopened) # on_time 0
341
+ ```
342
+
343
+ A wrong verdict on a `VALIDATED` claim is a correction: it re-opens what rests
344
+ on it. A gap reported after the due turns `not_by_due` into
345
+ `expired_unobserved` and restores the count while the watch window is open.
346
+ On a cloud store the server runs the pass, so `settle_due_claims()` raises;
347
+ `validate_claim()` and `report_coverage_gap()` go to the server.
348
+
349
+ `recall(reinforce=True)` and `decay()` still work but are deprecated: the first
350
+ only touches the hits, the second only counts the silent set.
351
+
255
352
  ### Privacy-First Mode
256
353
 
257
354
  Store only SHA-256 hashes of memory text — the content never touches disk:
258
355
 
259
356
  ```python
260
- mem = Memory(store="./private.db", store_raw=False)
357
+ mem = Memory(store="./private.db", user="alice", store_raw=False)
358
+ ```
359
+
360
+ ### Save Filters
361
+
362
+ Opt-in passes every write must clear. A filter has a `name` and a
363
+ `check(text)` that returns a `FilterVerdict`; it sees the text exactly as it
364
+ will be stored (stripped, cut to 500 characters).
365
+
366
+ ```python
367
+ from pdm_memory import FilterRefused, FilterVerdict, Memory
368
+
369
+ class NoSecrets:
370
+ name = "no_secrets"
371
+
372
+ def check(self, text: str) -> FilterVerdict:
373
+ hit = "password" in text.lower()
374
+ return FilterVerdict(self.name, "1", ran=True, passed=not hit,
375
+ terms=("password",) if hit else ())
376
+
377
+ mem = Memory(store="./my_app.db", user="alice", filters=[NoSecrets()])
378
+ # or later: mem.add_filter(NoSecrets())
379
+
380
+ try:
381
+ mem.save("The admin password is hunter2", tags=["admin", "access", "ops"])
382
+ except FilterRefused as err:
383
+ print(err) # no_secrets refused the save: password
384
+ ```
385
+
386
+ - **Refused** (`ran=True, passed=False`): nothing is written and `save` /
387
+ `update(text=...)` raise `FilterRefused` (a `ValueError`). On a cloud store
388
+ no request is sent.
389
+ - **Passed**: the record carries `metadata["filters"][name] = {"version", "ran", "passed", "terms"}`.
390
+ - **Could not read the text** (`ran=False`): the record is written and marked
391
+ with `"ran": False`, so you can find it later.
392
+ - **The filter raises**: the exception reaches you and nothing is written.
393
+ - `save_many` and `ingest` count refused items as `blocked` and write the
394
+ rest; the `blocked` key is there only when filters are set.
395
+ - A dedupe or idempotency hit returns the existing ID before any filter runs.
396
+
397
+ Without `filters`, nothing changes: no calls, no extra metadata, the same
398
+ result dicts.
399
+
400
+ #### Noun Probe filter
401
+
402
+ `NounProbeFilter` runs a Noun Probe AUDIT pass on each fact and refuses one
403
+ that uses a noun against its class (an actor that is only acted upon, a word
404
+ doing another class's job). The method itself is published at
405
+ <https://azus.ai/tools/noun-probe/>.
406
+
407
+ ```python
408
+ from pdm_memory import FilterRefused, Memory, NounProbeFilter
409
+
410
+ mem = Memory(store="./my_app.db", user="alice", filters=[NounProbeFilter()])
411
+
412
+ mem.save("The budget accumulates.", tags=["budget", "planning", "finance"])
413
+
414
+ try:
415
+ mem.save("The operator is deployed and the budget fails.", tags=["ops", "budget", "risk"])
416
+ except FilterRefused as err:
417
+ print(err.verdict.terms) # ('operator',)
261
418
  ```
262
419
 
420
+ - Deterministic: word lists and rules, no model calls, no network.
421
+ - The word lists are English. Text it finds no structure in is written and
422
+ marked as passed.
423
+ - Settings come from the environment: `PDM_NOUN_PROBE_ENABLED` (off → every
424
+ fact is written with `"ran": False`), `PDM_NOUN_PROBE_TOP_N` (12),
425
+ `PDM_NOUN_PROBE_SUBSTITUTES_PER_NOUN` (1).
426
+
263
427
  ---
264
428
 
265
429
  ## ☁️ Ecosystem Mode (AZUS Cloud)
@@ -301,7 +465,7 @@ access_token = data["tokens"]["access"]
301
465
  refresh_token = data["tokens"]["refresh"]
302
466
  ```
303
467
 
304
- Use the returned JWTs directly with `Memory(store="cloud", ...)`:
468
+ Use the returned JWTs directly with `Memory(store="cloud", user=..., ...)`:
305
469
 
306
470
  ### Connect to the Cloud
307
471
 
@@ -324,6 +488,8 @@ mem.save(
324
488
  p_magnitude=70,
325
489
  dedupe=True,
326
490
  )
491
+ # A cloud store requires at least 3 tags per memory (ValueError before any
492
+ # request otherwise); a local store accepts fewer.
327
493
  # Exact-once create on retries: pass idempotency_key=...
328
494
  hits = mem.recall("what timezone are they in?")
329
495
 
@@ -342,11 +508,150 @@ mem.save_many(
342
508
  - `mem.delete(id)` → soft-delete (`is_deleted`) when the API supports it; cloud list/get hide those rows.
343
509
  - Permanent removal is storage-level `hard_delete` (CloudDriver), not the default Memory facade API.
344
510
 
511
+ ### Field State
512
+
513
+ The reconciled state of a bounded field — who belongs to it, how they are
514
+ connected, and what is visible in it — at a moment.
515
+
516
+ ```python
517
+ from datetime import datetime, timezone
518
+
519
+ # As it stands now. The moment is left out of the request on purpose, so the
520
+ # server answers from its own clock rather than yours.
521
+ state = mem.current_state("westfield")
522
+
523
+ # As it stood then. Must carry a timezone, and must not be in the future.
524
+ state = mem.state_at("westfield", datetime(2026, 3, 1, 12, tzinfo=timezone.utc))
525
+
526
+ state.field_memberships # standing in the field, with the intervals it held
527
+ state.relationships # edges, each with how current its channel reads
528
+ state.entities # signatures filed in this field, plus any filed nowhere; what this
529
+ # observer may reveal, one keyset page
530
+
531
+ # Nested fields match by prefix: "westfield" covers "westfield/dqs".
532
+ state = mem.current_state("westfield/dqs")
533
+
534
+ # Paging: follow the cursor and drop the envelope, which does not change
535
+ # between pages.
536
+ page = mem.current_state("westfield", cursor=state.entities_next_cursor, envelope=False)
537
+ ```
538
+
539
+ - **Cloud only.** Fields and memberships do not exist in the local schema, so
540
+ both calls raise in privacy mode rather than inventing a second data model.
541
+ - **Every item declares its own provenance.** `state_type` is `"measured"` or
542
+ `"projected"` on each item, never inferred from where it sits. A payload with
543
+ an untagged item is rejected rather than guessed at.
544
+ - **`envelope_included=False` means the envelope is absent, not empty.** The
545
+ fields are omitted rather than returned as `[]`, so a page-2 response can
546
+ never be read as a statement about the field.
547
+ - **Results are filtered to what the observer may reveal.** There is no
548
+ unfiltered mode, and permission resolves against now — a revoked grant does
549
+ not reopen last year.
550
+
551
+ ### Relationships
552
+
553
+ `EventLog.link(...)` records that two entities stood in some relation; the
554
+ methods below read and reinforce that link's channel over time.
555
+
556
+ ```python
557
+ from pdm_memory import Memory
558
+ from pdm_memory.event_log import EventLog
559
+
560
+ mem = Memory(store="cloud", user="alice", token="eyJ...")
561
+ log = EventLog(mem)
562
+
563
+ relationship_id = log.link("subject:1", "entity:abc-123", "colleague")
564
+
565
+ # Point-in-time state of the pair — which links were live, which channel
566
+ # measurements applied, and (only within the channel's own recency window)
567
+ # the current resolution vector. at_time omitted means now.
568
+ state = mem.relationship_state("subject:1", "entity:abc-123")
569
+ state.relationships # the live/historical link rows for this pair
570
+ state.channels # {domain: channel snapshot}, by domain
571
+ state.current_resolution_by_domain # None outside the recency window
572
+ state.current_resolution_reason # "past_moment" when it is None
573
+
574
+ # Cite an existing fact as reinforcing or contrary evidence for the link's
575
+ # channel. No bare number: the citation itself is the input.
576
+ from pdm_memory.storage.fields import RelationshipRecord
577
+
578
+ relationship = RelationshipRecord(id=relationship_id, source_entity_id="subject:1",
579
+ target_entity_id="entity:abc-123", relationship_type="colleague")
580
+ log.reinforce(relationship, evidence="sig-1") # or a SignatureRecord/SourceEventRecord
581
+ log.apply_contrary_evidence(relationship, evidence="sig-2")
582
+ ```
583
+
584
+ - **Cloud only**, same as Field State — `RelationshipChannel` and its
585
+ evidence log live only in Companion.
586
+ - **Dispatch by target type**, not by guessing at a string. `reinforce`/
587
+ `apply_contrary_evidence` route to the relationship-evidence endpoint only
588
+ when *target* is a `RelationshipRecord`; a bare string id or a
589
+ `SignatureRecord` goes to the existing, unchanged `Memory.reinforce()` /
590
+ `Memory.apply_contrary_evidence()` — the same methods and behaviour as
591
+ before this feature existed.
592
+ - **Resubmitting the same evidence is refused** (`CloudConflictError`,
593
+ `error_code="EVIDENCE_ALREADY_APPLIED"`), not silently counted twice.
594
+
595
+ | This document's naming | SDK method |
596
+ |---|---|
597
+ | Point-in-time relationship state | `Memory.relationship_state(source, target, at_time=None, domain=None)` |
598
+ | Reinforcing evidence, on a link | `EventLog.reinforce(relationship_record, evidence)` |
599
+ | Contrary evidence, on a link | `EventLog.apply_contrary_evidence(relationship_record, evidence)` |
600
+ | Reinforcing evidence, on a memory (unchanged) | `EventLog.reinforce(memory_id_or_record)` → `Memory.reinforce` |
601
+ | Contrary evidence, on a memory (unchanged) | `EventLog.apply_contrary_evidence(memory_id_or_record, evidence)` → `Memory.apply_contrary_evidence` |
602
+
603
+ ### Projections
604
+
605
+ A forward fan of where your channel is heading, and — once time has passed —
606
+ how it turned out.
607
+
608
+ ```python
609
+ from datetime import datetime, timezone
610
+
611
+ fan = mem.project() # the fan now; nothing is written
612
+ fan = mem.project(horizon_days=30) # narrower window, clamped to the server's reach
613
+ fan = mem.project(record=True) # persist it so it can be scored later
614
+
615
+ for branch in fan.branches:
616
+ branch.state_type # always "projected"
617
+ branch.confidence_band["weight"] # this branch's share of the fan
618
+ branch.timing_range # {"start", "end"} — a window, never a point
619
+ branch.invalidation_conditions # what would make it wrong
620
+
621
+ # Later: settle one recorded branch against what actually happened.
622
+ settled = mem.record_outcome(
623
+ fan.projection_ids[0],
624
+ observed_at=datetime.now(timezone.utc),
625
+ connection_geometry="correct", # "correct" | "partial" | "incorrect"
626
+ meaning_propagation="partial",
627
+ )
628
+ settled.outcome.timing # "early" | "within" | "late" — derived by the server
629
+
630
+ mem.projection(settled.id) # read it back, with its outcome
631
+ ```
632
+
633
+ - **Cloud only.** The fan is built from the observer's channel, which lives
634
+ in Companion.
635
+ - **A different type from a field state.** `ProjectionFan` and
636
+ `RecordedProjection` share no base class with `FieldStateSnapshot`, and a
637
+ payload whose items do not say `state_type="projected"` is refused rather
638
+ than typed as a projection.
639
+ - **Not field-scoped.** Spec §7 names `project(field_id, horizon,
640
+ constraints)`; the fan is built per domain, not per field, so there is no
641
+ `field_id` to pass, and `horizon_days` is the one constraint the server honours.
642
+ - **Recorded once a day.** With `record=True`, `projection_ids` is empty on a
643
+ repeat the same UTC day — that fan is already on file.
644
+ - **Settles once.** A second outcome raises `CloudConflictError`
645
+ (`error_code="ALREADY_SETTLED"`); an outcome observed before the projection
646
+ was made raises `CloudStorageError` with `status_code=422`; someone else's
647
+ projection reads as `CloudNotFoundError`. `timing` is never sent — the
648
+ server derives it from `observed_at`.
649
+
345
650
  ### Sync Local ↔ Cloud
346
651
 
347
652
  ```python
348
653
  # Start with a local store
349
- local_mem = Memory(store="./local.db")
654
+ local_mem = Memory(store="./local.db", user="alice")
350
655
  local_mem.save("Local preference", tags=["pref", "local", "test"])
351
656
 
352
657
  # Push local memories to cloud
@@ -389,7 +694,7 @@ The wrapper is the demo; the primitives are the product. Most developers start h
389
694
  from pdm_memory import Memory
390
695
  from pdm_memory.integrations import wrap_openai
391
696
 
392
- mem = Memory(store="./my_app.db")
697
+ mem = Memory(store="./my_app.db", user="alice")
393
698
  client = wrap_openai(api_key="sk-...", memory=mem)
394
699
 
395
700
  # Memory is handled completely invisibly:
@@ -429,7 +734,7 @@ Before an agent **acts**, `verify()` scores the proposed intent against a plain
429
734
 
430
735
  Statuses:
431
736
 
432
- - **ALIGNED** — safe to proceed (`report.is_safe_to_act` is `True`)
737
+ - **ALIGNED** — GAA found no blocking conflict (`report.is_safe_to_act` is `True`); the host still owns permission for the actual operation
433
738
  - **CONFLICT** — soft mismatch / missing anchors (fail-closed by default)
434
739
  - **TORSION** — hard contradiction — block the ACT
435
740
 
@@ -460,7 +765,7 @@ When goals already live in a PDM store, `Memory.verify_alignment()` is the same
460
765
  ```python
461
766
  from pdm_memory import Memory
462
767
 
463
- mem = Memory(store="./agent.db")
768
+ mem = Memory(store="./agent.db", user="alice")
464
769
 
465
770
  # Goal signatures live in stewardship / foundational drawers.
466
771
  mem.save(
@@ -517,6 +822,166 @@ for report in mem.detect_torsion(threshold=0.5):
517
822
 
518
823
  Full walkthroughs: `python -m pdm_memory.examples.standalone_guard`, `python -m pdm_memory.examples.guarded_agent_logic` and `python -m pdm_memory.examples.handling_contradictions`.
519
824
 
825
+ ### Boundary Lock guarded effects preview
826
+
827
+ The opt-in `pdm_memory.guarded_effects` module adds a durable action boundary
828
+ around exact structured operations. The owner registers the actual executors and
829
+ current-condition checks. A request stays held until those checks permit it;
830
+ there is no mandatory three- or six-second timer.
831
+
832
+ - Retain full operation, target, parameters, program/policy versions and stable
833
+ action identity. A changed request cannot reuse an existing action identity.
834
+ - Reserve and record dispatch before executing a registered operation. An
835
+ interrupted or uncertain action is not blindly executed again on retry.
836
+ - Save bounded application-state checkpoints and recover a new worker branch
837
+ without erasing decisions, returned results or cumulative limits.
838
+ - Keep this record separate from ordinary memories that may decay or reconcile.
839
+ A returned tool result is not automatically an observed physical outcome.
840
+
841
+ The host must retain the guard and its files outside the worker's authority and
842
+ route protected access through it. This is an application-level action/recovery
843
+ module, not an operating-system sandbox or arbitrary computer-memory rollback.
844
+ Existing `verify()` and `Memory` calls keep their signatures and behavior.
845
+
846
+ See [Boundary Lock Guarded Effects Specification](docs/BOUNDARY_LOCK_GUARDED_EFFECTS_V1.md)
847
+ for the theme, lifecycle and integration responsibilities. The OpenClaw plugin
848
+ also now defaults to blocking when its checker cannot complete; see its
849
+ [configuration and migration notes](plugins/openclaw/README.md).
850
+
851
+ ### Goal Loop preview: the Goal Contract
852
+
853
+ A Goal Loop job is written down once, as one `GoalContract` record that every
854
+ part of the loop reads: what should be true when it is done (`outcome`), the
855
+ measurement that proves it (`proof`), what must never happen (`never`), what to
856
+ protect if possible (`preferences`), what is cheap to give up
857
+ (`sacrifice_order`), what wakes it up (`trigger`), what it may do without asking
858
+ (`autonomy`), how much it may spend (`budget`), who gets told (`notify`) and how
859
+ it can end (`end`).
860
+
861
+ The system may rewrite the plan. It may not rewrite the promise. A contract is
862
+ frozen, and every change goes through `ContractHistory.revise()`, which writes a
863
+ new dated version and keeps the earlier ones on record:
864
+
865
+ - `outcome`, `proof`, `never`, `autonomy`, `budget` and `sacrifice_order` are
866
+ the promise. Changing any of them without an `OwnerApproval` from the
867
+ contract's owner raises `PromiseChangeError`.
868
+ - `preferences`, `trigger`, `notify` and `end` are the plan. Changing them needs
869
+ no approval but still creates a new version.
870
+ - A contract with no named proof source cannot be armed: `ensure_armable()`
871
+ raises `NotArmableError`.
872
+
873
+ ```python
874
+ from datetime import datetime, timezone
875
+
876
+ from pdm_memory.goal_loop import (
877
+ Autonomy, Budget, ContractHistory, GoalContract, OwnerApproval, Trigger, ensure_armable,
878
+ )
879
+
880
+ contract = GoalContract(
881
+ contract_id="watch-mu",
882
+ owner="eric",
883
+ outcome="Eric gets a text when MU crosses $40 from below",
884
+ proof="sms_delivery_receipt",
885
+ never=["Never trade MU shares"],
886
+ trigger=Trigger(kind="threshold", metric="MU.price", direction="rising",
887
+ fire_at="40.00", reset_at="39.50"),
888
+ autonomy=Autonomy(allowed=["sms.send"]),
889
+ budget=Budget(deadline=datetime(2026, 9, 30, tzinfo=timezone.utc)),
890
+ )
891
+ ensure_armable(contract)
892
+
893
+ history = ContractHistory(contract)
894
+ history.revise(outcome="Eric gets a text at $45") # PromiseChangeError
895
+ history.revise(approval=OwnerApproval("eric", "new line"),
896
+ outcome="Eric gets a text at $45") # version 2, version 1 kept
897
+
898
+ saved = history.to_json() # store it anywhere
899
+ history = ContractHistory.from_json(saved)
900
+ ```
901
+
902
+ No PDM store, account or network is needed. Prices and costs are `Decimal` and
903
+ are serialized as text; every datetime must be timezone-aware. Owner approval
904
+ is cooperative: the SDK checks that the approval names the contract's owner,
905
+ and the host decides whether a person really gave it.
906
+
907
+ ### Goal Loop preview: the controller
908
+
909
+ `GoalLoopController` carries one contract from `drafted` to a final state:
910
+
911
+ ```
912
+ drafted -> approved -> armed -> waiting -> triggered -> guard_checked
913
+ -> acting -> verifying -> complete
914
+ ```
915
+
916
+ with side paths `retrying`, `escalated`, `paused`, `out_of_budget`, `conflict`,
917
+ `cancelled`, `impossible` and `stopped`. It has no threads and no timers. Your host hands it readings
918
+ with `observe()` and calls `tick()` now and then; between those calls nothing
919
+ runs and nothing is spent.
920
+
921
+ - **One crossing, one action.** A threshold trigger fires when the value crosses
922
+ `fire_at` and re-arms only after it drops below `reset_at` (the first reading
923
+ never fires). Each firing has a fixed `action_id`, which is also the
924
+ executor's idempotency key, and a repeated `observation_id` is ignored.
925
+ - **Guard before every step.** `DefaultGuard` denies any operation not listed in
926
+ `autonomy.allowed`, then runs `verify()` against `never`. Pass only rules
927
+ that forbid things; limits the controller enforces itself belong in the
928
+ trigger and budget. A guard that raises is a failed check: the step does not
929
+ run and is checked again on the next try.
930
+ - **A checker proves the result.** An executor's return is not proof. The job
931
+ reaches `complete` only when the checker returns a `ProofReceipt` from the
932
+ contract's proof source; `PROVEN` without one is recorded and ignored.
933
+ - **Honest endings.** Budget (`max_actions`, `max_attempts`, `max_cost`) ends a
934
+ job in `out_of_budget` with the reason; by default an action gets one retry.
935
+ The `deadline` ends the watch period: nothing new fires, a step already fired
936
+ still gets its retry and proof, and the job ends `complete` only if every
937
+ action was proved, `stopped` otherwise. A step that may have run is never
938
+ repeated on its own: the job escalates, and the owner settles it with
939
+ `submit_evidence()` (it did arrive) or `resolve(..., "retry")`. A question
940
+ nobody answers within `confirm_expiry` (7 days) stops the job as unconfirmed.
941
+ - **Pause.** `pause()` suspends a job between steps; `resume()` checks its
942
+ grounds again and never fires a crossing that happened during the pause.
943
+ - **Every move leaves a receipt**, chained by hash; `verify_receipts()` checks it.
944
+
945
+ ```python
946
+ from pdm_memory.goal_loop import (
947
+ ActionResult, CallableChecker, GoalLoopController, Observation, OwnerApproval,
948
+ ProofReceipt, ProofVerdict, SqliteJobStore, StepTemplate,
949
+ )
950
+
951
+ def send_sms(step, *, idempotency_key): # your hands
952
+ ...
953
+ return ActionResult(reference="msg-1")
954
+
955
+ def delivered(contract, step, result, evidence, now): # your proof of the result
956
+ return ProofVerdict("PROVEN", "delivered",
957
+ ProofReceipt("sms_delivery_receipt", "dlr-1", now))
958
+
959
+ controller = GoalLoopController(
960
+ store=SqliteJobStore("jobs.db"), # omit for an in-memory store
961
+ checkers={"sms_delivery_receipt": CallableChecker("sms_delivery_receipt", delivered)},
962
+ executors={"sms.send": send_sms},
963
+ )
964
+ job_id = controller.create(history, step=StepTemplate("sms.send", "+15550100",
965
+ "Send SMS to owner: {metric} crossed {fire_at}"))
966
+ controller.approve(job_id, OwnerApproval("eric"))
967
+ controller.arm(job_id) # needs a proof source and a checker
968
+ controller.observe(job_id, Observation(observation_id="t1", observed_at=now,
969
+ metric="MU.price", value="40.12"))
970
+ controller.tick() # retries, deadlines, stuck steps
971
+ ```
972
+
973
+ Run `python -m pdm_memory.examples.goal_loop_watch_price` for the full MU
974
+ example. Backends implement `JobStore`; check yours with
975
+ `pdm_memory.goal_loop.testing.run_job_store_contract`. See
976
+ [Goal Loop v1](docs/GOAL_LOOP_V1.md) for the state table, escalation kinds and
977
+ the store contract.
978
+
979
+ The controller is cooperative, like the Boundary Lock preview: it cannot stop an
980
+ executor that bypasses it or a caller that edits the store, and the guard,
981
+ checker and executor run on your thread. Version 1 runs one action at a time per
982
+ job; an event that arrives mid-action is recorded as `fire_suppressed_busy` for
983
+ the host to replay.
984
+
520
985
  ---
521
986
 
522
987
  ## 📥 Data Ingestion
@@ -584,7 +1049,7 @@ Inline smoke test:
584
1049
  ```bash
585
1050
  python -c "
586
1051
  from pdm_memory import Memory
587
- mem = Memory(store='./demo.db')
1052
+ mem = Memory(store='./demo.db', user='alice')
588
1053
  mem.save('User prefers metric units and short answers', source='demo',
589
1054
  tags=['units', 'formatting', 'preferences'], p_magnitude=85)
590
1055
  for h in mem.recall('how should I format the answer?', k=3):
@@ -720,6 +1185,38 @@ Opens `http://localhost:8080` with a D3 force graph:
720
1185
 
721
1186
  API endpoints used by the UI: `GET /api/v1/memory-map`, `GET /api/v1/torsion`.
722
1187
 
1188
+ ### Use it as a connector (Claude and other MCP assistants)
1189
+
1190
+ The connector gives your PDM to the chat assistant you already use, with no code. The assistant recalls before it answers and saves what lands.
1191
+
1192
+ ```bash
1193
+ pip install "pdm-memory[connector]"
1194
+ ```
1195
+
1196
+ Add it to a desktop app that speaks MCP (for example, the `mcpServers` section of Claude Desktop's config):
1197
+
1198
+ ```json
1199
+ {
1200
+ "mcpServers": {
1201
+ "pdm": {
1202
+ "command": "pdm-memory-connector",
1203
+ "env": { "PDM_STORE": "/path/to/my_pdm.db", "PDM_USER": "me" }
1204
+ }
1205
+ }
1206
+ }
1207
+ ```
1208
+
1209
+ For the cloud store use `"PDM_STORE": "cloud"` and add `"PDM_TOKEN"`. The token lives only in this config on your machine and never passes through a chat.
1210
+
1211
+ Four tools:
1212
+
1213
+ - `pdm_recall` — the memories that resonate with a query. A lookup is not a use: recall through the connector does not reinforce the memories it returns.
1214
+ - `pdm_save` — one durable memory, with a drawer, tags and a pressure. Saved memories carry the source label `connector` (`PDM_CONNECTOR_SOURCE` to change it).
1215
+ - `pdm_drawers` — the drawers with their counts and average pressure.
1216
+ - `pdm_explain` — why one memory holds the pressure it holds.
1217
+
1218
+ It runs over stdio by default. `PDM_CONNECTOR_TRANSPORT=streamable-http` serves it at `http://127.0.0.1:8000/mcp` instead, on this machine only. `python -m pdm_memory.connector` works too. If it can't start (no `PDM_STORE`, a wrong path, no token for the cloud store), it says why on stderr and exits.
1219
+
723
1220
  ---
724
1221
 
725
1222
  ## 📖 API Reference
@@ -737,18 +1234,46 @@ Store-free Goal-Anchor Alignment. Pass a proposed action and one or more rule st
737
1234
 
738
1235
  Use `report.is_safe_to_act` (True only when `status == "ALIGNED"`) before triggering ACT.
739
1236
 
740
- ### `Memory(store, user, token, refresh_token, cloud_url, store_raw)`
1237
+ ### `GoalContract`, `ContractHistory` and `GoalLoopController` (preview)
1238
+
1239
+ Store-free record of one Goal Loop job. See [Goal Loop preview](#goal-loop-preview-the-goal-contract) and [the controller](#goal-loop-preview-the-controller).
1240
+
1241
+ | Name | Description |
1242
+ |------|-------------|
1243
+ | `GoalContract(contract_id, owner, outcome, trigger, proof, never, preferences, sacrifice_order, autonomy, budget, notify, end)` | Frozen record; `proof` may be a `Proof` or a source name |
1244
+ | `ContractHistory(first)` | All versions of one contract, starting at version 1 |
1245
+ | `history.revise(*, approval=None, reason="", now=None, **changes)` → `GoalContract` | Writes version N+1; promise changes need `OwnerApproval` from the owner |
1246
+ | `history.current`, `history.versions()`, `history.version(n)` | Read versions; earlier versions never change |
1247
+ | `history.to_json()` / `ContractHistory.from_json(text)` | Canonical JSON; loading checks the version chain and approvals |
1248
+ | `ensure_armable(contract)` | Raises `NotArmableError` when no proof source is named |
1249
+ | `PROMISE_FIELDS` | `outcome`, `proof`, `never`, `autonomy`, `budget`, `sacrifice_order` |
1250
+ | `GoalLoopController(*, checkers, executors, store=None, guard=None, clock, retry_base, retry_cap, proof_timeout, action_timeout, confirm_expiry, default_max_attempts)` | Moves jobs through their states |
1251
+ | `create(history, *, step)` → job id; `approve`, `arm` | `drafted` to `approved` to `waiting` |
1252
+ | `observe(job_id, Observation)` → `Job` | A reading or event; fires at most once per crossing |
1253
+ | `tick(now=None)` → `list[Job]` | Retries, deadlines, lost steps, proof timeouts |
1254
+ | `submit_evidence(job_id, action_id, evidence)` | Proof from outside; also settles an escalated step |
1255
+ | `resolve(job_id, approval, *, decision)` | Owner answers an escalation: `proceed`, `skip` or `retry` |
1256
+ | `revise_contract(job_id, *, approval=None, **changes)` | New contract version while no step is in flight |
1257
+ | `pause(job_id, reason)`, `resume(job_id, reason="")` | Suspend between steps; resume after checking the grounds again |
1258
+ | `cancel(job_id, reason)`, `job()`, `receipts()`, `verify_receipts()` | Stop, read back, check the chain |
1259
+
1260
+ ### `Memory(store, *, user, token, refresh_token, cloud_url, store_raw)`
1261
+
1262
+ `user` is required and keyword-only. Against a cloud store it must be the username the token belongs to: the server takes the owner from the token and refuses a payload naming anyone else.
741
1263
 
742
1264
  | Method | Description |
743
1265
  |--------|-------------|
744
- | `save(text, source, tags, p_magnitude, t_persistence, drawer, regime, deadline, dedupe=True, idempotency_key=None)` | Store a memory (content dedupe and/or idempotency when storage supports it) |
745
- | `save_many(items, dedupe=True)` → `dict` | Batch save; returns `{saved, skipped, errors}` |
1266
+ | `save(text, source, tags, p_magnitude, t_persistence, drawer, regime, deadline, shape=None, dedupe=True, idempotency_key=None)` | Store a memory; optional `shape` (`ephemeral` / `behavioral` / `structural`) sets half-life via `metadata[memory_shape]` |
1267
+ | `save_many(items, dedupe=True)` → `dict` | Batch save; returns `{saved, skipped, errors}` (items may include `shape`) |
746
1268
  | `recall(query, k, min_pressure, search_cost, drawer, reinforce)` → `List[MemoryHit]` | Retrieve top-k relevant memories |
747
1269
  | `verify_alignment(intent_text, min_pressure, k_goals, torsion_threshold)` → `AlignmentReport` | Same GAA gate against goals already stored in Memory |
748
1270
  | `detect_torsion(drawer, threshold)` → `List[TorsionReport]` | Find contradicting facts (Reverse Resonance) |
749
- | `reinforce(memory_id, coupling_score)` | Manually raise a memory's pressure (and V-counters where supported) |
1271
+ | `reinforce(memory_id, coupling_score)` | Record a correct prediction: V rises, the memory becomes `VALIDATED`; P does not move |
1272
+ | `penalize(memory_id, coupling_score)` → `set[str]` | Record a wrong prediction: V falls; P does not move. On a `VALIDATED` memory it is a correction and returns the ids it re-opened |
1273
+ | `apply_contrary_evidence(target, evidence, …)` → `ContraryEvidenceResult` | Immediate V-miss + Δp on conflicting evidence; does not rewrite historical fact fields |
750
1274
  | `delete(memory_id)` → `bool` | Soft-delete when storage supports it |
751
- | `decay(dry_run)` → `dict` | Trigger decay pass (runs automatically on recall) |
1275
+ | `decay_at(signature, now=None)` → `DecaySnapshot` | Live shape-aware decay metrics for one memory (read-only) |
1276
+ | `decay(dry_run=False)` → `dict` | Deprecated: deletes nothing, only counts the silent set; call `count_silent()` |
752
1277
  | `explain(memory_id, query)` → `ExplainReport` | Show why a memory has its current pressure |
753
1278
  | `list(limit, min_pressure, drawer, cursor_id)` → `MemoryListPage` | Keyset page of memories (storage list API on cloud) |
754
1279
  | `sync(direction, token, cloud_url)` → `SyncReport` | Sync local ↔ cloud |
@@ -775,11 +1300,11 @@ Use `report.is_safe_to_act` (True only when `status == "ALIGNED"`) before trigge
775
1300
 
776
1301
  **Pressure** — every memory has a p_magnitude (0–100). Important, frequently-used memories stay strong. Unused ones decay. You control the baseline; the system adjusts dynamically.
777
1302
 
778
- **Decay** — computed at recall time based on elapsed days vs. domain-specific half-lives. No scheduler required (Celery-free). Market signals decay in 1 day; core facts persist for a year.
1303
+ **Decay** — live `P_effective` uses an exponential half-life at recall/explain time (stored `p_magnitude` is not rewritten on read). Domain half-lives still apply (market signals ~1 day; core facts ~1 year). When a **memory shape** is set (`ephemeral` / `behavioral` / `structural`), it overrides domain: 2 hours / 90 days / ∞. `mem.decay_at(id)` returns a live snapshot; `mem.decay()` soft-deletes signatures below the live threshold (rows are hidden, not erased).
779
1304
 
780
1305
  **Retrieval (TAS)** — Threshold-Adjustment Search lowers the pressure threshold based on query uncertainty (search_cost). Then coupling scores rank memories by tag overlap, domain, regime, and pressure proximity. The most resonant memories surface first.
781
1306
 
782
- **Validation Coefficient (V)** — Laplace-smoothed accuracy tracker. Memories that prove predictively useful grow stronger; ones that mislead decay faster.
1307
+ **Validation Coefficient (V)** — Laplace-smoothed accuracy tracker. Memories that prove predictively useful grow stronger; ones that mislead lose authority. Use `reinforce` / `penalize`, or `apply_contrary_evidence` when new facts conflict with a stored claim.
783
1308
 
784
1309
  ---
785
1310