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,304 @@
1
+ #!/usr/bin/env python3
2
+ """The one Python reading of the brain's markdown. Internal: it is a library, never invoked.
3
+
4
+ `common.sh`'s `fm_read` is the bash reading of the same bounded format and stays the authority
5
+ whenever the two disagree on the shape. On the Python side there is exactly one reading, and it is
6
+ this file: `recall_index.py` (spec 050) and `my_wiki_build.py` (spec 060) both import from here
7
+ instead of carrying a parser of their own. A second Python parser of frontmatter or of headings is
8
+ the desync this module exists to prevent — spec 060 says so as a stopping condition.
9
+
10
+ What lives here is the format: splitting a file into its frontmatter, its entries and its `##`
11
+ sections, and turning a block of that markdown into HTML. What a section *means* — a list of tasks,
12
+ a list of decisions — is the caller's, because it is the caller's feature, not the format's.
13
+ """
14
+
15
+ import re
16
+
17
+ # Same bound as `common.sh`: a frontmatter that does not close inside it is unreadable, and nothing
18
+ # is stripped, because nobody knows where a legitimate frontmatter would have closed.
19
+ CAP_FRONTMATTER = 30
20
+
21
+ DATE_RE = re.compile(r"^(\d{4}-\d{2}-\d{2})\b")
22
+ HEADING_RE = re.compile(r"^#{1,3}(\s|$)")
23
+ SECTION_RE = re.compile(r"^##(?!#)\s*(.*)$")
24
+ TASK_RE = re.compile(r"^\s*[-*]\s+\[([ xX])\]\s*(.*)$")
25
+ ITEM_RE = re.compile(r"^\s*[-*]\s+(?!\[[ xX]\])(.*)$")
26
+
27
+
28
+ def read_frontmatter(lines, keys=None):
29
+ """lines: the file's raw lines, no trailing newline. -> (dict, body_start_index).
30
+
31
+ `keys` limits which keys are kept; `None` keeps every key the block declares, which is what a
32
+ view that prints the header a file happens to carry needs.
33
+ """
34
+ if not lines or lines[0].strip() != "---":
35
+ return {}, 0
36
+ fm = {}
37
+ for i in range(1, min(len(lines), CAP_FRONTMATTER)):
38
+ line = lines[i]
39
+ if line.strip() == "---":
40
+ return fm, i + 1
41
+ if ":" not in line:
42
+ continue
43
+ key, _, value = line.partition(":")
44
+ key = key.strip()
45
+ value = value.strip()
46
+ if keys is not None and key not in keys:
47
+ continue
48
+ if key and key not in fm:
49
+ fm[key] = value
50
+ return {}, 0
51
+
52
+
53
+ def split_entries(body_lines, body_start, fallback=""):
54
+ """-> list of (line, header, text). The unit of `recall`'s index (spec 050).
55
+
56
+ `fallback` is the header of a file with nothing readable in its body — a name the caller
57
+ knows and this reader does not.
58
+
59
+ Heading beats item: a section under a heading that is itself a flat list —`# Backlog` followed
60
+ by nothing but `- ` items, no sub-heading in between— still comes out one entry per item, not
61
+ one entry for the whole section. What decides is the section's own body once its heading line
62
+ is set aside: no item line there means the section reads as prose (`decisions.md`) and stays one
63
+ entry; at least one does means the section is `backlog.md`/`inbox.md`-shaped.
64
+ """
65
+ n = len(body_lines)
66
+ heading_idx = [i for i, l in enumerate(body_lines) if HEADING_RE.match(l)]
67
+ entries = []
68
+ if heading_idx:
69
+ for j, start in enumerate(heading_idx):
70
+ end = heading_idx[j + 1] if j + 1 < len(heading_idx) else n
71
+ chunk = body_lines[start:end]
72
+ sub_item_idx = [k for k, l in enumerate(chunk) if k > 0 and l.startswith("- ")]
73
+ if sub_item_idx:
74
+ for jj, s2 in enumerate(sub_item_idx):
75
+ e2 = sub_item_idx[jj + 1] if jj + 1 < len(sub_item_idx) else len(chunk)
76
+ item_chunk = chunk[s2:e2]
77
+ header = item_chunk[0][2:].strip()
78
+ text = "\n".join(item_chunk)
79
+ entries.append((body_start + start + s2 + 1, header, text))
80
+ continue
81
+ header = chunk[0].lstrip("#").strip()
82
+ text = "\n".join(chunk)
83
+ entries.append((body_start + start + 1, header, text))
84
+ return entries
85
+ item_idx = [i for i, l in enumerate(body_lines) if l.startswith("- ")]
86
+ if item_idx:
87
+ for j, start in enumerate(item_idx):
88
+ end = item_idx[j + 1] if j + 1 < len(item_idx) else n
89
+ chunk = body_lines[start:end]
90
+ header = chunk[0][2:].strip()
91
+ text = "\n".join(chunk)
92
+ entries.append((body_start + start + 1, header, text))
93
+ return entries
94
+ header = ""
95
+ for l in body_lines:
96
+ if l.strip():
97
+ header = l.strip().lstrip("#").strip()
98
+ break
99
+ text = "\n".join(body_lines)
100
+ entries.append((body_start + 1, header or fallback, text))
101
+ return entries
102
+
103
+
104
+ def split_sections(body_lines):
105
+ """-> (title, lede_lines, [(name, lines)]). The unit a page of the wiki is made of (spec 060).
106
+
107
+ The title is the first `# ` line if there is one; the lede is everything between it and the
108
+ first `##`; each `##` opens a section that runs to the next one. A file with no `##` at all
109
+ comes out with an empty section list and its whole body as the lede — the page still reads.
110
+ """
111
+ title = ""
112
+ sections = []
113
+ lede = []
114
+ current = None
115
+ for line in body_lines:
116
+ if not title and line.startswith("# ") and current is None:
117
+ title = line[2:].strip()
118
+ continue
119
+ m = SECTION_RE.match(line)
120
+ if m:
121
+ current = (m.group(1).strip(), [])
122
+ sections.append(current)
123
+ continue
124
+ if current is None:
125
+ lede.append(line)
126
+ else:
127
+ current[1].append(line)
128
+ return title, lede, [(name, lines) for name, lines in sections]
129
+
130
+
131
+ def strip_lines(lines):
132
+ """The same block with its leading and trailing blank lines gone."""
133
+ out = list(lines)
134
+ while out and not out[0].strip():
135
+ out.pop(0)
136
+ while out and not out[-1].strip():
137
+ out.pop()
138
+ return out
139
+
140
+
141
+ def escape(text):
142
+ return (text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
143
+ .replace('"', "&quot;"))
144
+
145
+
146
+ _CODE_RE = re.compile(r"`([^`]+)`")
147
+ _BOLD_RE = re.compile(r"\*\*([^*]+)\*\*")
148
+ _ITALIC_RE = re.compile(r"(?<![\*\w])\*([^*\n]+)\*(?!\*)")
149
+ _LINK_RE = re.compile(r"\[([^\]]+)\]\(([^)\s]+)\)")
150
+
151
+
152
+ def render_inline(text, link=None):
153
+ """One line of markdown as HTML. `link(target) -> href or None` decides what a link points at:
154
+ a caller that knows its own routing passes one, and a target it does not recognise is dropped
155
+ to plain text rather than left as a dead href.
156
+
157
+ A backtick span is a path first (spec 063 C5): `link()` is tried on its raw content, and it
158
+ becomes `<a><code>` when that resolves. A span that is not a path — or resolves to nothing —
159
+ stays plain `<code>`, never a dead link."""
160
+ out = escape(text)
161
+
162
+ def do_link(m):
163
+ label, target = m.group(1), m.group(2)
164
+ href = link(target) if link else None
165
+ if not href:
166
+ return label
167
+ return '<a href="%s">%s</a>' % (escape(href), label)
168
+
169
+ def do_code(m):
170
+ content = m.group(1)
171
+ href = link(content) if link else None
172
+ if not href:
173
+ return "<code>%s</code>" % content
174
+ return '<a href="%s"><code>%s</code></a>' % (escape(href), content)
175
+
176
+ out = _LINK_RE.sub(do_link, out)
177
+ out = _CODE_RE.sub(do_code, out)
178
+ out = _BOLD_RE.sub(r"<b>\1</b>", out)
179
+ out = _ITALIC_RE.sub(r"<i>\1</i>", out)
180
+ return out
181
+
182
+
183
+ def render(lines, link=None):
184
+ """A block of markdown as HTML: paragraphs, `###` sub-headings, lists, quotes. Deliberately
185
+ small — what the brain's prose actually uses. Anything it does not know comes out as a
186
+ paragraph, never as raw markup."""
187
+ html = []
188
+ buf = []
189
+ items = []
190
+
191
+ def flush_para():
192
+ if buf:
193
+ html.append("<p>" + render_inline(" ".join(buf), link) + "</p>")
194
+ del buf[:]
195
+
196
+ def flush_items():
197
+ if items:
198
+ html.append("<ul>" + "".join(
199
+ "<li>" + render_inline(i, link) + "</li>" for i in items) + "</ul>")
200
+ del items[:]
201
+
202
+ rows = []
203
+ fence = []
204
+ in_fence = False
205
+
206
+ def flush_table():
207
+ if rows:
208
+ body = [r for r in rows if not all(set(c.strip()) <= set(":-") for c in r)]
209
+ has_sep = len(body) < len(rows)
210
+ out = ["<div class=\"tbl\"><table>"]
211
+ if has_sep and body:
212
+ out.append("<thead><tr>" + "".join("<th>" + render_inline(c.strip(), link) + "</th>" for c in body[0]) + "</tr></thead>")
213
+ body = body[1:]
214
+ out.append("<tbody>" + "".join(
215
+ "<tr>" + "".join("<td>" + render_inline(c.strip(), link) + "</td>" for c in r) + "</tr>" for r in body) + "</tbody>")
216
+ out.append("</table></div>")
217
+ html.append("".join(out))
218
+ del rows[:]
219
+
220
+ for line in lines:
221
+ stripped = line.strip()
222
+ # Fenced code stays verbatim, never re-read as prose.
223
+ if stripped.startswith("```"):
224
+ if in_fence:
225
+ html.append("<pre><code>" + "\n".join(fence).replace("&", "&amp;").replace("<", "&lt;") + "</code></pre>")
226
+ del fence[:]
227
+ in_fence = False
228
+ else:
229
+ flush_para(); flush_items(); flush_table()
230
+ in_fence = True
231
+ continue
232
+ if in_fence:
233
+ fence.append(line.rstrip("\n"))
234
+ continue
235
+ # A markdown table: rows that start and end with a pipe. The separator row marks the header.
236
+ if stripped.startswith("|") and stripped.endswith("|") and stripped.count("|") >= 2:
237
+ flush_para(); flush_items()
238
+ cells = stripped[1:-1].split("|")
239
+ rows.append(cells)
240
+ continue
241
+ elif rows:
242
+ flush_table()
243
+ if not stripped:
244
+ flush_para()
245
+ flush_items()
246
+ continue
247
+ if stripped.startswith("###"):
248
+ flush_para()
249
+ flush_items()
250
+ html.append("<h3>" + render_inline(stripped.lstrip("#").strip(), link) + "</h3>")
251
+ continue
252
+ if stripped.startswith("> "):
253
+ flush_para()
254
+ flush_items()
255
+ html.append("<p class=\"quote\">" + render_inline(stripped[2:], link) + "</p>")
256
+ continue
257
+ m = ITEM_RE.match(line)
258
+ if m:
259
+ flush_para()
260
+ items.append(m.group(1))
261
+ continue
262
+ m = TASK_RE.match(line)
263
+ if m:
264
+ flush_para()
265
+ items.append(m.group(2))
266
+ continue
267
+ # A non-blank line while a list is open continues its last item: the brain's prose wraps
268
+ # its bullets at 100 columns, and reading a wrapped line as a new paragraph broke the list
269
+ # in two around it.
270
+ if items:
271
+ items[-1] = items[-1] + " " + stripped
272
+ continue
273
+ buf.append(stripped)
274
+ flush_para()
275
+ flush_table()
276
+ if in_fence and fence:
277
+ html.append("<pre><code>" + "\n".join(fence).replace("&", "&amp;").replace("<", "&lt;") + "</code></pre>")
278
+ flush_items()
279
+ return "".join(html)
280
+
281
+
282
+ def plain(text):
283
+ """The same text with its markdown markers gone: what a listing or a card shows, where there
284
+ is no room to render anything."""
285
+ text = _LINK_RE.sub(r"\1", text)
286
+ text = _CODE_RE.sub(r"\1", text)
287
+ text = _BOLD_RE.sub(r"\1", text)
288
+ text = _ITALIC_RE.sub(r"\1", text)
289
+ return text
290
+
291
+
292
+ def first_paragraph(lines):
293
+ """The first paragraph of a block, as plain text: what a card or a listing shows."""
294
+ buf = []
295
+ for line in lines:
296
+ stripped = line.strip()
297
+ if not stripped:
298
+ if buf:
299
+ break
300
+ continue
301
+ if stripped.startswith("#") or stripped.startswith(">"):
302
+ continue
303
+ buf.append(stripped)
304
+ return plain(" ".join(buf))
@@ -0,0 +1,207 @@
1
+ #!/usr/bin/env bash
2
+ # One-time split of a workspace's or the root's own `backlog.md` — the destination `capture` and
3
+ # `close-session` used before spec 057 — into the `backlog.md` of the initiative each task names.
4
+ # Internal: not invocable — run on demand, over any brain; never commits, same pattern as
5
+ # `migrate-canonicals.sh` (specs 043/053) and `rename-workspaces.sh` (spec 039).
6
+ #
7
+ # Usage: migrate-backlogs.sh --brain DIR
8
+ #
9
+ # A task written before this spec names its initiative between parentheses, at the front of its own
10
+ # text — `- [ ] tsk-005 (lote-01) Renegotiate the deposit ...` — because that is all the old
11
+ # `capture` did with it: the parenthesis never changed where the line landed. This script reads that
12
+ # same parenthesis to decide where the line moves to now.
13
+ #
14
+ # For each task in a stray backlog (the root's `backlog.md`, or `<wsdir>/<org>/backlog.md`):
15
+ # 1. Take the text between the first `(` and its matching `)`, if the task's text starts with one.
16
+ # 2. Look for an initiative whose **slug** is exactly that text, in the same scope the stray
17
+ # backlog belongs to (the root, or that one workspace).
18
+ # 3. With no slug match, look for an initiative whose **head title** (`# Title`) is exactly that
19
+ # text — only when that produces at most one candidate. Two initiatives with the same title is
20
+ # an ambiguity this script does not resolve: the task stays listed, never guessed at.
21
+ # 4. No match at all — no parenthesis, an unknown slug, a title that resolves to zero or several
22
+ # initiatives, or an initiative the migration would have to create — the task stays exactly
23
+ # where it was and is named in the report. Nothing here ever writes a new initiative head: an
24
+ # initiative that does not exist is not created by a migration (the spec's own stopping rule).
25
+ #
26
+ # A matched line moves byte for byte — the parenthesis stays inside its text, since this script
27
+ # never rewrites the line, only its file. The `tsk-XXX` id is not renumbered: it already identifies
28
+ # the task everywhere it might be cited from.
29
+ #
30
+ # Idempotent: a second run over what the first run left finds the same unmatched lines, still
31
+ # unmatched, and changes nothing (`git status --porcelain` identical, no new commit — this script
32
+ # never commits, same as its two precedents).
33
+ #
34
+ # Stops without moving anything, brain-wide, when a `tsk-XXX` id already used in some initiative's
35
+ # `backlog.md` shows up again in a stray one: the spec's own stopping condition — a repeated id
36
+ # across a stray backlog and an initiative one is a data problem to fix by hand, never something
37
+ # this script renumbers on its own guess.
38
+ #
39
+ # Exit: 0 ran (whether or not everything got moved) · 1 an id collision stopped it before moving
40
+ # anything · 2 no brain at that path.
41
+
42
+ set -u
43
+
44
+ here=$(cd "$(dirname "$0")" && pwd)
45
+ . "$here/common.sh"
46
+
47
+ brain=""
48
+ while [ $# -gt 0 ]; do
49
+ case "$1" in
50
+ --brain) brain="${2:-}"; shift 2 ;;
51
+ *) os_die "argumento desconocido: $1" ;;
52
+ esac
53
+ done
54
+ [ -n "$brain" ] || os_die "falta --brain"
55
+ [ -d "$brain" ] || { printf 'no existe el brain: %s\n' "$brain" >&2; exit 2; }
56
+ brain=$(cd "$brain" && pwd)
57
+
58
+ nl=$(printf '\nx'); nl="${nl%x}"
59
+ os_ws_check "$brain"
60
+ wsdir=$(os_ws_dir "$brain")
61
+
62
+ # ---------------------------------------------------------------- el universo de backlogs sueltos
63
+ # Un backlog suelto es el que vive a la altura de la raíz o de una organización, nunca adentro de
64
+ # `initiatives/`: exactamente el destino que `capture` y `close-session` usaban antes de esta spec.
65
+ sueltos=""
66
+ [ -f "$brain/backlog.md" ] && sueltos="$sueltos$brain/backlog.md$nl"
67
+ while IFS= read -r o || [ -n "$o" ]; do
68
+ [ -n "$o" ] || continue
69
+ [ -f "$brain/$wsdir/$o/backlog.md" ] && sueltos="$sueltos$brain/$wsdir/$o/backlog.md$nl"
70
+ done <<ORGS
71
+ $(os_org_slugs "$brain")
72
+ ORGS
73
+
74
+ if [ -z "$sueltos" ]; then
75
+ printf 'ningún backlog.md fuera de una iniciativa: nada para migrar.\n'
76
+ exit 0
77
+ fi
78
+
79
+ # ---------------------------------------------------------------- chequeo de ids repetidos (parar)
80
+ # Un id que ya está citado en el backlog de una iniciativa y vuelve a aparecer en uno suelto es un
81
+ # dato roto, no algo que este script arregla renumerando. Se para antes de mover una sola línea.
82
+ sep="$OS_SEP"
83
+ todos=$(find "$brain" -name 'backlog.md' -not -path '*/.git/*' -not -path '*/.os/*' 2>/dev/null)
84
+ pares=""
85
+ while IFS= read -r f || [ -n "$f" ]; do
86
+ [ -n "$f" ] || continue
87
+ while IFS= read -r line || [ -n "$line" ]; do
88
+ os_backlog_lee "$line" || continue
89
+ [ -n "$bl_id" ] || continue
90
+ pares="$pares$bl_id$sep${f#$brain/}$nl"
91
+ done < "$f"
92
+ done <<TODOS
93
+ $todos
94
+ TODOS
95
+
96
+ colision=""
97
+ checados=""
98
+ while IFS= read -r par || [ -n "$par" ]; do
99
+ [ -n "$par" ] || continue
100
+ id="${par%%$sep*}"
101
+ case "$nl$checados$nl" in *"$nl$id$nl"*) continue ;; esac
102
+ checados="$checados$nl$id"
103
+ archivos=""
104
+ while IFS= read -r par2 || [ -n "$par2" ]; do
105
+ [ -n "$par2" ] || continue
106
+ [ "${par2%%$sep*}" = "$id" ] || continue
107
+ a="${par2#*$sep}"
108
+ case "$nl$archivos$nl" in *"$nl$a$nl"*) ;; *) archivos="$archivos$nl$a" ;; esac
109
+ done <<PARES2
110
+ $pares
111
+ PARES2
112
+ n=$(printf '%s\n' "$archivos" | grep -c .)
113
+ if [ "$n" -gt 1 ]; then
114
+ colision="$colision$id: $(printf '%s' "$archivos" | tr "$nl" ' ')$nl"
115
+ fi
116
+ done <<PARES
117
+ $pares
118
+ PARES
119
+
120
+ if [ -n "$colision" ]; then
121
+ printf 'ids repetidos entre backlogs — no se movió nada:\n' >&2
122
+ printf '%s' "$colision" | while IFS= read -r c || [ -n "$c" ]; do
123
+ [ -n "$c" ] && printf ' %s\n' "$c" >&2
124
+ done
125
+ exit 1
126
+ fi
127
+
128
+ # ---------------------------------------------------------------- reparto
129
+ movidas=0
130
+ listadas=""
131
+ n_listadas=0
132
+
133
+ migrar_archivo() {
134
+ # migrar_archivo RUTA PREFIX — PREFIX es "$wsdir/$org/" o "" para la raíz.
135
+ local ruta="$1" prefix="$2" tmp="$1.os-tmp" line texto ini destino
136
+ : > "$tmp"
137
+ while IFS= read -r line || [ -n "$line" ]; do
138
+ if ! os_backlog_lee "$line"; then
139
+ printf '%s\n' "$line" >> "$tmp"
140
+ continue
141
+ fi
142
+ texto="$bl_texto"
143
+ ini=""
144
+ case "$texto" in
145
+ '('*')'*)
146
+ candidato="${texto#\(}"
147
+ candidato="${candidato%%\)*}"
148
+ if os_ini_existe "$brain" "$prefix" "$candidato"; then
149
+ ini="$candidato"
150
+ else
151
+ # Sin slug exacto, por título — solo si produce un único candidato (delegado al agente,
152
+ # spec 057).
153
+ n_match=0
154
+ match_slug=""
155
+ while IFS= read -r s || [ -n "$s" ]; do
156
+ [ -n "$s" ] || continue
157
+ if [ "$(os_titulo "$brain/$(os_ini_head_rel "$brain" "$prefix" "$s")")" = "$candidato" ]; then
158
+ n_match=$(( n_match + 1 ))
159
+ match_slug="$s"
160
+ fi
161
+ done <<SLUGS
162
+ $(os_ini_slugs "$brain" "$prefix")
163
+ SLUGS
164
+ [ "$n_match" = "1" ] && ini="$match_slug"
165
+ fi
166
+ ;;
167
+ esac
168
+ if [ -n "$ini" ]; then
169
+ os_ini_backlog_asegurar "$brain" "$prefix" "$ini" > /dev/null || true
170
+ printf '%s\n' "$line" >> "$brain/$(os_ini_backlog_rel "$prefix" "$ini")"
171
+ movidas=$(( movidas + 1 ))
172
+ else
173
+ printf '%s\n' "$line" >> "$tmp"
174
+ n_listadas=$(( n_listadas + 1 ))
175
+ listadas="$listadas${ruta#$brain/}: $line$nl"
176
+ fi
177
+ done < "$ruta"
178
+ if diff -q "$tmp" "$ruta" > /dev/null 2>&1; then
179
+ rm -f "$tmp"
180
+ else
181
+ mv "$tmp" "$ruta"
182
+ fi
183
+ }
184
+
185
+ while IFS= read -r ruta || [ -n "$ruta" ]; do
186
+ [ -n "$ruta" ] || continue
187
+ if [ "$ruta" = "$brain/backlog.md" ]; then
188
+ migrar_archivo "$ruta" ""
189
+ else
190
+ resto="${ruta#$brain/$wsdir/}"
191
+ org="${resto%%/backlog.md}"
192
+ migrar_archivo "$ruta" "$wsdir/$org/"
193
+ fi
194
+ done <<SUELTOS
195
+ $sueltos
196
+ SUELTOS
197
+
198
+ printf 'movidas: %s\n' "$movidas"
199
+ if [ "$n_listadas" = "0" ]; then
200
+ printf 'listadas: 0\n'
201
+ else
202
+ printf 'listadas: %s — sin iniciativa reconocible, siguen donde estaban:\n' "$n_listadas"
203
+ printf '%s' "$listadas" | while IFS= read -r l || [ -n "$l" ]; do
204
+ [ -n "$l" ] && printf ' %s\n' "$l"
205
+ done
206
+ fi
207
+ exit 0