ai-first-os 1.10.1 → 2.1.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 (62) hide show
  1. package/README.md +33 -31
  2. package/core/CLAUDE.md +49 -12
  3. package/core/VERSION +1 -1
  4. package/core/install.sh +173 -52
  5. package/core/lib/bootstrap.sh +41 -26
  6. package/core/lib/build-indexes.sh +639 -0
  7. package/core/lib/capture.sh +126 -55
  8. package/core/lib/check-resolvable.sh +13 -2
  9. package/core/lib/close-session.sh +172 -119
  10. package/core/lib/common.sh +569 -92
  11. package/core/lib/focus-read.sh +153 -61
  12. package/core/lib/manual-link.sh +10 -8
  13. package/core/lib/markdown.py +2 -2
  14. package/core/lib/migrate-layout.sh +92 -0
  15. package/core/lib/migrate-root.sh +497 -0
  16. package/core/lib/migrate_layout.py +2000 -0
  17. package/core/lib/new-memory.sh +33 -44
  18. package/core/lib/new-product.sh +11 -13
  19. package/core/lib/new-workspace.sh +18 -9
  20. package/core/lib/orchestrator-init.sh +80 -0
  21. package/core/lib/pack-install.sh +44 -30
  22. package/core/lib/recall.sh +1 -1
  23. package/core/lib/recall_index.py +48 -6
  24. package/core/lib/remote-backup.sh +30 -20
  25. package/core/lib/rename-heads.sh +8 -8
  26. package/core/lib/rename-workspaces.sh +3 -3
  27. package/core/lib/session-read.sh +133 -73
  28. package/core/lib/session-start.sh +236 -222
  29. package/core/lib/supersede.sh +199 -3
  30. package/core/lib/sweep.sh +5 -0
  31. package/core/manual/COMO-FUNCIONA.md +186 -67
  32. package/core/manual/HOW-IT-WORKS.md +176 -67
  33. package/core/resolver.md +4 -2
  34. package/core/skills/bootstrap.md +63 -44
  35. package/core/skills/capture.md +15 -8
  36. package/core/skills/check-resolvable.md +1 -1
  37. package/core/skills/close-session.md +9 -5
  38. package/core/skills/grill.md +3 -3
  39. package/core/skills/migrate-layout.md +48 -0
  40. package/core/skills/migrate-root.md +64 -0
  41. package/core/skills/mount-repo.md +6 -6
  42. package/core/skills/new-memory.md +20 -18
  43. package/core/skills/new-product.md +4 -3
  44. package/core/skills/new-spec.md +6 -0
  45. package/core/skills/new-workspace.md +7 -5
  46. package/core/skills/orchestrator.md +101 -0
  47. package/core/skills/supersede.md +14 -0
  48. package/core/templates/node-repo/context/open-questions.md +3 -0
  49. package/core/templates/operator.md +1 -1
  50. package/core/templates/strings.md +561 -284
  51. package/core/templates/tree.md +22 -27
  52. package/core/templates/voice.md +1 -1
  53. package/package.json +1 -1
  54. package/core/lib/my-wiki-gates.sh +0 -137
  55. package/core/lib/my-wiki.sh +0 -202
  56. package/core/lib/my_wiki_build.py +0 -548
  57. package/core/lib/my_wiki_graph.py +0 -137
  58. package/core/lib/my_wiki_overview.py +0 -392
  59. package/core/skills/my-wiki.md +0 -103
  60. package/core/templates/my-wiki-graph.js +0 -431
  61. package/core/templates/my-wiki-overview.js +0 -174
  62. package/core/templates/my-wiki.html +0 -1017
