ai-first-os 1.9.0

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 (90) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +226 -0
  3. package/bin/ai-first-os.js +72 -0
  4. package/core/CLAUDE.md +148 -0
  5. package/core/VERSION +1 -0
  6. package/core/agents/ambiguous-spec.md +39 -0
  7. package/core/agents/complete-spec.md +36 -0
  8. package/core/agents/scout.md +25 -0
  9. package/core/install.sh +243 -0
  10. package/core/lib/archive.sh +347 -0
  11. package/core/lib/bootstrap.sh +276 -0
  12. package/core/lib/capture.sh +188 -0
  13. package/core/lib/check-resolvable.sh +172 -0
  14. package/core/lib/close-session.sh +741 -0
  15. package/core/lib/common.sh +1773 -0
  16. package/core/lib/focus-read.sh +282 -0
  17. package/core/lib/manual-link.sh +111 -0
  18. package/core/lib/markdown.py +304 -0
  19. package/core/lib/migrate-backlogs.sh +207 -0
  20. package/core/lib/migrate-canonicals.sh +523 -0
  21. package/core/lib/mount-repo.sh +543 -0
  22. package/core/lib/my-wiki-gates.sh +137 -0
  23. package/core/lib/my-wiki.sh +202 -0
  24. package/core/lib/my_wiki_build.py +548 -0
  25. package/core/lib/my_wiki_graph.py +137 -0
  26. package/core/lib/my_wiki_overview.py +392 -0
  27. package/core/lib/new-memory.sh +160 -0
  28. package/core/lib/new-product.sh +122 -0
  29. package/core/lib/new-workspace.sh +105 -0
  30. package/core/lib/pack-install.sh +114 -0
  31. package/core/lib/recall.sh +235 -0
  32. package/core/lib/recall_index.py +295 -0
  33. package/core/lib/remote-backup.sh +84 -0
  34. package/core/lib/rename-heads.sh +354 -0
  35. package/core/lib/rename-workspaces.sh +271 -0
  36. package/core/lib/session-read.sh +203 -0
  37. package/core/lib/session-start.sh +854 -0
  38. package/core/lib/supersede.sh +436 -0
  39. package/core/lib/sweep.sh +473 -0
  40. package/core/manual/COMO-FUNCIONA.md +251 -0
  41. package/core/manual/HOW-IT-WORKS.md +250 -0
  42. package/core/resolver.md +30 -0
  43. package/core/skills/archive.md +95 -0
  44. package/core/skills/bootstrap.md +226 -0
  45. package/core/skills/capture.md +65 -0
  46. package/core/skills/check-resolvable.md +38 -0
  47. package/core/skills/close-session.md +108 -0
  48. package/core/skills/grill.md +74 -0
  49. package/core/skills/mount-repo.md +97 -0
  50. package/core/skills/my-wiki.md +103 -0
  51. package/core/skills/new-memory.md +76 -0
  52. package/core/skills/new-product.md +55 -0
  53. package/core/skills/new-spec.md +114 -0
  54. package/core/skills/new-workspace.md +53 -0
  55. package/core/skills/recall.md +64 -0
  56. package/core/skills/rename-heads.md +72 -0
  57. package/core/skills/rename-workspaces.md +43 -0
  58. package/core/skills/supersede.md +83 -0
  59. package/core/skills/sweep.md +40 -0
  60. package/core/templates/my-wiki-graph.js +431 -0
  61. package/core/templates/my-wiki-overview.js +174 -0
  62. package/core/templates/my-wiki.html +1017 -0
  63. package/core/templates/node-folder/README.md +11 -0
  64. package/core/templates/node-folder/resolver.md +9 -0
  65. package/core/templates/node-light.md +22 -0
  66. package/core/templates/node-product/README.md +8 -0
  67. package/core/templates/node-repo/README.md +14 -0
  68. package/core/templates/node-repo/context/README.md +22 -0
  69. package/core/templates/node-repo/context/competitors.md +8 -0
  70. package/core/templates/node-repo/context/glossary.md +8 -0
  71. package/core/templates/node-repo/context/open-questions.md +9 -0
  72. package/core/templates/node-repo/context/opportunities.md +9 -0
  73. package/core/templates/node-repo/context/problem.md +8 -0
  74. package/core/templates/node-repo/context/scope.md +8 -0
  75. package/core/templates/node-repo/context/users.md +8 -0
  76. package/core/templates/node-repo/context/vision.md +8 -0
  77. package/core/templates/node-repo/resolver.md +14 -0
  78. package/core/templates/operator.md +17 -0
  79. package/core/templates/person.md +10 -0
  80. package/core/templates/repo-scaffold/ARCHITECTURE.md +3 -0
  81. package/core/templates/repo-scaffold/CLAUDE.md +23 -0
  82. package/core/templates/repo-scaffold/decisions.md +3 -0
  83. package/core/templates/repo-scaffold/evals-run.sh +14 -0
  84. package/core/templates/repo-scaffold/gitignore +3 -0
  85. package/core/templates/repo-scaffold/settings.json +8 -0
  86. package/core/templates/root-resolver.md +5 -0
  87. package/core/templates/strings.md +1361 -0
  88. package/core/templates/tree.md +59 -0
  89. package/core/templates/voice.md +5 -0
  90. package/package.json +23 -0
