ingatan 0.1.0__py3-none-any.whl

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 (87) hide show
  1. ingatan/__init__.py +5 -0
  2. ingatan/audit/__init__.py +197 -0
  3. ingatan/audit/_undo.py +656 -0
  4. ingatan/brief/__init__.py +406 -0
  5. ingatan/cli/__init__.py +35 -0
  6. ingatan/cli/__main__.py +6 -0
  7. ingatan/cli/_shared.py +234 -0
  8. ingatan/cli/cmd_audit.py +326 -0
  9. ingatan/cli/cmd_backup.py +272 -0
  10. ingatan/cli/cmd_conflicts.py +275 -0
  11. ingatan/cli/cmd_ingest.py +1018 -0
  12. ingatan/cli/cmd_memory.py +316 -0
  13. ingatan/cli/cmd_proposals.py +190 -0
  14. ingatan/cli/cmd_search.py +161 -0
  15. ingatan/cli/cmd_semantic.py +297 -0
  16. ingatan/cli/cmd_server.py +403 -0
  17. ingatan/cli/cmd_tokens.py +52 -0
  18. ingatan/cli/commands.py +42 -0
  19. ingatan/cli/conflicts.py +300 -0
  20. ingatan/cli/doctor.py +578 -0
  21. ingatan/cli/render.py +139 -0
  22. ingatan/cli/review.py +92 -0
  23. ingatan/cli/setup.py +162 -0
  24. ingatan/db/__init__.py +320 -0
  25. ingatan/db/backup.py +219 -0
  26. ingatan/db/migrations/0001_initial.sql +193 -0
  27. ingatan/db/migrations/0002_semantic_and_structure.sql +49 -0
  28. ingatan/db/migrations/0003_fact_text_key.sql +11 -0
  29. ingatan/db/migrations/0004_embed_queue.sql +13 -0
  30. ingatan/db/migrations/0005_note_extraction.sql +7 -0
  31. ingatan/db/migrations/0006_extract_failures.sql +9 -0
  32. ingatan/db/migrations/0007_lookup_indexes.sql +11 -0
  33. ingatan/db/migrations/0008_retraction.sql +10 -0
  34. ingatan/db/migrations/0009_log_ord.sql +28 -0
  35. ingatan/episodes/__init__.py +348 -0
  36. ingatan/errors.py +31 -0
  37. ingatan/extract/__init__.py +542 -0
  38. ingatan/extract/llm.py +214 -0
  39. ingatan/extract/prompt.py +114 -0
  40. ingatan/facts/__init__.py +42 -0
  41. ingatan/facts/_util.py +183 -0
  42. ingatan/facts/backfill.py +353 -0
  43. ingatan/facts/change.py +433 -0
  44. ingatan/facts/create.py +1146 -0
  45. ingatan/facts/export.py +116 -0
  46. ingatan/facts/forget.py +329 -0
  47. ingatan/facts/history.py +133 -0
  48. ingatan/facts/hygiene.py +161 -0
  49. ingatan/facts/links.py +208 -0
  50. ingatan/facts/overdue.py +144 -0
  51. ingatan/facts/retract.py +226 -0
  52. ingatan/facts/review.py +179 -0
  53. ingatan/ingest/__init__.py +331 -0
  54. ingatan/ingest/markdown.py +74 -0
  55. ingatan/integrations/__init__.py +3 -0
  56. ingatan/integrations/claude_code/__init__.py +3 -0
  57. ingatan/integrations/claude_code/hooks.py +392 -0
  58. ingatan/integrations/claude_code/install.py +274 -0
  59. ingatan/integrations/hermes/README.md +13 -0
  60. ingatan/integrations/hermes/__init__.py +706 -0
  61. ingatan/integrations/hermes/cli.py +33 -0
  62. ingatan/integrations/hermes/install.py +37 -0
  63. ingatan/integrations/hermes/plugin.yaml +21 -0
  64. ingatan/mcp/__init__.py +3 -0
  65. ingatan/mcp/http.py +595 -0
  66. ingatan/mcp/server.py +891 -0
  67. ingatan/proposals/__init__.py +528 -0
  68. ingatan/redact/__init__.py +236 -0
  69. ingatan/scope/__init__.py +1160 -0
  70. ingatan/scope/_net.py +208 -0
  71. ingatan/scope/configfile.py +160 -0
  72. ingatan/search/__init__.py +59 -0
  73. ingatan/search/aliases.py +98 -0
  74. ingatan/search/core.py +1833 -0
  75. ingatan/search/embed.py +986 -0
  76. ingatan/search/local.py +536 -0
  77. ingatan/search/shared.py +836 -0
  78. ingatan/search/stem_id.py +196 -0
  79. ingatan/search/stopwords.py +583 -0
  80. ingatan/timeutil.py +51 -0
  81. ingatan/tokens/__init__.py +405 -0
  82. ingatan-0.1.0.dist-info/METADATA +1014 -0
  83. ingatan-0.1.0.dist-info/RECORD +87 -0
  84. ingatan-0.1.0.dist-info/WHEEL +4 -0
  85. ingatan-0.1.0.dist-info/entry_points.txt +2 -0
  86. ingatan-0.1.0.dist-info/licenses/LICENSE +201 -0
  87. ingatan-0.1.0.dist-info/licenses/NOTICE +4 -0
