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,392 @@
1
+ #!/usr/bin/env python3
2
+ """Overview: what is waiting for the person, as My Wiki's first screen (spec 062).
3
+
4
+ Internal. `my_wiki_build.py` imports it and hands it what it already read; this file opens two
5
+ things nobody else in the product opens — the Claude Code session logs and nothing more — and
6
+ returns one dictionary. It never writes: not to the brain, not to a session (C7).
7
+
8
+ WHAT A SESSION IS, AND WHAT IT IS NOT. Claude Code keeps one `.jsonl` per session under
9
+ `~/.claude/projects/<the brain's path, punctuation turned into dashes>/`. Every line is one record.
10
+ The records this file uses are four, and it ignores the rest:
11
+
12
+ `user` / `assistant` a turn, with `message.content` and `timestamp`
13
+ `ai-title` the title the app gave the session
14
+ `custom-title` the title the person gave it, which wins over the other one
15
+
16
+ THE FILE'S OWN mtime IS NOT ITS AGE. A backup or a sync touches every log at once; measured over a
17
+ real brain, most files carried an mtime days newer than their last record. The age of a session is
18
+ the timestamp of its last turn, and only that.
19
+
20
+ THERE IS NO RECORD OF THE PERSON HAVING READ A SESSION. It was looked for, in the logs, in their
21
+ sidecar files and in the app's own state, and it does not exist (spec 062, design-first). So an
22
+ answered turn and a read turn cannot be told apart, and this file does not pretend otherwise: a
23
+ session whose last turn is the agent's and does not ask anything comes out as `finished · unread`
24
+ WITH `unreadByDefault` set, and the page says on the screen that it is showing it for lack of the
25
+ datum, never as a fact about what the person read.
26
+ """
27
+
28
+ import datetime
29
+ import json
30
+ import os
31
+ import re
32
+
33
+ # The delimiters of a pending question. A turn that ends in one is asking; the closing markdown a
34
+ # sentence may drag behind it (a bold marker, a quote, a bracket) is not part of the sentence.
35
+ TRAILING = " \t\r\n*`_\"')]}»”"
36
+ # A question that is asking for the approval of a spec is a Gate 1, not a question like any other:
37
+ # it is the one the supervision pattern of `CLAUDE.md` names, and it reads differently on the page.
38
+ GATE1_HINT = re.compile(r"\bgate ?-?1\b", re.IGNORECASE)
39
+ # What the session's first message writes to name the scope it works on, in both languages.
40
+ FOCUS_LEAD = re.compile(r"\b(?:foco|focus)\b[: ]+([^\n,.;]{2,60})", re.IGNORECASE)
41
+ WORD = re.compile(r"[a-z0-9][a-z0-9-]{2,}")
42
+ # A turn the harness injected rather than the person typing it: a command's output, a task
43
+ # notification, a system reminder. It is not the person answering, and it never opens a session.
44
+ INJECTED = ("<", "[Request interrupted", "Caveat:")
45
+
46
+
47
+ def _text(message):
48
+ content = (message or {}).get("content")
49
+ if isinstance(content, str):
50
+ return content
51
+ if isinstance(content, list):
52
+ return "".join(b.get("text", "") for b in content
53
+ if isinstance(b, dict) and b.get("type") == "text")
54
+ return ""
55
+
56
+
57
+ def _stamp(value):
58
+ if not value:
59
+ return None
60
+ try:
61
+ return datetime.datetime.fromisoformat(str(value).replace("Z", "+00:00"))
62
+ except ValueError:
63
+ return None
64
+
65
+
66
+ def _age(now, when):
67
+ """How long ago, as a number and the unit it is counted in. The page puts the word on it."""
68
+ minutes = int(max(0, (now - when).total_seconds()) // 60)
69
+ if minutes < 60:
70
+ return {"n": minutes, "unit": "min"}
71
+ if minutes < 60 * 24:
72
+ return {"n": minutes // 60, "unit": "h"}
73
+ return {"n": minutes // (60 * 24), "unit": "d"}
74
+
75
+
76
+ def _tail(text, cap=220):
77
+ """The last sentence of a turn: what the agent is actually asking, never the whole answer."""
78
+ clean = " ".join(text.strip().split())
79
+ if len(clean) <= cap:
80
+ return clean
81
+ cut = clean[-cap:]
82
+ for sep in (". ", "? ", "! ", "— ", "· "):
83
+ i = cut.find(sep)
84
+ if 0 <= i < cap - 40:
85
+ return cut[i + len(sep):]
86
+ return "…" + cut
87
+
88
+
89
+ # ------------------------------------------------------------------ one session, read once
90
+ def read_session(path):
91
+ """The four things a session says: its title, its first message, its last turn of each side.
92
+
93
+ The file is opened once, read forward and never written. A line that is not JSON is skipped:
94
+ a log the app is writing right now can end mid-line, and that is not a failure of this page.
95
+ """
96
+ title = ""
97
+ first = ""
98
+ last_user = None
99
+ last_agent = None
100
+ try:
101
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
102
+ for line in f:
103
+ line = line.strip()
104
+ if not line.startswith("{"):
105
+ continue
106
+ try:
107
+ rec = json.loads(line)
108
+ except ValueError:
109
+ continue
110
+ kind = rec.get("type")
111
+ if kind == "ai-title" and not title:
112
+ title = rec.get("aiTitle") or ""
113
+ continue
114
+ if kind == "custom-title":
115
+ title = rec.get("customTitle") or rec.get("title") or title
116
+ continue
117
+ if kind not in ("user", "assistant") or rec.get("isSidechain"):
118
+ continue
119
+ body = _text(rec.get("message")).strip()
120
+ if not body:
121
+ continue
122
+ when = _stamp(rec.get("timestamp"))
123
+ if kind == "user":
124
+ if rec.get("isMeta") or body.startswith(INJECTED):
125
+ continue
126
+ if not first:
127
+ first = body
128
+ if when:
129
+ last_user = when
130
+ elif when:
131
+ last_agent = (when, body)
132
+ except OSError:
133
+ return None
134
+ if last_agent is None and not first:
135
+ return None
136
+ return {"title": title, "first": first, "user": last_user, "agent": last_agent}
137
+
138
+
139
+ # ------------------------------------------------------------------ the focus of a session (C3)
140
+ class Focus(object):
141
+ """What the first message of a session names, resolved against the pages of the brain.
142
+
143
+ The rule is the startup's: the first message names the scope, and inside it the node. A message
144
+ that names a path the wiki has a page for wins; with no path, a slug of a node —the folder that
145
+ gives the node its identity— names it. Neither, and the session is grouped under *no focus*:
146
+ visible, never guessed.
147
+ """
148
+
149
+ def __init__(self, pages, wsdir, head_file):
150
+ self.by_path = pages
151
+ self.by_slug = {}
152
+ for path, page in pages.items():
153
+ if page["kind"] not in ("entity", "initiative", "workspace"):
154
+ continue
155
+ base = os.path.basename(path)
156
+ slug = os.path.basename(os.path.dirname(path)) if base == head_file \
157
+ else os.path.splitext(base)[0]
158
+ slug = slug.lower()
159
+ # An entity loses to an initiative of the same name on purpose: the initiative is the
160
+ # stretch of work being done, and that is what a session is opened on.
161
+ if slug not in self.by_slug or page["kind"] == "initiative":
162
+ self.by_slug[slug] = path
163
+
164
+ def of(self, message):
165
+ if not message:
166
+ return ""
167
+ head = message[:600]
168
+ for path in self.by_path:
169
+ if path in head:
170
+ # A document is not a focus: the focus is the node it belongs to. A session opened
171
+ # on a research file is a session about the initiative that holds it.
172
+ page = self.by_path[path]
173
+ if page["kind"] in ("entity", "initiative", "workspace"):
174
+ return path
175
+ owner = page.get("owner") or ""
176
+ if owner in self.by_path:
177
+ return owner
178
+ return self._slug(head) or ""
179
+ lead = FOCUS_LEAD.search(head)
180
+ if lead:
181
+ hit = self._slug(lead.group(1))
182
+ if hit:
183
+ return hit
184
+ return self._slug(head) or ""
185
+
186
+ def _slug(self, text):
187
+ best = ""
188
+ for word in WORD.findall(text.lower()):
189
+ path = self.by_slug.get(word)
190
+ if path and (not best or len(word) > len(best[0])):
191
+ best = (word, path)
192
+ return best[1] if best else ""
193
+
194
+ def label(self, path, pages):
195
+ """`Entity › Initiative`: what the node is about, and then the node. One jump, never a
196
+ chain — the same reach the focus read has."""
197
+ page = pages.get(path)
198
+ if not page:
199
+ return ""
200
+ parent = pages.get(page.get("about") or "")
201
+ if parent:
202
+ return parent["title"] + " › " + page["title"]
203
+ return page["title"]
204
+
205
+
206
+ # ------------------------------------------------------------------ threads (C2, C3, C8)
207
+ def threads(sessions_dir, now, days, pages, wsdir, head_file):
208
+ focus = Focus(pages, wsdir, head_file)
209
+ window = now - datetime.timedelta(days=days)
210
+ rows = []
211
+ try:
212
+ names = sorted(os.listdir(sessions_dir))
213
+ except OSError:
214
+ return None, rows
215
+ for name in names:
216
+ if not name.endswith(".jsonl"):
217
+ continue
218
+ got = read_session(os.path.join(sessions_dir, name))
219
+ if not got or not got["agent"]:
220
+ continue
221
+ when, body = got["agent"]
222
+ if when < window:
223
+ continue
224
+ # The person spoke last: the turn is theirs, and nothing is waiting for them here. This is
225
+ # the case the criterion asks to leave out.
226
+ if got["user"] and got["user"] > when:
227
+ continue
228
+ asking = body.rstrip(TRAILING).endswith("?")
229
+ if asking:
230
+ label = "gate1" if GATE1_HINT.search(body[-400:]) else "asks"
231
+ else:
232
+ label = "unread"
233
+ path = focus.of(got["first"])
234
+ rows.append({
235
+ "id": name[:-6],
236
+ "title": got["title"] or _tail(got["first"], 60),
237
+ "says": _tail(body),
238
+ "label": label,
239
+ "unreadByDefault": label == "unread",
240
+ "at": when.isoformat(),
241
+ "age": _age(now, when),
242
+ "focus": path,
243
+ "focusLabel": focus.label(path, pages) if path else "",
244
+ "ws": pages[path]["ws"] if path else "",
245
+ })
246
+ rows.sort(key=lambda r: r["at"], reverse=True)
247
+ groups, order = {}, []
248
+ for row in rows:
249
+ key = row["focus"]
250
+ if key not in groups:
251
+ groups[key] = {"focus": key, "label": row["focusLabel"], "threads": []}
252
+ order.append(key)
253
+ groups[key]["threads"].append(row)
254
+ # *No focus* goes last: it is the leftover, never the headline.
255
+ named = [k for k in order if k]
256
+ return len(names), [groups[k] for k in named + [k for k in order if not k]]
257
+
258
+
259
+ # ------------------------------------------------------------------ gates (C4)
260
+ def gates(rows, today):
261
+ out = []
262
+ for line in rows:
263
+ cells = line.split("\t")
264
+ if len(cells) < 5:
265
+ continue
266
+ when = cells[4].strip()
267
+ out.append({
268
+ "gate": cells[0].strip(),
269
+ "repo": cells[1].strip(),
270
+ "spec": cells[2].strip(),
271
+ "title": cells[3].strip(),
272
+ "date": when,
273
+ "branch": cells[5].strip() if len(cells) > 5 else "",
274
+ "days": _days_between(when, today),
275
+ })
276
+ out.sort(key=lambda g: (g["gate"], -(g["days"] if g["days"] is not None else -1), g["spec"]))
277
+ return out
278
+
279
+
280
+ def _days_between(when, today):
281
+ a, b = _date(when), _date(today)
282
+ if not a or not b:
283
+ return None
284
+ return (b - a).days
285
+
286
+
287
+ def _date(value):
288
+ try:
289
+ return datetime.date.fromisoformat(str(value)[:10])
290
+ except (ValueError, TypeError):
291
+ return None
292
+
293
+
294
+ # ------------------------------------------------------------------ waiting on others (C5)
295
+ def waiting(pages, ws, today, operator):
296
+ """The `waiting_on:` of the workspace's live initiatives that is not the operator.
297
+
298
+ WHO COUNTS AS THE OPERATOR IS THE STARTUP'S RULE, not a second one: the literal `operador`, a
299
+ `gate-*`, or the operator's own name. Anything else is somebody else, and that is what this
300
+ block is for — a gate is already its own block above.
301
+ """
302
+ op = (operator or "").strip().lower()
303
+ rows = []
304
+ for path, page in pages.items():
305
+ if page["kind"] != "initiative" or page["ws"] != ws:
306
+ continue
307
+ fm = page["fm"]
308
+ if (fm.get("status") or "").strip().lower() in ("closed", "cerrada", "cerrado"):
309
+ continue
310
+ who = (fm.get("waiting_on") or "").strip()
311
+ low = who.lower()
312
+ if not who or low == "operador" or low.startswith("gate-") or (op and low == op):
313
+ continue
314
+ rows.append({
315
+ "who": who,
316
+ "path": path,
317
+ "title": page["title"],
318
+ "reason": (fm.get("blocked") or "").strip(),
319
+ "days": _days_between(fm.get("updated", ""), today),
320
+ })
321
+ # Longest wait first: this block exists to surface the one that went stale, and a wait of a
322
+ # month is the one that needs a person, not the one from yesterday.
323
+ rows.sort(key=lambda r: (-(r["days"] if r["days"] is not None else -1), r["title"]))
324
+ return rows
325
+
326
+
327
+ # ------------------------------------------------------------------ this week (C6)
328
+ def week(pages, ws, today, span):
329
+ start = _date(today)
330
+ if not start:
331
+ return []
332
+ end = start + datetime.timedelta(days=span)
333
+ rows = []
334
+ for path, page in pages.items():
335
+ if page["ws"] != ws:
336
+ continue
337
+ owner = pages.get(page.get("owner") or "") or page
338
+ if owner["kind"] not in ("initiative", "entity", "workspace"):
339
+ continue
340
+ for section in page["sections"]:
341
+ if section["form"] != "tasks":
342
+ continue
343
+ for item in section["items"]:
344
+ if item.get("done"):
345
+ continue
346
+ day = _date(item.get("date", ""))
347
+ if not day or day < start or day > end:
348
+ continue
349
+ text = item.get("text", "").strip()
350
+ reason = ""
351
+ if " · " in text:
352
+ text, _, reason = text.partition(" · ")
353
+ rows.append({
354
+ "text": text.strip(),
355
+ "reason": reason.strip(),
356
+ "date": day.isoformat(),
357
+ "days": (day - start).days,
358
+ "path": owner["path"],
359
+ "node": owner["title"],
360
+ })
361
+ rows.sort(key=lambda r: (r["date"], r["node"], r["text"]))
362
+ return rows
363
+
364
+
365
+ # ------------------------------------------------------------------ the block the page receives
366
+ def build(pages, workspaces, wsdir, head_file, options, gate_rows):
367
+ now = _stamp(options.get("now")) or datetime.datetime.now(datetime.timezone.utc)
368
+ if now.tzinfo is None:
369
+ now = now.replace(tzinfo=datetime.timezone.utc)
370
+ today = options.get("today") or now.date().isoformat()
371
+ days = int(options.get("days") or 3)
372
+ span = int(options.get("week") or 7)
373
+ directory = options.get("sessions") or ""
374
+
375
+ seen, grouped = threads(directory, now, days, pages, wsdir, head_file) if directory \
376
+ else (None, [])
377
+ return {
378
+ "now": now.isoformat(),
379
+ "today": today,
380
+ "days": days,
381
+ "week": span,
382
+ # No sessions to read is not a failure: the brain may be worked from another machine, or
383
+ # from the app in the cloud. The page says so and shows the other three blocks (C7 of the
384
+ # spec's delegated criteria).
385
+ "sessions": {"dir": directory, "available": seen is not None, "files": seen or 0,
386
+ "readRecord": False},
387
+ "threads": grouped,
388
+ "gates": gates(gate_rows, today),
389
+ "waiting": {w["slug"]: waiting(pages, w["slug"], today, options.get("operator", ""))
390
+ for w in workspaces},
391
+ "week_items": {w["slug"]: week(pages, w["slug"], today, span) for w in workspaces},
392
+ }
@@ -0,0 +1,160 @@
1
+ #!/usr/bin/env bash
2
+ # Deterministic half of `new-memory`: writes the head of a memory node, of any type. The interview
3
+ # is conducted by core/skills/new-memory.md. Internal: not invocable.
4
+ #
5
+ # Usage: new-memory.sh --brain DIR --org SLUG --type TYPE --name NAME --owner PERSON
6
+ # [--slug SLUG] [--identity-file FILE]
7
+ # new-memory.sh --brain DIR --root --type TYPE --name NAME --owner PERSON
8
+ # [--slug SLUG] [--identity-file FILE]
9
+ # `--workspace` is an exact synonym of `--org` (spec 039), same as every other command that takes a
10
+ # workspace. `--root` and `--org`/`--workspace` are mutually exclusive, same rule `session-start.sh`
11
+ # already uses (spec 018/041): a flag, never a reserved value, so an operator can still name a
12
+ # workspace "root" without colliding.
13
+ #
14
+ # The carrier of "what kind of thing this is" is the folder, never a field (spec 041 decision): the
15
+ # TYPE argument is the name of the sibling folder — `products`, `accounts`, `channels`, or one the
16
+ # operator invents. `new-product.sh` is a fixed-type wrapper of this script (`--type products`); its
17
+ # own output never changes.
18
+ #
19
+ # A memory node is memory — what it is, what is known — never state: it never gets `role:` (that
20
+ # activates an oficio per organization, spec 009) and never `repo:` (mount-repo writes that once a
21
+ # body exists, and mount-repo mounts onto an initiative, never onto a memory node). Only the head is
22
+ # born here: `context/`, `resolver.md` and `decisions.md` are born with their first piece of data,
23
+ # same as every other canonical file in this product.
24
+
25
+ set -eu
26
+
27
+ here=$(cd "$(dirname "$0")" && pwd)
28
+ . "$here/common.sh"
29
+
30
+ brain=""
31
+ org=""
32
+ workspace=""
33
+ root=0
34
+ type=""
35
+ name=""
36
+ owner=""
37
+ slug=""
38
+ identity_file=""
39
+
40
+ while [ $# -gt 0 ]; do
41
+ case "$1" in
42
+ --brain) brain="$2"; shift 2 ;;
43
+ --org) org="$2"; shift 2 ;;
44
+ --workspace) workspace="$2"; shift 2 ;;
45
+ --root) root=1; shift ;;
46
+ --type) type="$2"; shift 2 ;;
47
+ --name) name="$2"; shift 2 ;;
48
+ --owner) owner="$2"; shift 2 ;;
49
+ --slug) slug="$2"; shift 2 ;;
50
+ --identity-file) identity_file="$2"; shift 2 ;;
51
+ *) os_die "argumento desconocido: $1" ;;
52
+ esac
53
+ done
54
+
55
+ # `--workspace` es sinónimo exacto de `--org` (P3, spec 039).
56
+ if [ -n "$org" ] && [ -n "$workspace" ] && [ "$org" != "$workspace" ]; then
57
+ os_die "--org y --workspace con valores distintos: $org / $workspace"
58
+ fi
59
+ [ -n "$org" ] || org="$workspace"
60
+
61
+ [ -n "$brain" ] || os_die "falta --brain"
62
+ if [ "$root" = "1" ]; then
63
+ [ -z "$org" ] || os_die "--root y --org/--workspace son excluyentes"
64
+ else
65
+ [ -n "$org" ] || os_die "falta --org, --workspace o --root"
66
+ fi
67
+ [ -n "$type" ] || os_die "falta --type"
68
+ case "$type" in
69
+ */*|.|..) os_die "--type inválido: $type" ;;
70
+ esac
71
+ [ -n "$name" ] || os_die "falta --name"
72
+ [ -n "$owner" ] || os_die "falta --owner"
73
+ [ -d "$brain" ] || os_die "no existe el brain: $brain"
74
+
75
+ # Layout inválido frena acá, antes de cualquier $(...) que arme una ruta con el nombre de la
76
+ # carpeta (P2, spec 039).
77
+ os_ws_check "$brain"
78
+ wsdir=$(os_ws_dir "$brain")
79
+
80
+ # El idioma es dato de la raíz (spec 021): lo declara `operator.md` y no se vuelve a preguntar.
81
+ language=$(os_language "$brain")
82
+ os_lang_load "$language"
83
+
84
+ if [ "$root" = "0" ]; then
85
+ # El ámbito se valida contra el listado real de la carpeta de espacios de trabajo, byte a byte —
86
+ # mismo criterio que `session-start.sh` (spec 002/003): sin el espacio de trabajo, el comando no
87
+ # escribe nada y lista los que hay, con el mismo par de claves del catálogo que ya usa el arranque
88
+ # de sesión.
89
+ if ! os_org_existe "$brain" "$org"; then
90
+ printf "$S_SESSION_ORG_NOT_FOUND\n" "$org" >&2
91
+ found=0
92
+ while IFS= read -r s || [ -n "$s" ]; do
93
+ [ -n "$s" ] || continue
94
+ found=1
95
+ printf ' %s\n' "$s" >&2
96
+ done <<SLUGS
97
+ $(os_org_slugs "$brain")
98
+ SLUGS
99
+ [ "$found" = "1" ] || printf ' %s\n' "$S_SESSION_NO_ORGS" >&2
100
+ exit 2
101
+ fi
102
+ fi
103
+
104
+ [ -n "$slug" ] || slug=$(os_slugify "$name")
105
+ [ -n "$slug" ] || os_die "el nombre no produce un slug utilizable: $name"
106
+
107
+ if [ "$root" = "1" ]; then
108
+ dir="$brain/$type/$slug"
109
+ rel="$type/$slug"
110
+ tree_prefix=""
111
+ else
112
+ dir="$brain/$wsdir/$org/$type/$slug"
113
+ rel="$wsdir/$org/$type/$slug"
114
+ tree_prefix="$wsdir/*/"
115
+ fi
116
+ if [ -e "$dir" ]; then
117
+ os_die "ya existe: $rel"
118
+ fi
119
+
120
+ # El texto de placeholder es el de `products` cuando el tipo es `products` —la salida de
121
+ # `new-product.sh` no cambia, letra por letra— y el genérico de cualquier otro tipo.
122
+ if [ "$type" = "products" ]; then
123
+ identity="$S_PRODUCT_IDENTITY_PLACEHOLDER"
124
+ else
125
+ identity="$S_MEMORY_IDENTITY_PLACEHOLDER"
126
+ fi
127
+ if [ -n "$identity_file" ]; then
128
+ [ -f "$identity_file" ] || os_die "no existe el archivo de identidad: $identity_file"
129
+ identity=$(cat "$identity_file")
130
+ fi
131
+
132
+ # La misma plantilla que ya usaba `new-product.sh`: sin campo `role:`, genérica de fábrica —
133
+ # NAME/OWNER/DATE/IDENTITY— y por eso sirve para cualquier tipo de nodo de memoria sin tocarla.
134
+ templates="$here/../templates/node-product"
135
+ today=$(date +%Y-%m-%d)
136
+
137
+ mkdir -p "$dir"
138
+
139
+ # El nombre de la cabeza es dato del brain (spec 040), igual que en `new-workspace`.
140
+ head=$(os_head_file "$brain") || true
141
+ os_render_lang "$templates/README.md" "$language" \
142
+ "NAME=$name" "OWNER=$owner" "DATE=$today" "IDENTITY=$identity" \
143
+ > "$dir/$head"
144
+
145
+ os_check_identity_cap "$dir/$head"
146
+
147
+ # Un tipo declara 5 líneas del árbol (spec 041 decisión cerrada): mismo reparto que `products/` ya
148
+ # usaba — 3 `glob:` (cabeza, resolver.md, decisions.md) y 2 `content:` (context/*.md, research/*.md)
149
+ # — a la altura del espacio de trabajo o de la raíz. La 043 suma una sexta: el cuerpo de las
150
+ # decisiones, alcanzado y nunca leído como cabeza, mismo criterio que las otras dos `content:`.
151
+ # Idempotente vía `os_tree_ensure`, así que sumar un segundo nodo al mismo tipo (mismo `--type`,
152
+ # otro `--slug`) no duplica ninguna línea.
153
+ os_tree_ensure "$brain" "${tree_prefix}${type}/*/$head" || true
154
+ os_tree_ensure "$brain" "${tree_prefix}${type}/*/resolver.md" || true
155
+ os_tree_ensure "$brain" "${tree_prefix}${type}/*/decisions.md" || true
156
+ os_tree_ensure "$brain" "${tree_prefix}${type}/*/decisions/*.md" content || true
157
+ os_tree_ensure "$brain" "${tree_prefix}${type}/*/context/*.md" content || true
158
+ os_tree_ensure "$brain" "${tree_prefix}${type}/*/research/*.md" content || true
159
+
160
+ printf '%s — %s\n' "$rel" "$head"
@@ -0,0 +1,122 @@
1
+ #!/usr/bin/env bash
2
+ # Deterministic half of `new-product`: writes the head of a product node.
3
+ # The interview is conducted by core/skills/new-product.md. Internal: not invocable.
4
+ #
5
+ # Usage: new-product.sh --brain DIR --org SLUG --name NAME --owner PERSON
6
+ # [--slug SLUG] [--identity-file FILE]
7
+ # `--workspace` is an exact synonym of `--org` (spec 039).
8
+ #
9
+ # A product node is memory — what it is, for whom, what is known — never state: it never gets
10
+ # `role:` (that activates an oficio per organization, spec 009) and never `repo:` (mount-repo writes
11
+ # that once a body exists, and mount-repo mounts onto an initiative, never onto a product). Only the
12
+ # head is born here: `context/`, `resolver.md` and `decisions.md` are born with their first piece of
13
+ # data, same as every other canonical file in this product.
14
+
15
+ set -eu
16
+
17
+ here=$(cd "$(dirname "$0")" && pwd)
18
+ . "$here/common.sh"
19
+
20
+ brain=""
21
+ org=""
22
+ workspace=""
23
+ name=""
24
+ owner=""
25
+ slug=""
26
+ identity_file=""
27
+
28
+ while [ $# -gt 0 ]; do
29
+ case "$1" in
30
+ --brain) brain="$2"; shift 2 ;;
31
+ --org) org="$2"; shift 2 ;;
32
+ --workspace) workspace="$2"; shift 2 ;;
33
+ --name) name="$2"; shift 2 ;;
34
+ --owner) owner="$2"; shift 2 ;;
35
+ --slug) slug="$2"; shift 2 ;;
36
+ --identity-file) identity_file="$2"; shift 2 ;;
37
+ *) os_die "argumento desconocido: $1" ;;
38
+ esac
39
+ done
40
+
41
+ # `--workspace` es sinónimo exacto de `--org` (P3, spec 039).
42
+ if [ -n "$org" ] && [ -n "$workspace" ] && [ "$org" != "$workspace" ]; then
43
+ os_die "--org y --workspace con valores distintos: $org / $workspace"
44
+ fi
45
+ [ -n "$org" ] || org="$workspace"
46
+
47
+ [ -n "$brain" ] || os_die "falta --brain"
48
+ [ -n "$org" ] || os_die "falta --org o --workspace"
49
+ [ -n "$name" ] || os_die "falta --name"
50
+ [ -n "$owner" ] || os_die "falta --owner"
51
+ [ -d "$brain" ] || os_die "no existe el brain: $brain"
52
+
53
+ # Layout inválido frena acá, antes de cualquier $(...) que arme una ruta con el nombre de la
54
+ # carpeta (P2, spec 039).
55
+ os_ws_check "$brain"
56
+ wsdir=$(os_ws_dir "$brain")
57
+
58
+ # El idioma es dato de la raíz (spec 021): lo declara `operator.md` y no se vuelve a preguntar.
59
+ language=$(os_language "$brain")
60
+ os_lang_load "$language"
61
+
62
+ # El ámbito se valida contra el listado real de la carpeta de espacios de trabajo, byte a byte —
63
+ # mismo criterio que `session-start.sh` (spec 002/003): sin el espacio de trabajo, el comando no
64
+ # escribe nada y lista los que hay, con el mismo par de claves del catálogo que ya usa el arranque
65
+ # de sesión.
66
+ if ! os_org_existe "$brain" "$org"; then
67
+ printf "$S_SESSION_ORG_NOT_FOUND\n" "$org" >&2
68
+ found=0
69
+ while IFS= read -r s || [ -n "$s" ]; do
70
+ [ -n "$s" ] || continue
71
+ found=1
72
+ printf ' %s\n' "$s" >&2
73
+ done <<SLUGS
74
+ $(os_org_slugs "$brain")
75
+ SLUGS
76
+ [ "$found" = "1" ] || printf ' %s\n' "$S_SESSION_NO_ORGS" >&2
77
+ exit 2
78
+ fi
79
+
80
+ [ -n "$slug" ] || slug=$(os_slugify "$name")
81
+ [ -n "$slug" ] || os_die "el nombre no produce un slug utilizable: $name"
82
+
83
+ dir="$brain/$wsdir/$org/products/$slug"
84
+ if [ -e "$dir" ]; then
85
+ os_die "ya existe: $wsdir/$org/products/$slug"
86
+ fi
87
+
88
+ identity="$S_PRODUCT_IDENTITY_PLACEHOLDER"
89
+ if [ -n "$identity_file" ]; then
90
+ [ -f "$identity_file" ] || os_die "no existe el archivo de identidad: $identity_file"
91
+ identity=$(cat "$identity_file")
92
+ fi
93
+
94
+ templates="$here/../templates/node-product"
95
+ today=$(date +%Y-%m-%d)
96
+
97
+ mkdir -p "$dir"
98
+
99
+ # El nombre de la cabeza es dato del brain (spec 040), igual que en `new-workspace`.
100
+ head=$(os_head_file "$brain") || true
101
+ os_render_lang "$templates/README.md" "$language" \
102
+ "NAME=$name" "OWNER=$owner" "DATE=$today" "IDENTITY=$identity" \
103
+ > "$dir/$head"
104
+
105
+ os_check_identity_cap "$dir/$head"
106
+
107
+ # Los tres globs del nivel llegan de fábrica en `core/templates/tree.md`; acá se agregan a un brain
108
+ # que ya existía antes de esta spec, sin duplicar (mismo patrón que `capture.sh`/`close-session.sh`
109
+ # con los archivos que nacen con su primer dato).
110
+ os_tree_ensure "$brain" "$wsdir/*/products/*/$head" || true
111
+ os_tree_ensure "$brain" "$wsdir/*/products/*/resolver.md" || true
112
+ os_tree_ensure "$brain" "$wsdir/*/products/*/decisions.md" || true
113
+ # El cuerpo de esa pregunta, uno por decisión: alcanzado, nunca leído como cabeza (spec 043).
114
+ os_tree_ensure "$brain" "$wsdir/*/products/*/decisions/*.md" content || true
115
+
116
+ # Las dos carpetas de un producto nacen con su primer dato y son contenido, nunca cabeza: `context/`
117
+ # es la capa estratégica y `research/` todo documento fechado (spec 040). Se declaran acá para que el
118
+ # primer archivo que el operador escriba adentro no aparezca como "ningún glob alcanza".
119
+ os_tree_ensure "$brain" "$wsdir/*/products/*/context/*.md" content || true
120
+ os_tree_ensure "$brain" "$wsdir/*/products/*/research/*.md" content || true
121
+
122
+ printf '%s/%s/products/%s — %s\n' "$wsdir" "$org" "$slug" "$head"