spine-memory 0.2.1__tar.gz → 0.2.2__tar.gz

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 (27) hide show
  1. {spine_memory-0.2.1/spine_memory.egg-info → spine_memory-0.2.2}/PKG-INFO +2 -2
  2. {spine_memory-0.2.1 → spine_memory-0.2.2}/README.md +1 -1
  3. {spine_memory-0.2.1 → spine_memory-0.2.2}/pyproject.toml +1 -1
  4. {spine_memory-0.2.1 → spine_memory-0.2.2/spine_memory.egg-info}/PKG-INFO +2 -2
  5. {spine_memory-0.2.1 → spine_memory-0.2.2}/spine_memory.egg-info/SOURCES.txt +1 -0
  6. spine_memory-0.2.2/tests/test_smoke.py +200 -0
  7. spine_memory-0.2.2/tools/_critic_check.py +183 -0
  8. {spine_memory-0.2.1 → spine_memory-0.2.2}/tools/_node_io.py +69 -2
  9. {spine_memory-0.2.1 → spine_memory-0.2.2}/tools/_quality_audit.py +7 -7
  10. {spine_memory-0.2.1 → spine_memory-0.2.2}/tools/_wander.py +3 -2
  11. {spine_memory-0.2.1 → spine_memory-0.2.2}/tools/cli.py +4 -2
  12. {spine_memory-0.2.1 → spine_memory-0.2.2}/tools/mcp_server.py +8 -7
  13. {spine_memory-0.2.1 → spine_memory-0.2.2}/tools/night_daemon.py +25 -31
  14. {spine_memory-0.2.1 → spine_memory-0.2.2}/tools/spine_preflight.py +3 -3
  15. spine_memory-0.2.1/tests/test_smoke.py +0 -96
  16. {spine_memory-0.2.1 → spine_memory-0.2.2}/LICENSE +0 -0
  17. {spine_memory-0.2.1 → spine_memory-0.2.2}/setup.cfg +0 -0
  18. {spine_memory-0.2.1 → spine_memory-0.2.2}/spine_memory.egg-info/dependency_links.txt +0 -0
  19. {spine_memory-0.2.1 → spine_memory-0.2.2}/spine_memory.egg-info/entry_points.txt +0 -0
  20. {spine_memory-0.2.1 → spine_memory-0.2.2}/spine_memory.egg-info/requires.txt +0 -0
  21. {spine_memory-0.2.1 → spine_memory-0.2.2}/spine_memory.egg-info/top_level.txt +0 -0
  22. {spine_memory-0.2.1 → spine_memory-0.2.2}/tools/_build_index.py +0 -0
  23. {spine_memory-0.2.1 → spine_memory-0.2.2}/tools/_check_anchors.py +0 -0
  24. {spine_memory-0.2.1 → spine_memory-0.2.2}/tools/_crosslink.py +0 -0
  25. {spine_memory-0.2.1 → spine_memory-0.2.2}/tools/_embed_links.py +0 -0
  26. {spine_memory-0.2.1 → spine_memory-0.2.2}/tools/_git_hook.py +0 -0
  27. {spine_memory-0.2.1 → spine_memory-0.2.2}/tools/benchmark_tokens.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spine-memory
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: Hierarchical Markdown/YAML graph memory for long-horizon AI agents — git-native, zero-token CI guardrails, no vector DB.
5
5
  License-Expression: MIT
6
6
  Project-URL: Homepage, https://github.com/Scrimal/SPINE-Memory
@@ -157,7 +157,7 @@ Dev tools:
157
157
  | Typed semantic links | 460+ edges |
158
158
  | Embedding links | 1496 (top-5, threshold 0.88) |
159
159
  | YAML validity — production | 100% (532/532), enforced by `critic_check` |
160
- | YAML validity — demo corpus | 100% (3/3 PASS) |
160
+ | YAML validity — demo corpus | 100% (6/6 PASS) |
161
161
  | Chunk granularity | ~5,000 chars |
162
162
  | Retrieval strategy | progressive disclosure |
163
163
 
@@ -123,7 +123,7 @@ Dev tools:
123
123
  | Typed semantic links | 460+ edges |
124
124
  | Embedding links | 1496 (top-5, threshold 0.88) |
125
125
  | YAML validity — production | 100% (532/532), enforced by `critic_check` |
126
- | YAML validity — demo corpus | 100% (3/3 PASS) |
126
+ | YAML validity — demo corpus | 100% (6/6 PASS) |
127
127
  | Chunk granularity | ~5,000 chars |
128
128
  | Retrieval strategy | progressive disclosure |
129
129
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "spine-memory"
7
- version = "0.2.1"
7
+ version = "0.2.2"
8
8
  description = "Hierarchical Markdown/YAML graph memory for long-horizon AI agents — git-native, zero-token CI guardrails, no vector DB."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spine-memory
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: Hierarchical Markdown/YAML graph memory for long-horizon AI agents — git-native, zero-token CI guardrails, no vector DB.
5
5
  License-Expression: MIT
6
6
  Project-URL: Homepage, https://github.com/Scrimal/SPINE-Memory
@@ -157,7 +157,7 @@ Dev tools:
157
157
  | Typed semantic links | 460+ edges |
158
158
  | Embedding links | 1496 (top-5, threshold 0.88) |
159
159
  | YAML validity — production | 100% (532/532), enforced by `critic_check` |
