pdm-memory 0.2.3__tar.gz → 0.2.5__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 (130) hide show
  1. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/PKG-INFO +425 -34
  2. pdm_memory-0.2.5/README.md +817 -0
  3. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/__init__.py +26 -4
  4. pdm_memory-0.2.5/pdm_memory/bench/__init__.py +1 -0
  5. pdm_memory-0.2.5/pdm_memory/bench/__main__.py +5 -0
  6. pdm_memory-0.2.5/pdm_memory/bench/correctability/__init__.py +1 -0
  7. pdm_memory-0.2.5/pdm_memory/bench/correctability/ablation.py +86 -0
  8. pdm_memory-0.2.5/pdm_memory/bench/correctability/baselines.py +229 -0
  9. pdm_memory-0.2.5/pdm_memory/bench/correctability/harness.py +335 -0
  10. pdm_memory-0.2.5/pdm_memory/bench/correctability/metrics.py +399 -0
  11. pdm_memory-0.2.5/pdm_memory/bench/correctability/scenarios.py +822 -0
  12. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/core/alignment.py +218 -22
  13. pdm_memory-0.2.5/pdm_memory/core/constraints.py +621 -0
  14. pdm_memory-0.2.5/pdm_memory/core/field_scoped_retrieval.py +180 -0
  15. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/core/math.py +121 -9
  16. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/core/retrieval.py +610 -65
  17. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/core/signature.py +55 -3
  18. pdm_memory-0.2.5/pdm_memory/event_log.py +904 -0
  19. pdm_memory-0.2.5/pdm_memory/examples/README.md +35 -0
  20. pdm_memory-0.2.5/pdm_memory/examples/__init__.py +12 -0
  21. pdm_memory-0.2.5/pdm_memory/examples/field_state_demo.py +213 -0
  22. pdm_memory-0.2.5/pdm_memory/examples/guarded_agent_logic.py +190 -0
  23. pdm_memory-0.2.5/pdm_memory/examples/handling_contradictions.py +160 -0
  24. pdm_memory-0.2.5/pdm_memory/examples/hello_pdm.py +145 -0
  25. pdm_memory-0.2.5/pdm_memory/examples/industrial_safety_gate.py +192 -0
  26. pdm_memory-0.2.5/pdm_memory/examples/standalone_guard.py +118 -0
  27. pdm_memory-0.2.5/pdm_memory/examples/temporal_recall_demo.py +225 -0
  28. pdm_memory-0.2.5/pdm_memory/geopass.py +279 -0
  29. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/io/__init__.py +2 -1
  30. pdm_memory-0.2.5/pdm_memory/io/csv_transfer.py +76 -0
  31. pdm_memory-0.2.5/pdm_memory/memory.py +2442 -0
  32. pdm_memory-0.2.5/pdm_memory/models.py +719 -0
  33. pdm_memory-0.2.5/pdm_memory/storage/base.py +195 -0
  34. pdm_memory-0.2.5/pdm_memory/storage/cloud_driver.py +1715 -0
  35. pdm_memory-0.2.5/pdm_memory/storage/errors.py +50 -0
  36. pdm_memory-0.2.5/pdm_memory/storage/event_hash.py +347 -0
  37. pdm_memory-0.2.5/pdm_memory/storage/event_store.py +863 -0
  38. pdm_memory-0.2.5/pdm_memory/storage/event_sync.py +333 -0
  39. pdm_memory-0.2.5/pdm_memory/storage/eventful_postgres.py +39 -0
  40. pdm_memory-0.2.5/pdm_memory/storage/eventful_sqlite.py +99 -0
  41. pdm_memory-0.2.5/pdm_memory/storage/events.py +991 -0
  42. pdm_memory-0.2.5/pdm_memory/storage/field_store.py +1053 -0
  43. pdm_memory-0.2.5/pdm_memory/storage/fields.py +581 -0
  44. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/storage/postgres_driver.py +210 -23
  45. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/storage/schema.py +17 -3
  46. pdm_memory-0.2.5/pdm_memory/storage/sqlite_driver.py +676 -0
  47. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/tools/bench.py +118 -32
  48. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/tools/cli.py +94 -33
  49. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/tools/explorer_actions.py +18 -4
  50. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/tools/server.py +45 -12
  51. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory.egg-info/PKG-INFO +425 -34
  52. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory.egg-info/SOURCES.txt +51 -1
  53. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory.egg-info/requires.txt +1 -1
  54. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pyproject.toml +3 -10
  55. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_alignment.py +108 -9
  56. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_cli.py +20 -1
  57. pdm_memory-0.2.5/tests/test_cloud_driver.py +748 -0
  58. pdm_memory-0.2.5/tests/test_cloud_events.py +292 -0
  59. pdm_memory-0.2.5/tests/test_cloud_fields.py +558 -0
  60. pdm_memory-0.2.5/tests/test_constraints.py +282 -0
  61. pdm_memory-0.2.5/tests/test_contrary_evidence.py +144 -0
  62. pdm_memory-0.2.5/tests/test_correctability.py +393 -0
  63. pdm_memory-0.2.5/tests/test_current_resolution.py +120 -0
  64. pdm_memory-0.2.5/tests/test_event_layer_parity.py +423 -0
  65. pdm_memory-0.2.5/tests/test_evidence_layer_regressions.py +672 -0
  66. pdm_memory-0.2.5/tests/test_extract_signatures.py +146 -0
  67. pdm_memory-0.2.5/tests/test_field_memberships.py +662 -0
  68. pdm_memory-0.2.5/tests/test_field_state.py +221 -0
  69. pdm_memory-0.2.5/tests/test_geopass.py +242 -0
  70. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_jwt_auth.py +3 -1
  71. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_math.py +106 -0
  72. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_memory.py +393 -4
  73. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_pdm_physics.py +7 -4
  74. pdm_memory-0.2.5/tests/test_postgres_driver.py +318 -0
  75. pdm_memory-0.2.5/tests/test_postgres_live.py +220 -0
  76. pdm_memory-0.2.5/tests/test_projection.py +301 -0
  77. pdm_memory-0.2.5/tests/test_relationship_state.py +192 -0
  78. pdm_memory-0.2.5/tests/test_review24_followup.py +339 -0
  79. pdm_memory-0.2.5/tests/test_source_events.py +772 -0
  80. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_sqlite_driver.py +201 -2
  81. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_storage_factory.py +37 -2
  82. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_tier2.py +63 -2
  83. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_torsion.py +76 -3
  84. pdm_memory-0.2.5/tests/test_trajectory.py +247 -0
  85. pdm_memory-0.2.5/tests/test_verify_live.py +173 -0
  86. pdm_memory-0.2.3/README.md +0 -426
  87. pdm_memory-0.2.3/pdm_memory/memory.py +0 -1380
  88. pdm_memory-0.2.3/pdm_memory/models.py +0 -128
  89. pdm_memory-0.2.3/pdm_memory/storage/base.py +0 -135
  90. pdm_memory-0.2.3/pdm_memory/storage/cloud_driver.py +0 -512
  91. pdm_memory-0.2.3/pdm_memory/storage/errors.py +0 -26
  92. pdm_memory-0.2.3/pdm_memory/storage/sqlite_driver.py +0 -392
  93. pdm_memory-0.2.3/tests/test_cloud_driver.py +0 -164
  94. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/LICENSE +0 -0
  95. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/auth/__init__.py +0 -0
  96. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/auth/jwt_handler.py +0 -0
  97. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/bench.py +0 -0
  98. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/core/__init__.py +0 -0
  99. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/ingest/__init__.py +0 -0
  100. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/ingest/auto_signature.py +0 -0
  101. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/ingest/batch.py +0 -0
  102. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/ingest/ingester.py +0 -0
  103. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/integrations/__init__.py +0 -0
  104. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/integrations/anthropic_adapter.py +0 -0
  105. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/integrations/context_manager.py +0 -0
  106. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/integrations/gemini_adapter.py +0 -0
  107. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/integrations/groq_adapter.py +0 -0
  108. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/integrations/ollama_adapter.py +0 -0
  109. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/integrations/openai_adapter.py +0 -0
  110. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/io/json_transfer.py +0 -0
  111. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/storage/__init__.py +0 -0
  112. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/storage/factory.py +0 -0
  113. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/sync.py +0 -0
  114. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/tools/__init__.py +0 -0
  115. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/tools/static/index.html +0 -0
  116. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory/types.py +0 -0
  117. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory.egg-info/dependency_links.txt +0 -0
  118. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory.egg-info/entry_points.txt +0 -0
  119. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/pdm_memory.egg-info/top_level.txt +0 -0
  120. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/setup.cfg +0 -0
  121. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_bench.py +0 -0
  122. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_explorer_console.py +0 -0
  123. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_explorer_ui.py +0 -0
  124. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_gemini_adapter.py +0 -0
  125. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_groq_adapter.py +0 -0
  126. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_memory_hooks.py +0 -0
  127. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_ollama_adapter.py +0 -0
  128. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_pdm_concurrency.py +0 -0
  129. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_retrieval_diversity.py +0 -0
  130. {pdm_memory-0.2.3 → pdm_memory-0.2.5}/tests/test_tier3.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pdm-memory