ingatan/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Ingatan: local-first shared memory for AI agents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.1.0"
@@ -0,0 +1,197 @@
1
+ """Append-only log of every change: write, read, scrub, diff and undo."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sqlite3
7
+ import threading
8
+ import time
9
+ from dataclasses import dataclass
10
+ from typing import Any
11
+
12
+ from ingatan import timeutil
13
+ from ingatan.errors import NotFoundError
14
+ from ingatan.scope import Context
15
+
16
+ __all__ = ["OPS", "Diff", "LogEntry", "diff", "entries", "get", "scrub", "undo", "write"]
17
+
18
+ # `conflict` records pairs opened after the fact was saved (see `facts.backfill`).
19
+ OPS = frozenset(
20
+ {
21
+ "create",
22
+ "supersede",
23
+ "confirm",
24
+ "forget",
25
+ "propose",
26
+ "approve",
27
+ "reject",
28
+ "ingest",
29
+ "link",
30
+ "unlink",
31
+ "pin",
32
+ "undo",
33
+ "conflict",
34
+ "retract",
35
+ }
36
+ )
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class LogEntry:
41
+ id: int
42
+ ts: str
43
+ agent: str
44
+ op: str
45
+ fact_id: str | None
46
+ tier: str | None
47
+ owner: str | None
48
+ # {"before": {...} | None, "after": {...} | None}, or None for a content-free entry
49
+ change: dict[str, Any] | None
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Diff:
54
+ log_id: int
55
+ op: str
56
+ fact_id: str | None
57
+ before: dict[str, Any] | None
58
+ after: dict[str, Any] | None
59
+
60
+
61
+ _ord_lock = threading.Lock()
62
+ _last_ord = 0
63
+
64
+
65
+ def _next_ord() -> int:
66
+ """The `log.ord` of a new entry: wall-clock nanoseconds, strictly increasing in this process.
67
+
68
+ `ts` counts whole seconds and ids order entries inside one file only, so this is what
69
+ tells which of two entries of the two files came first. `max(..., last + 1)` keeps the
70
+ values distinct on a clock that steps coarsely (milliseconds on older Windows Pythons)
71
+ or goes back a little. It uses the real clock on purpose: `timeutil.now()` is frozen in
72
+ tests, and the order of two writes inside one frozen second is what this value records.
73
+ It is a time and never content, so `scrub` leaves it alone.
74
+ """
75
+ global _last_ord
76
+ with _ord_lock:
77
+ _last_ord = max(time.time_ns(), _last_ord + 1)
78
+ return _last_ord
79
+
80
+
81
+ def write(
82
+ conn: sqlite3.Connection,
83
+ *,
84
+ agent: str,
85
+ op: str,
86
+ fact_id: str | None,
87
+ tier: str | None,
88
+ owner: str | None,
89
+ before: dict[str, Any] | None,
90
+ after: dict[str, Any] | None,
91
+ ) -> int:
92
+ """Append one entry and return its id. Must run inside `db.transaction`.
93
+
94
+ `before` and `after` both None gives a content-free entry (`change` is NULL).
95
+ """
96
+ if not conn.in_transaction:
97
+ raise RuntimeError("audit.write must be called inside db.transaction(conn)")
98
+ if op not in OPS:
99
+ raise ValueError(f"Unknown log op '{op}'. Known ops: {', '.join(sorted(OPS))}")
100
+ change = (
101
+ None
102
+ if before is None and after is None
103
+ else json.dumps({"before": before, "after": after}, ensure_ascii=False)
104
+ )
105
+ cursor = conn.execute(
106
+ "INSERT INTO log (ts, agent, op, fact_id, tier, owner, change, ord) "
107
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
108
+ (timeutil.iso(timeutil.now()), agent, op, fact_id, tier, owner, change, _next_ord()),
109
+ )
110
+ assert cursor.lastrowid is not None
111
+ return cursor.lastrowid
112
+
113
+
114
+ def _entry(row: sqlite3.Row) -> LogEntry:
115
+ raw = row["change"]
116
+ return LogEntry(
117
+ id=row["id"],
118
+ ts=row["ts"],
119
+ agent=row["agent"],
120
+ op=row["op"],
121
+ fact_id=row["fact_id"],
122
+ tier=row["tier"],
123
+ owner=row["owner"],
124
+ change=None if raw is None else json.loads(raw),
125
+ )
126
+
127
+
128
+ def entries(
129
+ ctx: Context,
130
+ *,
131
+ fact_id: str | None = None,
132
+ fact_ids: list[str] | None = None,
133
+ limit: int | None = None,
134
+ newest_first: bool = False,
135
+ ) -> list[LogEntry]:
136
+ """Log entries the caller may see, from both files, ordered by time then id."""
137
+ wanted: list[str] | None = None
138
+ if fact_id is not None or fact_ids is not None:
139
+ wanted = ([fact_id] if fact_id is not None else []) + list(fact_ids or [])
140
+ direction = "DESC" if newest_first else "ASC"
141
+ found: list[LogEntry] = []
142
+ for conn in ctx.connections():
143
+ where = ctx.visible_sql(conn, owner_column="owner")
144
+ params: dict[str, Any] = dict(ctx.params)
145
+ sql = f"SELECT * FROM log WHERE {where}"
146
+ if wanted is not None:
147
+ sql += " AND fact_id IN (SELECT value FROM json_each(:ids))"
148
+ params["ids"] = json.dumps(wanted)
149
+ sql += f" ORDER BY ts {direction}, id {direction}"
150
+ if limit is not None:
151
+ sql += " LIMIT :limit"
152
+ params["limit"] = limit
153
+ found.extend(_entry(row) for row in conn.execute(sql, params))
154
+ found.sort(key=lambda e: (e.ts, e.id), reverse=newest_first)
155
+ return found[:limit] if limit is not None else found
156
+
157
+
158
+ def scrub(conn: sqlite3.Connection, fact_id: str) -> None:
159
+ """Clear `change` on every entry of this fact. Used only by `forget`."""
160
+ conn.execute("UPDATE log SET change = NULL WHERE fact_id = ?", (fact_id,))
161
+
162
+
163
+ def get(ctx: Context, log_id: int) -> LogEntry:
164
+ """One entry by id. Missing and invisible entries both raise `NotFoundError`."""
165
+ for conn in ctx.connections():
166
+ where = ctx.visible_sql(conn, owner_column="owner")
167
+ row = conn.execute(
168
+ f"SELECT * FROM log WHERE id = :id AND {where}", {"id": log_id, **ctx.params}
169
+ ).fetchone()
170
+ if row is not None:
171
+ return _entry(row)
172
+ raise NotFoundError(f"No log entry {log_id}.")
173
+
174
+
175
+ def diff(ctx: Context, log_id: int) -> Diff:
176
+ """Before and after of one entry. Both are None for a scrubbed or content-free entry."""
177
+ entry = get(ctx, log_id)
178
+ change = entry.change or {}
179
+ return Diff(
180
+ log_id=entry.id,
181
+ op=entry.op,
182
+ fact_id=entry.fact_id,
183
+ before=change.get("before"),
184
+ after=change.get("after"),
185
+ )
186
+
187
+
188
+ def undo(ctx: Context, log_id: int) -> int:
189
+ """Reverse one entry and return the id of the new `undo` entry (OQ-16).
190
+
191
+ Handles create, supersede, confirm, approve, retract, link, unlink, pin and conflict.
192
+ Refuses a forget ("a forget cannot be undone"), an entry with later changes to the same
193
+ fact, and every other op.
194
+ """
195
+ from ingatan.audit._undo import undo_entry # lazy: _undo imports this package
196
+
197
+ return undo_entry(ctx, log_id)