160
- | YAML validity — demo corpus | 100% (3/3 PASS) |
160
+ | YAML validity — demo corpus | 100% (6/6 PASS) |
161
161
  | Chunk granularity | ~5,000 chars |
162
162
  | Retrieval strategy | progressive disclosure |
163
163
 
@@ -10,6 +10,7 @@ spine_memory.egg-info/top_level.txt
10
10
  tests/test_smoke.py
11
11
  tools/_build_index.py
12
12
  tools/_check_anchors.py
13
+ tools/_critic_check.py
13
14
  tools/_crosslink.py
14
15
  tools/_embed_links.py
15
16
  tools/_git_hook.py
@@ -0,0 +1,200 @@
1
+ #!/usr/bin/env python3
2
+ """Smoke tests for SPINE-Memory core (stdlib unittest, no pytest).
3
+
4
+ Run:
5
+ python -m unittest discover -s tests
6
+ """
7
+
8
+ import os
9
+ import sys
10
+ import tempfile
11
+ import unittest
12
+
13
+ BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
14
+ sys.path.insert(0, os.path.join(BASE, 'tools'))
15
+
16
+ try:
17
+ from spine_memory import _node_io
18
+ except ImportError:
19
+ import _node_io
20
+
21
+ NODES = os.path.join(BASE, 'nodes')
22
+
23
+
24
+ class TestReadNode(unittest.TestCase):
25
+ def test_read_kedr_001(self):
26
+ d = _node_io.read_node(os.path.join(NODES, 'KEDR_001.md'))
27
+ self.assertIsNotNone(d)
28
+ self.assertEqual(d['id'], 'KEDR_001')
29
+ self.assertEqual(d['domain'], 'Связь')
30
+ self.assertGreaterEqual(len(d['search_anchors']), 3)
31
+ self.assertIn('KEDR_002', d['semantic_links'])
32
+ self.assertTrue(d['source_base'])
33
+
34
+ def test_parse_inline_and_block_lists(self):
35
+ self.assertEqual(_node_io.parse_list('[a, b, c]'), ['a', 'b', 'c'])
36
+ self.assertEqual(_node_io.parse_list('- a\n- b\n'), ['a', 'b'])
37
+
38
+
39
+ class TestAddSemanticLink(unittest.TestCase):
40
+ def _write(self, content):
41
+ p = tempfile.mktemp(suffix='.md')
42
+ with open(p, 'w', encoding='utf-8') as f:
43
+ f.write(content)
44
+ return p
45
+
46
+ def test_add_to_node_without_field(self):
47
+ # Regression: a node with NO semantic_links must not get a
48
+ # leading-space ' semantic_links:' (it would become nested YAML and
49
+ # unreadable by the top-level key parser).
50
+ content = ('---\nid: T1\ndomain: X\nsearch_anchors:\n'
51
+ ' - aaa\n - bbb\n - ccc\n---\n\n'
52
+ '# IMPULSE\nimp\n\n# SOURCE_BASE\nraw\n')
53
+ p = self._write(content)
54
+ try:
55
+ self.assertTrue(_node_io.add_semantic_link(p, 'T2', 'reason'))
56
+ with open(p, 'r', encoding='utf-8') as f:
57
+ out = f.read()
58
+ self.assertNotIn('\n semantic_links:', out)
59
+ self.assertIn('\nsemantic_links:\n', out)
60
+ d = _node_io.read_node(p)
61
+ self.assertIn('T2', d['semantic_links'])
62
+ finally:
63
+ os.remove(p)
64
+
65
+ def test_add_existing_link_is_noop(self):
66
+ content = ('---\nid: T1\ndomain: X\nsemantic_links:\n'
67
+ ' - "[[T2]]::x"\nsearch_anchors:\n'
68
+ ' - aaa\n - bbb\n - ccc\n---\n\n# IMPULSE\nimp\n')
69
+ p = self._write(content)
70
+ try:
71
+ self.assertFalse(_node_io.add_semantic_link(p, 'T2', 'x'))
72
+ finally:
73
+ os.remove(p)
74
+
75
+
76
+ class TestSourceBaseProtection(unittest.TestCase):
77
+ def test_source_base_not_truncated(self):
78
+ # SOURCE_BASE must swallow '#' comment lines and mid-file '---'.
79
+ content = ('---\nid: T1\ndomain: X\nsearch_anchors:\n'
80
+ ' - aaa\n - bbb\n - ccc\n---\n\n'
81
+ '# IMPULSE\nimp\n\n# SOURCE_BASE\n'
82
+ 'line1\n# comment inside\n---\nline after\nlast\n')
83
+ p = tempfile.mktemp(suffix='.md')
84
+ with open(p, 'w', encoding='utf-8') as f:
85
+ f.write(content)
86
+ try:
87
+ d = _node_io.read_node(p)
88
+ self.assertIn('# comment inside', d['source_base'])
89
+ self.assertIn('line after', d['source_base'])
90
+ self.assertIn('last', d['source_base'])
91
+ finally:
92
+ os.remove(p)
93
+
94
+
95
+ class TestSentenceCounter(unittest.TestCase):
96
+ def test_decimal_and_version_dots_do_not_count(self):
97
+ self.assertEqual(_node_io.sentence_counter('Ratio 142.8 vs v0.2.1.'), 1)
98
+ self.assertEqual(_node_io.sentence_counter('v0.2.1'), 0)
99
+
100
+ def test_plain_sentences(self):
101
+ self.assertEqual(_node_io.sentence_counter('First. Second! Third?'), 3)
102
+
103
+ def test_empty(self):
104
+ self.assertEqual(_node_io.sentence_counter(''), 0)
105
+
106
+
107
+ class TestStripComment(unittest.TestCase):
108
+ def test_keeps_hash_inside_quotes(self):
109
+ self.assertEqual(_node_io._strip_comment('"fix #123" # note'), '"fix #123"')
110
+ self.assertEqual(_node_io._strip_comment("'a # b'"), "'a # b'")
111
+
112
+ def test_strips_plain_comment(self):
113
+ self.assertEqual(_node_io._strip_comment('value # comment'), 'value')
114
+
115
+
116
+ class TestPathsMatch(unittest.TestCase):
117
+ def test_no_false_suffix(self):
118
+ self.assertFalse(_node_io.paths_match('my_utils.py', 'utils.py'))
119
+ self.assertFalse(_node_io.paths_match('utils.py', 'my_utils.py'))
120
+
121
+ def test_directory_boundary(self):
122
+ self.assertTrue(_node_io.paths_match('src/utils.py', 'utils.py'))
123
+ self.assertTrue(_node_io.paths_match('src\\utils.py', 'utils.py'))
124
+
125
+ def test_equality(self):
126
+ self.assertTrue(_node_io.paths_match('utils.py', 'utils.py'))
127
+
128
+
129
+ class TestReadNodeFields(unittest.TestCase):
130
+ def test_strategic_weight_and_timestamp(self):
131
+ content = ('---\nid: T1\ndomain: X\ncreated: 2026-01-02\nsearch_anchors:\n'
132
+ ' - aaa\n - bbb\n - ccc\n---\n\n# IMPULSE\nimp\n\n'
133
+ '# IMPACT\nimpact:\n strategic_weight: 0.8\n key_insight: |\n x\n\n'
134
+ '# SOURCE_BASE\nraw\n')
135
+ p = tempfile.mktemp(suffix='.md')
136
+ with open(p, 'w', encoding='utf-8') as f:
137
+ f.write(content)
138
+ try:
139
+ d = _node_io.read_node(p)
140
+ self.assertEqual(d['strategic_weight'], 0.8)
141
+ self.assertIsInstance(d['timestamp'], float)
142
+ self.assertEqual(d['created'], '2026-01-02')
143
+ finally:
144
+ os.remove(p)
145
+
146
+
147
+ class TestBuildIndex(unittest.TestCase):
148
+ def test_invert(self):
149
+ import _build_index
150
+ rev = _build_index.invert({'a': ['b', 'c'], 'b': ['c']})
151
+ self.assertEqual(rev['c'], ['a', 'b'])
152
+ self.assertEqual(rev['b'], ['a'])
153
+
154
+
155
+ class TestCrosslink(unittest.TestCase):
156
+ def test_find_pairs_anchor_overlap(self):
157
+ import _crosslink
158
+ nodes = {
159
+ 'A': {'id': 'A', 'constellation': None, 'anchors': ['x', 'y', 'z'], 'existing_links': set()},
160
+ 'B': {'id': 'B', 'constellation': None, 'anchors': ['y', 'z', 'w'], 'existing_links': set()},
161
+ 'C': {'id': 'C', 'constellation': None, 'anchors': ['q', 'r', 's'], 'existing_links': set()},
162
+ }
163
+ reasons = {tuple(sorted((a, b))) for a, b, _r in _crosslink.find_pairs(nodes)}
164
+ self.assertIn(('A', 'B'), reasons)
165
+ self.assertNotIn(('A', 'C'), reasons)
166
+
167
+
168
+ class TestPreflight(unittest.TestCase):
169
+ def test_match_files(self):
170
+ import spine_preflight
171
+ m = spine_preflight.match_files({'src/auth.py': ['N1']}, ['src/auth.py'])
172
+ self.assertEqual(m['src/auth.py'], ['N1'])
173
+
174
+ def test_match_files_no_false_suffix(self):
175
+ import spine_preflight
176
+ m = spine_preflight.match_files({'utils.py': ['N2']}, ['my_utils.py'])
177
+ self.assertEqual(m, {})
178
+
179
+
180
+ class TestNightDaemon(unittest.TestCase):
181
+ def test_decay_factor(self):
182
+ import night_daemon
183
+ self.assertEqual(night_daemon.decay_factor(0), 1.0)
184
+ self.assertEqual(night_daemon.decay_factor(20), 0.9)
185
+ self.assertEqual(night_daemon.decay_factor(60), 0.7)
186
+ self.assertEqual(night_daemon.decay_factor(100), 0.5)
187
+
188
+
189
+ class TestMcpServer(unittest.TestCase):
190
+ def test_read_node(self):
191
+ try:
192
+ import mcp_server
193
+ except ImportError:
194
+ self.skipTest('fastmcp not installed')
195
+ d = mcp_server.read_node(os.path.join(NODES, 'KEDR_001.md'))
196
+ self.assertEqual(d['id'], 'KEDR_001')
197
+
198
+
199
+ if __name__ == '__main__':
200
+ unittest.main()
@@ -0,0 +1,183 @@
1
+ #!/usr/bin/env python3
2
+ """SPINE critic — deterministic node audit (pure Python, cross-platform).
3
+
4
+ Replaces ``_critic_check.sh`` so the main validator runs on stdlib Python
5
+ (works on a clean Windows box without Git Bash) and can emit machine-readable
6
+ JSON for CI / night_daemon.
7
+
8
+ Checks per node:
9
+ 1. IMPULSE — max 2 non-empty lines
10
+ 2. SUMMARY — max 7 sentences (``_node_io.sentence_counter``, decimal-dot safe)
11
+ 3. SOURCE_BASE — >= 70% of the raw chunk by bytes (when the raw file exists)
12
+ 4. ANCHORS — format + canon + fuzzy-duplicates (via ``_check_anchors``)
13
+ 5. VECTORS — every entry carries a ``# comment``
14
+ 6. YAML — no bare ``[[...]]`` anchors in ``search_anchors``
15
+
16
+ Usage (positional args mirror the legacy shell wrapper):
17
+ python tools/_critic_check.py [nodes_dir] [raw_dir] [anchor_dump] [--json]
18
+
19
+ Exit: 0 = all PASS, 1 = at least one FAIL.
20
+ """
21
+
22
+ import argparse
23
+ import json
24
+ import os
25
+ import re
26
+ import sys
27
+
28
+ if sys.platform == 'win32':
29
+ sys.stdout.reconfigure(encoding='utf-8', errors='replace')
30
+ sys.stderr.reconfigure(encoding='utf-8', errors='replace')
31
+
32
+ try:
33
+ from spine_memory import _node_io
34
+ except ImportError:
35
+ import _node_io
36
+
37
+ try:
38
+ from spine_memory import _check_anchors
39
+ except ImportError:
40
+ import _check_anchors
41
+
42
+ IMPULSE_LIMIT = 2
43
+ SUMMARY_LIMIT = 7 # methodology says 5; critic tolerates up to 7
44
+ SOURCE_MIN_PCT = 70
45
+
46
+
47
+ def _impulse_lines(impulse):
48
+ return len([l for l in impulse.split('\n') if l.strip()])
49
+
50
+
51
+ def _raw_path(raw_dir, node_id):
52
+ m = re.search(r'(\d+)$', node_id)
53
+ if not m:
54
+ return None
55
+ p = os.path.join(raw_dir, 'U' + m.group(1) + '.md')
56
+ return p if os.path.exists(p) else None
57
+
58
+
59
+ def _vectors_without_comment(content):
60
+ """Count vectors without a trailing ``# comment`` in the raw YAML block.
61
+
62
+ Parsed vectors lose the ``#`` (``_strip_comment`` removes it), so this
63
+ checks the raw ``vectors:`` block like the legacy shell critic did.
64
+ """
65
+ m = re.search(r'^vectors:\s*\n((?:\s+-\s.*\n?)*)', content, re.MULTILINE)
66
+ if not m:
67
+ return 0
68
+ block = m.group(1)
69
+ if '::' not in block:
70
+ return 0
71
+ return sum(1 for line in block.split('\n')
72
+ if re.match(r'^\s*-\s+', line) and '::' in line and '#' not in line)
73
+
74
+
75
+ def check_node(path, raw_dir, canon):
76
+ """Return {'id': ..., 'fails': [str, ...]} for one node file."""
77
+ node_id = os.path.basename(path).replace('.md', '')
78
+ d = _node_io.read_node(path)
79
+ if d is None:
80
+ return {'id': node_id, 'fails': ['YAML(no_frontmatter)']}
81
+
82
+ fails = []
83
+
84
+ # 1. IMPULSE
85
+ imp = _impulse_lines(d['impulse'])
86
+ if imp > IMPULSE_LIMIT:
87
+ fails.append('IMPULSE(%d)' % imp)
88
+
89
+ # 2. SUMMARY — sentence counter, decimal/version dots don't count.
90
+ ssum = _node_io.sentence_counter(d['summary'])
91
+ if ssum > SUMMARY_LIMIT:
92
+ fails.append('SUMMARY(%d)' % ssum)
93
+
94
+ # 3. SOURCE_BASE retention (only when the matching raw chunk exists).
95
+ raw_path = _raw_path(raw_dir, d['id'])
96
+ if raw_path:
97
+ raw_size = os.path.getsize(raw_path)
98
+ src_size = len(d['source_base'].encode('utf-8'))
99
+ if raw_size > 0:
100
+ pct = 100.0 * src_size / raw_size
101
+ if pct < SOURCE_MIN_PCT:
102
+ fails.append('SOURCE(%d%%<%d%%)' % (int(pct), SOURCE_MIN_PCT))
103
+
104
+ # 4. ANCHORS — format / canon / fuzzy duplicates (new anchors = warn only).
105
+ if not d['search_anchors']:
106
+ fails.append('ANCHORS(0)')
107
+ else:
108
+ fmt = dup = 0
109
+ for a in d['search_anchors']:
110
+ a_clean = str(a).split('#')[0].strip()
111
+ if _check_anchors.check_format(a_clean):
112
+ fmt += 1
113
+ continue
114
+ if a_clean in canon:
115
+ continue
116
+ best, _score = _check_anchors.fuzzy_match(a_clean, canon)
117
+ if best:
118
+ dup += 1
119
+ if fmt or dup:
120
+ fails.append('ANCHORS(fmt:%d dup:%d)' % (fmt, dup))
121
+
122
+ # 5. VECTORS — check the raw block (parsed vectors lose the trailing '#')
123
+ with open(path, 'r', encoding='utf-8', errors='replace') as f:
124
+ content = f.read()
125
+ vbad = _vectors_without_comment(content)
126
+ if vbad:
127
+ fails.append('VECTORS(%d)' % vbad)
128
+
129
+ # 6. YAML — bare [[...]] anchors
130
+ for a in d['search_anchors']:
131
+ if re.match(r'^\[\[.*\]\]$', a):
132
+ fails.append('YAML(bare_anchors)')
133
+ break
134
+
135
+ return {'id': node_id, 'fails': fails}
136
+
137
+
138
+ def main():
139
+ p = argparse.ArgumentParser(description='SPINE critic — deterministic node audit')
140
+ p.add_argument('nodes_dir', nargs='?', default='nodes')
141
+ p.add_argument('raw_dir', nargs='?', default='raw')
142
+ p.add_argument('anchor_dump', nargs='?', default=None,
143
+ help='path to anchor_dump.json (default: <root>/anchors/anchor_dump.json)')
144
+ p.add_argument('--json', action='store_true',
145
+ help='emit a machine-readable JSON summary')
146
+ args = p.parse_args()
147
+
148
+ dump = args.anchor_dump or os.path.join(
149
+ _node_io.find_spine_root(), 'anchors', 'anchor_dump.json')
150
+ canon = _check_anchors.load_anchor_dump(dump) if os.path.exists(dump) else set()
151
+
152
+ results = []
153
+ if os.path.isdir(args.nodes_dir):
154
+ for fn in sorted(os.listdir(args.nodes_dir)):
155
+ if fn.endswith('.md') and not fn.startswith('_'):
156
+ results.append(check_node(
157
+ os.path.join(args.nodes_dir, fn), args.raw_dir, canon))
158
+
159
+ passed = [r for r in results if not r['fails']]
160
+ failed = [r for r in results if r['fails']]
161
+
162
+ if args.json:
163
+ json.dump({
164
+ 'total': len(results),
165
+ 'passed': len(passed),
166
+ 'failed': len(failed),
167
+ 'failures': [{'id': r['id'], 'fails': r['fails']} for r in failed],
168
+ }, sys.stdout, ensure_ascii=False, indent=2)
169
+ sys.stdout.write('\n')
170
+ else:
171
+ for r in results:
172
+ if r['fails']:
173
+ print('FAIL %s : %s' % (r['id'], ' '.join(r['fails'])))
174
+ else:
175
+ print('PASS %s' % r['id'])
176
+ print()
177
+ print('=== TOTAL: %d PASSED / %d FAILED ===' % (len(passed), len(failed)))
178
+
179
+ sys.exit(0 if not failed else 1)
180
+
181
+
182
+ if __name__ == '__main__':
183
+ main()
@@ -19,6 +19,7 @@ Contract
19
19
 