@@ -0,0 +1,639 @@
1
+ #!/usr/bin/env bash
2
+ # Generates the indexes of one workspace (spec 076, C18). Internal: not invocable — the startup read
3
+ # (`session-read.sh`) runs it on every read; the startup scan never does, because the scan never
4
+ # writes (spec 072).
5
+ #
6
+ # Usage: build-indexes.sh --brain DIR --workspace SLUG
7
+ #
8
+ # What it writes, all of it derived and none of it edited by a person:
9
+ # - `<ws>/decisions/index.md` — every decision of the workspace, newest `date:` first.
10
+ # - `<ws>/learnings/index.md` — every learning of the workspace, the same way.
11
+ # - `<node>/index.md` — at the root of every area node (a product, a course, a channel, an account) of
12
+ # the workspace (spec 078, C1), whether or not anything names it. Spec 079 gives it, in this order: a
13
+ # title and a line that say what it is (C3); the marker `<!-- os:focus-start -->`; Initiatives in
14
+ # progress (a table: initiative linked to its `README.md` · status · horizon · tasks linked to its
15
+ # `backlog.md` with the open count; C1, C6, C9, C11); the marker `<!-- os:focus-end -->`; Closed
16
+ # initiatives (the same table); and then Key decisions and Other decisions (two tables), Learnings and
17
+ # Documents, each a table (C12). A node with nothing to list (no initiative, decision or learning about it,
18
+ # no document of its own) has no index, and a generated one it had is deleted (C13).
19
+ # The focus read prints only what is between the two markers (C4).
20
+ # Spec 079 (C10) takes out what spec 078 wrote for an initiative: no `<initiative>/index.md` is written
21
+ # any more, and every generated one found in the workspace is deleted, with its own `.gitignore` line.
22
+ # The workspace itself has no `index.md` (Gate 1, P4): its folders already show its initiatives,
23
+ # decisions and learnings.
24
+ #
25
+ # Every link is relative to the index. A decision or learning line of `decisions/index.md` and
26
+ # `learnings/index.md` is `os_doc_index_line` (common.sh), the one place that knows that shape. Every file
27
+ # opens with `generated: true` in its frontmatter, then a `# Title` and a line that say what it is, then the
28
+ # three-line warning of D8, in the language of the brain; the third line names where that index comes from.
29
+ #
30
+ # Rules, each in its one place here:
31
+ # - Content unchanged, file untouched: the comparison is against the bytes on disk, so a second read
32
+ # keeps the `mtime`, and a hand edit of a generated index is gone on the next read.
33
+ # - An `index.md` that exists without `generated: true` was written by a person: it is skipped,
34
+ # never overwritten (the scan names it as a finding).
35
+ # - Before a path is written its entry goes to the brain's `.gitignore`: that exact path anchored at
36
+ # the root (`/<path>`), its pattern characters escaped — never a pattern that could reach an
37
+ # `index.md` a person wrote — and the line `gitignore-declared: <path>` is printed. If the entry
38
+ # cannot be written, `gitignore-declare-failed: <path>` is printed and the index is not written.
39
+ # The session contract (`core/CLAUDE.md`) says what the session does with either.
40
+ # - The reverse, for the initiative indexes of spec 078 (spec 079, C10): a generated
41
+ # `<initiative>/index.md` is deleted, and only the exact `.gitignore` line that spec wrote for it is
42
+ # dropped, with the same `gitignore-declared: <path>` line so the session commits the `.gitignore`.
43
+ # One written by a person stays untouched and keeps its line.
44
+ #
45
+ # Deterministic and offline: it reads frontmatter and first titles, nothing else. Exit 0 always —
46
+ # an index that cannot be written never stops the read that called it.
47
+
48
+ set -u
49
+
50
+ here=$(cd "$(dirname "$0")" && pwd)
51
+ . "$here/common.sh"
52
+
53
+ nl=$(printf '\nx')
54
+ nl="${nl%x}"
55
+ tab=$(printf '\tx'); tab="${tab%x}"
56
+
57
+ brain=""
58
+ ws_slug=""
59
+ while [ $# -gt 0 ]; do
60
+ case "$1" in
61
+ --brain) [ $# -ge 2 ] || os_die "--brain needs a value"; brain="$2"; shift 2 ;;
62
+ --workspace) [ $# -ge 2 ] || os_die "--workspace needs a value"; ws_slug="$2"; shift 2 ;;
63
+ *) os_die "unknown argument: $1" ;;
64
+ esac
65
+ done
66
+ [ -n "$brain" ] || os_die "missing --brain"
67
+ [ -n "$ws_slug" ] || os_die "missing --workspace"
68
+ [ -d "$brain" ] || os_die "no such brain: $brain"
69
+ brain=$(cd "$brain" && pwd)
70
+
71
+ os_ws_check "$brain"
72
+ wsdir=$(os_ws_dir "$brain")
73
+ head=$(os_head_file "$brain") || true
74
+ os_org_existe "$brain" "$ws_slug" || exit 0
75
+ ws="$wsdir/$ws_slug"
76
+
77
+ os_lang_load "$(os_language "$brain")"
78
+
79
+ heads=$(os_tree_files "$brain" 2>/dev/null) || heads=""
80
+
81
+ # ---------------------------------------------------------------- the documents, read once
82
+ # Each decision and learning is read once into these arrays; every index is then built from them with
83
+ # string work only. Decisions and learnings come newest first (`os_docs_sorted`).
84
+ d_n=0
85
+ leer_docs() {
86
+ # leer_docs KIND DIR — appends the documents of DIR to the arrays, tagged with KIND.
87
+ local kind="$1" dir="$2" rel
88
+ while IFS= read -r rel || [ -n "$rel" ]; do
89
+ [ -n "$rel" ] || continue
90
+ fm_read "$brain/$rel"
91
+ d_kind[$d_n]="$kind"
92
+ d_rel[$d_n]="$rel"
93
+ d_about[$d_n]="$(os_about_set "$fm_about")$nl"
94
+ d_n=$(( d_n + 1 ))
95
+ done <<DOCS
96
+ $(os_docs_sorted "$brain" "$dir")
97
+ DOCS
98
+ }
99
+ leer_docs decision "$ws/decisions"
100
+ leer_docs learning "$ws/learnings"
101
+
102
+ # The initiatives of the workspace: the heads a `glob:` line reaches, by kind (spec 056), by path.
103
+ i_n=0
104
+ while IFS= read -r f || [ -n "$f" ]; do
105
+ [ -n "$f" ] || continue
106
+ case "$f" in "$ws"/initiatives/*) ;; *) continue ;; esac
107
+ case "$(os_head_kind "$wsdir" "$head" "$f")" in
108
+ "initiative $ws_slug") ;;
109
+ *) continue ;;
110
+ esac
111
+ fm_read "$brain/$f"
112
+ i_rel[$i_n]="$f"
113
+ i_about[$i_n]="$(os_about_set "$fm_about")$nl"
114
+ i_status[$i_n]="${fm_status//[[:cntrl:]]/ }"
115
+ i_horizon[$i_n]="${fm_horizon//[[:cntrl:]]/ }"
116
+ t=$(os_titulo "$brain/$f")
117
+ [ -n "$t" ] || t=$(os_node_name "$f")
118
+ i_title[$i_n]="${t//[[:cntrl:]]/ }"
119
+ # The open tasks (spec 079, C6): the unindented `- [ ] ` lines of the `backlog.md` that sits beside the
120
+ # head of an initiative with a folder of its own. Empty when there is no such backlog.
121
+ i_bl[$i_n]=""
122
+ i_blrel[$i_n]=""
123
+ idir="${f%/*}"
124
+ if [ "${f##*/}" = "$head" ] && [ "${idir%/*}" = "$ws/initiatives" ] && [ -f "$brain/$idir/backlog.md" ]; then
125
+ i_blrel[$i_n]="$idir/backlog.md"
126
+ i_bl[$i_n]=$(grep -c '^- \[ \] ' "$brain/$idir/backlog.md" 2>/dev/null) || true
127
+ [ -n "${i_bl[$i_n]}" ] || i_bl[$i_n]=0
128
+ fi
129
+ i_n=$(( i_n + 1 ))
130
+ done <<HEADS
131
+ $(printf '%s\n' "$heads" | LC_ALL=C sort -u)
132
+ HEADS
133
+
134
+ # ---------------------------------------------------------------- writing one index
135
+ # The `.gitignore` of the brain is read once: an unchanged index costs a string match, never a pass
136
+ # over the file. A missing entry is appended (with the newline the file may lack) and read back.
137
+ ignorados="$nl"
138
+ [ -f "$brain/.gitignore" ] && ignorados="$nl$(cat "$brain/.gitignore")$nl"
139
+
140
+ # ignorar_patron REL -> the exact `.gitignore` line for REL: anchored at the root, and with every
141
+ # character git reads as a pattern (`\ * ? [ ]`) escaped — the leading `/` keeps `!` and `#` literal — so a node folder
142
+ # named like `item[ab]` is still that one path and nothing else.
143
+ ignorar_patron() {
144
+ local r="$1" out="" c
145
+ while [ -n "$r" ]; do
146
+ c="${r%"${r#?}"}"; r="${r#?}"
147
+ case "$c" in
148
+ '\'|'*'|'?'|'['|']') out="$out\\$c" ;;
149
+ *) out="$out$c" ;;
150
+ esac
151
+ done
152
+ printf '/%s' "$out"
153
+ }
154
+
155
+ # declarar_ignorado REL -> 0 when REL is in `.gitignore` (already, or appended now and read back); the
156
+ # marker `gitignore-declared:` only for a line written now. 1 when the line could not be written.
157
+ declarar_ignorado() {
158
+ local linea
159
+ linea=$(ignorar_patron "$1")
160
+ case "$ignorados" in *"$nl$linea$nl"*) return 0 ;; esac
161
+ if [ -s "$brain/.gitignore" ] && [ -n "$(tail -c 1 "$brain/.gitignore")" ]; then
162
+ printf '\n' >> "$brain/.gitignore" 2>/dev/null || return 1
163
+ fi
164
+ printf '%s\n' "$linea" >> "$brain/.gitignore" 2>/dev/null || return 1
165
+ grep -qxF -- "$linea" "$brain/.gitignore" 2>/dev/null || return 1
166
+ ignorados="$ignorados$linea$nl"
167
+ printf 'gitignore-declared: %s\n' "$1"
168
+ return 0
169
+ }
170
+
171
+ # retirar_indices_de_iniciativa — spec 079, C10: the initiative indexes of spec 078 are gone. Every
172
+ # `<ws>/initiatives/<slug>/index.md` with `generated: true` is deleted; one without it was written by a
173
+ # person and stays. The `.gitignore` loses the exact line that spec wrote for each index that is deleted or
174
+ # already absent (never a line for a hand-written one, and never any other line), written back with every
175
+ # other byte as it was, and `gitignore-declared: <path>` is printed for each line dropped.
176
+ retirar_indices_de_iniciativa() {
177
+ local d rel quitar="" lineas=""
178
+ for d in "$brain/$ws"/initiatives/*/; do
179
+ # A folder that is a link, or resolves outside the brain, is never entered: nothing is read or deleted there.
180
+ [ -d "$d" ] && [ ! -L "${d%/}" ] || continue
181
+ rel="${d#"$brain"/}"
182
+ rel="${rel%/}/index.md"
183
+ os_inside_brain "$brain" "$rel" || continue
184
+ if [ -e "$brain/$rel" ] || [ -L "$brain/$rel" ]; then
185
+ [ ! -L "$brain/$rel" ] || continue
186
+ fm_read "$brain/$rel"
187
+ [ "$fm_generated" = "true" ] || continue
188
+ rm -f "$brain/$rel" 2>/dev/null || continue
189
+ fi
190
+ quitar="$quitar$(ignorar_patron "$rel")$nl"
191
+ lineas="$lineas$rel$nl"
192
+ done
193
+ soltar_ignorados "$quitar" "$lineas"
194
+ }
195
+
196
+ # retirar_indice_de_nodo REL — spec 079, C13: a node with nothing to list has no index. A generated one left from
197
+ # before is deleted, with its `.gitignore` line; one written by a person stays untouched and keeps its line. The
198
+ # line is dropped also when the file is already gone (a failed cleanup of an earlier read is retried), and a
199
+ # `.gitignore` that cannot be written is reported by `soltar_ignorados`.
200
+ retirar_indice_de_nodo() {
201
+ local rel="$1"
202
+ if [ -e "$brain/$rel" ] || [ -L "$brain/$rel" ]; then
203
+ [ ! -L "$brain/$rel" ] || return 0
204
+ fm_read "$brain/$rel"
205
+ [ "$fm_generated" = "true" ] || return 0
206
+ rm -f "$brain/$rel" 2>/dev/null || return 0
207
+ fi
208
+ soltar_ignorados "$(ignorar_patron "$rel")$nl" "$rel$nl"
209
+ }
210
+
211
+ # soltar_ignorados QUITAR LINEAS — drops from the `.gitignore` the exact lines of QUITAR (one per line), writes
212
+ # it back with every other byte as it was (each kept line keeps its own terminator, an unterminated last line
213
+ # stays unterminated only when it is kept), and prints `gitignore-declared: <path>` for each path of LINEAS whose
214
+ # line was there. A file that cannot be written prints `gitignore-declare-failed: <path>` for each of them.
215
+ soltar_ignorados() {
216
+ local quitar="$1" lineas="$2" gi="$brain/.gitignore" orig out line tmp hubo rel ultima_ok=1 ok=1
217
+ [ -n "$quitar" ] && [ -f "$gi" ] || return 0
218
+ # Nothing to do when the lines read at the start are not there: the common case costs a string match.
219
+ hubo=0
220
+ while IFS= read -r line || [ -n "$line" ]; do
221
+ [ -n "$line" ] || continue
222
+ case "$ignorados" in *"$nl$line$nl"*) hubo=1; break ;; esac
223
+ done < <(printf '%s' "$quitar")
224
+ [ "$hubo" = "1" ] || return 0
225
+ orig=$(cat "$gi"; printf x); orig="${orig%x}"
226
+ out=""; hubo=0
227
+ while IFS= read -r line || [ -n "$line" ]; do
228
+ case "$nl$quitar" in *"$nl$line$nl"*) hubo=1; ultima_ok=0; continue ;; esac
229
+ out="$out$line$nl"; ultima_ok=1
230
+ done < <(printf '%s' "$orig")
231
+ [ "$hubo" = "1" ] || return 0
232
+ # The loop ends every line with a newline: a last line that had none keeps it that way, if it was kept.
233
+ case "$orig" in *"$nl") ;; *) [ "$ultima_ok" = "1" ] && out="${out%"$nl"}" ;; esac
234
+ tmp=$(mktemp "$gi.os-tmp.XXXXXX" 2>/dev/null) || ok=0
235
+ if [ "$ok" = "1" ]; then
236
+ printf '%s' "$out" > "$tmp" 2>/dev/null || { rm -f "$tmp"; ok=0; }
237
+ fi
238
+ [ "$ok" = "0" ] || os_replace_file "$tmp" "$gi" || ok=0
239
+ while IFS= read -r rel || [ -n "$rel" ]; do
240
+ [ -n "$rel" ] || continue
241
+ case "$nl$orig$nl" in
242
+ *"$nl$(ignorar_patron "$rel")$nl"*)
243
+ if [ "$ok" = "1" ]; then printf 'gitignore-declared: %s\n' "$rel"; else printf 'gitignore-declare-failed: %s\n' "$rel"; fi ;;
244
+ esac
245
+ done < <(printf '%s' "$lineas")
246
+ [ "$ok" = "0" ] || ignorados="$nl$out$nl"
247
+ return 0
248
+ }
249
+ retirar_indices_de_iniciativa
250
+
251
+ # escribir REL CONTENT — writes the generated file at REL when its bytes differ, unless a person wrote
252
+ # that file. The ignore entry goes first: an index is never published untracked-and-visible to git. A
253
+ # `.gitignore` that cannot be written is reported (`gitignore-declare-failed: <path>`) and the index is
254
+ # not written. The content goes to a temporary file of its own (`mktemp`), so two reads at once never
255
+ # publish each other's half-written file.
256
+ escribir() {
257
+ local rel="$1" content="$2" full="$brain/$1" tmp
258
+ if [ -e "$full" ]; then
259
+ fm_read "$full"
260
+ [ "$fm_generated" = "true" ] || return 0
261
+ fi
262
+ if ! declarar_ignorado "$rel"; then
263
+ printf 'gitignore-declare-failed: %s\n' "$rel"
264
+ return 0
265
+ fi
266
+ if [ -e "$full" ] && [ "$(cat "$full"; printf x)" = "$content${nl}x" ]; then
267
+ return 0
268
+ fi
269
+ mkdir -p "$(dirname "$full")" 2>/dev/null || return 0
270
+ tmp=$(mktemp "$full.os-tmp.XXXXXX" 2>/dev/null) || return 0
271
+ printf '%s\n' "$content" > "$tmp" 2>/dev/null || { rm -f "$tmp"; return 0; }
272
+ mv -f "$tmp" "$full" 2>/dev/null || { rm -f "$tmp"; return 0; }
273
+ return 0
274
+ }
275
+
276
+ # cabecera TITLE DESCRIPTION SOURCE_LINE — the frontmatter, the title that says what the file is, the line
277
+ # that says what is in it (spec 079, C3) and the three lines of D8.
278
+ cabecera() {
279
+ printf -- '---\ngenerated: true\n---\n\n# %s\n%s\n\n%s\n%s\n%s\n' \
280
+ "$1" "$2" "$S_INDEX_WARNING_TITLE" "$S_INDEX_WARNING_NOT_SAVED" "$3"
281
+ }
282
+
283
+ # titulo_de_cabeza REL FALLBACK -> the `# Title` of the head at REL, else FALLBACK (the name of its folder).
284
+ titulo_de_cabeza() {
285
+ local t=""
286
+ [ -f "$brain/$1" ] && t=$(os_titulo "$brain/$1")
287
+ [ -n "$t" ] || t="$2"
288
+ printf '%s' "$t"
289
+ }
290
+
291
+ # etiqueta_estado CODE / etiqueta_horizonte CODE -> the label of a `status:` / `horizon:` value in the
292
+ # language of the brain (spec 079, C11); any other value as written, escaped for a cell.
293
+ etiqueta_estado() {
294
+ case "$1" in
295
+ active) printf '%s' "$S_INDEX_STATUS_ACTIVE" ;;
296
+ ongoing) printf '%s' "$S_INDEX_STATUS_ONGOING" ;;
297
+ closed) printf '%s' "$S_INDEX_STATUS_CLOSED" ;;
298
+ blocked) printf '%s' "$S_INDEX_STATUS_BLOCKED" ;;
299
+ *) printf '%s' "$(md_cell "$1")" ;;
300
+ esac
301
+ }
302
+ etiqueta_horizonte() {
303
+ case "$1" in
304
+ now) printf '%s' "$S_INDEX_HORIZON_NOW" ;;
305
+ next) printf '%s' "$S_INDEX_HORIZON_NEXT" ;;
306
+ later) printf '%s' "$S_INDEX_HORIZON_LATER" ;;
307
+ *) printf '%s' "$(md_cell "$1")" ;;
308
+ esac
309
+ }
310
+
311
+ # celda_tareas I FROM -> the Tasks cell of initiative I (spec 079, C1): the count of open tasks as the text of
312
+ # a link to its `backlog.md`; with no backlog, text and no link. The text and the destination are escaped
313
+ # apart, then joined.
314
+ celda_tareas() {
315
+ local i="$1" from="$2" texto
316
+ if [ -z "${i_blrel[$i]}" ]; then
317
+ printf '%s' "$(md_cell "$S_INDEX_TASKS_NO_BACKLOG")"
318
+ return 0
319
+ fi
320
+ case "${i_bl[$i]}" in
321
+ 0) texto="$S_INDEX_TASKS_NONE" ;;
322
+ 1) texto="$S_INDEX_TASKS_ONE" ;;
323
+ *) texto=$(printf "$S_INDEX_TASKS_MANY" "${i_bl[$i]}") ;;
324
+ esac
325
+ printf '[%s](%s)' "$(md_cell "$texto")" "$(md_dest "$(os_rel_link "$from" "${i_blrel[$i]}")")"
326
+ }
327
+
328
+ # linea_ini I FROM — the table row of initiative I, its title linked from the folder FROM to its head (spec 079,
329
+ # C1). Every cell and the link label are escaped and the destination encoded (`md_cell`, `md_dest`), so a row
330
+ # never splits and a link never breaks.
331
+ linea_ini() {
332
+ local i="$1" from="$2"
333
+ printf '| [%s](%s) | %s | %s | %s |' "$(md_cell "${i_title[$i]}")" "$(md_dest "$(os_rel_link "$from" "${i_rel[$i]}")")" \
334
+ "$(etiqueta_estado "${i_status[$i]}")" "$(etiqueta_horizonte "${i_horizon[$i]}")" "$(celda_tareas "$i" "$from")"
335
+ }
336
+
337
+ # ---------------------------------------------------------------- decisions/index.md, learnings/index.md
338
+ carpeta_index() {
339
+ # carpeta_index KIND FOLDER SOURCE_LINE TITLE DESCRIPTION
340
+ local kind="$1" folder="$2" source="$3" body="" i
341
+ i=0
342
+ while [ "$i" -lt "$d_n" ]; do
343
+ if [ "${d_kind[$i]}" = "$kind" ]; then
344
+ body="$body$(os_doc_index_line "$brain" "${d_rel[$i]}" "$folder")$nl"
345
+ fi
346
+ i=$(( i + 1 ))
347
+ done
348
+ [ -n "$body" ] || body="$S_INDEX_EMPTY$nl"
349
+ escribir "$folder/index.md" "$(cabecera "$4" "$5" "$source")$nl$nl${body%"$nl"}"
350
+ }
351
+ ws_title=$(titulo_de_cabeza "$ws/$head" "$ws_slug")
352
+ carpeta_index decision "$ws/decisions" "$S_INDEX_SOURCE_DECISIONS" "$(printf "$S_INDEX_DECISIONS_TITLE" "$ws_title")" "$S_INDEX_DECISIONS_DESC"
353
+ carpeta_index learning "$ws/learnings" "$S_INDEX_SOURCE_LEARNINGS" "$(printf "$S_INDEX_LEARNINGS_TITLE" "$ws_title")" "$S_INDEX_LEARNINGS_DESC"
354
+
355
+ # ---------------------------------------------------------------- the documents of an index (spec 078)
356
+ seccion() {
357
+ # seccion TITLE BODY — the heading and the body right under it, with no trailing newline; an empty body
358
+ # says there is nothing yet (a section with nothing in it has no table).
359
+ if [ -n "$2" ]; then
360
+ printf '## %s\n%s' "$1" "${2%"$nl"}"
361
+ else
362
+ printf '## %s\n%s' "$1" "$S_INDEX_EMPTY"
363
+ fi
364
+ }
365
+
366
+ # tabla HEADER_CELLS ROWS -> the table (header row, separator, rows), or nothing when there are no rows.
367
+ # HEADER_CELLS are the already-translated column names separated by a tab.
368
+ tabla() {
369
+ local cols="$1" rows="$2" h="" sep="" c
370
+ [ -n "$rows" ] || return 0
371
+ while IFS= read -r c || [ -n "$c" ]; do
372
+ h="$h $c |"
373
+ sep="$sep---|"
374
+ done <<COLS
375
+ ${cols//$tab/$nl}
376
+ COLS
377
+ printf '|%s%s|%s%s%s' "$h" "$nl" "$sep" "$nl" "${rows%"$nl"}"
378
+ }
379
+
380
+ # fecha_valida STR -> 0 when STR is a real day written `YYYY-MM-DD`. Anything else counts as no date.
381
+ fecha_valida() {
382
+ local d="$1" y m dd max
383
+ case "$d" in [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]) ;; *) return 1 ;; esac
384
+ y=$(( 10#${d:0:4} )); m=$(( 10#${d:5:2} )); dd=$(( 10#${d:8:2} ))
385
+ [ "$y" -ge 1 ] && [ "$m" -ge 1 ] && [ "$m" -le 12 ] && [ "$dd" -ge 1 ] || return 1
386
+ case "$m" in
387
+ 1|3|5|7|8|10|12) max=31 ;;
388
+ 4|6|9|11) max=30 ;;
389
+ *)
390
+ if [ $(( y % 400 )) -eq 0 ] || { [ $(( y % 4 )) -eq 0 ] && [ $(( y % 100 )) -ne 0 ]; }; then max=29; else max=28; fi
391
+ ;;
392
+ esac
393
+ [ "$dd" -le "$max" ]
394
+ }
395
+
396
+ # doc_record REL BASE FROM -> one record `sort-date TAB title TAB path TAB link TAB date` for the file at REL
397
+ # (relative to the brain). The date is the `date:` key of a `.md`, else the `YYYY-MM-DD` prefix of the file
398
+ # name; a value that is not a real day is no date (the fourth field is then empty), and no date sorts last. The
399
+ # title is `os_doc_title` for a `.md`, and the path relative to BASE for any other file. The link goes from the
400
+ # folder FROM.
401
+ doc_record() {
402
+ local rel="$1" base="$2" from="$3" name t d sd fecha
403
+ name="${rel##*/}"
404
+ d=""
405
+ case "$name" in
406
+ *.md)
407
+ t=$(os_doc_title "$brain/$rel")
408
+ fm_read "$brain/$rel"
409
+ d="$fm_date"
410
+ [ -n "$d" ] || d="${name:0:10}"
411
+ ;;
412
+ *)
413
+ t="${rel#"$base"/}"
414
+ d="${name:0:10}"
415
+ ;;
416
+ esac
417
+ t="${t//[[:cntrl:]]/ }"
418
+ sd="0000-00-00"
419
+ fecha=""
420
+ if fecha_valida "$d"; then sd="$d"; fecha="$d"; fi
421
+ printf '%s\t%s\t%s\t[%s](%s)\t%s\n' "$sd" "$t" "${rel//$tab/%09}" "$(md_cell "$t")" "$(md_dest "$(os_rel_link "$from" "$rel")")" "$fecha"
422
+ }
423
+
424
+ # docs_sorted LABEL BASE FROM -> the table rows `| LABEL | date | link |` of the files whose paths come on
425
+ # stdin: the dated first, newest date first; the same date, by title and then by path; the undated last, by
426
+ # title and then by path.
427
+ docs_sorted() {
428
+ local label="$1" base="$2" from="$3" rel
429
+ while IFS= read -r rel || [ -n "$rel" ]; do
430
+ [ -n "$rel" ] || continue
431
+ doc_record "$rel" "$base" "$from"
432
+ done | LC_ALL=C sort -t "$tab" -k1,1r -k2,2 -k3,3 | while IFS="$tab" read -r _d _t _r l f; do
433
+ printf '| %s | %s | %s |\n' "$(md_cell "$label")" "$(md_cell "$f")" "$l"
434
+ done
435
+ }
436
+
437
+ # limpiar TEXT -> TEXT with every control character (tab, newline...) turned into a space: a field that goes into a
438
+ # tab-separated record can never split it.
439
+ limpiar() {
440
+ printf '%s' "${1//[[:cntrl:]]/ }"
441
+ }
442
+
443
+ # tipo_de_titulo TITLE -> the tag at the start of a title, `[producto] Algo` -> `Producto` (first ASCII letter
444
+ # raised); empty when the title has no tag or nothing after it.
445
+ tipo_de_titulo() {
446
+ local re='^\[([^]]+)\][[:space:]]*(.+)$' tag f idx lower=abcdefghijklmnopqrstuvwxyz upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ
447
+ [[ "$1" =~ $re ]] || return 0
448
+ tag="${BASH_REMATCH[1]}"
449
+ f="${tag:0:1}"
450
+ idx="${lower%%"$f"*}"
451
+ if [ "${#idx}" -lt 26 ]; then tag="${upper:${#idx}:1}${tag:1}"; fi
452
+ printf '%s' "$tag"
453
+ }
454
+
455
+ # titulo_sin_etiqueta TITLE -> the title without the tag `tipo_de_titulo` read.
456
+ titulo_sin_etiqueta() {
457
+ local re='^\[([^]]+)\][[:space:]]*(.+)$'
458
+ [[ "$1" =~ $re ]] || { printf '%s' "$1"; return 0; }
459
+ printf '%s' "${BASH_REMATCH[2]}"
460
+ }
461
+
462
+ # fila_decision REL FROM -> a record `class TAB date TAB title TAB path TAB row` (spec 079, C12): class 0 for a
463
+ # key decision that was not replaced, 1 for the others (the node index prints them in two tables). The row is `| date | [title](link) | type | when |`.
464
+ fila_decision() {
465
+ local rel="$1" from="$2" title date key note sup clase=1 shown tipo="" cuando="" sup_title sd
466
+ title=$(os_doc_title "$brain/$rel")
467
+ fm_read "$brain/$rel"
468
+ date="$fm_date"; key="$fm_key"; note="$fm_index_note"; sup=$(os_doc_superseded_path)
469
+ # The tag of the title becomes the Type and leaves the title, for every decision; a replaced one then says
470
+ # «Reemplazada» instead (its tag is not shown twice).
471
+ tipo=$(tipo_de_titulo "$title")
472
+ shown="$title"
473
+ [ -z "$tipo" ] || shown=$(titulo_sin_etiqueta "$title")
474
+ if os_doc_superseded; then
475
+ tipo="$S_INDEX_TYPE_SUPERSEDED"
476
+ if [ -n "$sup" ]; then
477
+ if [ -f "$brain/$sup" ]; then sup_title=$(os_doc_title "$brain/$sup"); else sup_title="${sup##*/}"; fi
478
+ cuando="$S_INDEX_SUPERSEDED_BY_CELL [$(md_cell "$(limpiar "$sup_title")")]($(md_dest "$(os_rel_link "$from" "$sup")"))"
479
+ fi
480
+ else
481
+ os_doc_is_key "$key" && clase=0
482
+ fi
483
+ if [ -z "$cuando" ]; then
484
+ case "$note" in
485
+ '❓'*|'📌'*|'🔍'*) note="" ;;
486
+ esac
487
+ cuando="$(md_cell "$(limpiar "$note")")"
488
+ fi
489
+ date=$(limpiar "$date"); shown=$(limpiar "$shown"); tipo=$(limpiar "$tipo")
490
+ sd="${date:-0000-00-00}"
491
+ printf '%s\t%s\t%s\t%s\t| %s | [%s](%s) | %s | %s |\n' "$clase" "$sd" "$shown" "${rel//$tab/%09}" \
492
+ "$(md_cell "$date")" "$(md_cell "$shown")" "$(md_dest "$(os_rel_link "$from" "$rel")")" "$(md_cell "$tipo")" "$cuando"
493
+ }
494
+
495
+ # fila_aprendizaje REL FROM -> a record `date TAB title TAB path TAB row`, the row `| date | [title](link) |`.
496
+ fila_aprendizaje() {
497
+ local rel="$1" from="$2" title date sd
498
+ title=$(os_doc_title "$brain/$rel")
499
+ fm_read "$brain/$rel"
500
+ date=$(limpiar "$fm_date")
501
+ sd="${date:-0000-00-00}"
502
+ title=$(limpiar "$title")
503
+ printf '%s\t%s\t%s\t| %s | [%s](%s) |\n' "$sd" "$title" "${rel//$tab/%09}" \
504
+ "$(md_cell "$date")" "$(md_cell "$title")" "$(md_dest "$(os_rel_link "$from" "$rel")")"
505
+ }
506
+
507
+ # ultimo_campo -> the last tab-separated field of each record that comes on stdin, in the order they come.
508
+ ultimo_campo() {
509
+ local r
510
+ while IFS= read -r r || [ -n "$r" ]; do
511
+ [ -n "$r" ] || continue
512
+ printf '%s\n' "${r##*$tab}"
513
+ done
514
+ }
515
+
516
+ # ---------------------------------------------------------------- the index of each area node
517
+ contents=$(os_tree_content_files "$brain" 2>/dev/null | LC_ALL=C sort -u) || contents=""
518
+
519
+ # filas_iniciativas -> the sorted rows of the initiatives that come on stdin as `rank TAB title TAB path TAB row`.
520
+ filas_iniciativas() {
521
+ LC_ALL=C sort -t "$tab" -k1,1 -k2,2 -k3,3 | ultimo_campo
522
+ }
523
+
524
+ while IFS= read -r node || [ -n "$node" ]; do
525
+ [ -n "$node" ] || continue
526
+ case "$node" in "$ws"/*/*/*) ;; *) continue ;; esac
527
+ case "$(os_head_kind "$wsdir" "$head" "$node")" in
528
+ "entity $ws_slug") ;;
529
+ *) continue ;;
530
+ esac
531
+ from="${node%/*}"
532
+ inis_open=""; inis_closed=""; decs=""; lrns=""
533
+ i=0
534
+ while [ "$i" -lt "$i_n" ]; do
535
+ case "${i_about[$i]}" in
536
+ *"$nl$node$nl"*)
537
+ t="${i_title[$i]//$tab/ }"
538
+ pth="${i_rel[$i]//$tab/%09}"
539
+ if [ "${i_status[$i]}" = "closed" ]; then
540
+ inis_closed="${inis_closed}0$tab$t$tab$pth$tab$(linea_ini "$i" "$from")$nl"
541
+ else
542
+ case "${i_horizon[$i]}" in now) rk=0 ;; next) rk=1 ;; later) rk=2 ;; *) rk=3 ;; esac
543
+ inis_open="$inis_open$rk$tab$t$tab$pth$tab$(linea_ini "$i" "$from")$nl"
544
+ fi
545
+ ;;
546
+ esac
547
+ i=$(( i + 1 ))
548
+ done
549
+ # Initiatives: the open ones by horizon (the codes, not the labels), title and path; the closed ones by title.
550
+ cols_ini="$S_INDEX_COL_INITIATIVE$tab$S_INDEX_COL_STATUS$tab$S_INDEX_COL_HORIZON$tab$S_INDEX_COL_TASKS"
551
+ rows="$(printf '%s' "$inis_open" | filas_iniciativas)"
552
+ sec_open="$(seccion "$S_INDEX_INITIATIVES_OPEN" "$(tabla "$cols_ini" "$rows")")"
553
+ rows="$(printf '%s' "$inis_closed" | filas_iniciativas)"
554
+ sec_closed=""
555
+ [ -z "$rows" ] || sec_closed="$nl$nl$(seccion "$S_INDEX_INITIATIVES_CLOSED" "$(tabla "$cols_ini" "$rows")")"
556
+ # Decisions and learnings about the node.
557
+ recs_d=""; recs_l=""
558
+ i=0
559
+ while [ "$i" -lt "$d_n" ]; do
560
+ case "${d_about[$i]}" in
561
+ *"$nl$node$nl"*)
562
+ if [ "${d_kind[$i]}" = "decision" ]; then
563
+ recs_d="$recs_d$(fila_decision "${d_rel[$i]}" "$from")$nl"
564
+ else
565
+ recs_l="$recs_l$(fila_aprendizaje "${d_rel[$i]}" "$from")$nl"
566
+ fi
567
+ ;;
568
+ esac
569
+ i=$(( i + 1 ))
570
+ done
571
+ # Decisions: two tables like the initiatives, the key ones that were not replaced and all the others (C12).
572
+ cols_dec="$S_INDEX_COL_DATE$tab$S_INDEX_COL_DECISION$tab$S_INDEX_COL_TYPE$tab$S_INDEX_COL_WHEN_TO_READ"
573
+ rows_k="$(printf '%s' "$recs_d" | LC_ALL=C sort -t "$tab" -k1,1 -k2,2r -k3,3 -k4,4 | while IFS= read -r r || [ -n "$r" ]; do
574
+ [ "${r%%$tab*}" = "0" ] && printf '%s\n' "$r"; done | ultimo_campo)"
575
+ rows_o="$(printf '%s' "$recs_d" | LC_ALL=C sort -t "$tab" -k1,1 -k2,2r -k3,3 -k4,4 | while IFS= read -r r || [ -n "$r" ]; do
576
+ [ "${r%%$tab*}" = "1" ] && printf '%s\n' "$r"; done | ultimo_campo)"
577
+ decs=""
578
+ if [ -z "$rows_k$rows_o" ]; then
579
+ decs="$(seccion "$S_INDEX_DECISIONS" "")"
580
+ else
581
+ [ -z "$rows_k" ] || decs="$(seccion "$S_INDEX_DECISIONS_KEY" "$(tabla "$cols_dec" "$rows_k")")"
582
+ [ -z "$rows_o" ] || decs="$decs${decs:+$nl$nl}$(seccion "$S_INDEX_DECISIONS_OTHER" "$(tabla "$cols_dec" "$rows_o")")"
583
+ fi
584
+ lrns="$(tabla "$S_INDEX_COL_DATE$tab$S_INDEX_COL_LEARNING" \
585
+ "$(printf '%s' "$recs_l" | LC_ALL=C sort -t "$tab" -k1,1r -k2,2 -k3,3 | ultimo_campo)")"
586
+ # The node's own documents: what the tree reaches directly in its `context/`, `research/` and
587
+ # `resources/`, one folder after the other, never deeper than the tree goes.
588
+ g_context=""; g_research=""; g_resources=""
589
+ while IFS= read -r f || [ -n "$f" ]; do
590
+ [ -n "$f" ] || continue
591
+ [ -f "$brain/$f" ] || continue
592
+ case "${f##*/}" in *.os-tmp.*) continue ;; esac
593
+ if [ "${f##*/}" = "index.md" ]; then
594
+ fm_read "$brain/$f"
595
+ [ "$fm_generated" = "true" ] && continue
596
+ fi
597
+ case "$f" in
598
+ "$from/context/"*) g_context="$g_context$f$nl" ;;
599
+ "$from/research/"*) g_research="$g_research$f$nl" ;;
600
+ "$from/resources/"*) g_resources="$g_resources$f$nl" ;;
601
+ esac
602
+ done <<CONTENTS
603
+ $contents
604
+ CONTENTS
605
+ docs=""
606
+ for g in context research resources; do
607
+ case "$g" in
608
+ context) list="$g_context"; label="$S_INDEX_FOLDER_CONTEXT" ;;
609
+ research) list="$g_research"; label="$S_INDEX_FOLDER_RESEARCH" ;;
610
+ *) list="$g_resources"; label="$S_INDEX_FOLDER_RESOURCES" ;;
611
+ esac
612
+ [ -n "$list" ] || continue
613
+ docs="$docs$(docs_sorted "$label" "$from" "$from" <<LIST
614
+ $list
615
+ LIST
616
+ )$nl"
617
+ done
618
+ docs="$(tabla "$S_INDEX_COL_FOLDER$tab$S_INDEX_COL_DATE$tab$S_INDEX_COL_DOCUMENT" "$docs")"
619
+ # A node with nothing to list (no initiative, decision or learning about it, no document of its own) has no index.
620
+ if [ -z "$inis_open$inis_closed$recs_d$recs_l$docs" ]; then
621
+ retirar_indice_de_nodo "$from/index.md"
622
+ continue
623
+ fi
624
+ # The title and the line that say what this index is: the type of the node comes from the folder it lives in.
625
+ case "${node#"$ws"/}" in
626
+ products/*) desc="$S_INDEX_NODE_DESC_PRODUCT" ;;
627
+ courses/*) desc="$S_INDEX_NODE_DESC_COURSE" ;;
628
+ channels/*) desc="$S_INDEX_NODE_DESC_CHANNEL" ;;
629
+ accounts/*) desc="$S_INDEX_NODE_DESC_ACCOUNT" ;;
630
+ *) desc="$S_INDEX_NODE_DESC_NODE" ;;
631
+ esac
632
+ node_title=$(titulo_de_cabeza "$node" "$(os_entity_name "$node")")
633
+ contenido="$(cabecera "$(printf "$S_INDEX_NODE_TITLE" "$node_title")" "$desc" "$S_INDEX_SOURCE_NODE")$nl$nl$OS_FOCUS_START$nl$sec_open$nl$nl$OS_FOCUS_END$sec_closed$nl$nl$decs$nl$nl$(seccion "$S_INDEX_LEARNINGS" "$lrns")$nl$nl$(seccion "$S_INDEX_DOCUMENTS" "$docs")"
634
+ escribir "$from/index.md" "$contenido"
635
+ done <<NODES
636
+ $(printf '%s\n' "$heads" | LC_ALL=C sort -u)
637
+ NODES
638
+
639
+ exit 0