3
- Version: 0.2.3
3
+ Version: 0.2.5
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)
@@ -166,16 +166,15 @@ Requires-Dist: tiktoken>=0.7; extra == "dev"
166
166
  Requires-Dist: google-genai>=0.1.0; extra == "dev"
167
167
  Requires-Dist: ollama>=0.2.0; extra == "dev"
168
168
  Requires-Dist: groq>=0.9.0; extra == "dev"
169
- Requires-Dist: ruff>=0.4; extra == "dev"
170
169
  Requires-Dist: fastapi>=0.110; extra == "dev"
171
170
  Requires-Dist: uvicorn[standard]>=0.27; extra == "dev"
171
+ Requires-Dist: psycopg[binary]>=3.1; extra == "dev"
172
172
  Dynamic: license-file
173
173
 
174
174
  # PDM — Memory for AI Apps That Works Like Memory
175
175
 
176
176
  [![PyPI](https://img.shields.io/pypi/v/pdm-memory)](https://pypi.org/project/pdm-memory/)
177
177
  [![Python](https://img.shields.io/pypi/pyversions/pdm-memory)](https://pypi.org/project/pdm-memory/)
178
- [![CI](https://github.com/westfield-innovations/pdm-memory/actions/workflows/ci.yml/badge.svg)](https://github.com/westfield-innovations/pdm-memory/actions)
179
178
  [![License: Proprietary](https://img.shields.io/badge/License-Proprietary%20ELv2-blue)](LICENSE)
180
179
  [![Documentation](https://img.shields.io/badge/Docs-azus.ai%2Fsupport-blue)](https://azus.ai/support)
181
180
 
@@ -185,11 +184,12 @@ Your LLM forgets everything between conversations. The standard fix — stuff a
185
184
 
186
185
  - 🔑 **Your API key.** Works with your existing Anthropic/OpenAI account.
187
186
  - 🗄️ **Your storage.** One local file. Your data never leaves your machine. Check the source — there's no phone-home in it.
187
+ - 🛡️ **Guarded agents.** Pass a rule as a string — blocks actions that contradict it. No store required. Catches contradicting facts automatically.
188
188
  - ⚡ **Ten minutes.** `pip install pdm-memory` → three lines → persistent memory.
189
189
 
190
190
  📖 **Documentation:** [azus.ai/support](https://azus.ai/support)
191
191
 
192
- **Benchmarks vs standard RAG:** [azus.ai/pdm/benchmarks](https://azus.ai/pdm/benchmarks)
192
+ **Benchmarks vs standard RAG:** PDM wins **7 of 8** metrics — **15×** fewer tokens, **35×** less storage. One loss published. [See full methodology →](https://azus.ai/pdm/benchmarks)
193
193
 
194
194
  ---
195
195
 
@@ -199,10 +199,11 @@ Your LLM forgets everything between conversations. The standard fix — stuff a
199
199
  1. [Privacy Mode](#-privacy-mode-local-sqlite)
200
200
  2. [Ecosystem Mode](#-ecosystem-mode-azus-cloud)
201
201
  3. [LLM Adapters](#-llm-adapters)
202
- 4. [Data Ingestion](#-data-ingestion)
203
- 5. [Developer Tools](#-developer-tools)
204
- 6. [API Reference](#-api-reference)
205
- 7. [License](#-license)
202
+ 4. [Guarded Agents (GAA & Torsion)](#-guarded-agents-gaa--torsion)
203
+ 5. [Data Ingestion](#-data-ingestion)
204
+ 6. [Developer Tools](#-developer-tools)
205
+ 7. [API Reference](#-api-reference)
206
+ 8. [License](#-license)
206
207
 
207
208
  ---
208
209
 
@@ -228,11 +229,13 @@ pip install "pdm-memory[all]"
228
229
  from pdm_memory import Memory
229
230
 
230
231
  # One line to start. The .db file is created automatically.
231
- mem = Memory(store="./my_app_memory.db")
232
+ mem = Memory(store="./my_app_memory.db", user="alice")
232
233
 
233
234
  # 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"])
235
+ # Optional shape: ephemeral (2h) / behavioral (90d) / structural (∞).
236
+ mem.save("User prefers metric units and short answers", source="manual",
237
+ tags=["units", "formatting", "preferences"], p_magnitude=85,
238
+ shape="behavioral")
236
239
 
237
240
  # Read: resonance retrieval — surfaces what's relevant, not just what matches.
238
241
  hits = mem.recall("how should I format the answer?", k=5)
@@ -243,11 +246,23 @@ for h in hits:
243
246
  # Reinforce a memory manually (recall() does this automatically).
244
247
  mem.reinforce(hits[0].id)
245
248
 
249
+ # Contrary evidence: lower active pressure/V without rewriting the stored fact.
250
+ result = mem.apply_contrary_evidence(
251
+ hits[0].id,
252
+ "User prefers imperial units",
253
+ evidence_tags=["units", "formatting", "preferences"],
254
+ )
255
+ print(result.p_before, "→", result.p_after)
256
+
246
257
  # Inspect why a memory surfaced.
247
258
  report = mem.explain(hits[0].id, query="how should I format the answer?")
248
259
  print(report.render())
249
260
 
250
- # Decay runs automatically on each recall(). Manual trigger:
261
+ # Live decay snapshot for one memory (read-only):
262
+ snap = mem.decay_at(hits[0].id)
263
+ print(snap.shape, snap.half_life_days, snap.p_effective)
264
+
265
+ # Store-wide soft-delete of memories below the live P_effective threshold:
251
266
  counts = mem.decay()
252
267
  print(f"Decayed: {counts['decayed']}, Deleted: {counts['deleted']}")
253
268
  ```
@@ -257,14 +272,51 @@ print(f"Decayed: {counts['decayed']}, Deleted: {counts['deleted']}")
257
272
  Store only SHA-256 hashes of memory text — the content never touches disk:
258
273
 
259
274
  ```python
260
- mem = Memory(store="./private.db", store_raw=False)
275
+ mem = Memory(store="./private.db", user="alice", store_raw=False)
261
276
  ```
262
277
 
263
278
  ---
264
279
 
265
280
  ## ☁️ Ecosystem Mode (AZUS Cloud)
266
281
 
267
- Connect to the AZUS Companion API to sync memories across devices and share them with the AI companion.
282
+ Connect to the **AZUS Companion API** so memories sync across devices and the companion app.
283
+
284
+ **Cloud endpoint:** default base URL is `https://api.azus.ai` (not the marketing site `https://azus.ai`). Staging: `https://staging.azus.ai`.
285
+
286
+ CloudDriver expects a Companion build that exposes the PDM SDK routes (list, batch, by-hash / by-idempotency-key, soft-delete). Older deploys still support single-row `ingest` / get / patch / hard delete only.
287
+
288
+ ### Getting your JWT access token
289
+
290
+ AZUS Cloud uses standard JWT auth. If you already have an AZUS account, sign in and use the returned `access` token as `token="..."`.
291
+
292
+ If you do not have an account yet, create one here:
293
+
294
+ - Web signup: [azus.ai/auth/register](https://azus.ai/auth/register)
295
+ - API signup: `POST https://api.azus.ai/api/v1/accounts/auth/register/`
296
+ - API login: `POST https://api.azus.ai/api/v1/accounts/auth/login/`
297
+ - Token refresh: `POST https://api.azus.ai/api/v1/accounts/token/refresh/`
298
+
299
+ Example registration flow:
300
+
301
+ ```python
302
+ import requests
303
+
304
+ r = requests.post(
305
+ "https://api.azus.ai/api/v1/accounts/auth/register/",
306
+ json={
307
+ "email": "user@example.com",
308
+ "username": "user123",
309
+ "password": "SecurePass123!",
310
+ "profile": {"first_name": "John", "last_name": "Doe"},
311
+ },
312
+ )
313
+ data = r.json()
314
+
315
+ access_token = data["tokens"]["access"]
316
+ refresh_token = data["tokens"]["refresh"]
317
+ ```
318
+
319
+ Use the returned JWTs directly with `Memory(store="cloud", user=..., ...)`:
268
320
 
269
321
  ### Connect to the Cloud
270
322
 
@@ -273,20 +325,183 @@ from pdm_memory import Memory
273
325
 
274
326
  mem = Memory(
275
327
  store="cloud",
276
- token="eyJ...", # Your AZUS JWT access token
277
- cloud_url="https://api.azus.ai",
328
+ token="eyJ...", # AZUS JWT access token
329
+ refresh_token="eyJ...", # optional — auto-refresh on 401
330
+ cloud_url="https://api.azus.ai", # optional; this is the default
331
+ user="your_username", # ownership scope for storage ops
278
332
  )
279
333
 
280
- # All save/recall operations go to the cloud.
281
- mem.save("User's team is in Kyiv (UTC+3)", tags=["location", "team", "timezone"])
334
+ # Writes use POST /api/v1/pdm/ingest; dedupe hits the by-hash API when available.
335
+ mem.save(
336
+ "User's team is in Kyiv (UTC+3)",
337
+ source="manual",
338
+ tags=["location", "team", "timezone"],
339
+ p_magnitude=70,
340
+ dedupe=True,
341
+ )
342
+ # A cloud store requires at least 3 tags per memory (ValueError before any
343
+ # request otherwise); a local store accepts fewer.
344
+ # Exact-once create on retries: pass idempotency_key=...
282
345
  hits = mem.recall("what timezone are they in?")
346
+
347
+ # Batch write (POST /pdm/ingest/batch when supported)
348
+ mem.save_many(
349
+ [
350
+ {"text": "Fact A", "tags": ["a", "b", "c"], "p_magnitude": 70, "source": "manual"},
351
+ {"text": "Fact B", "tags": ["a", "b", "c"], "p_magnitude": 70, "source": "manual"},
352
+ ],
353
+ dedupe=False,
354
+ )
355
+ ```
356
+
357
+ ### Soft delete vs hard delete
358
+
359
+ - `mem.delete(id)` → soft-delete (`is_deleted`) when the API supports it; cloud list/get hide those rows.
360
+ - Permanent removal is storage-level `hard_delete` (CloudDriver), not the default Memory facade API.
361
+
362
+ ### Field State
363
+
364
+ The reconciled state of a bounded field — who belongs to it, how they are
365
+ connected, and what is visible in it — at a moment.
366
+
367
+ ```python
368
+ from datetime import datetime, timezone
369
+
370
+ # As it stands now. The moment is left out of the request on purpose, so the
371
+ # server answers from its own clock rather than yours.
372
+ state = mem.current_state("westfield")
373
+
374
+ # As it stood then. Must carry a timezone, and must not be in the future.
375
+ state = mem.state_at("westfield", datetime(2026, 3, 1, 12, tzinfo=timezone.utc))
376
+
377
+ state.field_memberships # standing in the field, with the intervals it held
378
+ state.relationships # edges, each with how current its channel reads
379
+ state.entities # what this observer may reveal, one keyset page
380
+
381
+ # Nested fields match by prefix: "westfield" covers "westfield/dqs".
382
+ state = mem.current_state("westfield/dqs")
383
+
384
+ # Paging: follow the cursor and drop the envelope, which does not change
385
+ # between pages.
386
+ page = mem.current_state("westfield", cursor=state.entities_next_cursor, envelope=False)
387
+ ```
388
+
389
+ - **Cloud only.** Fields and memberships do not exist in the local schema, so
390
+ both calls raise in privacy mode rather than inventing a second data model.
391
+ - **Every item declares its own provenance.** `state_type` is `"measured"` or
392
+ `"projected"` on each item, never inferred from where it sits. A payload with
393
+ an untagged item is rejected rather than guessed at.
394
+ - **`envelope_included=False` means the envelope is absent, not empty.** The
395
+ fields are omitted rather than returned as `[]`, so a page-2 response can
396
+ never be read as a statement about the field.
397
+ - **Results are filtered to what the observer may reveal.** There is no
398
+ unfiltered mode, and permission resolves against now — a revoked grant does
399
+ not reopen last year.
400
+
401
+ ### Relationships
402
+
403
+ `EventLog.link(...)` records that two entities stood in some relation; the
404
+ methods below read and reinforce that link's channel over time.
405
+
406
+ ```python
407
+ from pdm_memory import Memory
408
+ from pdm_memory.event_log import EventLog
409
+
410
+ mem = Memory(store="cloud", user="alice", token="eyJ...")
411
+ log = EventLog(mem)
412
+
413
+ relationship_id = log.link("subject:1", "entity:abc-123", "colleague")
414
+
415
+ # Point-in-time state of the pair — which links were live, which channel
416
+ # measurements applied, and (only within the channel's own recency window)
417
+ # the current resolution vector. at_time omitted means now.
418
+ state = mem.relationship_state("subject:1", "entity:abc-123")
419
+ state.relationships # the live/historical link rows for this pair
420
+ state.channels # {domain: channel snapshot}, by domain
421
+ state.current_resolution_by_domain # None outside the recency window
422
+ state.current_resolution_reason # "past_moment" when it is None
423
+
424
+ # Cite an existing fact as reinforcing or contrary evidence for the link's
425
+ # channel. No bare number: the citation itself is the input.
426
+ from pdm_memory.storage.fields import RelationshipRecord
427
+
428
+ relationship = RelationshipRecord(id=relationship_id, source_entity_id="subject:1",
429
+ target_entity_id="entity:abc-123", relationship_type="colleague")
430
+ log.reinforce(relationship, evidence="sig-1") # or a SignatureRecord/SourceEventRecord
431
+ log.apply_contrary_evidence(relationship, evidence="sig-2")
432
+ ```
433
+
434
+ - **Cloud only**, same as Field State — `RelationshipChannel` and its
435
+ evidence log live only in Companion.
436
+ - **Dispatch by target type**, not by guessing at a string. `reinforce`/
437
+ `apply_contrary_evidence` route to the relationship-evidence endpoint only
438
+ when *target* is a `RelationshipRecord`; a bare string id or a
439
+ `SignatureRecord` goes to the existing, unchanged `Memory.reinforce()` /
440
+ `Memory.apply_contrary_evidence()` — the same methods and behaviour as
441
+ before this feature existed.
442
+ - **Resubmitting the same evidence is refused** (`CloudConflictError`,
443
+ `error_code="EVIDENCE_ALREADY_APPLIED"`), not silently counted twice.
444
+
445
+ | This document's naming | SDK method |
446
+ |---|---|
447
+ | Point-in-time relationship state | `Memory.relationship_state(source, target, at_time=None, domain=None)` |
448
+ | Reinforcing evidence, on a link | `EventLog.reinforce(relationship_record, evidence)` |
449
+ | Contrary evidence, on a link | `EventLog.apply_contrary_evidence(relationship_record, evidence)` |
450
+ | Reinforcing evidence, on a memory (unchanged) | `EventLog.reinforce(memory_id_or_record)` → `Memory.reinforce` |
451
+ | Contrary evidence, on a memory (unchanged) | `EventLog.apply_contrary_evidence(memory_id_or_record, evidence)` → `Memory.apply_contrary_evidence` |
452
+
453
+ ### Projections
454
+
455
+ A forward fan of where your channel is heading, and — once time has passed —
456
+ how it turned out.
457
+
458
+ ```python
459
+ from datetime import datetime, timezone
460
+
461
+ fan = mem.project() # the fan now; nothing is written
462
+ fan = mem.project(horizon_days=30) # narrower window, clamped to the server's reach
463
+ fan = mem.project(record=True) # persist it so it can be scored later
464
+
465
+ for branch in fan.branches:
466
+ branch.state_type # always "projected"
467
+ branch.confidence_band["weight"] # this branch's share of the fan
468
+ branch.timing_range # {"start", "end"} — a window, never a point
469
+ branch.invalidation_conditions # what would make it wrong
470
+
471
+ # Later: settle one recorded branch against what actually happened.
472
+ settled = mem.record_outcome(
473
+ fan.projection_ids[0],
474
+ observed_at=datetime.now(timezone.utc),
475
+ connection_geometry="correct", # "correct" | "partial" | "incorrect"
476
+ meaning_propagation="partial",
477
+ )
478
+ settled.outcome.timing # "early" | "within" | "late" — derived by the server
479
+
480
+ mem.projection(settled.id) # read it back, with its outcome
283
481
  ```
284
482
 
483
+ - **Cloud only.** The fan is built from the observer's channel, which lives
484
+ in Companion.
485
+ - **A different type from a field state.** `ProjectionFan` and
486
+ `RecordedProjection` share no base class with `FieldStateSnapshot`, and a
487
+ payload whose items do not say `state_type="projected"` is refused rather
488
+ than typed as a projection.
489
+ - **Not field-scoped.** Spec §7 names `project(field_id, horizon,
490
+ constraints)`; the fan is built per domain, not per field, so there is no
491
+ `field_id` to pass, and `horizon_days` is the one constraint the server honours.
492
+ - **Recorded once a day.** With `record=True`, `projection_ids` is empty on a
493
+ repeat the same UTC day — that fan is already on file.
494
+ - **Settles once.** A second outcome raises `CloudConflictError`
495
+ (`error_code="ALREADY_SETTLED"`); an outcome observed before the projection
496
+ was made raises `CloudStorageError` with `status_code=422`; someone else's
497
+ projection reads as `CloudNotFoundError`. `timing` is never sent — the
498
+ server derives it from `observed_at`.
499
+
285
500
  ### Sync Local ↔ Cloud
286
501
 
287
502
  ```python
288
503
  # Start with a local store
289
- local_mem = Memory(store="./local.db")
504
+ local_mem = Memory(store="./local.db", user="alice")
290
505
  local_mem.save("Local preference", tags=["pref", "local", "test"])
291
506
 
292
507
  # Push local memories to cloud
@@ -329,7 +544,7 @@ The wrapper is the demo; the primitives are the product. Most developers start h
329
544
  from pdm_memory import Memory
330
545
  from pdm_memory.integrations import wrap_openai
331
546
 
332
- mem = Memory(store="./my_app.db")
547
+ mem = Memory(store="./my_app.db", user="alice")
333
548
  client = wrap_openai(api_key="sk-...", memory=mem)
334
549
 
335
550
  # Memory is handled completely invisibly:
@@ -363,6 +578,102 @@ print(system_block)
363
578
 
364
579
  ---
365
580
 
581
+ ## 🛡️ Guarded Agents (GAA & Torsion)
582
+
583
+ Before an agent **acts**, `verify()` scores the proposed intent against a plain list of rules and returns **ALIGNED**, **CONFLICT**, or **TORSION**. No store, account, or signup.
584
+
585
+ Statuses:
586
+
587
+ - **ALIGNED** — safe to proceed (`report.is_safe_to_act` is `True`)
588
+ - **CONFLICT** — soft mismatch / missing anchors (fail-closed by default)
589
+ - **TORSION** — hard contradiction — block the ACT
590
+
591
+ ```python
592
+ from pdm_memory import verify
593
+
594
+ report = verify(
595
+ "ignore errors and ship the build",
596
+ ["never ignore production errors"],
597
+ )
598
+ print(report.status, report.is_safe_to_act) # TORSION False
599
+
600
+ good = verify(
601
+ "run full validation suite then ship with reliability checks enabled",
602
+ ["Prioritize high reliability and careful validation before shipping"],
603
+ )
604
+ print(good.status, good.is_safe_to_act) # ALIGNED True
605
+
606
+ def guarded_act(intent, tool_call, goals):
607
+ report = verify(intent, goals)
608
+ if not report.is_safe_to_act:
609
+ raise PermissionError(f"GAA blocked ACT: {report.status}")
610
+ return tool_call()
611
+ ```
612
+
613
+ When goals already live in a PDM store, `Memory.verify_alignment()` is the same gate over stored stewardship signatures:
614
+
615
+ ```python
616
+ from pdm_memory import Memory
617
+
618
+ mem = Memory(store="./agent.db", user="alice")
619
+
620
+ # Goal signatures live in stewardship / foundational drawers.
621
+ mem.save(
622
+ "Core goal: high reliability; never ignore production errors",
623
+ tags=["reliability", "errors", "goal", "integrity"],
624
+ drawer="stewardship",
625
+ p_magnitude=92,
626
+ source="policy",
627
+ metadata={"iaw": 0.90, "role": "goal"},
628
+ )
629
+ mem.save(
630
+ "Foundational principle: validate before deploy",
631
+ tags=["validation", "deploy", "principle", "quality"],
632
+ drawer="foundational",
633
+ p_magnitude=88,
634
+ source="policy",
635
+ metadata={"iaw": 0.85, "role": "goal"},
636
+ )
637
+
638
+ # Block an action that opposes stored goals.
639
+ bad = mem.verify_alignment("ignore errors and bypass validation")
640
+ print(bad.status, bad.is_safe_to_act) # TORSION False
641
+
642
+ # Allow an action that resonates with those goals.
643
+ good = mem.verify_alignment("validate thoroughly then deploy with reliability checks")
644
+ print(good.status, good.is_safe_to_act) # ALIGNED True
645
+ ```
646
+
647
+ Catch contradicting facts already in the store:
648
+
649
+ ```python
650
+ from datetime import datetime, timezone
651
+
652
+ mem.save(
653
+ "Project Orion launch date is 2026-08-01",
654
+ tags=["orion", "launch", "deadline", "project"],
655
+ drawer="product",
656
+ p_magnitude=70,
657
+ deadline=datetime(2026, 8, 1, tzinfo=timezone.utc),
658
+ metadata={"cluster_id": "orion-launch"},
659
+ )
660
+ mem.save(
661
+ "Project Orion launch date is 2026-09-01",
662
+ tags=["orion", "launch", "deadline", "project"],
663
+ drawer="product",
664
+ p_magnitude=72,
665
+ deadline=datetime(2026, 9, 1, tzinfo=timezone.utc),
666
+ metadata={"cluster_id": "orion-launch"},
667
+ )
668
+
669
+ for report in mem.detect_torsion(threshold=0.5):
670
+ print(report.torsion_score, report.conflict_kind, report.explanation)
671
+ ```
672
+
673
+ 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`.
674
+
675
+ ---
676
+
366
677
  ## 📥 Data Ingestion
367
678
 
368
679
  ### Import Legacy Data
@@ -414,17 +725,64 @@ mem.ingest(
414
725
 
415
726
  ## 🛠️ Developer Tools
416
727
 
417
- ### Examples (DX walkthrough)
728
+ ### Quick Start (PyPI install)
729
+
730
+ Everything below works after `pip install pdm-memory` — no repository clone required.
731
+
732
+ ```bash
733
+ pip install pdm-memory
734
+ python -m pdm_memory.examples.hello_pdm
735
+ ```
736
+
737
+ Inline smoke test:
738
+
739
+ ```bash
740
+ python -c "
741
+ from pdm_memory import Memory
742
+ mem = Memory(store='./demo.db', user='alice')
743
+ mem.save('User prefers metric units and short answers', source='demo',
744
+ tags=['units', 'formatting', 'preferences'], p_magnitude=85)
745
+ for h in mem.recall('how should I format the answer?', k=3):
746
+ print(h.text, round(h.pressure, 1))
747
+ "
748
+ ```
749
+
750
+ Other PyPI-shipped tools:
751
+
752
+ ```bash
753
+ python -m pdm_memory.bench --quick # smoke benchmark (5 scenarios)
754
+ pdm-cli stats --store ./demo.db # inspect the store created above
755
+ ```
756
+
757
+ ### Example walkthroughs (bundled in PyPI)
758
+
759
+ All scripts below ship inside the wheel — run them with `python -m`:
760
+
761
+ ```bash
762
+ pip install pdm-memory
763
+ python -m pdm_memory.examples.hello_pdm # save / recall / explain
764
+ python -m pdm_memory.examples.standalone_guard # GAA: no store
765
+ python -m pdm_memory.examples.guarded_agent_logic # GAA: store-backed TORSION vs ALIGNED
766
+ python -m pdm_memory.examples.handling_contradictions # detect + reconcile torsion
767
+ python -m pdm_memory.examples.temporal_recall_demo # event_at + deadline (PDM-T)
768
+ python -m pdm_memory.examples.industrial_safety_gate # Oil Field: Auto-Discovery + heal
769
+ ```
770
+
771
+ See [`pdm_memory/examples/README.md`](pdm_memory/examples/README.md).
772
+
773
+ From a source checkout, the wrappers in [`examples/`](examples/) delegate to the same modules:
418
774
 
419
775
  ```bash
420
776
  pip install .
421
- python examples/hello_pdm.py # save / recall / explain
422
- python examples/guarded_agent_logic.py # GAA: TORSION vs ALIGNED
423
- python examples/handling_contradictions.py # detect + reconcile torsion
424
- python examples/temporal_recall_demo.py # event_at + deadline (PDM-T)
777
+ python examples/hello_pdm.py
425
778
  ```
426
779
 
427
- See [`examples/README.md`](examples/README.md).
780
+ To run the test suite (contributors):
781
+
782
+ ```bash
783
+ pip install ".[dev]"
784
+ pytest
785
+ ```
428
786
 
429
787
  ### The explain Method
430
788
 
@@ -489,6 +847,9 @@ pdm-cli decay --store ./my_app.db
489
847
  # Show stats
490
848
  pdm-cli stats --store ./my_app.db
491
849
 
850
+ # Store-free GAA — no .db required
851
+ pdm-cli verify "ignore errors and ship" --goal "never ignore production errors"
852
+
492
853
  # List drawers (categories)
493
854
  pdm-cli drawers --store ./my_app.db
494
855
 
@@ -518,15 +879,38 @@ API endpoints used by the UI: `GET /api/v1/memory-map`, `GET /api/v1/torsion`.
518
879
 
519
880
  ## 📖 API Reference
520
881
 
521
- ### `Memory(store, user, token, cloud_url, store_raw)`
882
+ ### `verify(intent_text, goals)`
883
+
884
+ Store-free Goal-Anchor Alignment. Pass a proposed action and one or more rule strings. Returns `AlignmentReport` (`ALIGNED` / `CONFLICT` / `TORSION`). No SQLite, cloud, or account.
885
+
886
+ | Arg | Description |
887
+ |-----|-------------|
888
+ | `intent_text` | Proposed action / intent to validate |
889
+ | `goals` | One rule string, or a list of rule strings |
890
+ | `torsion_threshold` | Peak torsion that escalates to `TORSION` (default `0.70`) |
891
+ | `conflict_threshold` | Soft-mismatch floor for `CONFLICT` (default `0.40`) |
892
+
893
+ Use `report.is_safe_to_act` (True only when `status == "ALIGNED"`) before triggering ACT.
894
+
895
+ ### `Memory(store, *, user, token, refresh_token, cloud_url, store_raw)`
896
+
897
+ `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.
522
898
 
523
899
  | Method | Description |
524
900
  |--------|-------------|
525
- | `save(text, source, tags, p_magnitude, t_persistence, drawer, regime, deadline)` | Store a new memory |
901
+ | `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]` |
902
+ | `save_many(items, dedupe=True)` → `dict` | Batch save; returns `{saved, skipped, errors}` (items may include `shape`) |
526
903
  | `recall(query, k, min_pressure, search_cost, drawer, reinforce)` → `List[MemoryHit]` | Retrieve top-k relevant memories |
527
- | `reinforce(memory_id, coupling_score)` | Manually raise a memory's pressure |
528
- | `decay(dry_run)` → `dict` | Trigger decay pass (runs automatically on recall) |
904
+ | `verify_alignment(intent_text, min_pressure, k_goals, torsion_threshold)` → `AlignmentReport` | Same GAA gate against goals already stored in Memory |
905
+ | `detect_torsion(drawer, threshold)` → `List[TorsionReport]` | Find contradicting facts (Reverse Resonance) |
906
+ | `reinforce(memory_id, coupling_score)` | Manually raise a memory's pressure (and V-counters where supported) |
907
+ | `penalize(memory_id, coupling_score)` | Record a wrong prediction: lower P and V |
908
+ | `apply_contrary_evidence(target, evidence, …)` → `ContraryEvidenceResult` | Immediate V-miss + Δp on conflicting evidence; does not rewrite historical fact fields |
909
+ | `delete(memory_id)` → `bool` | Soft-delete when storage supports it |
910
+ | `decay_at(signature, now=None)` → `DecaySnapshot` | Live shape-aware decay metrics for one memory (read-only) |
911
+ | `decay(dry_run=False)` → `dict` | Soft-delete signatures whose live `P_effective` is below threshold |
529
912
  | `explain(memory_id, query)` → `ExplainReport` | Show why a memory has its current pressure |
913
+ | `list(limit, min_pressure, drawer, cursor_id)` → `MemoryListPage` | Keyset page of memories (storage list API on cloud) |
530
914
  | `sync(direction, token, cloud_url)` → `SyncReport` | Sync local ↔ cloud |
531
915
  | `ingest(data_source, mapping, llm_client, batch_size)` → `dict` | Import legacy data |
532
916
  | `list_drawers()` → `List[DrawerInfo]` | List memory categories |
@@ -551,11 +935,11 @@ API endpoints used by the UI: `GET /api/v1/memory-map`, `GET /api/v1/torsion`.
551
935
 
552
936
  **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.
553
937
 
554
- **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.
938
+ **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).
555
939
 
556
940
  **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.
557
941
 
558
- **Validation Coefficient (V)** — Laplace-smoothed accuracy tracker. Memories that prove predictively useful grow stronger; ones that mislead decay faster.
942
+ **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.
559
943
 
560
944
  ---
561
945
 
@@ -568,11 +952,18 @@ from pdm_memory.storage.base import BaseStorage
568
952
 
569
953
  class MyPostgresStorage(BaseStorage):
570
954
  def save(self, sig): ...
955
+ def save_batch(self, sigs): ...
571
956
  def get(self, memory_id, user): ...
957
+ def get_many(self, ids, user): ...
572
958
  def update(self, memory_id, **fields): ...
573
- def delete(self, memory_id, user): ...
574
- def list(self, user, limit, min_pressure, drawer): ...
959
+ def update_batch(self, updates, user): ...
960
+ def delete(self, memory_id, user): ... # soft-delete when supported
961
+ def hard_delete(self, memory_id, user): ...
962
+ def list(self, user, limit, min_pressure, drawer, cursor_id=None, include_deleted=False): ...
575
963
  def list_drawers(self, user): ...
964
+ def find_by_idempotency_key(self, key, user): ...
965
+ def find_by_hash(self, text_hash, user): ...
966
+ def ping(self): ...
576
967
 
577
968
  mem = Memory.__new__(Memory)
578
969
  mem._storage = MyPostgresStorage(...)