ai-first-os 1.10.0 → 2.0.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 (60) hide show
  1. package/README.md +33 -31
  2. package/core/CLAUDE.md +48 -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 +283 -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 +505 -92
  11. package/core/lib/focus-read.sh +94 -58
  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 +238 -221
  29. package/core/lib/supersede.sh +199 -3
  30. package/core/lib/sweep.sh +5 -0
  31. package/core/manual/COMO-FUNCIONA.md +169 -58
  32. package/core/manual/HOW-IT-WORKS.md +158 -57
  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/strings.md +396 -271
  50. package/core/templates/tree.md +22 -27
  51. package/package.json +1 -1
  52. package/core/lib/my-wiki-gates.sh +0 -137
  53. package/core/lib/my-wiki.sh +0 -202
  54. package/core/lib/my_wiki_build.py +0 -548
  55. package/core/lib/my_wiki_graph.py +0 -137
  56. package/core/lib/my_wiki_overview.py +0 -392
  57. package/core/skills/my-wiki.md +0 -103
  58. package/core/templates/my-wiki-graph.js +0 -431
  59. package/core/templates/my-wiki-overview.js +0 -174
  60. package/core/templates/my-wiki.html +0 -1017
@@ -0,0 +1,2000 @@
1
+ #!/usr/bin/env python3
2
+ # migrate_layout.py — the engine of migrate-layout.sh (spec 076, delivery C). Internal: not invocable.
3
+ # The shell wrapper reads the brain's language and facts (workspaces folder, head file, initiative head
4
+ # form, memory-node types) with the product's own functions and hands them over in OS_ML_* variables.
5
+ #
6
+ # The engine plans first: it replays the whole migration on a virtual copy of the brain (VFS) and records
7
+ # every operation with the fingerprint of what it reads and of what it writes. Printing that record is the
8
+ # plan (C22); applying it is replaying the record on the disk (C25). Nothing here reads the disk twice for
9
+ # the same decision: the plan is the single source of what happens.
10
+ #
11
+ # Exit: 0 ran (or nothing to do) · 1 stopped, nothing (more) written · 3 interrupted by the eval hook.
12
+ import datetime
13
+ import fnmatch
14
+ import hashlib
15
+ import json
16
+ import os
17
+ import posixpath
18
+ import re
19
+ import subprocess
20
+ import sys
21
+
22
+ ENV = os.environ
23
+ PLAN_REL = '.os/migrate-layout.plan'
24
+ BLOB_REL = '.os/migrate-layout.blobs'
25
+ DELIMS = set(' \t`|()[]<>"\',;!')
26
+ MARCAS = ('blocked-by', 'hold', 'hold-until', 'since')
27
+ LINE_RE = re.compile(r'^- (\d{4}-\d{2}-\d{2}) · (clave · )?\[(.+?)\]\(([^)]+)\)(.*)$')
28
+ SUP_RE = re.compile(r' — \*\*reemplazada por\*\*: \[(.*)\]\(([^)]*)\)\s*$')
29
+ KEY_RE = re.compile(r'^([A-Za-z0-9_-]+):[ \t]*(.*)$')
30
+ ENTRY_LIKE_RE = re.compile(r'^- \d{4}-\d{2}-\d{2}')
31
+ INDEX_LINK_RE = re.compile(r'\]\(<?(\./)?(decisions|learnings)/[^)]*\)')
32
+ REFDEF_RE = re.compile(r'^ {0,3}\[[^\]]+\]:[ \t]*(?:<([^>]*)>|((?:\\.|\S)+))')
33
+ EXT_RE = re.compile(r'\.[A-Za-z][A-Za-z0-9]{0,5}$')
34
+
35
+
36
+ def sha(b):
37
+ return hashlib.sha256(b).hexdigest()
38
+
39
+
40
+ class Unreadable(Exception):
41
+ pass
42
+
43
+
44
+ # ---------------------------------------------------------------- the catalog
45
+ def load_strings(path, lang):
46
+ cat = {}
47
+ key = None
48
+ with open(path, encoding='utf-8') as f:
49
+ for line in f.read().split('\n'):
50
+ if line.startswith('key: '):
51
+ key = line[5:].strip()
52
+ cat[key] = {}
53
+ continue
54
+ if key is None:
55
+ continue
56
+ m = re.match(r'^([a-z][a-z]):(?: (.*))?$', line)
57
+ if m and m.group(1) in ('en', lang):
58
+ cat[key].setdefault(m.group(1), []).append(m.group(2) or '')
59
+ out = {}
60
+ for k, v in cat.items():
61
+ out[k] = '\n'.join(v.get(lang) or v.get('en') or [])
62
+ return out
63
+
64
+
65
+ def split_fm(text):
66
+ """(fm_lines or None, index of the first body line, lines). Raises Unreadable on an unclosed block."""
67
+ lines = text.split('\n')
68
+ if lines and lines[0].rstrip('\r') == '---':
69
+ for i in range(1, len(lines)):
70
+ if lines[i].rstrip('\r') == '---':
71
+ return lines[1:i], i + 1, lines
72
+ raise Unreadable('unclosed frontmatter')
73
+ return None, 0, lines
74
+
75
+
76
+ def fm_dict(text):
77
+ try:
78
+ fm, _, _ = split_fm(text)
79
+ except Unreadable:
80
+ return None
81
+ d = {}
82
+ for l in fm or []:
83
+ m = KEY_RE.match(l)
84
+ if m and m.group(1) not in d:
85
+ d[m.group(1)] = m.group(2).strip()
86
+ return d
87
+
88
+
89
+ def body_title(text):
90
+ fm, bs, lines = split_fm(text)
91
+ for l in lines[bs:]:
92
+ if l.startswith('# '):
93
+ return l[2:].strip()
94
+ return ''
95
+
96
+
97
+ def add_fm_keys(text, adds):
98
+ fm, bs, lines = split_fm(text)
99
+ new = ['%s: %s' % (k, v) for k, v in adds]
100
+ if fm is None:
101
+ return '---\n' + '\n'.join(new) + '\n---\n\n' + text
102
+ lines[bs - 1:bs - 1] = new
103
+ return '\n'.join(lines)
104
+
105
+
106
+ def unquote(v):
107
+ """V without one pair of matching surrounding quotes: the rule of `os_unquote` in common.sh."""
108
+ if len(v) >= 2 and v[0] == v[-1] and v[0] in '"\'':
109
+ return v[1:-1]
110
+ return v
111
+
112
+
113
+ def parse_list(v):
114
+ """The values of `about:` as `os_about_values` reads them: one value, or `[a, b]` on one line, each
115
+ trimmed and unquoted."""
116
+ v = v.strip()
117
+ if v.startswith('[') and v.endswith(']'):
118
+ v = v[1:-1]
119
+ return [unquote(x.strip()) for x in v.split(',') if x.strip()]
120
+
121
+
122
+ def parse_task(line):
123
+ """-> (id, texto) with the same reading as os_backlog_lee."""
124
+ resto = line[6:]
125
+ while resto.endswith(')') and '(' in resto:
126
+ grupo = resto[resto.rindex('(') + 1:-1]
127
+ if grupo.startswith('since '):
128
+ clave = 'since'
129
+ elif ':' in grupo:
130
+ clave = grupo.split(':', 1)[0].strip()
131
+ else:
132
+ break
133
+ if clave not in MARCAS:
134
+ break
135
+ resto = resto[:resto.rindex('(')].strip()
136
+ tid = ''
137
+ if resto.startswith('tsk-'):
138
+ parts = resto.split(' ', 1)
139
+ tid = parts[0]
140
+ resto = parts[1] if len(parts) > 1 else ''
141
+ return tid, resto.strip()
142
+
143
+
144
+ def rel_norm(p):
145
+ """The same normal form as `os_rel_norm` of common.sh: no `./`, no `//`, no `/./`, no trailing slash."""
146
+ prev = None
147
+ while p != prev:
148
+ prev = p
149
+ if p.startswith('./'):
150
+ p = p[2:]
151
+ p = p.replace('//', '/').replace('/./', '/')
152
+ if p.endswith('/.'):
153
+ p = p[:-2]
154
+ if p.endswith('/'):
155
+ p = p[:-1]
156
+ return p
157
+
158
+
159
+ def about_is_single(value, head):
160
+ """The reading of `os_about_is_single`: VALUE names HEAD and nothing else. It is how `capture --about`
161
+ recognises the standing initiative of a node (C30); the migration reuses the same one (C31 step 7)."""
162
+ vals = parse_list(value)
163
+ return len(vals) == 1 and rel_norm(vals[0]) == head
164
+
165
+
166
+ def render_ini(title, status, about):
167
+ """The head of an initiative the migration creates, rendered by `os_ini_render` of common.sh: the one
168
+ writer of that shape, shared with `capture --about --create` and the system's `tasks-to-sort`. Owned by
169
+ the operator (the title of the account file, `OS_ML_OWNER`), dated the day the plan is made."""
170
+ out = subprocess.run(
171
+ ['bash', '-c', '. "$1" && os_ini_render "$2" "$3" "$4" "$5" "$6"', '_', ENV['OS_ML_COMMON'],
172
+ title, status, about, ENV.get('OS_ML_OWNER', ''), datetime.date.today().isoformat()],
173
+ capture_output=True, text=True)
174
+ if out.returncode != 0:
175
+ raise RuntimeError('os_ini_render failed: ' + out.stderr.strip())
176
+ return out.stdout
177
+
178
+
179
+ def is_task(line):
180
+ return line.startswith('- [ ] ') or line.startswith('- [x] ')
181
+
182
+
183
+ class Planner:
184
+ def __init__(self, brain, S):
185
+ self.brain = brain
186
+ self.S = S
187
+ self.lang = ENV['OS_ML_LANG']
188
+ self.wsdir = ENV['OS_ML_WSDIR']
189
+ self.head = ENV['OS_ML_HEAD']
190
+ self.ini_form = ENV['OS_ML_INI_FORM']
191
+ self.types = ENV.get('OS_ML_TYPES', '').split()
192
+ self.core = os.path.realpath(ENV['OS_ML_CORE'])
193
+ self.core_claude = os.path.join(self.core, 'CLAUDE.md')
194
+ self.ops = []
195
+ self.blockers = []
196
+ self.unknown = []
197
+ self.warnings = []
198
+ self.kind = {}
199
+ self.target = {}
200
+ self.mem = {}
201
+ self.disk = {}
202
+ self.dirs = set()
203
+ self.walk()
204
+ self.old_kind = dict(self.kind)
205
+ self.old_dirs = set(self.dirs)
206
+ self.old_target = dict(self.target)
207
+ self.touched = set()
208
+ self.created = {}
209
+ self.origin = {p: p for p in self.kind}
210
+ self.fmap = {}
211
+ self.dirmap = {}
212
+ self.skill_dirs = {}
213
+ self.prov = {}
214
+ self.index_prose = {}
215
+
216
+ # ------------------------------------------------------------ the virtual brain
217
+ def walk(self):
218
+ root = self.brain
219
+ for dp, dn, fn in os.walk(root):
220
+ rel = os.path.relpath(dp, root)
221
+ rel = '' if rel == '.' else rel.replace(os.sep, '/')
222
+ keep = []
223
+ for d in dn:
224
+ p = posixpath.join(rel, d) if rel else d
225
+ full = os.path.join(dp, d)
226
+ if d == '.git' or (rel == '' and d in ('.os', '.claude')):
227
+ continue
228
+ if os.path.islink(full):
229
+ self.kind[p] = 'l'
230
+ self.target[p] = os.readlink(full)
231
+ self.add_dirs(p)
232
+ continue
233
+ keep.append(d)
234
+ self.dirs.add(p)
235
+ dn[:] = keep
236
+ for f in fn:
237
+ if f == '.git':
238
+ continue
239
+ p = posixpath.join(rel, f) if rel else f
240
+ full = os.path.join(dp, f)
241
+ if os.path.islink(full):
242
+ self.kind[p] = 'l'
243
+ self.target[p] = os.readlink(full)
244
+ else:
245
+ self.kind[p] = 'f'
246
+ self.disk[p] = p
247
+ self.add_dirs(p)
248
+
249
+ def add_dirs(self, p):
250
+ d = posixpath.dirname(p)
251
+ while d:
252
+ self.dirs.add(d)
253
+ d = posixpath.dirname(d)
254
+
255
+ def exists(self, p):
256
+ return p in self.kind or p in self.dirs
257
+
258
+ def is_dir(self, p):
259
+ return p in self.dirs and p not in self.kind
260
+
261
+ def read(self, p):
262
+ if p in self.mem:
263
+ return self.mem[p]
264
+ with open(os.path.join(self.brain, self.disk[p]), 'rb') as f:
265
+ return f.read()
266
+
267
+ def text(self, p):
268
+ return self.read(p).decode('utf-8', errors='surrogateescape')
269
+
270
+ def fp(self, p):
271
+ if self.kind.get(p) == 'l':
272
+ return 'L:' + self.target[p]
273
+ return sha(self.read(p))
274
+
275
+ def listdir(self, d):
276
+ pre = d + '/' if d else ''
277
+ out = set()
278
+ for p in list(self.kind):
279
+ if p.startswith(pre):
280
+ out.add(p[len(pre):].split('/')[0])
281
+ for p in self.dirs:
282
+ if p.startswith(pre) and p != d:
283
+ out.add(p[len(pre):].split('/')[0])
284
+ return sorted(out)
285
+
286
+ def files_under(self, d):
287
+ pre = d + '/'
288
+ return sorted(p for p in self.kind if p.startswith(pre))
289
+
290
+ def block(self, msg):
291
+ if msg not in self.blockers:
292
+ self.blockers.append(msg)
293
+
294
+ # ------------------------------------------------------------ recording
295
+ def touch(self, op, path):
296
+ if path in self.touched:
297
+ return
298
+ self.touched.add(path)
299
+ if path in self.old_kind:
300
+ op.setdefault('pre', []).append([path, self.orig_fp(path)])
301
+ else:
302
+ op.setdefault('absent', []).append(path)
303
+
304
+ def orig_fp(self, path):
305
+ if self.old_kind.get(path) == 'l':
306
+ return 'L:' + self.old_target[path]
307
+ with open(os.path.join(self.brain, path), 'rb') as f:
308
+ return sha(f.read())
309
+
310
+ def rec(self, step, op, **kw):
311
+ d = {'op': op, 'step': step}
312
+ d.update(kw)
313
+ d['i'] = len(self.ops)
314
+ self.ops.append(d)
315
+ return d
316
+
317
+ def check_dest(self, path, why):
318
+ """A destination is written only under real directories of the brain: no symlink in the way, no file
319
+ where a directory is needed."""
320
+ d = posixpath.dirname(path)
321
+ while d:
322
+ full = os.path.join(self.brain, d)
323
+ if d in self.kind or os.path.islink(full) or (os.path.lexists(full) and not os.path.isdir(full)):
324
+ self.block(self.S['MIGRATE_LAYOUT_B_ANCESTOR'] % (d, why))
325
+ return False
326
+ d = posixpath.dirname(d)
327
+ return True
328
+
329
+ def mv(self, src, dst, step):
330
+ if src not in self.kind:
331
+ return False
332
+ if not self.check_dest(dst, src):
333
+ return False
334
+ if dst in self.created:
335
+ self.block(self.S['MIGRATE_LAYOUT_B_SAME_DEST'] % (self.created[dst], src, dst))
336
+ return False
337
+ dup = False
338
+ if dst in self.kind:
339
+ if self.fp(dst) == self.fp(src):
340
+ dup = True
341
+ else:
342
+ self.block(self.S['MIGRATE_LAYOUT_B_EXISTS'] % (dst, src))
343
+ return False
344
+ elif dst in self.dirs:
345
+ self.block(self.S['MIGRATE_LAYOUT_B_EXISTS'] % (dst, src))
346
+ return False
347
+ op = self.rec(step, 'move', src=src, dst=dst, fp=self.fp(src), dup=dup)
348
+ self.touch(op, src)
349
+ self.touch(op, dst)
350
+ self.created[dst] = src
351
+ self.kind[dst] = self.kind[src]
352
+ if self.kind[src] == 'l':
353
+ self.target[dst] = self.target[src]
354
+ else:
355
+ self.disk[dst] = self.disk.get(src)
356
+ if src in self.mem:
357
+ self.mem[dst] = self.mem.pop(src)
358
+ if self.disk[dst] is None:
359
+ del self.disk[dst]
360
+ self.origin[dst] = self.origin.get(src, src)
361
+ self.fmap[self.origin[dst]] = dst
362
+ self.unset(src)
363
+ self.add_dirs(dst)
364
+ return True
365
+
366
+ def unset(self, p):
367
+ self.kind.pop(p, None)
368
+ self.target.pop(p, None)
369
+ self.mem.pop(p, None)
370
+ if p in self.disk:
371
+ pass
372
+
373
+ def put(self, path, data, step, detail='', origin=None):
374
+ if isinstance(data, str):
375
+ data = data.encode('utf-8', errors='surrogateescape')
376
+ before = self.fp(path) if path in self.kind else None
377
+ if before == sha(data):
378
+ return
379
+ if not self.check_dest(path, path):
380
+ return
381
+ if before is None and path in self.created:
382
+ self.block(self.S['MIGRATE_LAYOUT_B_SAME_DEST'] % (self.created[path], path, path))
383
+ return
384
+ op = self.rec(step, 'put', path=path, before=before, after=sha(data), detail=detail)
385
+ self.touch(op, path)
386
+ op['blob'] = data
387
+ if before is None:
388
+ self.created[path] = path
389
+ if origin:
390
+ self.origin[path] = origin
391
+ self.kind[path] = 'f'
392
+ self.mem[path] = data
393
+ self.add_dirs(path)
394
+
395
+ def delete(self, path, step, detail=''):
396
+ if path not in self.kind:
397
+ return
398
+ op = self.rec(step, 'delete', path=path, fp=self.fp(path), detail=detail)
399
+ self.touch(op, path)
400
+ self.unset(path)
401
+
402
+ def delete_disk(self, path, step, detail=''):
403
+ """Delete something the walk does not cover (inside `.claude/`) or that is in the model."""
404
+ if path in self.kind:
405
+ return self.delete(path, step, detail)
406
+ full = os.path.join(self.brain, path)
407
+ if not os.path.lexists(full):
408
+ return
409
+ if os.path.islink(full):
410
+ fp = 'L:' + os.readlink(full)
411
+ else:
412
+ with open(full, 'rb') as f:
413
+ fp = sha(f.read())
414
+ op = self.rec(step, 'delete', path=path, fp=fp, detail=detail)
415
+ if path not in self.touched:
416
+ self.touched.add(path)
417
+ op.setdefault('pre', []).append([path, fp])
418
+
419
+ def link(self, path, target, step):
420
+ if not self.check_dest(path, path):
421
+ return
422
+ op = self.rec(step, 'link', path=path, target=target)
423
+ self.touch(op, path)
424
+ if path in self.old_kind or not path.startswith('.claude/'):
425
+ self.kind[path] = 'l'
426
+ self.target[path] = target
427
+ self.add_dirs(path)
428
+
429
+ # ------------------------------------------------------------ the layout
430
+ def workspaces(self):
431
+ out = []
432
+ for n in self.listdir(self.wsdir):
433
+ if self.is_dir(posixpath.join(self.wsdir, n)):
434
+ out.append(posixpath.join(self.wsdir, n))
435
+ return out
436
+
437
+ def nodes(self, ws):
438
+ out = []
439
+ for t in self.types:
440
+ base = posixpath.join(ws, t)
441
+ for n in self.listdir(base):
442
+ if self.is_dir(posixpath.join(base, n)):
443
+ out.append(posixpath.join(base, n))
444
+ return out
445
+
446
+ def node_head(self, node):
447
+ return posixpath.join(node, self.head)
448
+
449
+ def initiatives(self, ws):
450
+ out = {}
451
+ base = posixpath.join(ws, 'initiatives')
452
+ for n in self.listdir(base):
453
+ full = posixpath.join(base, n)
454
+ if self.is_dir(full):
455
+ for h in (self.head, 'README.md'):
456
+ if posixpath.join(full, h) in self.kind:
457
+ out[n] = posixpath.join(full, h)
458
+ break
459
+ elif n.endswith('.md') and full in self.kind and not n == 'backlog.md':
460
+ out[n[:-3]] = full
461
+ return out
462
+
463
+ def ini_head_path(self, ws, slug):
464
+ return posixpath.join(ws, self.ini_form.replace('@SLUG@', slug))
465
+
466
+ # ------------------------------------------------------------ tokens (step 11 and the roles)
467
+ def md_dests(self, line):
468
+ """The destinations of the inline Markdown links of LINE, as (start, end, kind): angle brackets keep
469
+ their spaces, a plain destination ends at an unescaped space or at its unbalanced `)`."""
470
+ out = []
471
+ # A reference definition (`[label]: destination`) is a link like an inline one.
472
+ m = REFDEF_RE.match(line)
473
+ if m:
474
+ if m.group(1) is not None:
475
+ out.append((m.start(1), m.end(1), 'angle'))
476
+ else:
477
+ out.append((m.start(2), m.end(2), 'plain'))
478
+ return out
479
+ i = 0
480
+ while True:
481
+ k = line.find('](', i)
482
+ if k < 0:
483
+ break
484
+ j = k + 2
485
+ if j < len(line) and line[j] == '<':
486
+ e = line.find('>', j + 1)
487
+ if e < 0:
488
+ i = j
489
+ continue
490
+ out.append((j + 1, e, 'angle'))
491
+ i = e + 1
492
+ else:
493
+ e = j
494
+ depth = 0
495
+ while e < len(line):
496
+ c = line[e]
497
+ if c == '\\' and e + 1 < len(line):
498
+ e += 2
499
+ continue
500
+ if c in ' \t':
501
+ break
502
+ if c == '(':
503
+ depth += 1
504
+ elif c == ')':
505
+ if depth == 0:
506
+ break
507
+ depth -= 1
508
+ e += 1
509
+ out.append((j, e, 'plain'))
510
+ i = e
511
+ return out
512
+
513
+ def scan_tokens(self, line, dir_o):
514
+ """Yield (start, end, info) for every token of LINE that names an existing old path, by the product's
515
+ convention (every path is relative to the brain; only a Markdown link is relative to its file):
516
+ - the destination of an inline Markdown link, whole (spaces and escapes included), read from the file's
517
+ old folder (`mode: file`);
518
+ - every token inside a backtick span, and a table cell that is a single path, read from the brain root
519
+ only (`mode: brain`);
520
+ - nothing else: a word of prose outside backticks and links is never a path, even if it names a file."""
521
+ found = []
522
+ masked = list(line)
523
+ for s, e, kind in self.md_dests(line):
524
+ raw = line[s:e]
525
+ dec = raw.replace('%20', ' ')
526
+ if kind == 'plain':
527
+ dec = re.sub(r'\\(.)', r'\1', dec)
528
+ r = self.token(dec, dir_o, ('file',)) if dec else None
529
+ if r and r[0] == 0 and r[1] == len(dec):
530
+ info = dict(r[2])
531
+ info.update({'md': kind, 'esc': '\\' in raw, 'pct': '%20' in raw})
532
+ found.append((s, e, info))
533
+ for t in range(s, e):
534
+ masked[t] = ' '
535
+ line2 = ''.join(masked)
536
+ spans = []
537
+ for m in re.finditer(r'(`+)(.+?)\1', line2):
538
+ spans.append((m.start(2), m.end(2)))
539
+ for a, b in spans:
540
+ if not self.brain_whole(line2, a, b, found):
541
+ self.brain_tokens(line2, a, b, found)
542
+ masked2 = list(line2)
543
+ for a, b in spans:
544
+ for t in range(a - 1, b + 1):
545
+ if 0 <= t < len(masked2):
546
+ masked2[t] = ' '
547
+ line3 = ''.join(masked2)
548
+ if line3.lstrip().startswith('|'):
549
+ pos = 0
550
+ for cell in line3.split('|'):
551
+ a = pos
552
+ b = pos + len(cell)
553
+ pos = b + 1
554
+ body = cell.strip()
555
+ if body:
556
+ k = a + cell.index(body)
557
+ if not self.brain_whole(line3, k, k + len(body), found) and not re.search(r'\s', body):
558
+ self.brain_tokens(line3, k, k + len(body), found)
559
+ found.sort(key=lambda x: x[0])
560
+ return found
561
+
562
+ def brain_whole(self, line, a, b, found):
563
+ """LINE[a:b], whole (spaces included), as one path relative to the brain: appended to FOUND and True
564
+ when it names an existing old path. A span or a cell is tried whole before it is split in words."""
565
+ seg = line[a:b].strip()
566
+ if not seg or seg != line[a:b] or not re.search(r'\s', seg):
567
+ return False
568
+ r = self.token(seg, '', ('brain',))
569
+ if r and r[0] == 0 and r[1] == len(seg):
570
+ found.append((a, b, r[2]))
571
+ return True
572
+ return False
573
+
574
+ def brain_tokens(self, line, a, b, found):
575
+ """The tokens of LINE[a:b] that name an existing old path relative to the brain, appended to FOUND."""
576
+ i = a
577
+ while i < b:
578
+ if line[i] in DELIMS:
579
+ i += 1
580
+ continue
581
+ j = i
582
+ while j < b and line[j] not in DELIMS:
583
+ j += 1
584
+ r = self.token(line[i:j], '', ('brain',))
585
+ if r:
586
+ s, e, info = r
587
+ found.append((i + s, i + e, info))
588
+ i = j
589
+
590
+ def token(self, tok, dir_o, modes=('file', 'brain')):
591
+ s = 0
592
+ e = len(tok)
593
+ while s < e and tok[s] in '*_~':
594
+ s += 1
595
+ while e > s and tok[e - 1] in '*_~':
596
+ e -= 1
597
+ core = tok[s:e]
598
+ if not core or '://' in core or core.startswith(('mailto:', '#', '/', '~', '$', '-')):
599
+ return None
600
+ if '*' in core or '?' in core or '{{' in core:
601
+ return None
602
+ anch = ''
603
+ if '#' in core:
604
+ k = core.index('#')
605
+ anch = core[k:]
606
+ core = core[:k]
607
+ lsuf = ''
608
+ m = re.search(r':\d+(-\d+)?$', core)
609
+ if m:
610
+ lsuf = core[m.start():]
611
+ core = core[:m.start()]
612
+ elif core.endswith(':'):
613
+ lsuf = ':'
614
+ core = core[:-1]
615
+ trail = ''
616
+ while core.endswith('.') and core not in ('.', '..') and not core.endswith('/.') and not core.endswith('/..'):
617
+ trail += '.'
618
+ core = core[:-1]
619
+ if not core:
620
+ return None
621
+ slash = core.endswith('/')
622
+ path = core.rstrip('/') if slash else core
623
+ if not path:
624
+ return None
625
+ if '/' not in path and not EXT_RE.search(path):
626
+ return None
627
+ cands = []
628
+ c1 = posixpath.normpath(posixpath.join(dir_o, path))
629
+ if 'file' in modes and not c1.startswith('..'):
630
+ cands.append(('file', c1))
631
+ if 'brain' in modes and not path.startswith('../'):
632
+ c2 = posixpath.normpath(path)
633
+ if not c2.startswith('..'):
634
+ cands.append(('brain', c2))
635
+ for mode, P in cands:
636
+ if P in self.old_kind or P in self.old_dirs:
637
+ return (s, e,
638
+ {'mode': mode, 'P': P, 'slash': slash, 'anch': anch, 'lsuf': lsuf, 'trail': trail,
639
+ 'dot': path.startswith('./'), 'path': path})
640
+ return None
641
+
642
+ def map_path(self, P):
643
+ if P in self.fmap:
644
+ return self.fmap[P]
645
+ best = None
646
+ for d, nd in self.dirmap.items():
647
+ if P == d or P.startswith(d + '/'):
648
+ if best is None or len(d) > len(best[0]):
649
+ best = (d, nd)
650
+ if best:
651
+ return best[1] + P[len(best[0]):]
652
+ return None
653
+
654
+ # The frontmatter keys whose value is a path relative to the brain (`superseded_by`, spec 046) or a
655
+ # list of them (`about`, specs 049 and 076): rewritten through the move map like a backticked path.
656
+ FM_PATH_KEYS = ('superseded_by', 'about')
657
+
658
+ def fm_path_line(self, line):
659
+ m = KEY_RE.match(line)
660
+ if not m or m.group(1) not in self.FM_PATH_KEYS:
661
+ return line
662
+ raw = m.group(2).strip()
663
+ is_list = raw.startswith('[') and raw.endswith(']')
664
+ vals = parse_list(raw)
665
+ if not vals:
666
+ return line
667
+ changed = False
668
+ new = []
669
+ for v in vals:
670
+ P = rel_norm(v)
671
+ T = self.map_path(P)
672
+ if T is not None and T != P:
673
+ new.append(T)
674
+ changed = True
675
+ else:
676
+ new.append(v)
677
+ if not changed:
678
+ return line
679
+ value = '[%s]' % ', '.join(new) if is_list else new[0]
680
+ return '%s: %s' % (m.group(1), value)
681
+
682
+ def rewrite_text(self, text, dir_o, dir_n, dirs=None):
683
+ """TEXT with every moved path rewritten once. `dirs` gives, per line, the old directory its relative paths
684
+ are read from (a task block that moved from another backlog keeps the one it came from)."""
685
+ out = []
686
+ count = 0
687
+ all_lines = text.split('\n')
688
+ fm_end = 0
689
+ if all_lines and all_lines[0].rstrip('\r') == '---':
690
+ for k in range(1, len(all_lines)):
691
+ if all_lines[k].rstrip('\r') == '---':
692
+ fm_end = k
693
+ break
694
+ for no, line in enumerate(all_lines):
695
+ if 0 < no < fm_end:
696
+ new_line = self.fm_path_line(line)
697
+ if new_line != line:
698
+ count += 1
699
+ out.append(new_line)
700
+ continue
701
+ d_o = dirs[no] if dirs and no < len(dirs) else dir_o
702
+ if ('/' not in line and '.' not in line):
703
+ out.append(line)
704
+ continue
705
+ res = []
706
+ last = 0
707
+ for s, e, info in self.scan_tokens(line, d_o):
708
+ P = info['P']
709
+ T = self.map_path(P)
710
+ moved = T is not None and T != P
711
+ if T is None and P not in self.kind and P not in self.dirs:
712
+ continue
713
+ if info['mode'] == 'brain':
714
+ if not moved:
715
+ continue
716
+ new = T
717
+ else:
718
+ Tn = T if T is not None else P
719
+ newrel = posixpath.relpath(Tn, dir_n or '.')
720
+ if not moved and newrel == posixpath.normpath(info['path']):
721
+ continue
722
+ new = newrel
723
+ if info['dot'] and not new.startswith('.'):
724
+ new = './' + new
725
+ elif info['dot'] and new.startswith('.') and not new.startswith('..') and not new.startswith('./'):
726
+ new = './' + new
727
+ if info['slash']:
728
+ new += '/'
729
+ full_old = line[s:e]
730
+ tail = info['trail'] + info['lsuf'] + info['anch']
731
+ rep = new + tail
732
+ if info.get('md') == 'plain':
733
+ if info['esc']:
734
+ rep = re.sub(r'([ ()])', r'\\\1', rep)
735
+ elif info['pct']:
736
+ rep = rep.replace(' ', '%20')
737
+ elif re.search(r'[ ()]', rep):
738
+ rep = re.sub(r'([ ()])', r'\\\1', rep)
739
+ if rep == full_old:
740
+ continue
741
+ res.append(line[last:s])
742
+ res.append(rep)
743
+ last = e
744
+ count += 1
745
+ res.append(line[last:])
746
+ out.append(''.join(res))
747
+ return '\n'.join(out), count
748
+
749
+ def plan(self):
750
+ self.collect_unknown()
751
+ self.step1()
752
+ self.step2()
753
+ self.step3()
754
+ self.step4()
755
+ self.step5()
756
+ self.step6()
757
+ self.step7()
758
+ self.step8()
759
+ self.step9()
760
+ self.step10()
761
+ self.step11()
762
+ self.step12()
763
+ self.prune()
764
+
765
+ def unk(self, path, reason=''):
766
+ if not any(u[0] == path for u in self.unknown):
767
+ self.unknown.append((path, reason))
768
+
769
+ def collect_unknown(self):
770
+ ws_known = set([self.head, 'README.md', 'resolver.md', '.resolver.md', 'backlog.md',
771
+ 'decisions.md', 'learnings.md', 'decisions', 'learnings', 'glossary.md', 'context-map.md',
772
+ 'voice.md', 'voice', 'visual-style.md', 'initiatives', 'people', 'records', 'context',
773
+ 'resources', 'index.md'] + self.types)
774
+ node_known = set([self.head, 'README.md', 'resolver.md', '.resolver.md', 'backlog.md',
775
+ 'decisions.md', 'decisions', 'context', 'research', 'material', 'resources', 'archive',
776
+ 'index.md'])
777
+ for ws in self.workspaces():
778
+ for n in self.listdir(ws):
779
+ if n.startswith('.') and n != '.resolver.md':
780
+ continue
781
+ if n not in ws_known:
782
+ self.unk(posixpath.join(ws, n))
783
+ for node in self.nodes(ws):
784
+ for n in self.listdir(node):
785
+ if n.startswith('.') and n != '.resolver.md':
786
+ continue
787
+ if n not in node_known:
788
+ self.unk(posixpath.join(node, n))
789
+ if 'backlog.md' in self.kind:
790
+ self.unk('backlog.md', self.S['MIGRATE_LAYOUT_R_ROOT_BACKLOG'])
791
+
792
+ # step 1 · the account
793
+ def step1(self):
794
+ self.mv('operator.md', 'account/operator.md', 1)
795
+ self.mv('voice.md', 'account/voice/voice.md', 1)
796
+ if self.is_dir('voice'):
797
+ for p in self.files_under('voice'):
798
+ self.mv(p, 'account/' + p, 1)
799
+ self.dirmap['voice'] = 'account/voice'
800
+
801
+ # step 2 · the session contract: adoption and links, each operation on its own
802
+ def contract_state(self, loc):
803
+ full = os.path.join(self.brain, loc)
804
+ if os.path.islink(full):
805
+ if not os.path.exists(full):
806
+ return 'ours'
807
+ return 'ours' if os.path.realpath(full) == self.core_claude else 'foreign'
808
+ if os.path.exists(full):
809
+ return 'foreign'
810
+ return 'absent'
811
+
812
+ def step2(self):
813
+ S = self.S
814
+ locs = ['CLAUDE.md', 'AGENTS.md', '.claude/CLAUDE.md']
815
+ foreign = [l for l in locs if self.contract_state(l) == 'foreign']
816
+ opfile = 'account/operator.md'
817
+ if foreign:
818
+ if opfile not in self.kind:
819
+ self.block(S['MIGRATE_LAYOUT_B_NO_OPERATOR'])
820
+ return
821
+ snaps = []
822
+ seen = set()
823
+ for loc in foreign:
824
+ real = os.path.realpath(os.path.join(self.brain, loc))
825
+ if not os.path.isfile(real) or not os.access(real, os.R_OK):
826
+ self.block(S['MIGRATE_LAYOUT_B_NOT_A_FILE'] % loc)
827
+ return
828
+ if real in seen:
829
+ continue
830
+ seen.add(real)
831
+ with open(real, 'rb') as f:
832
+ snaps.append((loc, f.read()))
833
+ # The adopted text first (one atomic write of the whole account file), the foreign files after it:
834
+ # a cut between the two leaves each operation on its own fingerprint, never half an adoption.
835
+ content = self.read(opfile)
836
+ if content and not content.endswith(b'\n'):
837
+ content += b'\n'
838
+ content += ('\n## %s\n' % S['INSTALL_ADOPTED_HEADING']).encode()
839
+ lines = []
840
+ for loc, data in snaps:
841
+ content += ('\n### %s\n\n' % loc).encode() + data
842
+ if data and not data.endswith(b'\n'):
843
+ content += b'\n'
844
+ lines.append('%s → %s' % (loc, opfile))
845
+ self.put(opfile, content, 2, S['MIGRATE_LAYOUT_D_ADOPT'])
846
+ self.ops[-1]['adopt_lines'] = lines
847
+ for loc in foreign:
848
+ self.delete_disk(loc, 2, S['MIGRATE_LAYOUT_D_ADOPTED'])
849
+ # A root contract that is a link to the product (or broken) is replaced by the two new places.
850
+ if 'CLAUDE.md' not in foreign and os.path.islink(os.path.join(self.brain, 'CLAUDE.md')):
851
+ self.delete_disk('CLAUDE.md', 2, S['MIGRATE_LAYOUT_D_CLAUDE'])
852
+ for loc in ('AGENTS.md', '.claude/CLAUDE.md'):
853
+ full = os.path.join(self.brain, loc)
854
+ if os.path.islink(full) and os.path.realpath(full) == self.core_claude:
855
+ continue
856
+ if loc not in foreign and os.path.islink(full):
857
+ self.delete_disk(loc, 2, '')
858
+ self.link(loc, self.core_claude, 2)
859
+
860
+ # step 3 · the machinery of the root goes to .system/
861
+ def step3(self):
862
+ moved_mounts = self.mv('mounts.md', '.system/mounts.md', 3)
863
+ self.mv('tree.md', '.system/tree.md', 3)
864
+ self.mv('resolver.md', '.system/resolver.md', 3)
865
+ if moved_mounts:
866
+ gi = '.gitignore'
867
+ cur = self.text(gi) if gi in self.kind else ''
868
+ out = []
869
+ have = False
870
+ for l in cur.split('\n'):
871
+ if l.strip() == 'mounts.md':
872
+ if not have:
873
+ out.append('.system/mounts.md')
874
+ have = True
875
+ continue
876
+ if l.strip() == '.system/mounts.md':
877
+ have = True
878
+ out.append(l)
879
+ if not have:
880
+ if out and out[-1] == '':
881
+ out.insert(len(out) - 1, '.system/mounts.md')
882
+ else:
883
+ out.append('.system/mounts.md')
884
+ new = '\n'.join(out)
885
+ if gi not in self.kind and not new.endswith('\n'):
886
+ new += '\n'
887
+ self.put(gi, new, 3, '.system/mounts.md')
888
+
889
+ # step 4 · roles become skills
890
+ def step4(self):
891
+ if not self.is_dir('roles'):
892
+ return
893
+ mds = []
894
+ for n in self.listdir('roles'):
895
+ p = 'roles/' + n
896
+ if p in self.kind and n.endswith('.md'):
897
+ mds.append(n)
898
+ else:
899
+ self.unk(p)
900
+ # Who links each role file by its path: the other roles and, on a brain already half migrated, the
901
+ # skills made from roles (their text still names `roles/<file>`): a file shared by two stays put.
902
+ linkers = {n: set() for n in mds}
903
+ sources = [('r:' + n, 'roles/' + n, 'roles') for n in mds]
904
+ for p in sorted(self.kind):
905
+ if p.startswith('.agents/skills/') and p.endswith('.md') and self.kind[p] == 'f':
906
+ parts = p.split('/')
907
+ if len(parts) >= 4:
908
+ sources.append(('s:' + parts[2], p, posixpath.dirname(p)))
909
+ for key, path, dir_o in sources:
910
+ for line in self.text(path).split('\n'):
911
+ for s_, e_, info in self.scan_tokens(line, dir_o):
912
+ P = info['P']
913
+ if P.startswith('roles/') and P[6:] in linkers and key != 'r:' + P[6:]:
914
+ linkers[P[6:]].add(key)
915
+ owner = {}
916
+ for n in mds:
917
+ ls = linkers[n]
918
+ if len(ls) >= 2:
919
+ self.unk('roles/' + n, self.S['MIGRATE_LAYOUT_R_SHARED_ROLE'])
920
+ owner[n] = False
921
+ elif len(ls) == 1:
922
+ k = next(iter(ls))
923
+ owner[n] = k[2:] if k.startswith('r:') else k
924
+ else:
925
+ owner[n] = None
926
+
927
+ def top(n, seen=()):
928
+ o = owner.get(n)
929
+ if o is None:
930
+ return n
931
+ if isinstance(o, str) and o.startswith('s:'):
932
+ return o
933
+ if o is False or o in seen:
934
+ return False
935
+ return top(o, seen + (n,))
936
+ for n in mds:
937
+ if owner[n] is False:
938
+ continue
939
+ t = top(n)
940
+ if t is False or owner.get(t) is False:
941
+ self.block(self.S['MIGRATE_LAYOUT_B_ROLE_CYCLE'] % ('roles/' + n))
942
+ continue
943
+ name = n[:-3]
944
+ if t == n:
945
+ dst = '.agents/skills/%s/SKILL.md' % name
946
+ if not self.mv('roles/' + n, dst, 4):
947
+ continue
948
+ self.skill_file(dst, name)
949
+ lk = '.claude/skills/%s' % name
950
+ want = '../../.agents/skills/%s' % name
951
+ full = os.path.join(self.brain, lk)
952
+ if os.path.islink(full) and os.readlink(full) == want:
953
+ continue
954
+ if os.path.lexists(full):
955
+ self.block(self.S['MIGRATE_LAYOUT_B_EXISTS'] % (lk, 'roles/' + n))
956
+ continue
957
+ self.link(lk, want, 4)
958
+ elif t.startswith('s:'):
959
+ self.mv('roles/' + n, '.agents/skills/%s/%s' % (t[2:], n), 4)
960
+ else:
961
+ self.mv('roles/' + n, '.agents/skills/%s/%s' % (t[:-3], n), 4)
962
+
963
+ def skill_file(self, path, name):
964
+ text = self.text(path)
965
+ title = ''
966
+ try:
967
+ fm, bs, lines = split_fm(text)
968
+ except Unreadable:
969
+ self.block(self.S['MIGRATE_LAYOUT_B_FM'] % path)
970
+ return
971
+ for l in lines[bs:]:
972
+ if l.startswith('# '):
973
+ title = l[2:].strip()
974
+ break
975
+ desc = re.sub(r'^(Rol|Role)\s*:\s*', '', title, flags=re.I)
976
+ desc = re.sub(r'\s*\(SSOT\)\s*$', '', desc).strip() or name
977
+ if re.search(r'(^[\[\]{}&*!|>\'"%@`#-]|: | #|:$)', desc):
978
+ desc = '"' + desc.replace('\\', '\\\\').replace('"', '\\"') + '"'
979
+ have = fm_dict(text) or {}
980
+ adds = []
981
+ if 'name' not in have:
982
+ adds.append(('name', name))
983
+ if 'description' not in have:
984
+ adds.append(('description', desc))
985
+ if adds:
986
+ self.put(path, add_fm_keys(text, adds), 4, 'name, description')
987
+
988
+ # step 5 · the link to the manual
989
+ def step5(self):
990
+ """The manual link at the root is always `OS_MANUAL_LINK` (D16, C11), to the manual of the brain's
991
+ language (`os_manual_file`, its physical path handed over by the wrapper), as `manual-link.sh` leaves it. An old link with
992
+ the Spanish name is replaced; a brain with no link at all gets one. A file of the operator with that
993
+ name is never touched."""
994
+ name = ENV.get('OS_ML_MANUAL_LINK') or 'HOW-IT-WORKS.md'
995
+ target = ENV.get('OS_ML_MANUAL_TARGET') or os.path.join(self.core, 'manual', name)
996
+ old = 'COMO-FUNCIONA.md'
997
+ if old != name and self.kind.get(old) == 'l':
998
+ self.delete(old, 5, self.S['MIGRATE_LAYOUT_D_MANUAL'])
999
+ self.fmap[old] = name
1000
+ if name not in self.kind:
1001
+ self.link(name, target, 5)
1002
+
1003
+ # step 6 · the hand-written indexes go to the frontmatter of the files they link
1004
+ STD_SUBTITLES = (
1005
+ 'Registro append-only. Nunca se corrige: si una decisión cambia, se agrega otra que la reemplaza y la nombra.',
1006
+ 'Vivo: se actualiza o se borra. Lo que se intentó y no cerró queda con status: provisional, para que nadie lo reintente sin saberlo.',
1007
+ )
1008
+
1009
+ def parse_index(self, idx):
1010
+ """The entries of a hand-written index, and the rest of its text. A line that looks like an entry (a
1011
+ list line that opens with a date, or any line with a link into the index's `decisions/` or `learnings/`)
1012
+ and cannot be read stops the run: its data would be lost. Every other line that is not the first title, a
1013
+ standard subtitle of the product or blank is prose, wherever it sits (before, between or after the
1014
+ entries), and is kept verbatim in `legacy-<index>-notes.md`: consecutive lines stay together, with the
1015
+ blank lines between them, and separate stretches are joined by one blank line."""
1016
+ entries = []
1017
+ chunks = []
1018
+ cur = []
1019
+ pending = []
1020
+ titled = False
1021
+
1022
+ def close():
1023
+ if cur:
1024
+ chunks.append(list(cur))
1025
+ cur[:] = []
1026
+ pending[:] = []
1027
+
1028
+ for no, raw in enumerate(self.text(idx).split('\n'), 1):
1029
+ l = raw.rstrip('\r')
1030
+ if l.strip() == '':
1031
+ if cur:
1032
+ pending.append(raw)
1033
+ continue
1034
+ m = LINE_RE.match(l)
1035
+ if m:
1036
+ close()
1037
+ rest = m.group(5)
1038
+ sup = None
1039
+ note = None
1040
+ mm = SUP_RE.search(rest)
1041
+ if mm:
1042
+ sup = (mm.group(1), mm.group(2))
1043
+ rest = rest[:mm.start()]
1044
+ if rest.startswith(' — '):
1045
+ note = rest[3:]
1046
+ elif rest.strip() != '':
1047
+ self.block(self.S['MIGRATE_LAYOUT_B_INDEX_LINE'] % (idx, no, l))
1048
+ continue
1049
+ entries.append({'date': m.group(1), 'clave': bool(m.group(2)), 'title': m.group(3),
1050
+ 'rel': m.group(4), 'note': note or None, 'sup': sup, 'no': no, 'raw': l})
1051
+ elif ENTRY_LIKE_RE.match(l) or INDEX_LINK_RE.search(l):
1052
+ close()
1053
+ self.block(self.S['MIGRATE_LAYOUT_B_INDEX_LINE'] % (idx, no, l))
1054
+ elif l.startswith('# ') and not titled and not entries and not chunks and not cur:
1055
+ titled = True
1056
+ elif l in self.STD_SUBTITLES:
1057
+ close()
1058
+ else:
1059
+ cur.extend(pending)
1060
+ pending[:] = []
1061
+ cur.append(raw)
1062
+ close()
1063
+ if chunks:
1064
+ self.index_prose[idx] = ['\n'.join(c) for c in chunks]
1065
+ return entries
1066
+
1067
+ def step6(self):
1068
+ idxs = []
1069
+ for ws in self.workspaces():
1070
+ for f in ('decisions.md', 'learnings.md'):
1071
+ if posixpath.join(ws, f) in self.kind:
1072
+ idxs.append(posixpath.join(ws, f))
1073
+ for node in self.nodes(ws):
1074
+ if posixpath.join(node, 'decisions.md') in self.kind:
1075
+ idxs.append(posixpath.join(node, 'decisions.md'))
1076
+ pending = {}
1077
+ order = []
1078
+ all_entries = []
1079
+ for idx in idxs:
1080
+ for e in self.parse_index(idx):
1081
+ tgt = posixpath.normpath(posixpath.join(posixpath.dirname(idx), e['rel']))
1082
+ if tgt not in self.kind or self.kind[tgt] != 'f':
1083
+ self.block(self.S['MIGRATE_LAYOUT_B_INDEX_LINE'] % (idx, e['no'], e['raw']))
1084
+ continue
1085
+ text = self.text(tgt)
1086
+ try:
1087
+ have = fm_dict(text)
1088
+ except Unreadable:
1089
+ have = None
1090
+ if have is None:
1091
+ self.block(self.S['MIGRATE_LAYOUT_B_FM'] % tgt)
1092
+ continue
1093
+ want = {}
1094
+ if 'date' not in have:
1095
+ want['date'] = e['date']
1096
+ if e['clave'] and 'key' not in have:
1097
+ want['key'] = 'true'
1098
+ if 'title' not in have and e['title'] != body_title(text):
1099
+ want['title'] = e['title']
1100
+ if e['note'] and 'index_note' not in have:
1101
+ want['index_note'] = e['note']
1102
+ if e['sup'] and 'superseded_by' not in have:
1103
+ want['superseded_by'] = posixpath.normpath(posixpath.join(posixpath.dirname(idx), e['sup'][1]))
1104
+ cur = pending.setdefault(tgt, {})
1105
+ if tgt not in order:
1106
+ order.append(tgt)
1107
+ for k, v in want.items():
1108
+ if k in cur and cur[k] != v:
1109
+ self.block(self.S['MIGRATE_LAYOUT_B_INDEX_DISAGREE'] % (tgt, k))
1110
+ cur.setdefault(k, v)
1111
+ all_entries.append((tgt, e, have))
1112
+ for tgt in order:
1113
+ adds = [(k, v) for k, v in pending[tgt].items()]
1114
+ if adds:
1115
+ self.put(tgt, add_fm_keys(self.text(tgt), adds), 6, ', '.join(k for k, _ in adds))
1116
+ for tgt, e, have in all_entries:
1117
+ text = self.text(tgt)
1118
+ fmv = fm_dict(text) or {}
1119
+ ok = True
1120
+ if 'date' not in have and fmv.get('date') != e['date']:
1121
+ ok = False
1122
+ if e['clave'] and 'key' not in fmv:
1123
+ ok = False
1124
+ if 'title' not in have and (fmv.get('title') or body_title(text)) != e['title']:
1125
+ ok = False
1126
+ if e['note'] and 'index_note' not in have and fmv.get('index_note') != e['note']:
1127
+ ok = False
1128
+ if e['sup'] and 'superseded_by' not in have and 'superseded_by' not in fmv:
1129
+ ok = False
1130
+ if not ok:
1131
+ self.block(self.S['MIGRATE_LAYOUT_B_INDEX_LINE'] % (tgt, e['no'], e['raw']))
1132
+ if self.blockers:
1133
+ return
1134
+ for idx in idxs:
1135
+ if idx in self.index_prose:
1136
+ notes = posixpath.join(posixpath.dirname(idx), 'legacy-%s-notes.md' % posixpath.basename(idx)[:-3])
1137
+ if notes in self.kind:
1138
+ self.block(self.S['MIGRATE_LAYOUT_B_EXISTS'] % (notes, idx))
1139
+ else:
1140
+ self.put(notes, '\n\n'.join(self.index_prose[idx]) + '\n', 6, '', origin=idx)
1141
+ if self.blockers:
1142
+ return
1143
+ for idx in idxs:
1144
+ base = posixpath.basename(idx)
1145
+ d = posixpath.dirname(idx)
1146
+ if d.count('/') == 1:
1147
+ gen = posixpath.join(d, base[:-3], 'index.md')
1148
+ self.fmap[idx] = gen
1149
+ self.delete(idx, 6, self.S['MIGRATE_LAYOUT_D_INDEX'])
1150
+ else:
1151
+ self.fmap[idx] = posixpath.join(d, 'index.md')
1152
+
1153
+ # step 7 · no backlog outside an initiative (C31)
1154
+ def step7(self):
1155
+ # Only a regular file is a backlog the migration splits: a symbolic link named backlog.md is listed as
1156
+ # not moved, and never read or counted (its target, if it is a backlog, is counted where it lives).
1157
+ strays = []
1158
+ for ws in self.workspaces():
1159
+ for node in [None] + self.nodes(ws):
1160
+ p = (node or ws) + '/backlog.md'
1161
+ if self.kind.get(p) == 'f':
1162
+ strays.append((ws, node, p))
1163
+ elif self.kind.get(p) == 'l':
1164
+ self.unk(p, self.S['MIGRATE_LAYOUT_R_LINKED_BACKLOG'])
1165
+ if not strays:
1166
+ return
1167
+ # A task id already used by two tasks is a numbering collision of the brain's history: the migration
1168
+ # never renumbers, so it is a warning of the plan, one line per id with its backlogs, and never a stop.
1169
+ # What the migration must never do is create one: every block moves once, and the count of each id
1170
+ # after step 7 is checked against the count before it.
1171
+ before = self.task_id_counts()
1172
+ files = {}
1173
+ for p in self.kind:
1174
+ if self.kind[p] != 'f':
1175
+ continue
1176
+ if p.endswith('/backlog.md') or p == 'backlog.md':
1177
+ if p.startswith(self.wsdir + '/') or p == 'backlog.md':
1178
+ for line in self.text(p).split('\n'):
1179
+ if is_task(line):
1180
+ tid, _ = parse_task(line)
1181
+ if tid:
1182
+ files.setdefault(tid, set()).add(p)
1183
+ stray_paths = set(s[2] for s in strays)
1184
+ for tid in sorted(before):
1185
+ if before[tid] > 1 and files.get(tid, set()) & stray_paths:
1186
+ self.warnings.append(self.S['MIGRATE_LAYOUT_W_DUP_ID'] % (tid, ', '.join(sorted(files[tid]))))
1187
+ self.recv = {}
1188
+ self.intro = set()
1189
+ for lg in ('en', 'es'):
1190
+ cat = load_strings(ENV['OS_ML_STRINGS'], lg)
1191
+ for l in cat.get('BACKLOG_INTRO', '').split('\n'):
1192
+ self.intro.add(l.rstrip())
1193
+ for ws, node, path in strays:
1194
+ self.split_backlog(ws, node, path)
1195
+ after = self.task_id_counts()
1196
+ for tid in sorted(after):
1197
+ if after[tid] > before.get(tid, 0):
1198
+ self.block(self.S['MIGRATE_LAYOUT_B_DUP_CREATED'] % (tid, before.get(tid, 0), after[tid]))
1199
+
1200
+ def task_id_counts(self):
1201
+ """How many task lines carry each id, over every backlog.md of the walk (as the model stands now)."""
1202
+ n = {}
1203
+ for p in self.kind:
1204
+ if posixpath.basename(p) == 'backlog.md' and self.kind[p] == 'f':
1205
+ for line in self.text(p).split('\n'):
1206
+ if is_task(line.lstrip(' ')):
1207
+ tid, _ = parse_task(line.lstrip(' '))
1208
+ if tid:
1209
+ n[tid] = n.get(tid, 0) + 1
1210
+ return n
1211
+
1212
+ def ini_title(self, head):
1213
+ t = ''
1214
+ if head in self.kind:
1215
+ try:
1216
+ t = body_title(self.text(head))
1217
+ except Unreadable:
1218
+ t = ''
1219
+ return t
1220
+
1221
+ def paren_target(self, ws, texto, inits):
1222
+ if not texto.startswith('(') or ')' not in texto:
1223
+ return None
1224
+ cand = texto[1:].split(')', 1)[0]
1225
+ if cand in inits:
1226
+ return cand
1227
+ hits = [s for s, h in inits.items() if self.ini_title(h) == cand]
1228
+ return hits[0] if len(hits) == 1 else None
1229
+
1230
+ def receiving(self, ws, node):
1231
+ key = (ws, node)
1232
+ if key in self.recv:
1233
+ return self.recv[key]
1234
+ S = self.S
1235
+ inits = self.initiatives(ws)
1236
+ if node:
1237
+ name = posixpath.basename(node)
1238
+ nh = self.node_head(node)
1239
+ cands = []
1240
+ for s, h in inits.items():
1241
+ d = fm_dict(self.text(h)) or {}
1242
+ if d.get('status') == 'ongoing' and about_is_single(d.get('about', ''), nh):
1243
+ cands.append(s)
1244
+ if len(cands) > 1:
1245
+ self.block(S['MIGRATE_LAYOUT_B_INI_TWO'] % (node, ', '.join(sorted(cands))))
1246
+ self.recv[key] = None
1247
+ return None
1248
+ if len(cands) == 1:
1249
+ self.recv[key] = cands[0]
1250
+ return cands[0]
1251
+ if name in inits or posixpath.join(ws, 'initiatives', name) in self.dirs:
1252
+ self.block(S['MIGRATE_LAYOUT_B_INI_TAKEN'] % (name, node))
1253
+ self.recv[key] = None
1254
+ return None
1255
+ head = self.ini_head_path(ws, name)
1256
+ title = ''
1257
+ if nh in self.kind:
1258
+ try:
1259
+ title = body_title(self.text(nh))
1260
+ except Unreadable:
1261
+ title = ''
1262
+ self.put(head, render_ini(title or name, 'ongoing', nh), 7, '')
1263
+ self.recv[key] = name
1264
+ return name
1265
+ slug = 'tasks-to-sort'
1266
+ if slug in inits:
1267
+ d = fm_dict(self.text(inits[slug])) or {}
1268
+ if d.get('about'):
1269
+ self.block(S['MIGRATE_LAYOUT_B_INI_TAKEN'] % (slug, ws))
1270
+ self.recv[key] = None
1271
+ return None
1272
+ self.recv[key] = slug
1273
+ return slug
1274
+ if posixpath.join(ws, 'initiatives', slug) in self.dirs:
1275
+ self.block(S['MIGRATE_LAYOUT_B_INI_TAKEN'] % (slug, ws))
1276
+ self.recv[key] = None
1277
+ return None
1278
+ head = self.ini_head_path(ws, slug)
1279
+ self.put(head, render_ini(S['TASKS_TO_SORT_TITLE'], 'active', ''), 7, '')
1280
+ self.recv[key] = slug
1281
+ return slug
1282
+
1283
+ def backlog_header(self, title):
1284
+ return '# %s %s\n\n%s\n\n' % (self.S['BACKLOG_TITLE'], title, self.S['BACKLOG_INTRO'])
1285
+
1286
+ def append_tasks(self, ws, slug, blocks, origin):
1287
+ bl = posixpath.join(ws, 'initiatives', slug, 'backlog.md')
1288
+ add = ''.join(l + '\n' for blk in blocks for l in blk)
1289
+ if bl in self.kind:
1290
+ cur = self.text(bl)
1291
+ if cur and not cur.endswith('\n'):
1292
+ cur += '\n'
1293
+ else:
1294
+ head = self.initiatives(ws).get(slug)
1295
+ title = self.ini_title(head) if head else ''
1296
+ cur = self.backlog_header(title or slug)
1297
+ new = cur + add
1298
+ self.put(bl, new, 7, '')
1299
+ if bl not in self.origin:
1300
+ self.origin[bl] = bl
1301
+ # Provenance is the range of lines this append wrote, recorded here: never recovered later by matching
1302
+ # task text, which an identical task already in the destination would steal.
1303
+ first = cur.count('\n')
1304
+ self.prov.setdefault(bl, []).append((first, add.count('\n'), posixpath.dirname(origin)))
1305
+ got = self.text(bl)
1306
+ for blk in blocks:
1307
+ if '\n'.join(blk) + '\n' not in got:
1308
+ self.block(self.S['MIGRATE_LAYOUT_B_TASK_LOST'] % blk[0])
1309
+
1310
+ def split_backlog(self, ws, node, path):
1311
+ lines = self.text(path).split('\n')
1312
+ if lines and lines[-1] == '':
1313
+ lines.pop()
1314
+ blocks = []
1315
+ notes = []
1316
+ title_seen = False
1317
+ owner_of = [None] * len(lines)
1318
+ i, n = 0, len(lines)
1319
+ while i < n:
1320
+ l = lines[i]
1321
+ if is_task(l):
1322
+ # the task, and everything indented that follows it, blank lines inside included
1323
+ end = i
1324
+ j = i + 1
1325
+ while j < n:
1326
+ if lines[j].strip() == '':
1327
+ j += 1
1328
+ elif lines[j][:1] in (' ', '\t'):
1329
+ end = j
1330
+ j += 1
1331
+ else:
1332
+ break
1333
+ blocks.append(lines[i:end + 1])
1334
+ for t in range(i, end + 1):
1335
+ owner_of[t] = 'block'
1336
+ i = end + 1
1337
+ continue
1338
+ if l.strip() == '':
1339
+ i += 1
1340
+ continue
1341
+ if l.startswith('# ') and not title_seen:
1342
+ title_seen = True
1343
+ owner_of[i] = 'title'
1344
+ i += 1
1345
+ continue
1346
+ if l.rstrip() in self.intro:
1347
+ owner_of[i] = 'intro'
1348
+ i += 1
1349
+ continue
1350
+ notes.append(l)
1351
+ owner_of[i] = 'note'
1352
+ i += 1
1353
+ # every line that says something belongs to exactly one place before the file can go
1354
+ for t, l in enumerate(lines):
1355
+ if l.strip() != '' and owner_of[t] is None:
1356
+ self.block(self.S['MIGRATE_LAYOUT_B_TASK_LOST'] % l)
1357
+ inits = self.initiatives(ws)
1358
+ routed = {}
1359
+ loose = []
1360
+ for blk in blocks:
1361
+ _, texto = parse_task(blk[0])
1362
+ tgt = self.paren_target(ws, texto, inits)
1363
+ if tgt:
1364
+ routed.setdefault(tgt, []).append(blk)
1365
+ else:
1366
+ loose.append(blk)
1367
+ for slug in sorted(routed):
1368
+ self.append_tasks(ws, slug, routed[slug], path)
1369
+ if loose or notes:
1370
+ slug = self.receiving(ws, node)
1371
+ if slug is None:
1372
+ return
1373
+ if loose:
1374
+ self.append_tasks(ws, slug, loose, path)
1375
+ if notes:
1376
+ np_ = posixpath.join(ws, 'initiatives', slug, 'legacy-backlog-notes.md')
1377
+ if np_ in self.kind:
1378
+ self.block(self.S['MIGRATE_LAYOUT_B_EXISTS'] % (np_, path))
1379
+ else:
1380
+ self.put(np_, '\n'.join(notes) + '\n', 7, '', origin=path)
1381
+ self.delete(path, 7, self.S['MIGRATE_LAYOUT_D_BACKLOG'])
1382
+
1383
+ # step 8 · the decisions of a node go to the workspace
1384
+ def step8(self):
1385
+ for ws in self.workspaces():
1386
+ for node in self.nodes(ws):
1387
+ nh = self.node_head(node)
1388
+ dd = node + '/decisions'
1389
+ if self.is_dir(dd):
1390
+ for p in self.files_under(dd):
1391
+ dst = posixpath.join(ws, 'decisions', posixpath.basename(p))
1392
+ if self.mv(p, dst, 8) and dst.endswith('.md'):
1393
+ text = self.text(dst)
1394
+ have = fm_dict(text)
1395
+ if have is None:
1396
+ self.block(self.S['MIGRATE_LAYOUT_B_FM'] % dst)
1397
+ elif 'about' not in have:
1398
+ self.put(dst, add_fm_keys(text, [('about', nh)]), 8, 'about')
1399
+ self.dirmap[dd] = posixpath.join(ws, 'decisions')
1400
+ if node + '/decisions.md' in self.kind:
1401
+ self.delete(node + '/decisions.md', 8, self.S['MIGRATE_LAYOUT_D_INDEX'])
1402
+
1403
+ # step 9 · resolvers become hidden
1404
+ def rows(self, text):
1405
+ ls = [l for l in text.split('\n') if l.lstrip().startswith('|')]
1406
+ sep = [i for i, l in enumerate(ls) if re.match(r'^\s*\|[\s:|-]+\|?\s*$', l)]
1407
+ heads = set(i - 1 for i in sep if i > 0)
1408
+ return len([i for i in range(len(ls)) if i not in sep and i not in heads])
1409
+
1410
+ def step9(self):
1411
+ for ws in self.workspaces():
1412
+ self.mv(ws + '/resolver.md', ws + '/.resolver.md', 9)
1413
+ for node in self.nodes(ws):
1414
+ r = node + '/resolver.md'
1415
+ if r not in self.kind:
1416
+ continue
1417
+ if self.rows(self.text(r)) == 0:
1418
+ self.delete(r, 9, self.S['MIGRATE_LAYOUT_D_RESOLVER'])
1419
+ else:
1420
+ self.mv(r, node + '/.resolver.md', 9)
1421
+
1422
+ # step 10 · resources and context
1423
+ def step10(self):
1424
+ for ws in self.workspaces():
1425
+ for f in ('voice.md', 'visual-style.md'):
1426
+ self.mv(posixpath.join(ws, f), posixpath.join(ws, 'resources', f), 10)
1427
+ vd = ws + '/voice'
1428
+ if self.is_dir(vd):
1429
+ for p in self.files_under(vd):
1430
+ self.mv(p, posixpath.join(ws, 'resources', p[len(ws) + 1:]), 10)
1431
+ self.dirmap[vd] = ws + '/resources/voice'
1432
+ for f in ('glossary.md', 'context-map.md'):
1433
+ self.mv(posixpath.join(ws, f), posixpath.join(ws, 'context', f), 10)
1434
+ for node in self.nodes(ws):
1435
+ md = node + '/material'
1436
+ if self.is_dir(md):
1437
+ for p in self.files_under(md):
1438
+ self.mv(p, node + '/resources/' + p[len(md) + 1:], 10)
1439
+ self.dirmap[md] = node + '/resources'
1440
+
1441
+ # step 11 · every link, once, from the fixed map
1442
+ def fix_symlinks(self):
1443
+ """A relative symlink that moved, or whose target moved, is recomputed against the mapped target."""
1444
+ for p in sorted(p for p, k in self.kind.items() if k == 'l'):
1445
+ o = self.origin.get(p, p)
1446
+ if o not in self.old_target:
1447
+ continue
1448
+ t = self.old_target[o]
1449
+ absolute = t.startswith('/')
1450
+ if absolute:
1451
+ root = self.brain.rstrip('/') + '/'
1452
+ if not t.startswith(root):
1453
+ continue
1454
+ old_abs = posixpath.normpath(t[len(root):])
1455
+ else:
1456
+ old_abs = posixpath.normpath(posixpath.join(posixpath.dirname(o), t))
1457
+ if old_abs.startswith('..') or not (old_abs in self.old_kind or old_abs in self.old_dirs):
1458
+ continue
1459
+ T = self.map_path(old_abs) or old_abs
1460
+ new = (self.brain.rstrip('/') + '/' + T) if absolute else posixpath.relpath(T, posixpath.dirname(p) or '.')
1461
+ if new != self.target[p]:
1462
+ self.delete(p, 11, self.S['MIGRATE_LAYOUT_D_RELINK'])
1463
+ self.link(p, new, 11)
1464
+
1465
+ def step11(self):
1466
+ if self.blockers:
1467
+ return
1468
+ self.fix_symlinks()
1469
+ for p in sorted(self.kind):
1470
+ if not p.endswith('.md') or self.kind[p] != 'f' or p == '.system/tree.md':
1471
+ continue
1472
+ if p not in self.origin:
1473
+ continue
1474
+ o = self.origin[p]
1475
+ text = self.text(p)
1476
+ lines = text.split('\n')
1477
+ dirs = None
1478
+ if p in self.prov:
1479
+ dirs = [posixpath.dirname(o)] * len(lines)
1480
+ for first, count, odir in self.prov[p]:
1481
+ for t in range(first, min(first + count, len(lines))):
1482
+ dirs[t] = odir
1483
+ new, n = self.rewrite_text(text, posixpath.dirname(o), posixpath.dirname(p), dirs)
1484
+ if n and new != text:
1485
+ self.put(p, new, 11, self.S['MIGRATE_LAYOUT_N_LINKS'] % n)
1486
+
1487
+ # step 12 · tree.md, last
1488
+ def tree_map(self, pat):
1489
+ """Where a tree declaration goes through the move map: the new pattern, 'drop' when what it reached is
1490
+ deleted, or None when the migration does not touch what it reaches."""
1491
+ segs = pat.split('/')
1492
+ n = len(segs)
1493
+ root = {'operator.md': 'account/operator.md', 'voice.md': 'account/voice/voice.md',
1494
+ 'tree.md': '.system/tree.md', 'resolver.md': '.system/resolver.md',
1495
+ 'mounts.md': '.system/mounts.md', 'COMO-FUNCIONA.md': 'HOW-IT-WORKS.md'}
1496
+ if segs[0] != self.wsdir:
1497
+ if pat in root:
1498
+ return root[pat]
1499
+ if segs[0] == 'voice' and n > 1:
1500
+ return 'account/' + pat
1501
+ return None
1502
+ if n < 3:
1503
+ return None
1504
+ ws = segs[:2]
1505
+ rest = segs[2:]
1506
+ if len(rest) == 1:
1507
+ f = rest[0]
1508
+ if f == 'resolver.md':
1509
+ return '/'.join(ws + ['.resolver.md'])
1510
+ if f in ('decisions.md', 'learnings.md', 'backlog.md'):
1511
+ return 'drop'
1512
+ if f in ('voice.md', 'visual-style.md'):
1513
+ return '/'.join(ws + ['resources', f])
1514
+ if f in ('glossary.md', 'context-map.md'):
1515
+ return '/'.join(ws + ['context', f])
1516
+ return None
1517
+ if rest[0] == 'voice':
1518
+ return '/'.join(ws + ['resources'] + rest)
1519
+ if len(rest) >= 3 and rest[0] in self.types:
1520
+ node = ws + rest[:2]
1521
+ r2 = rest[2:]
1522
+ if r2 == ['resolver.md']:
1523
+ return '/'.join(node + ['.resolver.md'])
1524
+ if r2 in (['decisions.md'], ['backlog.md']):
1525
+ return 'drop'
1526
+ if r2[0] == 'material' and len(r2) > 1:
1527
+ return '/'.join(node + ['resources'] + r2[1:])
1528
+ if r2[0] == 'decisions':
1529
+ return '/'.join(ws + ['decisions', r2[1]]) if len(r2) == 2 else 'drop'
1530
+ return None
1531
+
1532
+ @staticmethod
1533
+ def glob_match(pat, path):
1534
+ a, b = pat.split('/'), path.split('/')
1535
+ return len(a) == len(b) and all(fnmatch.fnmatchcase(y, x) for x, y in zip(a, b))
1536
+
1537
+ def step12(self):
1538
+ if self.blockers:
1539
+ return
1540
+ tp = '.system/tree.md'
1541
+ if tp not in self.kind:
1542
+ self.block(self.S['MIGRATE_LAYOUT_B_NO_TREE'])
1543
+ return
1544
+ text = self.text(tp)
1545
+ lines = text.split('\n')
1546
+ unmoved = [p for p in self.kind if self.origin.get(p, p) == p and p not in self.created]
1547
+ out = []
1548
+ removed = 0
1549
+ for l in lines:
1550
+ m = re.match(r'^(glob|content|archive):\s*(.*?)\s*$', l)
1551
+ if not m:
1552
+ out.append(l)
1553
+ continue
1554
+ r = self.tree_map(m.group(2))
1555
+ if r is None:
1556
+ out.append(l)
1557
+ continue
1558
+ # what the pattern still reaches where it is keeps the declaration; what moved gets it transformed
1559
+ if any(self.glob_match(m.group(2), p) for p in unmoved):
1560
+ out.append(l)
1561
+ else:
1562
+ removed += 1
1563
+ if r != 'drop':
1564
+ out.append('%s: %s' % (m.group(1), r))
1565
+ keep = []
1566
+ seen = set()
1567
+ for l in out:
1568
+ m = re.match(r'^(glob|content|archive):\s*(.*?)\s*$', l)
1569
+ if m:
1570
+ key = '%s: %s' % (m.group(1), m.group(2))
1571
+ if key in seen:
1572
+ continue
1573
+ seen.add(key)
1574
+ keep.append(l)
1575
+ have = seen
1576
+ tpl = os.path.join(self.core, 'templates', 'tree.md')
1577
+ add = []
1578
+ with open(tpl, encoding='utf-8') as f:
1579
+ for l in f.read().split('\n'):
1580
+ m = re.match(r'^(glob|content|archive):\s*(.*?)\s*$', l)
1581
+ if not m:
1582
+ continue
1583
+ pat = m.group(2).replace('{{MANUAL}}', 'HOW-IT-WORKS.md')
1584
+ if pat.startswith('workspaces/'):
1585
+ pat = self.wsdir + pat[len('workspaces'):]
1586
+ line = '%s: %s' % (m.group(1), pat)
1587
+ if self.tree_map(pat) is not None:
1588
+ continue
1589
+ if pat.endswith('/README.md') and self.head != 'README.md':
1590
+ continue
1591
+ if line not in have:
1592
+ have.add(line)
1593
+ add.append(line)
1594
+ # The notes the migration keeps from a hand-written index (`legacy-<index>-notes.md`, step 6) sit next to
1595
+ # the generated index, where no line of the template reaches: each kind gets one `content:` line, with
1596
+ # the workspace and the node as `*`, unless a line already reaches it.
1597
+ for p in sorted(self.kind):
1598
+ if not re.match(r'^legacy-(decisions|learnings)-notes\.md$', posixpath.basename(p)):
1599
+ continue
1600
+ if '/initiatives/' in p or not p.startswith(self.wsdir + '/'):
1601
+ continue
1602
+ reached = False
1603
+ for l in keep + add:
1604
+ m = re.match(r'^(glob|content|archive):\s*(.*?)\s*$', l)
1605
+ if m and self.glob_match(m.group(2), p):
1606
+ reached = True
1607
+ break
1608
+ if reached:
1609
+ continue
1610
+ seg = p.split('/')
1611
+ seg[1] = '*'
1612
+ if len(seg) == 5:
1613
+ seg[3] = '*'
1614
+ line = 'content: ' + '/'.join(seg)
1615
+ if line not in have:
1616
+ have.add(line)
1617
+ add.append(line)
1618
+ new = '\n'.join(keep)
1619
+ while new.endswith('\n\n'):
1620
+ new = new[:-1]
1621
+ if not new.endswith('\n'):
1622
+ new += '\n'
1623
+ new += ''.join(l + '\n' for l in add)
1624
+ if new == text:
1625
+ return
1626
+ self.put(tp, new, 12, self.S['MIGRATE_LAYOUT_N_TREE'] % (removed, len(add)))
1627
+
1628
+ def prune(self):
1629
+ dirs = set()
1630
+ for op in self.ops:
1631
+ for k in ('src', 'path'):
1632
+ p = op.get(k)
1633
+ if p and op['op'] in ('move', 'delete'):
1634
+ d = posixpath.dirname(p)
1635
+ while d:
1636
+ dirs.add(d)
1637
+ d = posixpath.dirname(d)
1638
+ empty = []
1639
+ for d in sorted(dirs, key=lambda x: -x.count('/')):
1640
+ pre = d + '/'
1641
+ if not any(k.startswith(pre) for k in self.kind):
1642
+ empty.append(d)
1643
+ if empty:
1644
+ self.rec(12, 'prune', dirs=empty)
1645
+
1646
+
1647
+ # ---------------------------------------------------------------- printing the plan
1648
+ def op_lines(S, op):
1649
+ k = op['op']
1650
+ if k == 'move':
1651
+ return ['%s %s → %s' % (S['MIGRATE_LAYOUT_V_MOVE'], op['src'], op['dst'])]
1652
+ if k == 'put':
1653
+ if op['before'] is None:
1654
+ return ['%s %s' % (S['MIGRATE_LAYOUT_V_CREATE'], op['path'])]
1655
+ d = ' (%s)' % op['detail'] if op.get('detail') else ''
1656
+ out = ['%s %s%s' % (S['MIGRATE_LAYOUT_V_REWRITE'], op['path'], d)]
1657
+ for l in op.get('adopt_lines', []):
1658
+ out.append('%s %s' % (S['MIGRATE_LAYOUT_V_ADOPT'], l))
1659
+ return out
1660
+ if k == 'delete':
1661
+ d = ' (%s)' % op['detail'] if op.get('detail') else ''
1662
+ return ['%s %s%s' % (S['MIGRATE_LAYOUT_V_DELETE'], op['path'], d)]
1663
+ if k == 'link':
1664
+ return ['%s %s → %s' % (S['MIGRATE_LAYOUT_V_LINK'], op['path'], op['target'])]
1665
+ return []
1666
+
1667
+
1668
+ def print_plan(S, ops, unknown, header=True):
1669
+ n = len([o for o in ops if o['op'] != 'prune'])
1670
+ if header:
1671
+ print(S['MIGRATE_LAYOUT_PLAN_HEAD'] % n)
1672
+ last = None
1673
+ for op in ops:
1674
+ ls = op_lines(S, op)
1675
+ if not ls:
1676
+ continue
1677
+ if op['step'] != last:
1678
+ last = op['step']
1679
+ print(S['MIGRATE_LAYOUT_STEP_%d' % last])
1680
+ for l in ls:
1681
+ print(' ' + l)
1682
+ if unknown:
1683
+ print(S['MIGRATE_LAYOUT_UNKNOWN_HEAD'])
1684
+ for path, reason in unknown:
1685
+ print(' %s · %s%s' % (S['MIGRATE_LAYOUT_V_UNKNOWN'], path, ' (%s)' % reason if reason else ''))
1686
+
1687
+
1688
+ # ---------------------------------------------------------------- applying the plan
1689
+ class Runner:
1690
+ def __init__(self, brain, S, ops, core):
1691
+ self.brain = brain
1692
+ self.S = S
1693
+ self.ops = ops
1694
+ self.core = core
1695
+ self.core_claude = os.path.join(os.path.realpath(core), 'CLAUDE.md')
1696
+ self.plan_file = os.path.join(brain, PLAN_REL)
1697
+ self.blobs = os.path.join(brain, BLOB_REL)
1698
+ self.counts = {}
1699
+ hook = ENV.get('OS_MIGRATE_LAYOUT_INTERRUPT_AFTER', '')
1700
+ self.hook = None
1701
+ if hook and ':' in hook:
1702
+ k, n = hook.rsplit(':', 1)
1703
+ self.hook = (k, int(n))
1704
+
1705
+ def cur(self, path):
1706
+ full = os.path.join(self.brain, path)
1707
+ if os.path.islink(full):
1708
+ return 'L:' + os.readlink(full)
1709
+ if os.path.isfile(full):
1710
+ with open(full, 'rb') as f:
1711
+ return sha(f.read())
1712
+ if os.path.exists(full):
1713
+ return 'D'
1714
+ return None
1715
+
1716
+ def state(self, op):
1717
+ k = op['op']
1718
+ if k == 'move':
1719
+ s, d = self.cur(op['src']), self.cur(op['dst'])
1720
+ if s is None and d == op['fp']:
1721
+ return 'done'
1722
+ if s == op['fp'] and (d is None or d == op['fp']):
1723
+ return 'pending'
1724
+ return 'foreign'
1725
+ if k == 'put':
1726
+ c = self.cur(op['path'])
1727
+ if c == op['after']:
1728
+ return 'done'
1729
+ if c == op['before']:
1730
+ return 'pending'
1731
+ return 'foreign'
1732
+ if k == 'delete':
1733
+ c = self.cur(op['path'])
1734
+ if c is None:
1735
+ return 'done'
1736
+ return 'pending' if c == op['fp'] else 'foreign'
1737
+ if k == 'link':
1738
+ c = self.cur(op['path'])
1739
+ if c == 'L:' + op['target']:
1740
+ return 'done'
1741
+ return 'pending' if c is None else 'foreign'
1742
+ return 'pending'
1743
+
1744
+ def guard(self, rel):
1745
+ """Refuse to write under a symlink or a file standing where a directory should be."""
1746
+ d = posixpath.dirname(rel)
1747
+ parts = []
1748
+ while d:
1749
+ parts.append(d)
1750
+ d = posixpath.dirname(d)
1751
+ for a in reversed(parts):
1752
+ full = os.path.join(self.brain, a)
1753
+ if os.path.islink(full) or (os.path.lexists(full) and not os.path.isdir(full)):
1754
+ raise RuntimeError('unsafe destination ancestor: ' + a)
1755
+
1756
+ def execute(self, op):
1757
+ k = op['op']
1758
+ b = self.brain
1759
+ if k == 'move':
1760
+ src, dst = os.path.join(b, op['src']), os.path.join(b, op['dst'])
1761
+ self.guard(op['dst'])
1762
+ if os.path.lexists(dst):
1763
+ os.remove(src)
1764
+ else:
1765
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
1766
+ os.rename(src, dst)
1767
+ elif k == 'put':
1768
+ path = os.path.join(b, op['path'])
1769
+ self.guard(op['path'])
1770
+ with open(os.path.join(self.blobs, op['after']), 'rb') as f:
1771
+ data = f.read()
1772
+ os.makedirs(os.path.dirname(path), exist_ok=True)
1773
+ mode = os.stat(path).st_mode & 0o7777 if os.path.isfile(path) else 0o644
1774
+ tmp = path + '.os-tmp'
1775
+ with open(tmp, 'wb') as f:
1776
+ f.write(data)
1777
+ os.chmod(tmp, mode)
1778
+ os.replace(tmp, path)
1779
+ elif k == 'delete':
1780
+ os.remove(os.path.join(b, op['path']))
1781
+ elif k == 'link':
1782
+ path = os.path.join(b, op['path'])
1783
+ self.guard(op['path'])
1784
+ os.makedirs(os.path.dirname(path), exist_ok=True)
1785
+ os.symlink(op['target'], path)
1786
+ elif k == 'prune':
1787
+ for d in op['dirs']:
1788
+ try:
1789
+ os.rmdir(os.path.join(b, d))
1790
+ except OSError:
1791
+ pass
1792
+
1793
+ def mark(self, i):
1794
+ with open(self.plan_file, 'a') as f:
1795
+ f.write(json.dumps({'done': i}) + '\n')
1796
+
1797
+ def preflight(self, done_n):
1798
+ """Resume check: nothing the plan has not yet touched may differ from what the plan fingerprinted."""
1799
+ bad = []
1800
+ first = done_n
1801
+ while first < len(self.ops) and self.ops[first]['op'] != 'prune' and self.state(self.ops[first]) == 'done':
1802
+ first += 1
1803
+ # Everything the completed operations left behind must still be as they left it.
1804
+ expected = {}
1805
+ for op in self.ops[:first]:
1806
+ k = op['op']
1807
+ if k == 'move':
1808
+ expected[op['src']] = None
1809
+ expected[op['dst']] = op['fp']
1810
+ elif k == 'put':
1811
+ expected[op['path']] = op['after']
1812
+ elif k == 'delete':
1813
+ expected[op['path']] = None
1814
+ elif k == 'link':
1815
+ expected[op['path']] = 'L:' + op['target']
1816
+ for path, fp in expected.items():
1817
+ if self.cur(path) != fp:
1818
+ bad.append(path)
1819
+ for op in self.ops[first:]:
1820
+ for path, fp in op.get('pre', []):
1821
+ if self.cur(path) != fp:
1822
+ bad.append(path)
1823
+ for path in op.get('absent', []):
1824
+ if self.cur(path) is not None:
1825
+ bad.append(path)
1826
+ return bad
1827
+
1828
+ def run(self, done):
1829
+ S = self.S
1830
+ for op in self.ops:
1831
+ if op['i'] in done:
1832
+ continue
1833
+ st = self.state(op)
1834
+ if st == 'foreign':
1835
+ return 1, S['MIGRATE_LAYOUT_B_FOREIGN'] % (op.get('src') or op.get('path') or 'install')
1836
+ if st == 'pending':
1837
+ try:
1838
+ self.execute(op)
1839
+ except Exception as ex:
1840
+ return 1, S['MIGRATE_LAYOUT_B_OP_FAILED'] % (op.get('src') or op.get('path') or 'install', ex)
1841
+ if op['op'] != 'prune' and self.state(op) != 'done':
1842
+ return 1, S['MIGRATE_LAYOUT_B_OP_FAILED'] % (op.get('src') or op.get('path') or 'install', 'result differs from the plan')
1843
+ self.mark(op['i'])
1844
+ if op['op'] != 'prune':
1845
+ for key in (op['op'], 'step%d' % op['step']):
1846
+ self.counts[key] = self.counts.get(key, 0) + 1
1847
+ if self.hook and self.counts.get(self.hook[0], 0) >= self.hook[1]:
1848
+ return 3, ''
1849
+ return 0, ''
1850
+
1851
+
1852
+ def plan_paths(ops):
1853
+ s = set()
1854
+ for op in ops:
1855
+ for k in ('src', 'dst', 'path'):
1856
+ if op.get(k):
1857
+ s.add(op[k])
1858
+ for p in op.get('extra', []):
1859
+ s.add(p)
1860
+ return s
1861
+
1862
+
1863
+ def git_changes(brain):
1864
+ if not os.path.exists(os.path.join(brain, '.git')):
1865
+ return []
1866
+ r = subprocess.run(['git', '-C', brain, 'status', '--porcelain', '-z', '--untracked-files=all'],
1867
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
1868
+ parts = r.stdout.decode('utf-8', 'surrogateescape').split('\0')
1869
+ out = []
1870
+ i = 0
1871
+ while i < len(parts):
1872
+ e = parts[i]
1873
+ i += 1
1874
+ if len(e) < 4:
1875
+ continue
1876
+ xy, path = e[:2], e[3:]
1877
+ if xy[0] in 'RC':
1878
+ i += 1
1879
+ if xy == '??' and (path.startswith('.claude/') or path.startswith('.os/')):
1880
+ continue
1881
+ out.append(path)
1882
+ return out
1883
+
1884
+
1885
+ def save_plan(brain, ops, unknown, lang):
1886
+ os.makedirs(os.path.join(brain, BLOB_REL), exist_ok=True)
1887
+ lines = [json.dumps({'v': 1, 'lang': lang, 'unknown': unknown})]
1888
+ for op in ops:
1889
+ o = dict(op)
1890
+ blob = o.pop('blob', None)
1891
+ if blob is not None:
1892
+ with open(os.path.join(brain, BLOB_REL, o['after']), 'wb') as f:
1893
+ f.write(blob)
1894
+ lines.append(json.dumps(o))
1895
+ tmp = os.path.join(brain, PLAN_REL + '.tmp')
1896
+ with open(tmp, 'w') as f:
1897
+ f.write('\n'.join(lines) + '\n')
1898
+ os.replace(tmp, os.path.join(brain, PLAN_REL))
1899
+
1900
+
1901
+ def load_plan(brain):
1902
+ ops, done, unknown = [], set(), []
1903
+ with open(os.path.join(brain, PLAN_REL)) as f:
1904
+ for n, line in enumerate(f):
1905
+ line = line.strip()
1906
+ if not line:
1907
+ continue
1908
+ d = json.loads(line)
1909
+ if n == 0:
1910
+ unknown = d.get('unknown', [])
1911
+ elif 'done' in d:
1912
+ done.add(d['done'])
1913
+ else:
1914
+ ops.append(d)
1915
+ return ops, done, unknown
1916
+
1917
+
1918
+ def cleanup(brain):
1919
+ import shutil
1920
+ try:
1921
+ os.remove(os.path.join(brain, PLAN_REL))
1922
+ except OSError:
1923
+ pass
1924
+ shutil.rmtree(os.path.join(brain, BLOB_REL), ignore_errors=True)
1925
+
1926
+
1927
+ def stop(S, msgs):
1928
+ print(S['MIGRATE_LAYOUT_STOPPED'])
1929
+ for m in msgs:
1930
+ print(' ' + m)
1931
+ return 1
1932
+
1933
+
1934
+ def main():
1935
+ brain = ENV['OS_ML_BRAIN']
1936
+ apply_ = ENV.get('OS_ML_APPLY') == '1'
1937
+ S = load_strings(ENV['OS_ML_STRINGS'], ENV['OS_ML_LANG'])
1938
+ core = ENV['OS_ML_CORE']
1939
+ plan_file = os.path.join(brain, PLAN_REL)
1940
+ if os.path.exists(plan_file):
1941
+ ops, done, unknown = load_plan(brain)
1942
+ n_done = 0
1943
+ while n_done in done:
1944
+ n_done += 1
1945
+ total = len([o for o in ops if o['op'] != 'prune'])
1946
+ runner = Runner(brain, S, ops, core)
1947
+ if not apply_:
1948
+ print(S['MIGRATE_LAYOUT_RESUME_PENDING'] % (n_done, len(ops)))
1949
+ print_plan(S, [o for o in ops if o['i'] >= n_done], unknown, header=False)
1950
+ return 0
1951
+ print(S['MIGRATE_LAYOUT_RESUME'] % (n_done, len(ops)))
1952
+ allowed = plan_paths(ops)
1953
+ foreign = [p for p in git_changes(brain) if p not in allowed]
1954
+ bad = runner.preflight(n_done)
1955
+ if foreign or bad:
1956
+ return stop(S, [S['MIGRATE_LAYOUT_B_FOREIGN'] % p for p in (foreign + bad)[:8]])
1957
+ rc, msg = runner.run(done)
1958
+ if rc == 1:
1959
+ return stop(S, [msg])
1960
+ if rc == 3:
1961
+ return 3
1962
+ cleanup(brain)
1963
+ print(S['MIGRATE_LAYOUT_DONE'] % total)
1964
+ return 0
1965
+ P = Planner(brain, S)
1966
+ P.plan()
1967
+ if not P.ops:
1968
+ print(S['MIGRATE_LAYOUT_NOTHING'])
1969
+ return 0
1970
+ print_plan(S, P.ops, P.unknown)
1971
+ if P.warnings:
1972
+ print(S['MIGRATE_LAYOUT_WARN_HEAD'])
1973
+ for w in P.warnings:
1974
+ print(' ' + w)
1975
+ if P.blockers:
1976
+ print(S['MIGRATE_LAYOUT_STOPPED'] if apply_ else S['MIGRATE_LAYOUT_WOULD_STOP'])
1977
+ for b in P.blockers:
1978
+ print(' ' + b)
1979
+ return 1 if apply_ else 0
1980
+ if not apply_:
1981
+ print(S['MIGRATE_LAYOUT_HINT'])
1982
+ return 0
1983
+ dirty = git_changes(brain)
1984
+ if dirty:
1985
+ return stop(S, [S['MIGRATE_LAYOUT_B_DIRTY'] % ', '.join(dirty[:5])])
1986
+ save_plan(brain, P.ops, P.unknown, ENV['OS_ML_LANG'])
1987
+ ops, done, unknown = load_plan(brain)
1988
+ runner = Runner(brain, S, ops, core)
1989
+ rc, msg = runner.run(done)
1990
+ if rc == 1:
1991
+ return stop(S, [msg])
1992
+ if rc == 3:
1993
+ return 3
1994
+ cleanup(brain)
1995
+ print(S['MIGRATE_LAYOUT_DONE'] % len([o for o in ops if o['op'] != 'prune']))
1996
+ return 0
1997
+
1998
+
1999
+ if __name__ == '__main__':
2000
+ sys.exit(main())