spine-memory 0.2.0__py3-none-any.whl

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.
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env python3
2
+ """SPINE index builder — compile reverse_index.json and refresh anchor_dump.json.
3
+
4
+ Reads nodes/*.md and:
5
+ 1. builds forward semantic links {node_id: [target_ids]} (YAML semantic_links)
6
+ 2. builds embed links {node_id: [target_ids]} (body ## EMBED_LINKS)
7
+ 3. inverts both → reverse_index.json:
8
+ forward / reverse / embed_forward / embed_reverse
9
+ 4. refreshes anchors/anchor_dump.json (canon)
10
+
11
+ Usage:
12
+ python tools/_build_index.py
13
+ """
14
+
15
+ import json
16
+ import os
17
+ import re
18
+ import sys
19
+
20
+ BASE = os.path.dirname(os.path.abspath(__file__))
21
+
22
+ try:
23
+ from spine_memory import _node_io
24
+ except ImportError:
25
+ import _node_io
26
+ NODES_DIR = os.path.join(_node_io.find_spine_root(), 'nodes')
27
+ ANCHOR_DUMP = os.path.join(_node_io.find_spine_root(), 'anchors', 'anchor_dump.json')
28
+ REVERSE_INDEX = os.path.join(_node_io.find_spine_root(), 'reverse_index.json')
29
+
30
+
31
+ def read_node(path):
32
+ """Read a node via the canonical _node_io parser.
33
+
34
+ Returns (nid, semantic_links, embed_links, anchors, code_refs).
35
+ """
36
+ d = _node_io.read_node(path)
37
+ if d is None:
38
+ return None, [], [], [], []
39
+ return (d['id'], d['semantic_links'], d['embed_links'],
40
+ d['search_anchors'], d['code_refs'])
41
+
42
+
43
+ def _code_ref_path(ref):
44
+ """Extract the file path from a code_ref like 'src/a.py::fn@commit'."""
45
+ return ref.split('::')[0].split('@')[0].strip()
46
+
47
+
48
+ def invert(forward):
49
+ rev = {}
50
+ for src, targets in forward.items():
51
+ for t in targets:
52
+ rev.setdefault(t, []).append(src)
53
+ for k in rev:
54
+ rev[k] = sorted(set(rev[k]))
55
+ return rev
56
+
57
+
58
+ def main():
59
+ forward, embed_forward, anchor_nodes, code_index = {}, {}, {}, {}
60
+ if os.path.isdir(NODES_DIR):
61
+ for fn in sorted(os.listdir(NODES_DIR)):
62
+ if not fn.endswith('.md'):
63
+ continue
64
+ nid, sem, embed, anchors, code_refs = read_node(os.path.join(NODES_DIR, fn))
65
+ forward[nid] = sem
66
+ embed_forward[nid] = embed
67
+ for a in anchors:
68
+ anchor_nodes.setdefault(a, []).append(nid)
69
+ for ref in code_refs:
70
+ p = _code_ref_path(ref)
71
+ if p:
72
+ code_index.setdefault(p, []).append(nid)
73
+
74
+ for p in code_index:
75
+ code_index[p] = sorted(set(code_index[p]))
76
+
77
+ reverse = invert(forward)
78
+ embed_reverse = invert(embed_forward)
79
+
80
+ with open(REVERSE_INDEX, 'w', encoding='utf-8', newline='\n') as f:
81
+ json.dump({
82
+ 'forward': forward,
83
+ 'reverse': reverse,
84
+ 'embed_forward': embed_forward,
85
+ 'embed_reverse': embed_reverse,
86
+ 'code_index': code_index,
87
+ }, f, ensure_ascii=False, indent=2)
88
+
89
+ canon = {}
90
+ if os.path.exists(ANCHOR_DUMP):
91
+ with open(ANCHOR_DUMP, 'r', encoding='utf-8') as f:
92
+ canon = json.load(f)
93
+ for a, nids in anchor_nodes.items():
94
+ canon.setdefault(a, []).extend(nids)
95
+ for a in canon:
96
+ canon[a] = sorted(set(canon[a]))
97
+ with open(ANCHOR_DUMP, 'w', encoding='utf-8', newline='\n') as f:
98
+ json.dump(canon, f, ensure_ascii=False, indent=2)
99
+
100
+ print('reverse_index.json: semantic %d nodes / embed %d nodes' % (
101
+ len(forward), len(embed_forward)))
102
+ print('anchor_dump.json: %d anchors' % len(canon))
103
+
104
+
105
+ if __name__ == '__main__':
106
+ main()
@@ -0,0 +1,209 @@
1
+ #!/usr/bin/env python3
2
+ """SPINE anchor validator — validate search_anchors against the canon.
3
+
4
+ The canon file `anchor_dump.json` supports two formats:
5
+ - new: {"anchor": ["node_id", ...], ...} (anchor as key)
6
+ - old: {"node_id": ["anchor", ...], ...} (node id as key)
7
+
8
+ Format is detected by key shape, not by a hardcoded prefix list, so any node
9
+ id works (DOC_001, NOTE_12, KEDR_001, ...).
10
+
11
+ Usage:
12
+ python tools/_check_anchors.py nodes/KEDR_001.md --dump anchors/anchor_dump.json
13
+ python tools/_check_anchors.py nodes/KEDR_001.md --dump anchors/anchor_dump.json --quiet
14
+
15
+ Exit: 0 = PASS, 1 = WARN (new anchor), 2 = FAIL (duplicate/format).
16
+ """
17
+
18
+ import argparse
19
+ import json
20
+ import os
21
+ import re
22
+ import sys
23
+ from difflib import SequenceMatcher
24
+
25
+ if sys.platform == 'win32':
26
+ sys.stdout.reconfigure(encoding='utf-8', errors='replace')
27
+ sys.stderr.reconfigure(encoding='utf-8', errors='replace')
28
+
29
+ try:
30
+ from spine_memory import _node_io
31
+ except ImportError:
32
+ import _node_io
33
+
34
+ FUZZY_THRESHOLD = 0.78
35
+ MAX_TOKENS = 5
36
+ MIN_TOKENS = 2
37
+ ANCHOR_PATTERN = re.compile(r'^[a-zа-яё0-9_]+$')
38
+ NODE_ID_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_]*\d+$')
39
+
40
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
41
+ DEFAULT_DUMP = os.environ.get(
42
+ 'SPINE_ANCHOR_DUMP',
43
+ os.path.join(_node_io.find_spine_root(), 'anchors', 'anchor_dump.json'),
44
+ )
45
+
46
+
47
+ def load_anchor_dump(path):
48
+ if not os.path.exists(path):
49
+ print(f"[WARN] anchor_dump.json not found: {path}")
50
+ return set()
51
+ with open(path, 'r', encoding='utf-8') as f:
52
+ data = json.load(f)
53
+
54
+ if not data:
55
+ return set()
56
+
57
+ all_anchors = set()
58
+ keys = list(data.keys())
59
+ # Old format: every key looks like a node id (U001, KEDR_001, DOC_001, NOTE_12).
60
+ if all(NODE_ID_RE.match(k) for k in keys):
61
+ for anchors in data.values():
62
+ for a in anchors:
63
+ a_clean = str(a).split('#')[0].strip()
64
+ if a_clean:
65
+ all_anchors.add(a_clean)
66
+ else:
67
+ for anchor in data.keys():
68
+ a_clean = anchor.split('#')[0].strip()
69
+ if a_clean:
70
+ all_anchors.add(a_clean)
71
+ return all_anchors
72
+
73
+
74
+ def extract_anchors(node_path):
75
+ if not os.path.exists(node_path):
76
+ print(f"file not found: {node_path}")
77
+ return []
78
+ d = _node_io.read_node(node_path)
79
+ if d is None:
80
+ print("YAML frontmatter not found")
81
+ return []
82
+ return d['search_anchors']
83
+
84
+
85
+ def fuzzy_match(anchor, canonical_set, threshold=FUZZY_THRESHOLD):
86
+ best_match = None
87
+ best_score = 0.0
88
+ anchor_lower = anchor.lower()
89
+ for canonical in canonical_set:
90
+ canon_lower = canonical.lower()
91
+ if anchor_lower in canon_lower or canon_lower in anchor_lower:
92
+ continue
93
+ score = SequenceMatcher(None, anchor_lower, canon_lower).ratio()
94
+ if score > best_score:
95
+ best_score = score
96
+ best_match = canonical
97
+ if best_score >= threshold:
98
+ return best_match, best_score
99
+ return None, best_score
100
+
101
+
102
+ def check_format(anchor):
103
+ errors = []
104
+ if not ANCHOR_PATTERN.match(anchor):
105
+ errors.append("format: use snake_case (a-z, a-ya, 0-9, _)")
106
+ tokens = anchor.split('_')
107
+ if len(tokens) > MAX_TOKENS:
108
+ errors.append(f"tokens: {len(tokens)} > {MAX_TOKENS}")
109
+ if len(tokens) < MIN_TOKENS:
110
+ errors.append(f"tokens: {len(tokens)} < {MIN_TOKENS}")
111
+ if anchor[0].isdigit():
112
+ errors.append("starts with digit")
113
+ return errors
114
+
115
+
116
+ def main():
117
+ parser = argparse.ArgumentParser(
118
+ description='Validate search_anchors against the anchor canon.'
119
+ )
120
+ parser.add_argument('node', help='path to a node file')
121
+ parser.add_argument('--dump', default=None,
122
+ help='path to anchor_dump.json (default: anchors/anchor_dump.json)')
123
+ parser.add_argument('--quiet', '-q', action='store_true',
124
+ help='short one-line output')
125
+ args = parser.parse_args()
126
+
127
+ node_path = args.node
128
+ dump_path = args.dump or os.environ.get('SPINE_ANCHOR_DUMP', DEFAULT_DUMP)
129
+ node_name = os.path.basename(node_path)
130
+
131
+ canonical = load_anchor_dump(dump_path)
132
+ node_anchors = extract_anchors(node_path)
133
+
134
+ if not node_anchors:
135
+ print(f"FAIL {node_name} — anchors not found")
136
+ sys.exit(2)
137
+
138
+ format_errors = []
139
+ duplicates = []
140
+ new_anchors = []
141
+ passed = []
142
+
143
+ for anchor in node_anchors:
144
+ anchor_clean = anchor.split('#')[0].strip()
145
+ fmt_errs = check_format(anchor_clean)
146
+ if fmt_errs:
147
+ format_errors.append((anchor_clean, fmt_errs))
148
+ continue
149
+ if anchor_clean in canonical:
150
+ passed.append(anchor_clean)
151
+ continue
152
+ best, score = fuzzy_match(anchor_clean, canonical)
153
+ if best:
154
+ duplicates.append((anchor_clean, best, round(score, 2)))
155
+ else:
156
+ new_anchors.append(anchor_clean)
157
+
158
+ exit_code = 0
159
+ issues = len(format_errors) + len(duplicates)
160
+
161
+ if args.quiet:
162
+ if issues > 0:
163
+ print(f"FAIL {node_name}: {issues} issue(s)")
164
+ for a, errs in format_errors:
165
+ print(f" FMT {a}: {errs[0]}")
166
+ for a, best, sc in duplicates:
167
+ print(f" DUP {a} -> {best} ({sc})")
168
+ exit_code = 2
169
+ elif new_anchors:
170
+ print(f"WARN {node_name}: {len(passed)} OK + {len(new_anchors)} new")
171
+ exit_code = 1
172
+ else:
173
+ print(f"PASS {node_name}: {len(passed)} OK")
174
+ sys.exit(exit_code)
175
+
176
+ print(f"=== ANCHOR CHECK: {node_name} ===")
177
+ print(f"node anchors: {len(node_anchors)} | canon: {len(canonical)}\n")
178
+ if passed:
179
+ print(f"OK ({len(passed)}):")
180
+ for a in passed:
181
+ print(f" + {a}")
182
+ print()
183
+ if new_anchors:
184
+ print(f"NEW ({len(new_anchors)}):")
185
+ for a in new_anchors:
186
+ print(f" ? {a}")
187
+ print(" -> verify: is there an existing anchor with the same meaning?\n")
188
+ exit_code = 1
189
+ if duplicates:
190
+ print(f"DUPLICATES ({len(duplicates)}):")
191
+ for a, best, sc in duplicates:
192
+ print(f" x '{a}' -> existing '{best}' ({sc})")
193
+ print()
194
+ exit_code = 2
195
+ if format_errors:
196
+ print(f"FORMAT ERRORS ({len(format_errors)}):")
197
+ for a, errs in format_errors:
198
+ for e in errs:
199
+ print(f" x '{a}' — {e}")
200
+ print()
201
+ exit_code = 2
202
+
203
+ if exit_code == 0:
204
+ print("ALL ANCHORS PASSED")
205
+ sys.exit(exit_code)
206
+
207
+
208
+ if __name__ == '__main__':
209
+ main()
@@ -0,0 +1,150 @@
1
+ #!/usr/bin/env python3
2
+ """SPINE crosslink — generate semantic links between nodes.
3
+
4
+ Rules: a link is created inside the same constellation OR on overlap of
5
+ >=2 anchors. Per-node link limit is controlled by --max (default 1).
6
+
7
+ Links are written into the YAML frontmatter `semantic_links:` list so that
8
+ _wander.py and any v2.1-compliant reader can see them.
9
+
10
+ Usage:
11
+ python tools/_crosslink.py --folder nodes # dry run
12
+ python tools/_crosslink.py --folder nodes --apply # apply
13
+ """
14
+
15
+ import argparse
16
+ import os
17
+ import re
18
+ import sys
19
+ from collections import defaultdict
20
+
21
+ if sys.platform == 'win32':
22
+ sys.stdout.reconfigure(encoding='utf-8', errors='replace')
23
+
24
+ try:
25
+ from spine_memory import _node_io
26
+ except ImportError:
27
+ import _node_io
28
+
29
+ MIN_ANCHOR_OVERLAP = 2
30
+
31
+
32
+ def read_node(path):
33
+ d = _node_io.read_node(path)
34
+ if d is None:
35
+ return None
36
+ return {
37
+ 'path': path,
38
+ 'id': d['id'],
39
+ 'constellation': d['constellation'],
40
+ 'anchors': d['search_anchors'],
41
+ 'existing_links': set(d['semantic_links']),
42
+ }
43
+
44
+
45
+ def load_all(folders):
46
+ nodes = {}
47
+ for folder in folders:
48
+ if not os.path.exists(folder):
49
+ continue
50
+ for fn in sorted(os.listdir(folder)):
51
+ if not fn.endswith('.md'):
52
+ continue
53
+ data = read_node(os.path.join(folder, fn))
54
+ if data and data['id']:
55
+ nodes[data['id']] = data
56
+ return nodes
57
+
58
+
59
+ def find_pairs(nodes):
60
+ pairs = []
61
+ ids = list(nodes.keys())
62
+
63
+ const_groups = defaultdict(list)
64
+ for nid, nd in nodes.items():
65
+ if nd['constellation']:
66
+ const_groups[nd['constellation']].append(nid)
67
+
68
+ const_linked = set()
69
+ for const, members in const_groups.items():
70
+ for i in range(len(members)):
71
+ for j in range(i + 1, len(members)):
72
+ pairs.append((members[i], members[j], f'const:{const}'))
73
+ const_linked.add(tuple(sorted([members[i], members[j]])))
74
+
75
+ for i in range(len(ids)):
76
+ for j in range(i + 1, len(ids)):
77
+ key = tuple(sorted([ids[i], ids[j]]))
78
+ if key in const_linked:
79
+ continue
80
+ overlap = set(nodes[ids[i]]['anchors']) & set(nodes[ids[j]]['anchors'])
81
+ if len(overlap) >= MIN_ANCHOR_OVERLAP:
82
+ pairs.append((ids[i], ids[j], f'anchors:{",".join(sorted(overlap)[:3])}'))
83
+
84
+ seen = set()
85
+ unique = []
86
+ for a, b, reason in pairs:
87
+ key = tuple(sorted([a, b]))
88
+ if key not in seen:
89
+ seen.add(key)
90
+ unique.append((a, b, reason))
91
+ return unique
92
+
93
+
94
+ def apply_link(nid, target, reason, nodes, max_links):
95
+ nd = nodes.get(nid)
96
+ if not nd:
97
+ return False
98
+ if target in nd['existing_links']:
99
+ return False
100
+ if len(nd['existing_links']) >= max_links:
101
+ return False
102
+ return _node_io.add_semantic_link(nd['path'], target, reason)
103
+
104
+
105
+ def main():
106
+ p = argparse.ArgumentParser(description='Generate semantic links between SPINE nodes.')
107
+ p.add_argument('--folder', action='append', default=None,
108
+ help='folder with nodes (repeatable)')
109
+ p.add_argument('--apply', action='store_true', help='write links to files')
110
+ p.add_argument('--max', type=int, default=3, help='max links per node')
111
+ args = p.parse_args()
112
+
113
+ folders = args.folder or [os.path.join(_node_io.find_spine_root(), 'nodes')]
114
+
115
+ nodes = load_all(folders)
116
+ pairs = find_pairs(nodes)
117
+
118
+ node_link_count = defaultdict(int)
119
+ for nid in nodes:
120
+ node_link_count[nid] = len(nodes[nid]['existing_links'])
121
+
122
+ filtered = []
123
+ for a, b, reason in pairs:
124
+ if node_link_count[a] < args.max and node_link_count[b] < args.max:
125
+ filtered.append((a, b, reason))
126
+ node_link_count[a] += 1
127
+ node_link_count[b] += 1
128
+
129
+ print(f'CROSSLINK | nodes: {len(nodes)} | candidates: {len(pairs)} | filtered: {len(filtered)}')
130
+ print(f'rules: max {args.max} links/node, min {MIN_ANCHOR_OVERLAP} anchor overlap\n')
131
+
132
+ if args.apply:
133
+ applied = 0
134
+ for a, b, reason in filtered:
135
+ r1 = apply_link(a, b, reason, nodes, args.max)
136
+ r2 = apply_link(b, a, reason, nodes, args.max)
137
+ if r1 or r2:
138
+ applied += 1
139
+ print(f' {a} <-> {b} [{reason}]')
140
+ print(f'\napplied: {applied} links')
141
+ else:
142
+ print('DRY RUN (use --apply). Samples:')
143
+ for a, b, reason in filtered[:20]:
144
+ print(f' {a} <-> {b} [{reason}]')
145
+ if len(filtered) > 20:
146
+ print(f' ... and {len(filtered) - 20} more')
147
+
148
+
149
+ if __name__ == '__main__':
150
+ main()
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env python3
2
+ """SPINE embed links importer — inject precomputed embedding links.
3
+
4
+ The agent never computes vectors; an external GPU worker does. This tool only
5
+ stores the result into the `## EMBED_LINKS` body section of nodes.
6
+
7
+ Input JSON format:
8
+ {"NODE_ID": [["TARGET_ID", score], ...], ...}
9
+
10
+ Usage:
11
+ python tools/_embed_links.py --input embed_links.json --folder nodes
12
+ """
13
+
14
+ import argparse
15
+ import json
16
+ import os
17
+
18
+ try:
19
+ from spine_memory._node_io import find_spine_root
20
+ except ImportError:
21
+ from _node_io import find_spine_root
22
+
23
+
24
+ def inject_embed_links(content, links):
25
+ lines = content.split('\n')
26
+ # drop any existing EMBED_LINKS section
27
+ out = []
28
+ skip = False
29
+ for line in lines:
30
+ s = line.strip()
31
+ if s.startswith('## EMBED_LINKS'):
32
+ skip = True
33
+ continue
34
+ if skip and s.startswith('## ') and s != '## EMBED_LINKS':
35
+ skip = False
36
+ if not skip:
37
+ out.append(line)
38
+
39
+ text = '\n'.join(out).rstrip()
40
+ section = '## EMBED_LINKS\n' + '\n'.join(
41
+ '- [[%s]] (%.3f)' % (t, float(sc)) for t, sc in links
42
+ )
43
+ if text.endswith('---'):
44
+ text = text[:-3].rstrip() + '\n\n' + section + '\n---\n'
45
+ else:
46
+ text = text + '\n\n' + section + '\n'
47
+ return text
48
+
49
+
50
+ def main():
51
+ p = argparse.ArgumentParser(
52
+ description='Inject precomputed embedding links into SPINE nodes.'
53
+ )
54
+ p.add_argument('--input', required=True, help='path to embed links JSON')
55
+ p.add_argument('--folder', default=None, help='folder with nodes')
56
+ args = p.parse_args()
57
+ folder = args.folder or os.path.join(find_spine_root(), 'nodes')
58
+
59
+ with open(args.input, 'r', encoding='utf-8') as f:
60
+ data = json.load(f)
61
+
62
+ applied = 0
63
+ for nid, links in data.items():
64
+ if not links:
65
+ continue
66
+ path = os.path.join(folder, nid + '.md')
67
+ if not os.path.exists(path):
68
+ print('skip (not found): %s' % nid)
69
+ continue
70
+ with open(path, 'r', encoding='utf-8') as f:
71
+ content = f.read()
72
+ new = inject_embed_links(content, links)
73
+ with open(path, 'w', encoding='utf-8') as f:
74
+ f.write(new)
75
+ applied += 1
76
+ print('embed links: %s <- %d links' % (nid, len(links)))
77
+
78
+ print('applied: %d nodes' % applied)
79
+
80
+
81
+ if __name__ == '__main__':
82
+ main()
@@ -0,0 +1,155 @@
1
+ #!/usr/bin/env python3
2
+ """SPINE git hook — scaffold a CODE_MEMORY node from a merged PR.
3
+
4
+ Deterministic byproduct-filling: takes PR metadata and writes a node skeleton
5
+ with ``repo_ref`` / ``code_refs`` and a raw ``# SOURCE_BASE``. The agent (or a
6
+ later LLM pass) fills IMPULSE / SUMMARY / CLEANED_DATA, then critic + commit.
7
+
8
+ This is the anti-cold-start mechanism: memory fills itself as a side effect of
9
+ normal work, instead of requiring a manual "write a memory node" step.
10
+
11
+ Usage:
12
+ python tools/_git_hook.py --kind postmortem --title "fix: auth timeout" \
13
+ --repo /path/to/repo --commit a1b2c3d \
14
+ --files src/auth/jwt.py migrations/0042_users.sql
15
+ """
16
+
17
+ import argparse
18
+ import datetime
19
+ import os
20
+ import re
21
+
22
+ try:
23
+ from spine_memory._node_io import find_spine_root
24
+ except ImportError:
25
+ from _node_io import find_spine_root
26
+
27
+ BASE = os.path.dirname(os.path.abspath(__file__))
28
+ ROOT = find_spine_root()
29
+
30
+ KIND_DOMAIN = {
31
+ 'adr': 'Архитектура',
32
+ 'postmortem': 'Инциденты',
33
+ 'contract': 'Контракты',
34
+ 'gotcha': 'Грабли',
35
+ }
36
+ KIND_PREFIX = {
37
+ 'adr': 'ADR',
38
+ 'postmortem': 'PM',
39
+ 'contract': 'CTR',
40
+ 'gotcha': 'GOTCHA',
41
+ }
42
+
43
+
44
+ def next_id(nodes_dir, prefix):
45
+ pat = re.compile(r'^%s_(\d+)' % re.escape(prefix))
46
+ mx = 0
47
+ if os.path.isdir(nodes_dir):
48
+ for fn in os.listdir(nodes_dir):
49
+ m = pat.match(fn.replace('.md', ''))
50
+ if m:
51
+ mx = max(mx, int(m.group(1)))
52
+ return '%s_%03d' % (prefix, mx + 1)
53
+
54
+
55
+ def slugify(s):
56
+ s = s.lower()
57
+ s = re.sub(r'[^a-zа-яё0-9]+', '_', s)
58
+ return s.strip('_')[:40]
59
+
60
+
61
+ def render(args):
62
+ node_id = next_id(args.nodes, KIND_PREFIX[args.kind])
63
+ today = datetime.date.today().isoformat()
64
+ domain = KIND_DOMAIN[args.kind]
65
+
66
+ anchors = [slugify(args.title), args.kind]
67
+ if args.repo:
68
+ anchors.append(slugify(os.path.basename(args.repo.rstrip('/\\'))))
69
+ anchors = [a for a in anchors if a]
70
+
71
+ lines = ['---']
72
+ lines.append('id: %s' % node_id)
73
+ lines.append('type: spine_node')
74
+ lines.append('created: %s' % today)
75
+ lines.append('tags: [code_memory, %s]' % args.kind)
76
+ lines.append('domain: %s' % domain)
77
+ lines.append('kind: %s' % args.kind)
78
+ lines.append('status: active')
79
+ if args.repo and args.commit:
80
+ lines.append('repo_ref:')
81
+ lines.append(' path: %s' % (args.repo_ref_path or ''))
82
+ lines.append(' commit: %s' % args.commit)
83
+ if args.files:
84
+ lines.append('code_refs:')
85
+ for f in args.files:
86
+ lines.append(' - "%s"' % f)
87
+ lines.append('search_anchors:')
88
+ for a in anchors:
89
+ lines.append(' - %s' % a)
90
+ lines.append('---')
91
+ lines.append('')
92
+ lines.append('# IMPULSE')
93
+ lines.append('TODO: две строки — суть решения/инцидента')
94
+ lines.append('')
95
+ lines.append('# SUMMARY')
96
+ lines.append('TODO: 3-5 предложений')
97
+ lines.append('')
98
+ lines.append('# CLEANED_DATA')
99
+ lines.append('TODO: сухие факты')
100
+ lines.append('')
101
+ lines.append('# IMPACT')
102
+ lines.append('impact:')
103
+ lines.append(' strategic_weight: 0.5')
104
+ lines.append(' key_insight: |')
105
+ lines.append(' TODO')
106
+ lines.append('')
107
+ lines.append('# SOURCE_BASE')
108
+ lines.append('TITLE: %s' % args.title)
109
+ if args.body:
110
+ lines.append('')
111
+ lines.append(args.body)
112
+ if args.files:
113
+ lines.append('')
114
+ lines.append('FILES:')
115
+ for f in args.files:
116
+ lines.append('- %s' % f)
117
+ lines.append('')
118
+ lines.append('---')
119
+ return node_id, '\n'.join(lines) + '\n'
120
+
121
+
122
+ def main():
123
+ p = argparse.ArgumentParser(
124
+ description='Scaffold a CODE_MEMORY node from a merged PR.')
125
+ p.add_argument('--kind', required=True,
126
+ choices=['adr', 'postmortem', 'contract', 'gotcha'])
127
+ p.add_argument('--title', required=True)
128
+ p.add_argument('--body', default=None, help='PR body text')
129
+ p.add_argument('--body-file', default=None, help='read PR body from file')
130
+ p.add_argument('--repo', default=None, help='repo path (for slug anchor)')
131
+ p.add_argument('--repo-ref-path', default=None,
132
+ help='primary repo path for repo_ref (e.g. src/auth/jwt.py)')
133
+ p.add_argument('--commit', default=None, help='commit hash')
134
+ p.add_argument('--files', nargs='*', default=None, help='changed files')
135
+ p.add_argument('--nodes', default=os.path.join(ROOT, 'nodes'))
136
+ p.add_argument('--out', default=None,
137
+ help='output dir (default: <nodes>/../temp)')
138
+ args = p.parse_args()
139
+
140
+ if args.body_file:
141
+ with open(args.body_file, 'r', encoding='utf-8') as f:
142
+ args.body = f.read().strip()
143
+
144
+ node_id, text = render(args)
145
+
146
+ out_dir = args.out or os.path.join(os.path.dirname(args.nodes), 'temp')
147
+ os.makedirs(out_dir, exist_ok=True)
148
+ out_path = os.path.join(out_dir, node_id + '.md')
149
+ with open(out_path, 'w', encoding='utf-8', newline='\n') as f:
150
+ f.write(text)
151
+ print('scaffolded %s -> %s' % (node_id, out_path))
152
+
153
+
154
+ if __name__ == '__main__':
155
+ main()