@@ -0,0 +1,295 @@
1
+ #!/usr/bin/env python3
2
+ """Living Memory's indexer and query engine (spec 050). Internal: `recall.sh` is the invocable;
3
+ this file has no `command:` header and is never called on its own.
4
+
5
+ Called as: recall_index.py DB BRAIN MODE SCOPE_KIND WSDIR SCOPE_SLUG ARG LIMIT
6
+
7
+ Reads the file list on stdin, two blocks separated by the sentinel line `%%FILES%%`: the node
8
+ heads first (the subset of the `glob:` class whose basename is the brain's head file — computed in
9
+ bash from `os_tree_files`/`os_head_file`, no second parser of `tree.md` here), then every file to
10
+ index (the union of the `glob:` and `content:` classes).
11
+
12
+ THE MARKDOWN READING IS NOT HERE. `markdown.py` next to this file is the one Python reading of
13
+ frontmatter and of the entry split (spec 060 moved them there when a second feature needed the
14
+ same traversal); this file imports it and adds nothing of its own about the format. `common.sh`'s
15
+ `fm_read` is the bash reading of the same bounded format and stays the authority whenever the two
16
+ disagree on the shape.
17
+ """
18
+
19
+ import hashlib
20
+ import os
21
+ import sqlite3
22
+ import sys
23
+
24
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
25
+ from markdown import DATE_RE, read_frontmatter, split_entries # noqa: E402
26
+
27
+ db_path, brain, mode, scope_kind, wsdir, scope_slug, arg, limit = sys.argv[1:9]
28
+ limit = int(limit)
29
+ FM_KEYS = ("updated", "fecha", "date", "status", "about", "superseded_by")
30
+
31
+
32
+ def file_status(fm):
33
+ if fm.get("superseded_by"):
34
+ return "superseded"
35
+ if fm.get("status") == "superseded":
36
+ return "superseded"
37
+ return "current"
38
+
39
+
40
+ def mtime_date(path):
41
+ try:
42
+ t = os.path.getmtime(path)
43
+ except OSError:
44
+ return ""
45
+ import datetime
46
+ return datetime.date.fromtimestamp(t).isoformat()
47
+
48
+
49
+ def entry_date(header_text, fm, path):
50
+ m = DATE_RE.match(header_text.strip())
51
+ if m:
52
+ return m.group(1)
53
+ for k in ("updated", "fecha", "date"):
54
+ v = fm.get(k, "").strip()
55
+ if v:
56
+ return v
57
+ return mtime_date(path)
58
+
59
+
60
+ def parse_file(abspath, relpath):
61
+ try:
62
+ with open(abspath, "r", encoding="utf-8", errors="replace") as f:
63
+ raw = f.read()
64
+ except OSError:
65
+ return {}, [], ""
66
+ lines = raw.split("\n")
67
+ if lines and lines[-1] == "":
68
+ lines = lines[:-1]
69
+ fm, body_start = read_frontmatter(lines, FM_KEYS)
70
+ body_lines = lines[body_start:]
71
+ entries = split_entries(body_lines, body_start, os.path.basename(relpath))
72
+ status = file_status(fm)
73
+ superseded_by = fm.get("superseded_by", "") if status == "superseded" else ""
74
+ out_entries = []
75
+ for line, header, text in entries:
76
+ date = entry_date(header, fm, abspath)
77
+ out_entries.append((line, header, text, date))
78
+ title = out_entries[0][1] if out_entries else os.path.splitext(os.path.basename(relpath))[0]
79
+ return fm, out_entries, status, superseded_by, title
80
+
81
+
82
+ def connect(path):
83
+ conn = sqlite3.connect(path)
84
+ conn.execute("PRAGMA journal_mode=WAL")
85
+ conn.execute(
86
+ "CREATE TABLE IF NOT EXISTS files ("
87
+ " path TEXT PRIMARY KEY, size INTEGER, mtime REAL, hash TEXT,"
88
+ " node TEXT, title TEXT, status TEXT, superseded_by TEXT, about TEXT)"
89
+ )
90
+ conn.execute(
91
+ "CREATE VIRTUAL TABLE IF NOT EXISTS entries USING fts5("
92
+ " header, body, path UNINDEXED, line UNINDEXED, date UNINDEXED,"
93
+ " node UNINDEXED, status UNINDEXED, superseded_by UNINDEXED,"
94
+ " tokenize='unicode61 remove_diacritics 2')"
95
+ )
96
+ conn.execute(
97
+ "CREATE TABLE IF NOT EXISTS relations (src TEXT, rel TEXT, dst TEXT)"
98
+ )
99
+ conn.execute("CREATE INDEX IF NOT EXISTS relations_src ON relations(src)")
100
+ conn.execute("CREATE INDEX IF NOT EXISTS relations_dst ON relations(dst)")
101
+ return conn
102
+
103
+
104
+ def node_of(relpath, true_heads_dirs):
105
+ d = os.path.dirname(relpath)
106
+ best = None
107
+ for hd in true_heads_dirs:
108
+ if d == hd or d.startswith(hd + "/"):
109
+ if best is None or len(hd) > len(best):
110
+ best = hd
111
+ return true_heads_dirs.get(best, "") if best is not None else ""
112
+
113
+
114
+ def reconcile(conn, brain, all_files, true_heads):
115
+ true_heads_dirs = {}
116
+ for h in true_heads:
117
+ true_heads_dirs[os.path.dirname(h)] = h
118
+
119
+ stored = {}
120
+ for row in conn.execute("SELECT path, size, mtime, hash FROM files"):
121
+ stored[row[0]] = (row[1], row[2], row[3])
122
+
123
+ current_set = set(all_files)
124
+ to_delete = [p for p in stored if p not in current_set]
125
+
126
+ to_reindex = []
127
+ to_touch = [] # (path, size, mtime) -- hash unchanged, only refresh stat
128
+ to_insert = [] # new files
129
+
130
+ for rel in all_files:
131
+ abspath = os.path.join(brain, rel)
132
+ try:
133
+ st = os.stat(abspath)
134
+ except OSError:
135
+ to_delete.append(rel)
136
+ continue
137
+ size, mtime = st.st_size, st.st_mtime
138
+ prev = stored.get(rel)
139
+ if prev is not None and prev[0] == size and prev[1] == mtime:
140
+ continue # first filter: unchanged size and mtime, skip entirely
141
+ h = hashlib.sha256()
142
+ try:
143
+ with open(abspath, "rb") as f:
144
+ h.update(f.read())
145
+ except OSError:
146
+ to_delete.append(rel)
147
+ continue
148
+ digest = h.hexdigest()
149
+ if prev is not None and prev[2] == digest:
150
+ to_touch.append((rel, size, mtime))
151
+ continue
152
+ if prev is None:
153
+ to_insert.append((rel, size, mtime, digest))
154
+ else:
155
+ to_reindex.append((rel, size, mtime, digest))
156
+
157
+ cur = conn.cursor()
158
+ for p in to_delete:
159
+ cur.execute("DELETE FROM files WHERE path=?", (p,))
160
+ cur.execute("DELETE FROM entries WHERE path=?", (p,))
161
+ cur.execute("DELETE FROM relations WHERE src=? OR dst=?", (p, p))
162
+
163
+ for rel, size, mtime in to_touch:
164
+ cur.execute("UPDATE files SET size=?, mtime=? WHERE path=?", (size, mtime, rel))
165
+
166
+ for rel, size, mtime, digest in to_reindex + to_insert:
167
+ abspath = os.path.join(brain, rel)
168
+ fm, out_entries, status, superseded_by, title = parse_file(abspath, rel)
169
+ node = node_of(rel, true_heads_dirs)
170
+ about = fm.get("about", "")
171
+ cur.execute("DELETE FROM entries WHERE path=?", (rel,))
172
+ cur.execute("DELETE FROM relations WHERE src=?", (rel,))
173
+ cur.execute(
174
+ "INSERT OR REPLACE INTO files"
175
+ " (path, size, mtime, hash, node, title, status, superseded_by, about)"
176
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
177
+ (rel, size, mtime, digest, node, title, status, superseded_by, about),
178
+ )
179
+ if about:
180
+ cur.execute("INSERT INTO relations (src, rel, dst) VALUES (?, 'about', ?)", (rel, about))
181
+ if superseded_by:
182
+ cur.execute(
183
+ "INSERT INTO relations (src, rel, dst) VALUES (?, 'superseded_by', ?)",
184
+ (rel, superseded_by),
185
+ )
186
+ for line, header, text, date in out_entries:
187
+ cur.execute(
188
+ "INSERT INTO entries"
189
+ " (header, body, path, line, date, node, status, superseded_by)"
190
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
191
+ (header, text, rel, line, date, node, status, superseded_by),
192
+ )
193
+ conn.commit()
194
+
195
+
196
+ def fts_query(q):
197
+ tokens = q.split()
198
+ if not tokens:
199
+ return '""'
200
+ return " ".join('"' + t.replace('"', '""') + '"' for t in tokens)
201
+
202
+
203
+ def fragment(text, limit=200):
204
+ text = " ".join(text.split())
205
+ if len(text) > limit:
206
+ text = text[: limit - 1].rstrip() + "…"
207
+ return text
208
+
209
+
210
+ def scope_filter(scope_kind, wsdir, scope_slug):
211
+ if scope_kind == "all":
212
+ return "1=1", ()
213
+ if scope_kind == "root":
214
+ return "path NOT LIKE ?", (wsdir + "/%",)
215
+ if scope_kind == "workspace":
216
+ return "path LIKE ?", (wsdir + "/" + scope_slug + "/%",)
217
+ return "1=1", ()
218
+
219
+
220
+ def run_search():
221
+ conn = connect(db_path)
222
+ reconcile(conn, brain, all_files, true_heads)
223
+ n_files = conn.execute("SELECT COUNT(*) FROM files").fetchone()[0]
224
+
225
+ clause, params = scope_filter(scope_kind, wsdir, scope_slug)
226
+ match = fts_query(arg)
227
+ sql = (
228
+ "SELECT path, line, date, status, superseded_by, header,"
229
+ " snippet(entries, -1, '', '', '...', 20) AS frag"
230
+ " FROM entries WHERE entries MATCH ? AND " + clause +
231
+ " ORDER BY (status='superseded') ASC, bm25(entries, 10.0, 1.0) ASC"
232
+ " LIMIT ?"
233
+ )
234
+ rows = conn.execute(sql, (match,) + params + (limit,)).fetchall()
235
+
236
+ hits = len(rows)
237
+ print("scope: %s · %d hits · %d files indexed" % (
238
+ scope_slug if scope_kind == "workspace" else scope_kind, hits, n_files))
239
+ if hits == 0:
240
+ print("__NO_RESULTS__")
241
+ return
242
+ for path, line, date, status, superseded_by, header, frag in rows:
243
+ estado = "current" if status != "superseded" else ("superseded → " + superseded_by)
244
+ print("%s:%s · %s · %s · %s · %s" % (
245
+ path, line, date, estado, header, fragment(frag)))
246
+
247
+
248
+ def title_of(conn, path):
249
+ row = conn.execute("SELECT title FROM files WHERE path=?", (path,)).fetchone()
250
+ if row:
251
+ return row[0]
252
+ return os.path.splitext(os.path.basename(path))[0]
253
+
254
+
255
+ def run_expand():
256
+ conn = connect(db_path)
257
+ reconcile(conn, brain, all_files, true_heads)
258
+
259
+ lines = []
260
+ row = conn.execute("SELECT about FROM files WHERE path=?", (arg,)).fetchone()
261
+ if row and row[0]:
262
+ dst = row[0]
263
+ lines.append("about · %s · %s" % (dst, title_of(conn, dst)))
264
+ for (src,) in conn.execute(
265
+ "SELECT src FROM relations WHERE rel='about' AND dst=?", (arg,)
266
+ ):
267
+ lines.append("about-by · %s · %s" % (src, title_of(conn, src)))
268
+ row = conn.execute("SELECT superseded_by FROM files WHERE path=?", (arg,)).fetchone()
269
+ if row and row[0]:
270
+ dst = row[0]
271
+ lines.append("superseded-by · %s · %s" % (dst, title_of(conn, dst)))
272
+ for (src,) in conn.execute(
273
+ "SELECT src FROM relations WHERE rel='superseded_by' AND dst=?", (arg,)
274
+ ):
275
+ lines.append("supersedes · %s · %s" % (src, title_of(conn, src)))
276
+ for l in lines:
277
+ print(l)
278
+
279
+
280
+ data = sys.stdin.read().split("\n")
281
+ true_heads = []
282
+ all_files = []
283
+ target = true_heads
284
+ for l in data:
285
+ if l == "%%FILES%%":
286
+ target = all_files
287
+ continue
288
+ if l:
289
+ target.append(l)
290
+
291
+ if mode == "expand":
292
+ run_expand()
293
+ else:
294
+ run_search()
295
+
@@ -0,0 +1,84 @@
1
+ #!/usr/bin/env bash
2
+ # La mitad remota del respaldo del brain (spec 021). Interno: no es invocable.
3
+ # La conduce core/skills/bootstrap.md al cerrar el bootstrap, y la puede volver a correr cualquier
4
+ # sesión posterior — que es lo que la tarea pendiente del backlog le pide al operador.
5
+ #
6
+ # Uso: remote-backup.sh --brain DIR
7
+ #
8
+ # El script NUNCA crea el repo ni pushea: eso escapa del sistema —queda algo en la cuenta de una
9
+ # persona— y se hace con la confirmación del operador en la sesión. Acá se decide cuál de las dos
10
+ # mitades corresponde y se deja dicho:
11
+ # - con `gh` autenticado: imprime el ofrecimiento y el comando exacto, para que lo corra la sesión
12
+ # después del sí del operador;
13
+ # - sin `gh`, o sin sesión iniciada: deja la tarea guiada en el backlog de la raíz y lo dice.
14
+ #
15
+ # Exit: 0 siempre que haya podido decidir · 1 si el brain no está versionado.
16
+
17
+ set -eu
18
+
19
+ here=$(cd "$(dirname "$0")" && pwd)
20
+ . "$here/common.sh"
21
+
22
+ brain=""
23
+
24
+ while [ $# -gt 0 ]; do
25
+ case "$1" in
26
+ --brain) brain="$2"; shift 2 ;;
27
+ *) os_die "argumento desconocido: $1" ;;
28
+ esac
29
+ done
30
+
31
+ [ -n "$brain" ] || os_die "falta --brain"
32
+ [ -d "$brain" ] || os_die "no existe el brain: $brain"
33
+ # Ruta física: ver el comentario de bootstrap.sh.
34
+ brain=$(cd "$brain" && pwd -P)
35
+
36
+ command -v git > /dev/null 2>&1 || os_die "git no está en el PATH: sin respaldo local no hay remoto que armar"
37
+ top=$(git -C "$brain" rev-parse --show-toplevel 2>/dev/null) || top=""
38
+ if [ "$top" != "$brain" ]; then
39
+ os_die "el brain no es un repo git: el respaldo remoto va después del local"
40
+ fi
41
+
42
+ # Con remoto ya declarado no hay nada que decidir: el respaldo está armado.
43
+ remoto=$(git -C "$brain" remote get-url origin 2>/dev/null) || remoto=""
44
+ if [ -n "$remoto" ]; then
45
+ printf 'respaldo remoto: ya está en %s\n' "$remoto"
46
+ exit 0
47
+ fi
48
+
49
+ # `gh auth status` solo lee. Ningún otro comando de `gh` corre desde acá.
50
+ autenticado=0
51
+ if command -v gh > /dev/null 2>&1; then
52
+ if gh auth status > /dev/null 2>&1; then
53
+ autenticado=1
54
+ fi
55
+ fi
56
+
57
+ if [ "$autenticado" = "1" ]; then
58
+ printf 'respaldo remoto: gh autenticado — el repo lo crea el operador con su sí, nunca este script\n'
59
+ printf ' comando: gh repo create %s --private --source %s --push\n' "$(basename "$brain")" "$brain"
60
+ exit 0
61
+ fi
62
+
63
+ # Sin gh no se puede armar el remoto hoy: la tarea queda en el backlog de la raíz, con la guía
64
+ # adentro, y el que la termina es cualquier sesión posterior. Un pendiente que nadie escribe es un
65
+ # pendiente que nadie completa. Ese `backlog.md` de la raíz, fuera de toda iniciativa, es el
66
+ # hallazgo que la spec 057 declara aparte (S057-C5) hasta que el operador arma el remoto.
67
+ language=$(os_language "$brain")
68
+ os_lang_load "$language"
69
+ tarea="$S_BACKUP_TASK"
70
+
71
+ if [ -f "$brain/backlog.md" ] && grep -qF "$tarea" "$brain/backlog.md"; then
72
+ printf 'respaldo remoto: la tarea pendiente ya estaba en el backlog de la raíz\n'
73
+ exit 0
74
+ fi
75
+
76
+ # No pasa por `capture` (spec 057, decisión 2): este paso corre determinístico, sin ningún modelo
77
+ # en el medio que pueda nombrar una iniciativa y esperar la confirmación del operador — armar el
78
+ # remoto de respaldo no es trabajo de ninguna iniciativa. Mismo criterio y mismo formato que
79
+ # `pack-install.sh --defer`.
80
+ hoy=$(date +%Y-%m-%d)
81
+ [ -f "$brain/backlog.md" ] || os_backlog_cabecera "$brain" "$(os_titulo "$brain/operator.md")" > "$brain/backlog.md"
82
+ id=$(os_backlog_next_id "$brain")
83
+ printf '%s\n' "$(os_backlog_linea "$id" "$tarea" "" "" "" "0" "$hoy")" >> "$brain/backlog.md"
84
+ printf 'respaldo remoto: pendiente — sin gh autenticado, la tarea guiada quedó en el backlog de la raíz\n'