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,243 @@
1
+ #!/usr/bin/env bash
2
+ # command: install.sh
3
+ # Engancha el producto a un brain por symlink. Idempotente: correrlo dos veces no cambia nada.
4
+ #
5
+ # Uso: install.sh RUTA-BRAIN [--adopt]
6
+ #
7
+ # Qué deja en el brain:
8
+ # CLAUDE.md -> symlink al contrato de sesión del producto
9
+ # .os/core -> symlink a core/
10
+ # .os/packs/<pack> -> symlink a cada pack
11
+ # .claude/agents/<n> -> symlink a cada agente de core/agents/, uno por archivo (el harness del
12
+ # operador los lee de ahí; symlinkear el directorio entero se
13
+ # llevaría por delante configuración propia del operador en .claude/)
14
+ #
15
+ # --adopt: si el brain ya tiene un CLAUDE.md que no es el de este producto —propio, o symlink a
16
+ # otro— lo guarda como CLAUDE.md.adopted, un nombre que ningún harness carga, y engancha el
17
+ # symlink. Sin --adopt el instalador para y no toca nada.
18
+
19
+ set -eu
20
+
21
+ # Ruta física, no lógica (spec 016): invocado a través del symlink instalado en un brain,
22
+ # `pwd` lógico devuelve la ruta del symlink y cada `ln` posterior escribe un enlace sobre sí
23
+ # mismo — el brain entero queda circular. `pwd -P` atraviesa el symlink hasta el checkout real.
24
+ core=$(cd "$(dirname "$0")" && pwd -P)
25
+ product=$(cd "$core/.." && pwd -P)
26
+
27
+ brain=""
28
+ adopt=0
29
+
30
+ while [ $# -gt 0 ]; do
31
+ case "$1" in
32
+ --adopt) adopt=1; shift ;;
33
+ -*) printf 'error: argumento desconocido: %s\n' "$1" >&2; exit 1 ;;
34
+ *) brain="$1"; shift ;;
35
+ esac
36
+ done
37
+
38
+ if [ -z "$brain" ]; then
39
+ printf 'uso: install.sh RUTA-BRAIN [--adopt]\n' >&2
40
+ exit 1
41
+ fi
42
+
43
+ mkdir -p "$brain"
44
+ brain=$(cd "$brain" && pwd)
45
+
46
+ # El idioma del brain, leído una sola vez acá: lo usan tanto el aviso del nombre anterior de la
47
+ # carpeta de espacios de trabajo como la línea de versión, más abajo. Mismo criterio liviano que el
48
+ # resto de este script — sin `lib/`, porque el instalador es lo primero que corre.
49
+ lang="en"
50
+ if [ -f "$brain/operator.md" ]; then
51
+ while IFS= read -r line || [ -n "$line" ]; do
52
+ case "$line" in
53
+ 'language: '*)
54
+ case "${line#language: }" in en) lang="en" ;; es) lang="es" ;; esac
55
+ break
56
+ ;;
57
+ esac
58
+ done < "$brain/operator.md"
59
+ fi
60
+
61
+ claude="$brain/CLAUDE.md"
62
+ claude_target="$core/CLAUDE.md"
63
+ adopted="$brain/CLAUDE.md.adopted"
64
+ # Ruta física de este producto, para comparar destinos y no cadenas. El instalador resuelve esto
65
+ # solo, sin lib/: es lo primero que se corre y no puede depender del layout de lo que instala.
66
+ core_real=$(cd "$core" && pwd -P)
67
+
68
+ # Destino real de un symlink: un readlink, y el directorio resuelto con `cd -P`, que atraviesa los
69
+ # symlinks que haya en el medio del camino. Vacío si no se puede resolver.
70
+ resolve_link() {
71
+ local link="$1" t d
72
+ t=$(readlink "$link") || return 0
73
+ case "$t" in
74
+ /*) ;;
75
+ *) t="$(dirname "$link")/$t" ;;
76
+ esac
77
+ d=$(cd "$(dirname "$t")" 2>/dev/null && pwd -P) || return 0
78
+ [ -n "$d" ] || return 0
79
+ printf '%s/%s' "$d" "$(basename "$t")"
80
+ }
81
+
82
+ # Chequeo antes de tocar nada. Adoptar es para un CLAUDE.md **ajeno**: un archivo propio del
83
+ # operador, o un symlink vivo hacia otro producto. Lo que no es adopción es re-instalación, y se
84
+ # relinkea callado: un symlink colgado —el producto se movió— y uno que ya apunta acá escrito de
85
+ # otra forma. Comparar por cadena de ruta trataba a los dos como ajenos: al colgado lo "adoptaba"
86
+ # dejando un CLAUDE.md.adopted roto, y al otro le pedía --adopt sin motivo.
87
+ needs_adopt=0
88
+ if [ -L "$claude" ]; then
89
+ if [ -e "$claude" ] && [ "$(resolve_link "$claude")" != "$core_real/CLAUDE.md" ]; then
90
+ needs_adopt=1
91
+ fi
92
+ elif [ -e "$claude" ]; then
93
+ needs_adopt=1
94
+ fi
95
+
96
+ if [ "$needs_adopt" = "1" ]; then
97
+ if [ "$adopt" = "0" ]; then
98
+ printf 'error: %s ya existe y no es el contrato de este producto.\n' "$claude" >&2
99
+ printf ' Correlo con --adopt: lo guarda como CLAUDE.md.adopted y engancha el symlink.\n' >&2
100
+ printf ' Ese nombre no lo carga ningún harness. Lo que valga de ahí se mueve a mano a\n' >&2
101
+ printf ' operator.md.\n' >&2
102
+ exit 1
103
+ fi
104
+ if [ -e "$adopted" ] || [ -L "$adopted" ]; then
105
+ printf 'error: %s ya existe. Resolvelo a mano antes de volver a correr --adopt.\n' "$adopted" >&2
106
+ exit 1
107
+ fi
108
+ fi
109
+
110
+ # La guarda del self-link (spec 016): si el destino de un enlace por escribir resuelve —tras
111
+ # atravesar los symlinks del camino— a su propio origen, no se escribe nada y se aborta. Cubre
112
+ # el brain cuyo `.os` es symlink a la raíz del producto: ahí cada `ln` escribiría adentro del
113
+ # producto un enlace sobre sí mismo. Se chequean todos los pares antes del primer mkdir/ln.
114
+ guard_selflink() {
115
+ local dest="$1" src="$2" ddir dreal sreal
116
+ ddir=$(cd -P "$(dirname "$dest")" 2>/dev/null && pwd -P) || return 0
117
+ dreal="$ddir/$(basename "$dest")"
118
+ if [ -d "$src" ]; then
119
+ sreal=$(cd -P "$src" && pwd -P)
120
+ else
121
+ sreal="$(cd -P "$(dirname "$src")" && pwd -P)/$(basename "$src")"
122
+ fi
123
+ if [ "$dreal" = "$sreal" ]; then
124
+ printf 'error: el enlace %s resolvería a sí mismo (%s).\n' "$dest" "$sreal" >&2
125
+ printf ' No se escribió nada. Corré install.sh desde el checkout del producto,\n' >&2
126
+ printf ' nunca a través de un enganche ya instalado.\n' >&2
127
+ exit 1
128
+ fi
129
+ }
130
+
131
+ guard_selflink "$brain/.os/core" "$core"
132
+ for pack in "$product"/packs/*; do
133
+ [ -d "$pack" ] || continue
134
+ guard_selflink "$brain/.os/packs/$(basename "$pack")" "$pack"
135
+ done
136
+ for agent in "$core"/agents/*.md; do
137
+ [ -f "$agent" ] || continue
138
+ guard_selflink "$brain/.claude/agents/$(basename "$agent")" "$agent"
139
+ done
140
+ guard_selflink "$claude" "$claude_target"
141
+
142
+ mkdir -p "$brain/.os/packs"
143
+ ln -sfn "$core" "$brain/.os/core"
144
+
145
+ for pack in "$product"/packs/*; do
146
+ [ -d "$pack" ] || continue
147
+ ln -sfn "$pack" "$brain/.os/packs/$(basename "$pack")"
148
+ done
149
+
150
+ mkdir -p "$brain/.claude/agents"
151
+
152
+ # Removes dangling symlinks from a previous install: a renamed agent (spec 033) leaves its old
153
+ # symlink behind, which `ln -sfn` does not overwrite because the file name changed, not the
154
+ # content. It only gets removed if both conditions hold at once:
155
+ # 1. it is dangling — `[ -e ]` on the symlink follows the link and is false if the target does
156
+ # not exist. A live symlink (the agent is still there, or the operator points somewhere else
157
+ # on purpose) is never touched.
158
+ # 2. the link's text — unresolved, exactly as `ln` wrote it — ends in `/core/agents/<name>.md`.
159
+ # It does not require resolving INSIDE this checkout: if the whole product moved folders, or
160
+ # the brain was installed from a different checkout of this same product, the old symlink
161
+ # points at a `core/agents/` that is no longer there — resolving it by physical path would
162
+ # give nothing and it would stay dangling next to the new one. The raw text is still
163
+ # recognizable even when the path no longer exists.
164
+ # A real file never enters here: the first check is `[ -L ]`.
165
+ for existing in "$brain/.claude/agents"/*; do
166
+ [ -L "$existing" ] || continue
167
+ [ -e "$existing" ] && continue
168
+ raw=$(readlink "$existing") || continue
169
+ case "$raw" in
170
+ */core/agents/*.md) rm -f "$existing" ;;
171
+ esac
172
+ done
173
+
174
+ for agent in "$core"/agents/*.md; do
175
+ [ -f "$agent" ] || continue
176
+ ln -sfn "$agent" "$brain/.claude/agents/$(basename "$agent")"
177
+ done
178
+
179
+ if [ "$needs_adopt" = "1" ]; then
180
+ mv "$claude" "$adopted"
181
+ printf 'aviso: el CLAUDE.md que estaba en el brain quedó como CLAUDE.md.adopted.\n' >&2
182
+ printf ' Ningún harness lo carga. Lo que valga de ahí va a operator.md.\n' >&2
183
+ fi
184
+ ln -sfn "$claude_target" "$claude"
185
+
186
+ printf 'brain: %s\n' "$brain"
187
+ printf 'CLAUDE.md -> %s\n' "$claude_target"
188
+ printf '.os/core -> %s\n' "$core"
189
+ for pack in "$product"/packs/*; do
190
+ [ -d "$pack" ] || continue
191
+ printf '.os/packs/%s -> %s\n' "$(basename "$pack")" "$pack"
192
+ done
193
+ for agent in "$core"/agents/*.md; do
194
+ [ -f "$agent" ] || continue
195
+ printf '.claude/agents/%s -> %s\n' "$(basename "$agent")" "$agent"
196
+ done
197
+
198
+ # ---------------------------------------------------------------- lectura liviana del catálogo
199
+ # Sin `lib/`: el instalador es lo primero que se corre y no puede depender del layout de lo que
200
+ # instala. La usan el aviso del nombre anterior de la carpeta y la línea de versión, más abajo.
201
+ catalogo_linea() {
202
+ local key="$1" lang="$2" file="$core/templates/strings.md" line dentro=0 valor=""
203
+ [ -f "$file" ] || return 0
204
+ while IFS= read -r line || [ -n "$line" ]; do
205
+ case "$line" in
206
+ "key: $key") dentro=1; continue ;;
207
+ 'key: '*) [ "$dentro" = "1" ] && break; continue ;;
208
+ esac
209
+ [ "$dentro" = "1" ] || continue
210
+ case "$line" in
211
+ "$lang: "*) valor="${line#$lang: }"; break ;;
212
+ 'en: '*) [ -n "$valor" ] || valor="${line#en: }" ;;
213
+ esac
214
+ done < "$file"
215
+ printf '%s' "$valor"
216
+ }
217
+
218
+ # ---------------------------------------------------------------- aviso del nombre anterior (P6, spec 039)
219
+ # Un brain con la carpeta de espacios de trabajo todavía en su nombre anterior sigue funcionando
220
+ # igual: esto avisa una vez, sin tocar nada — adoptar el nombre actual es `rename-workspaces`, a
221
+ # pedido del operador. Con las dos carpetas a la vez el layout es inválido y lo declara cualquier
222
+ # otro comando que lea o escriba el brain; el instalador no valida layout, solo avisa del caso simple.
223
+ if [ -d "$brain/orgs" ] && [ ! -d "$brain/workspaces" ]; then
224
+ formato=$(catalogo_linea INSTALL_WS_OLD_NAME "$lang")
225
+ [ -n "$formato" ] && printf '%s\n' "$formato"
226
+ fi
227
+
228
+ # ---------------------------------------------------------------- la versión que quedó instalada
229
+ # Última línea: el nombre del producto y la versión de `core/VERSION` (spec 038). El texto sale del
230
+ # catálogo (`core/templates/strings.md`, clave `INSTALL_VERSION_LINE`), nunca escrito acá: hasta el
231
+ # rename, el nombre que viaja adentro del producto vive en una clave y cambiarlo es un cambio de
232
+ # catálogo. Sin VERSION o sin la clave, no hay línea.
233
+ version=""
234
+ [ -f "$core/VERSION" ] && { IFS= read -r version < "$core/VERSION" || true; }
235
+ # Mismo saneo que `os_version` en `lib/common.sh`: un `\r` de fin de línea o un espacio de más en el
236
+ # archivo haría que el instalador imprima una versión y el barrido otra.
237
+ version="${version%$'\r'}"
238
+ while [ "${version# }" != "$version" ]; do version="${version# }"; done
239
+ while [ "${version% }" != "$version" ]; do version="${version% }"; done
240
+ if [ -n "$version" ]; then
241
+ formato=$(catalogo_linea INSTALL_VERSION_LINE "$lang")
242
+ [ -n "$formato" ] && printf "$formato\n" "$version"
243
+ fi
@@ -0,0 +1,347 @@
1
+ #!/usr/bin/env bash
2
+ # The command behind the rule that `core/CLAUDE.md` states about `archive/` (spec 048). Internal: not
3
+ # invocable — the invocable is `skills/archive.md`. The rule itself is not restated here.
4
+ #
5
+ # Usage: archive.sh --brain DIR --file PATH [--file PATH …]
6
+ # archive.sh --brain DIR --file PATH [--file PATH …] --unarchive --to FOLDER
7
+ # archive.sh --brain DIR --stale
8
+ #
9
+ # WHY A FOLDER, AND NOT A KEY. A frontmatter key that leaves the file where it is forces every read
10
+ # to open every document to learn whether it loads it, and that is exactly the property this system
11
+ # sells: what gets read is decided without opening anything. The folder is the answer, the same way
12
+ # the folder is what gives a node its type. It is PARA's Archive.
13
+ #
14
+ # WHAT ARCHIVING CHANGES, AND WHAT IT DOES NOT. It changes what a read **loads**: `focus-read.sh`
15
+ # prints the names of what an `archive:` line reaches and opens none of them. It changes nothing
16
+ # else — `supersede --check` still audits the file, `recall` still searches inside it, and the
17
+ # startup scan still counts it as reached. A document that stopped being loaded and also stopped
18
+ # being findable is a document that was lost, not archived.
19
+ #
20
+ # THE FILE IS MOVED, NEVER REWRITTEN. Same bytes, same name, same date in the name. `git mv` in a
21
+ # git brain — so the index records a rename and the history follows the file — and `mv -n` otherwise,
22
+ # never one that overwrites.
23
+ #
24
+ # THE ORDER, AND WHY IT IS THIS ONE (the same as `rename-heads.sh`):
25
+ #
26
+ # 1. The plan. Every `--file` is checked and its destination computed **before one byte moves**.
27
+ # One file that fails a precondition cancels the whole batch: a half-applied batch whose
28
+ # references were never rewritten is a brain that points at files that are not there, and the
29
+ # operator would have to reconstruct by hand which half went through.
30
+ # 2. The moves, in the order of the plan.
31
+ # 3. The rewriting of references, once, with the map of everything that moved. Running it per file
32
+ # would leave a reference pointing at a file that a later move takes away again.
33
+ #
34
+ # A MOVE THAT FAILS AFTER THE PLAN STOPS THE BATCH; IT DOES NOT ROLL IT BACK. A rollback is a second
35
+ # write path that can itself fail, and a failed rollback leaves a state nobody planned for. What
36
+ # stopping leaves is a state that re-running the same command finishes: the files that moved are
37
+ # already in `archive/` and their references already point there, and the ones that did not are
38
+ # exactly where they were.
39
+ #
40
+ # `superseded_by:` GETS NO SPECIAL CASE. Its value is a path, the rewrite is over paths, and the one
41
+ # walk covers both directions — the mark written **on** the file that moved, and the mark on another
42
+ # file that **names** it. A file whose `superseded_by:` names another file in the same batch resolves
43
+ # because the rewrite runs after every move, over the full map.
44
+ #
45
+ # `--stale` IS THE ONLY THING THAT SUGGESTS ANYTHING, AND IT IS NOT AGE. It lists the files that
46
+ # carry a `superseded_by:` and are not reached by an `archive:` line — documents the brain itself
47
+ # already declared out of date and still keeps in the loaded set. Age is not staleness: a brief from
48
+ # July can be the most current document a node has. The startup scan gains no line for this: it reads
49
+ # the frontmatter of heads and never opens a content file (spec 045 decision 1, spec 046), so a line
50
+ # there would count half the files and present it as a check.
51
+ #
52
+ # Exit: 0 moved, or nothing to do · 1 invalid arguments, a refusal, or `--stale` with findings ·
53
+ # 2 a named file does not exist · 3 the batch stopped part-way through the moves.
54
+ #
55
+ # No `set -e`: a refusal is reported, never a stack trace.
56
+
57
+ set -u
58
+
59
+ here=$(cd "$(dirname "$0")" && pwd)
60
+ . "$here/common.sh"
61
+
62
+ nl=$(printf '\nx')
63
+ nl="${nl%x}"
64
+
65
+ # The name of the folder. One word, written once: the tree lines of `templates/tree.md`, the
66
+ # destination this command computes and the listing of `focus-read.sh` all mean this folder.
67
+ ARCHIVE_DIR="archive"
68
+
69
+ brain=""
70
+ files=""
71
+ unarchive=0
72
+ to=""
73
+ stale=0
74
+
75
+ while [ $# -gt 0 ]; do
76
+ case "$1" in
77
+ --brain) [ $# -ge 2 ] || os_die "--brain needs a value"; brain="$2"; shift 2 ;;
78
+ --file) [ $# -ge 2 ] || os_die "--file needs a value"; files="$files$2$nl"; shift 2 ;;
79
+ --to) [ $# -ge 2 ] || os_die "--to needs a value"; to="$2"; shift 2 ;;
80
+ --unarchive) unarchive=1; shift ;;
81
+ --stale) stale=1; shift ;;
82
+ *) os_die "unknown argument: $1" ;;
83
+ esac
84
+ done
85
+
86
+ [ -n "$brain" ] || os_die "missing --brain"
87
+ [ -d "$brain" ] || os_die "no such brain: $brain"
88
+ brain=$(cd "$brain" && pwd)
89
+
90
+ if [ "$stale" = "1" ]; then
91
+ [ -z "$files" ] || os_die "--stale takes no --file"
92
+ [ "$unarchive" = "0" ] || os_die "--stale and --unarchive are two different questions"
93
+ else
94
+ [ -n "$files" ] || os_die "missing --file"
95
+ fi
96
+ if [ "$unarchive" = "1" ]; then
97
+ # The folder a document came from is recorded nowhere — the move keeps the bytes and the name, and
98
+ # nothing else. Guessing `research/` because most of them came from there is inventing a fact.
99
+ [ -n "$to" ] || os_die "--unarchive needs --to <folder>: the folder a document came from is not recorded anywhere"
100
+ case "$to" in
101
+ */*|.|..|"$ARCHIVE_DIR") os_die "--to takes one folder name inside the node, and it is not $ARCHIVE_DIR" ;;
102
+ esac
103
+ else
104
+ [ -z "$to" ] || os_die "--to is only for --unarchive"
105
+ fi
106
+
107
+ os_ws_check "$brain"
108
+ lang=$(os_language "$brain")
109
+ os_lang_load "$lang"
110
+
111
+ # The three classes of the tree, from the one reader of the format.
112
+ heads=$(os_tree_files "$brain") || os_die "no tree.md to read in: $brain"
113
+ contents=$(os_tree_content_files "$brain") || os_die "no tree.md to read in: $brain"
114
+ archived=$(os_tree_archive_files "$brain") || archived=""
115
+
116
+ en_lista() {
117
+ # en_lista RUTA LISTA
118
+ case "$nl$2$nl" in *"$nl$1$nl"*) return 0 ;; esac
119
+ return 1
120
+ }
121
+
122
+ alcanzado() {
123
+ en_lista "$1" "$heads" && return 0
124
+ en_lista "$1" "$contents" && return 0
125
+ en_lista "$1" "$archived" && return 0
126
+ return 1
127
+ }
128
+
129
+ head_file=$(os_head_file "$brain") || head_file="README.md"
130
+
131
+ # nodo_de CARPETA -> the nearest folder at or above CARPETA that holds a head, by stdout; empty if
132
+ # there is none. Walking up instead of counting slashes is what makes one command serve an
133
+ # initiative —whose documents sit in its own folder— and a product —whose documents sit one level
134
+ # down, in `research/` or `context/`— without either of them being a special case.
135
+ nodo_de() {
136
+ local d="$1"
137
+ while [ -n "$d" ] && [ "$d" != "." ]; do
138
+ if en_lista "$d/$head_file" "$heads"; then printf '%s' "$d"; return 0; fi
139
+ case "$d" in
140
+ */*) d="${d%/*}" ;;
141
+ *) d="" ;;
142
+ esac
143
+ done
144
+ return 1
145
+ }
146
+
147
+ # ================================================================ --stale
148
+ # Writes nothing. Exits non-zero with findings, the shape of `supersede --check`, so it can hang off
149
+ # anything that reads an exit code.
150
+ if [ "$stale" = "1" ]; then
151
+ n=0
152
+ vistos="$nl"
153
+ todos="$heads$nl$contents"
154
+ while IFS= read -r f || [ -n "$f" ]; do
155
+ [ -n "$f" ] || continue
156
+ case "$vistos" in *"$nl$f$nl"*) continue ;; esac
157
+ vistos="$vistos$f$nl"
158
+ en_lista "$f" "$archived" && continue
159
+ fm_read "$brain/$f"
160
+ [ -n "$fm_superseded_by" ] || continue
161
+ printf "$S_ARCHIVE_STALE_ROW\n" "$f" "$fm_superseded_by"
162
+ n=$(( n + 1 ))
163
+ done <<TODOS
164
+ $todos
165
+ TODOS
166
+ if [ "$n" = "0" ]; then
167
+ printf "$S_ARCHIVE_STALE_NONE\n"
168
+ exit 0
169
+ fi
170
+ printf "$S_ARCHIVE_STALE_TOTAL\n" "$n"
171
+ exit 1
172
+ fi
173
+
174
+ # ================================================================ (1) the plan
175
+ # Nothing below this point writes anything until the whole batch has passed. A refusal names the file
176
+ # and the reason, and the command exits without having touched the brain.
177
+ plan=""
178
+ destinos="$nl"
179
+ origenes="$nl"
180
+ rechazos=""
181
+ falta=0
182
+
183
+ rechazar() {
184
+ rechazos="$rechazos$(printf "$S_ARCHIVE_REFUSED" "$1" "$2")$nl"
185
+ }
186
+
187
+ while IFS= read -r raw || [ -n "$raw" ]; do
188
+ [ -n "$raw" ] || continue
189
+
190
+ # The spelling of a path is not a way around the checks (spec 047): `./d/a.md`, `d//a.md` and
191
+ # `d/a.md` are the same file here, and the plan is always built on the normalised form.
192
+ f=$(os_rel_norm "$raw")
193
+ if ! os_rel_ok "$f"; then rechazar "$raw" "$S_ARCHIVE_NOT_RELATIVE"; continue; fi
194
+ case "$f" in
195
+ *.md) ;;
196
+ *) rechazar "$f" "$S_ARCHIVE_NOT_MD"; continue ;;
197
+ esac
198
+ # A file that is not there is said to be not there. `os_inside_brain` resolves the parent folder
199
+ # and fails when it does not exist, so asking it first turns every typo into "resolves outside the
200
+ # brain" — a refusal that sends the operator looking for a symlink that was never there. `..` and
201
+ # an absolute path are already refused above, by `os_rel_ok`.
202
+ if [ -L "$brain/$f" ]; then rechazar "$f" "$S_ARCHIVE_IS_A_LINK"; continue; fi
203
+ if [ ! -f "$brain/$f" ]; then rechazar "$f" "$S_ARCHIVE_NOT_THERE"; falta=1; continue; fi
204
+ if ! os_inside_brain "$brain" "$f"; then rechazar "$f" "$S_ARCHIVE_OUT_OF_BRAIN"; continue; fi
205
+ if ! alcanzado "$f"; then rechazar "$f" "$S_ARCHIVE_NOT_IN_TREE"; continue; fi
206
+ case "$origenes" in *"$nl$f$nl"*) rechazar "$f" "$S_ARCHIVE_TWICE"; continue ;; esac
207
+
208
+ # Which node owns this file. It is not derivable from how deep the path is: an initiative keeps
209
+ # its documents directly in its own folder (`<node>/x.md`) and a product keeps them one level
210
+ # down (`<node>/research/x.md`). The node is the nearest folder above the file that holds a head
211
+ # a `glob:` line reaches — the same definition of "node" the rest of the system uses, read again
212
+ # instead of a second rule about depth.
213
+ carpeta="${f%/*}"
214
+ base="${f##*/}"
215
+ nodo=$(nodo_de "$carpeta")
216
+ if [ -z "$nodo" ]; then rechazar "$f" "$S_ARCHIVE_NOT_IN_A_NODE"; continue; fi
217
+
218
+ if [ "$unarchive" = "1" ]; then
219
+ if [ "$carpeta" != "$nodo/$ARCHIVE_DIR" ]; then rechazar "$f" "$S_ARCHIVE_NOT_ARCHIVED"; continue; fi
220
+ destino="$nodo/$to/$base"
221
+ else
222
+ if [ "$carpeta" = "$nodo/$ARCHIVE_DIR" ]; then rechazar "$f" "$S_ARCHIVE_ALREADY"; continue; fi
223
+ destino="$nodo/$ARCHIVE_DIR/$base"
224
+ fi
225
+
226
+ if [ -e "$brain/$destino" ]; then rechazar "$f" "$(printf "$S_ARCHIVE_DEST_TAKEN" "$destino")"; continue; fi
227
+ case "$destinos" in *"$nl$destino$nl"*) rechazar "$f" "$(printf "$S_ARCHIVE_DEST_TAKEN" "$destino")"; continue ;; esac
228
+
229
+ # The destination has to be a path the tree reaches, in the right class. Archiving into a folder no
230
+ # `archive:` line reaches produces a document invisible to `supersede --check` and to `recall`: the
231
+ # mark of vigency would be a promise nobody keeps (spec 047). Unarchiving into a folder no
232
+ # `content:` line reaches is the same hole in the other direction.
233
+ if [ "$unarchive" = "1" ]; then
234
+ if ! os_tree_class_matches "$brain" "content" "$destino"; then
235
+ rechazar "$f" "$(printf "$S_ARCHIVE_DEST_NOT_CONTENT" "$destino")"; continue
236
+ fi
237
+ else
238
+ if ! os_tree_class_matches "$brain" "archive" "$destino"; then
239
+ rechazar "$f" "$(printf "$S_ARCHIVE_DEST_NOT_ARCHIVE" "$destino")"; continue
240
+ fi
241
+ fi
242
+
243
+ origenes="$origenes$f$nl"
244
+ destinos="$destinos$destino$nl"
245
+ plan="$plan$f$OS_SEP$destino$nl"
246
+ done <<ARCHIVOS
247
+ $files
248
+ ARCHIVOS
249
+
250
+ if [ -n "$rechazos" ]; then
251
+ printf '%s' "$rechazos" >&2
252
+ printf "$S_ARCHIVE_NOTHING_MOVED\n" >&2
253
+ [ "$falta" = "1" ] && exit 2
254
+ exit 1
255
+ fi
256
+
257
+ if [ -z "$plan" ]; then
258
+ printf "$S_ARCHIVE_NOTHING_TO_DO\n"
259
+ exit 0
260
+ fi
261
+
262
+ # ================================================================ (2) the moves
263
+ es_git=0
264
+ [ -d "$brain/.git" ] && es_git=1
265
+
266
+ mover() {
267
+ if [ "$es_git" = "1" ]; then
268
+ git -C "$brain" mv "$1" "$2" > /dev/null 2>&1 && return 0
269
+ fi
270
+ mv -n "$brain/$1" "$brain/$2" 2>/dev/null || return 1
271
+ [ -e "$brain/$1" ] && return 1
272
+ [ -e "$brain/$2" ] || return 1
273
+ return 0
274
+ }
275
+
276
+ mapa=""
277
+ movidos=""
278
+ no_movidos=""
279
+ corte=0
280
+
281
+ while IFS= read -r registro || [ -n "$registro" ]; do
282
+ [ -n "$registro" ] || continue
283
+ origen="${registro%%$OS_SEP*}"
284
+ destino="${registro#*$OS_SEP}"
285
+ if [ "$corte" = "1" ]; then
286
+ no_movidos="$no_movidos $origen$nl"
287
+ continue
288
+ fi
289
+ if ! mkdir -p "$brain/${destino%/*}" 2>/dev/null; then
290
+ corte=1; no_movidos="$no_movidos $origen$nl"; continue
291
+ fi
292
+ if ! mover "$origen" "$destino"; then
293
+ corte=1; no_movidos="$no_movidos $origen$nl"; continue
294
+ fi
295
+ mapa="$mapa$origen$OS_SEP$destino$nl"
296
+ movidos="$movidos $origen -> $destino$nl"
297
+ done <<PLAN
298
+ $plan
299
+ PLAN
300
+
301
+ # ================================================================ (3) the rewriting of references
302
+ # Once, with the full map. The rule —an exact token match, never by suffix; a bare name with no
303
+ # slash is never resolved against the folder— lives in `common.sh` and is shared with
304
+ # `rename-heads.sh`.
305
+ #
306
+ # The targets are every file the tree reaches, in all three classes: a reference to a research
307
+ # document lives in a resolver, in a decision, in another research document, and in an archived one.
308
+ # The list is what the tree says, never a hardcoded set — a hardcoded set is a reference this command
309
+ # silently leaves broken the day somebody adds a height.
310
+ reescritos=""
311
+ if [ -n "$mapa" ]; then
312
+ OS_RW_MAP="$mapa"
313
+ vistos="$nl"
314
+ while IFS= read -r rel || [ -n "$rel" ]; do
315
+ [ -n "$rel" ] || continue
316
+ case "$vistos" in *"$nl$rel$nl"*) continue ;; esac
317
+ vistos="$vistos$rel$nl"
318
+ os_rw_file "$brain" "$rel"; rc_rw=$?
319
+ case "$rc_rw" in
320
+ 0) reescritos="$reescritos $rel$nl" ;;
321
+ 2) printf "$S_ARCHIVE_REWRITE_FAILED\n" "$rel" >&2; corte=1 ;;
322
+ esac
323
+ done <<OBJETIVOS
324
+ $heads
325
+ $contents
326
+ $archived
327
+ $destinos
328
+ OBJETIVOS
329
+ fi
330
+
331
+ # ================================================================ what happened
332
+ if [ -n "$movidos" ]; then
333
+ if [ "$unarchive" = "1" ]; then printf "$S_ARCHIVE_UNARCHIVED\n"; else printf "$S_ARCHIVE_ARCHIVED\n"; fi
334
+ printf '%s' "$movidos"
335
+ fi
336
+ if [ -n "$reescritos" ]; then
337
+ printf "$S_ARCHIVE_REWROTE\n"
338
+ printf '%s' "$reescritos"
339
+ fi
340
+ if [ -n "$no_movidos" ]; then
341
+ printf "$S_ARCHIVE_STOPPED\n" >&2
342
+ printf '%s' "$no_movidos" >&2
343
+ fi
344
+
345
+ # The brain is not committed here: the session commits, like everything else it writes.
346
+ [ "$corte" = "1" ] && exit 3
347
+ exit 0