20
20
  import os
21
21
  import re
22
+ from datetime import datetime
22
23
 
23
24
  # The first ``---`` opens the frontmatter; the closing one must be a ``---``
24
25
  # on its own line. Everything after it is the body.
@@ -82,8 +83,47 @@ def _unquote(s):
82
83
 
83
84
 
84
85
  def _strip_comment(s):
85
- """Strip a trailing ``# comment`` (but keep ``#`` inside quotes)."""
86
- return s.split('#')[0].strip()
86
+ """Strip a trailing ``# comment`` but keep ``#`` inside quotes."""
87
+ s = s.strip()
88
+ quote = None
89
+ for i, ch in enumerate(s):
90
+ if ch in ('"', "'"):
91
+ if quote is None:
92
+ quote = ch
93
+ elif quote == ch:
94
+ quote = None
95
+ elif ch == '#' and quote is None:
96
+ return s[:i].rstrip()
97
+ return s
98
+
99
+
100
+ _SENTENCE_END_RE = re.compile(r'[.!?](?=\s+[A-ZА-ЯЁ0-9]|\s*$)')
101
+
102
+
103
+ def sentence_counter(text):
104
+ """Count sentences in ``text``.
105
+
106
+ Terminators are ``. ! ?`` followed by whitespace + uppercase/digit (or end
107
+ of text). Dots BETWEEN digits (``142.8``, ``v0.2.1``) are masked first so
108
+ they never count as terminators.
109
+ """
110
+ if not text:
111
+ return 0
112
+ masked = re.sub(r'(?<=\d)\.(?=\d)', '', text)
113
+ return len(_SENTENCE_END_RE.findall(masked))
114
+
115
+
116
+ def paths_match(fp, ref):
117
+ """True if two file paths refer to the same file, ignoring ``\\`` vs ``/``.
118
+
119
+ The suffix match requires a directory boundary, so ``my_utils.py`` does
120
+ NOT match ``utils.py`` (kills the false ``endswith`` hits from the audit).
121
+ """
122
+ if not fp or not ref:
123
+ return False
124
+ a = fp.replace('\\', '/')
125
+ b = ref.replace('\\', '/')
126
+ return a == b or a.endswith('/' + b) or b.endswith('/' + a)
87
127
 
88
128
 
89
129
  def parse_list(value):
@@ -280,6 +320,28 @@ def read_node(path):
280
320
  if l not in sem:
281
321
  sem.append(l)
282
322
 
323
+ # strategic_weight lives in the # IMPACT body section, not in the YAML.
324
+ sw = None
325
+ m = re.search(r'strategic_weight:\s*([\d.]+)', secs.get('impact', ''))
326
+ if m:
327
+ try:
328
+ sw = float(m.group(1))
329
+ except ValueError:
330
+ sw = None
331
+
332
+ # Parsed timestamp: last_accessed > updated > created, else file mtime.
333
+ ts = None
334
+ for key in ('last_accessed', 'updated', 'created'):
335
+ v = fm.get(key)
336
+ if v:
337
+ try:
338
+ ts = datetime.strptime(str(v)[:10], '%Y-%m-%d').timestamp()
339
+ break
340
+ except ValueError:
341
+ pass
342
+ if ts is None:
343
+ ts = os.path.getmtime(path)
344
+
283
345
  return {
284
346
  'id': nid,
285
347
  'path': path,
@@ -298,6 +360,11 @@ def read_node(path):
298
360
  'cleaned_data': secs.get('cleaned_data', ''),
299
361
  'impact': secs.get('impact', ''),
300
362
  'source_base': secs.get('source_base', ''),
363
+ 'strategic_weight': sw,
364
+ 'timestamp': ts,
365
+ 'created': fm.get('created'),
366
+ 'updated': fm.get('updated'),
367
+ 'last_accessed': fm.get('last_accessed'),
301
368
  # dev-overlay fields (CODE_MEMORY preset) — generic frontmatter pass-through
302
369
  'kind': fm.get('kind'),
303
370
  'status': fm.get('status'),
@@ -82,10 +82,10 @@ def read_node(path, raw_folder):
82
82
  if imp_lines > 2:
83
83
  result['issues'].append('IMPULSE:%d' % imp_lines)
84
84
 
85
- sum_lines = count_lines(d['summary'])
86
- result['summary'] = sum_lines
87
- if sum_lines > 5:
88
- result['issues'].append('SUMMARY:%d' % sum_lines)
85
+ sum_sent = _node_io.sentence_counter(d['summary'])
86
+ result['summary'] = sum_sent
87
+ if sum_sent > 5:
88
+ result['issues'].append('SUMMARY:%d' % sum_sent)
89
89
 
90
90
  cln_lines = count_lines(d['cleaned_data'])
91
91
  result['cleaned'] = cln_lines
@@ -95,10 +95,10 @@ def read_node(path, raw_folder):
95
95
  src_lines = count_lines(d['source_base'])
96
96
  result['source'] = src_lines
97
97
 
98
- if sum_lines > 0 and cln_lines > 0 and sum_lines > cln_lines / 2:
99
- result['issues'].append('S>C_RATIO:%.1f' % (sum_lines / max(cln_lines, 1)))
98
+ if sum_sent > 0 and cln_lines > 0 and sum_sent > cln_lines / 2:
99
+ result['issues'].append('S>C_RATIO:%.1f' % (sum_sent / max(cln_lines, 1)))
100
100
 
101
- if imp_lines > 0 and sum_lines > 0 and imp_lines > sum_lines:
101
+ if imp_lines > 0 and sum_sent > 0 and imp_lines > sum_sent:
102
102
  result['issues'].append('IMP>SUM')
103
103
 
104
104
  if not d['impact']:
@@ -14,6 +14,7 @@ import json
14
14
  import os
15
15
  import re
16
16
  import sys
17
+ from collections import deque
17
18
 
18
19
  if sys.platform == 'win32':
19
20
  sys.stdout.reconfigure(encoding='utf-8', errors='replace')
@@ -80,10 +81,10 @@ def wander(start, hops, node_index, anchor_index, backlinks=None,
80
81
  return
81
82
 
82
83
  visited = set()
83
- queue = [(current, 0)]
84
+ queue = deque([(current, 0)])
84
85
 
85
86
  while queue:
86
- nid, depth = queue.pop(0)
87
+ nid, depth = queue.popleft()
87
88
  if nid in visited or depth > hops:
88
89
  continue
89
90
  visited.add(nid)
@@ -6,6 +6,7 @@ Commands:
6
6
  spine index rebuild reverse_index.json
7
7
  spine wander --from ID --hops N traverse the graph
8
8
  spine preflight --files ... memory for changed code files
9
+ spine critic [nodes] [raw] [anchor_dump] deterministic node audit
9
10
  spine mcp start the MCP server
10
11
 
11
12
  All non-init commands forward to the sibling tool scripts, so they work both
@@ -157,12 +158,13 @@ SCRIPT_MAP = {
157
158
  'daemon': 'night_daemon.py',
158
159
  'benchmark': 'benchmark_tokens.py',
159
160
  'embed': '_embed_links.py',
161
+ 'critic': '_critic_check.py',
160
162
  }
161
163
 
162
164
 
163
165
  def main():
164
166
  if len(sys.argv) < 2:
165
- print('usage: spine <init|index|wander|preflight|mcp|audit|crosslink|hook|daemon|benchmark|embed> [args]')
167
+ print('usage: spine <init|index|wander|preflight|critic|mcp|audit|crosslink|hook|daemon|benchmark|embed> [args]')
166
168
  return
167
169
 
168
170
  cmd = sys.argv[1]
@@ -178,7 +180,7 @@ def main():
178
180
  script = SCRIPT_MAP.get(cmd)
179
181
  if not script:
180
182
  print('unknown command: %s' % cmd)
181
- print('usage: spine <init|index|wander|preflight|mcp|audit|crosslink|hook|daemon|benchmark|embed> [args]')
183
+ print('usage: spine <init|index|wander|preflight|critic|mcp|audit|crosslink|hook|daemon|benchmark|embed> [args]')
182
184
  return
183
185
 
184
186
  subprocess.run([sys.executable, os.path.join(BASE, script)] + rest)
@@ -25,6 +25,7 @@ import json
25
25
  import os
26
26
  import re
27
27
  import sys
28
+ from collections import deque
28
29
 
29
30
  try:
30
31
  from mcp.server.fastmcp import FastMCP
@@ -37,7 +38,6 @@ try:
37
38
  from spine_memory import _node_io
38
39
  except ImportError:
39
40
  import _node_io
40
- NODES_DIR = os.path.join(_node_io.find_spine_root(), 'nodes')
41
41
  METHODOLOGY_EN = os.path.join(BASE, '..', 'methodology', 'SPINE_METHODOLOGY_EN.md')
42
42
 
43
43
  LAYERS = ('impulse', 'summary', 'cleaned', 'impact', 'source_base')
@@ -69,12 +69,13 @@ def read_node(path):
69
69
 
70
70
  def load_index():
71
71
  node_index, anchor_index = {}, {}
72
- if not os.path.isdir(NODES_DIR):
72
+ nodes_dir = os.path.join(_node_io.find_spine_root(), 'nodes')
73
+ if not os.path.isdir(nodes_dir):
73
74
  return node_index, anchor_index
74
- for fn in sorted(os.listdir(NODES_DIR)):
75
+ for fn in sorted(os.listdir(nodes_dir)):
75
76
  if not fn.endswith('.md'):
76
77
  continue
77
- data = read_node(os.path.join(NODES_DIR, fn))
78
+ data = read_node(os.path.join(nodes_dir, fn))
78
79
  node_index[data['id']] = data
79
80
  for a in data['anchors']:
80
81
  anchor_index.setdefault(a, []).append(data['id'])
@@ -117,10 +118,10 @@ def spine_wander(start: str, hops: int = 2, include_embed: bool = False) -> list
117
118
  return [{'error': f'node or anchor not found: {start}'}]
118
119
 
119
120
  visited = []
120
- queue = [(current, 0)]
121
+ queue = deque([(current, 0)])
121
122
  seen = set()
122
123
  while queue:
123
- nid, depth = queue.pop(0)
124
+ nid, depth = queue.popleft()
124
125
  if nid in seen or depth > hops:
125
126
  continue
126
127
  seen.add(nid)
@@ -174,7 +175,7 @@ def spine_for_file(filepath: str) -> list[dict]:
174
175
  code_index = data.get('code_index', {})
175
176
  hits = set()
176
177
  for fp, nids in code_index.items():
177
- if fp == filepath or fp.endswith(filepath) or filepath.endswith(fp):
178
+ if _node_io.paths_match(fp, filepath):
178
179
  hits.update(nids)
179
180
  node_index, _ = load_index()
180
181
  return [{'id': n, 'impulse': node_index.get(n, {}).get('impulse', '')}
@@ -55,40 +55,34 @@ def decay_factor(days):
55
55
  return 0.5
56
56
 
57
57
 
58
- def _node_stamp(content, path):
59
- for key in ('last_accessed', 'updated', 'created'):
60
- m = re.search(r'^%s:\s*(\d{4}-\d{2}-\d{2})' % key, content, re.MULTILINE)
61
- if m:
62
- try:
63
- return datetime.strptime(m.group(1), '%Y-%m-%d').timestamp()
64
- except ValueError:
65
- pass
66
- return os.path.getmtime(path)
67
-
68
-
69
58
  def read_node(path):
59
+ """Load a node through the canonical parser; expose daemon-facing fields."""
70
60
  d = _node_io.read_node(path)
71
- with open(path, 'r', encoding='utf-8', errors='replace') as f:
72
- content = f.read()
73
- data = {
74
- 'id': d['id'] if d else os.path.basename(path).replace('.md', ''),
75
- 'impulse': d['impulse'] if d else '',
76
- 'weight': 0.0,
77
- 'sem_links': d['semantic_links'] if d else [],
78
- 'anchors': d['search_anchors'] if d else [],
79
- 'code_refs': d['code_refs'] if d else [],
80
- 'repo_ref': d['repo_ref'] if d else {},
81
- 'source_base': d['source_base'] if d else '',
82
- 'yaml_ok': d is not None,
83
- 'mtime': _node_stamp(content, path),
61
+ if d is None:
62
+ return {
63
+ 'id': os.path.basename(path).replace('.md', ''),
64
+ 'impulse': '',
65
+ 'weight': 0.0,
66
+ 'sem_links': [],
67
+ 'anchors': [],
68
+ 'code_refs': [],
69
+ 'repo_ref': {},
70
+ 'source_base': '',
71
+ 'yaml_ok': False,
72
+ 'mtime': os.path.getmtime(path),
73
+ }
74
+ return {
75
+ 'id': d['id'],
76
+ 'impulse': d['impulse'],
77
+ 'weight': d['strategic_weight'] or 0.0,
78
+ 'sem_links': d['semantic_links'],
79
+ 'anchors': d['search_anchors'],
80
+ 'code_refs': d['code_refs'],
81
+ 'repo_ref': d['repo_ref'],
82
+ 'source_base': d['source_base'],
83
+ 'yaml_ok': True,
84
+ 'mtime': d['timestamp'],
84
85
  }
85
- m = re.search(r'strategic_weight:\s*([\d.]+)', content)
86
- if m:
87
- try:
88
- data['weight'] = float(m.group(1))
89
- except ValueError:
90
- pass
91
- return data
92
86
 
93
87
 
94
88
  def load_all(folders):
@@ -19,9 +19,9 @@ import subprocess
19
19
  import sys
20
20
 
21
21
  try:
22
- from spine_memory._node_io import read_node, find_spine_root
22
+ from spine_memory._node_io import read_node, find_spine_root, paths_match
23
23
  except ImportError:
24
- from _node_io import read_node, find_spine_root
24
+ from _node_io import read_node, find_spine_root, paths_match
25
25
 
26
26
  BASE = os.path.dirname(os.path.abspath(__file__))
27
27
  ROOT = find_spine_root()
@@ -52,7 +52,7 @@ def match_files(code_index, files):
52
52
  for fp in files:
53
53
  hits = set()
54
54
  for ref_path, nids in code_index.items():
55
- if fp == ref_path or fp.endswith(ref_path) or ref_path.endswith(fp):
55
+ if paths_match(fp, ref_path):
56
56
  hits.update(nids)
57
57
  if hits:
58
58
  out[fp] = sorted(hits)
@@ -1,96 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Smoke tests for SPINE-Memory core (stdlib unittest, no pytest).
3
-
4
- Run:
5
- python -m unittest discover -s tests
6
- """
7
-
8
- import os
9
- import sys
10
- import tempfile
11
- import unittest
12
-
13
- BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
14
- sys.path.insert(0, os.path.join(BASE, 'tools'))
15
-
16
- try:
17
- from spine_memory import _node_io
18
- except ImportError:
19
- import _node_io
20
-
21
- NODES = os.path.join(BASE, 'nodes')
22
-
23
-
24
- class TestReadNode(unittest.TestCase):
25
- def test_read_kedr_001(self):
26
- d = _node_io.read_node(os.path.join(NODES, 'KEDR_001.md'))
27
- self.assertIsNotNone(d)
28
- self.assertEqual(d['id'], 'KEDR_001')
29
- self.assertEqual(d['domain'], 'Связь')
30
- self.assertGreaterEqual(len(d['search_anchors']), 3)
31
- self.assertIn('KEDR_002', d['semantic_links'])
32
- self.assertTrue(d['source_base'])
33
-
34
- def test_parse_inline_and_block_lists(self):
35
- self.assertEqual(_node_io.parse_list('[a, b, c]'), ['a', 'b', 'c'])
36
- self.assertEqual(_node_io.parse_list('- a\n- b\n'), ['a', 'b'])
37
-
38
-
39
- class TestAddSemanticLink(unittest.TestCase):
40
- def _write(self, content):
41
- p = tempfile.mktemp(suffix='.md')
42
- with open(p, 'w', encoding='utf-8') as f:
43
- f.write(content)
44
- return p
45
-
46
- def test_add_to_node_without_field(self):
47
- # Regression: a node with NO semantic_links must not get a
48
- # leading-space ' semantic_links:' (it would become nested YAML and
49
- # unreadable by the top-level key parser).
50
- content = ('---\nid: T1\ndomain: X\nsearch_anchors:\n'
51
- ' - aaa\n - bbb\n - ccc\n---\n\n'
52
- '# IMPULSE\nimp\n\n# SOURCE_BASE\nraw\n')
53
- p = self._write(content)
54
- try:
55
- self.assertTrue(_node_io.add_semantic_link(p, 'T2', 'reason'))
56
- with open(p, 'r', encoding='utf-8') as f:
57
- out = f.read()
58
- self.assertNotIn('\n semantic_links:', out)
59
- self.assertIn('\nsemantic_links:\n', out)
60
- d = _node_io.read_node(p)
61
- self.assertIn('T2', d['semantic_links'])
62
- finally:
63
- os.remove(p)
64
-
65
- def test_add_existing_link_is_noop(self):
66
- content = ('---\nid: T1\ndomain: X\nsemantic_links:\n'
67
- ' - "[[T2]]::x"\nsearch_anchors:\n'
68
- ' - aaa\n - bbb\n - ccc\n---\n\n# IMPULSE\nimp\n')
69
- p = self._write(content)
70
- try:
71
- self.assertFalse(_node_io.add_semantic_link(p, 'T2', 'x'))
72
- finally:
73
- os.remove(p)
74
-
75
-
76
- class TestSourceBaseProtection(unittest.TestCase):
77
- def test_source_base_not_truncated(self):
78
- # SOURCE_BASE must swallow '#' comment lines and mid-file '---'.
79
- content = ('---\nid: T1\ndomain: X\nsearch_anchors:\n'
80
- ' - aaa\n - bbb\n - ccc\n---\n\n'
81
- '# IMPULSE\nimp\n\n# SOURCE_BASE\n'
82
- 'line1\n# comment inside\n---\nline after\nlast\n')
83
- p = tempfile.mktemp(suffix='.md')
84
- with open(p, 'w', encoding='utf-8') as f:
85
- f.write(content)
86
- try:
87
- d = _node_io.read_node(p)
88
- self.assertIn('# comment inside', d['source_base'])
89
- self.assertIn('line after', d['source_base'])
90
- self.assertIn('last', d['source_base'])
91
- finally:
92
- os.remove(p)
93
-
94
-
95
- if __name__ == '__main__':
96
- unittest.main()
File without changes
File without changes