@massa-ai/cursor-plugin 1.21.0 → 1.23.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.
- package/.cursor-plugin/plugin.json +1 -1
- package/package.json +1 -1
- package/skills/massa-ai/SKILL.md +9 -0
- package/skills/massa-ai/references/evidence-gate.md +1 -1
- package/skills/massa-ai/references/figma-pre-analysis.md +69 -0
- package/skills/massa-ai/references/hook-enforcement.md +2 -2
- package/skills/massa-ai/references/implementation-delivery.md +17 -3
- package/skills/massa-ai/references/lessons.md +9 -10
- package/skills/massa-ai/references/mcp-tools.md +1 -1
- package/skills/massa-ai/references/mobile-context.md +19 -0
- package/skills/massa-ai/references/mobile-diagnosis.md +1 -1
- package/skills/massa-ai/references/project-context.md +1 -1
- package/skills/massa-ai/references/spec-driven/artifact-store.md +7 -8
- package/skills/massa-ai/references/spec-driven/design.md +1 -1
- package/skills/massa-ai/references/spec-driven/execute.md +5 -5
- package/skills/massa-ai/references/spec-driven/specify.md +6 -6
- package/skills/massa-ai/references/spec-driven/sub-agents.md +1 -1
- package/skills/massa-ai/references/spec-driven/tasks.md +2 -2
- package/skills/massa-ai/references/spec-driven/validate.md +3 -3
- package/skills/massa-ai/scripts/check_commit.ts +231 -0
- package/skills/massa-ai/scripts/check_specs_delivered.ts +209 -0
- package/skills/massa-ai/scripts/lessons.ts +907 -0
- package/skills/massa-ai/scripts/validate_spec.ts +413 -0
- package/skills/massa-ai/scripts/validate_state.ts +276 -0
- package/skills/massa-ai/scripts/validate_tasks.ts +498 -0
- package/skills/massa-ai/workflows/architecture/architecture-fix.md +1 -1
- package/skills/massa-ai/workflows/bugs/bugs-fix.md +1 -1
- package/skills/massa-ai/workflows/code-quality/code-quality-fix.md +1 -1
- package/skills/massa-ai/workflows/debug.md +1 -1
- package/skills/massa-ai/workflows/design.md +1 -1
- package/skills/massa-ai/workflows/feature.md +2 -2
- package/skills/massa-ai/workflows/general.md +2 -2
- package/skills/massa-ai/workflows/implementation/implementation-fix.md +1 -1
- package/skills/massa-ai/workflows/maestro/maestro-fix.md +1 -1
- package/skills/massa-ai/workflows/mobile-figma/mobile-figma-audit.md +1 -0
- package/skills/massa-ai/workflows/mobile-figma/mobile-figma-fix.md +2 -1
- package/skills/massa-ai/workflows/refactor.md +1 -1
- package/skills/massa-ai/workflows/requirements/requirements-fix.md +1 -1
- package/skills/massa-ai/workflows/security/security-fix.md +1 -1
- package/skills/massa-ai/workflows/spec-driven.md +6 -6
- package/skills/massa-ai/workflows/tests/tests-fix.md +1 -1
- package/skills/massa-ai/scripts/check_commit.py +0 -128
- package/skills/massa-ai/scripts/check_specs_delivered.py +0 -137
- package/skills/massa-ai/scripts/lessons.py +0 -630
- package/skills/massa-ai/scripts/validate_spec.py +0 -272
- package/skills/massa-ai/scripts/validate_state.py +0 -183
- package/skills/massa-ai/scripts/validate_tasks.py +0 -302
|
@@ -1,630 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
"""
|
|
3
|
-
Deterministic bookkeeping for the massa-ai spec-driven lessons layer.
|
|
4
|
-
|
|
5
|
-
The LLM supplies judgment (which failure happened, how to phrase the lesson, what
|
|
6
|
-
signal grounds it). This script owns everything mechanical: IDs, distinct-feature
|
|
7
|
-
recurrence counting, candidate->confirmed promotion, pruning, demotion, and
|
|
8
|
-
rendering the human/agent-readable playbook. Bookkeeping by hand is exactly what
|
|
9
|
-
rots a lessons file, so it lives here, not in a prompt.
|
|
10
|
-
|
|
11
|
-
Canonical state: .specs/lessons.json (machine-owned - do NOT hand-edit)
|
|
12
|
-
Rendered view: .specs/LESSONS.md (regenerated on every write)
|
|
13
|
-
|
|
14
|
-
Pure standard library. No dependencies. Pass --root with the target workspace
|
|
15
|
-
root so the package-local script writes that workspace's .specs directory.
|
|
16
|
-
|
|
17
|
-
Commands:
|
|
18
|
-
add Record a grounded lesson from a verification signal.
|
|
19
|
-
list Print lessons (default: confirmed) for loading at Specify/Design.
|
|
20
|
-
penalize Mark a confirmed lesson as having failed when applied (-> quarantine).
|
|
21
|
-
prune Drop stale uncorroborated candidates (also runs automatically on add/list).
|
|
22
|
-
status Print counts (used by the self-check in validate.md).
|
|
23
|
-
init Create empty store + rendered file.
|
|
24
|
-
observe Ingest a JSON observation into the gitignored observations buffer.
|
|
25
|
-
export Export the lessons store as JSON (round-trips with import).
|
|
26
|
-
import Import lessons from JSON (merge by dedup key; best-effort massa-ai memory).
|
|
27
|
-
selftest Run stdlib regressions (normalization).
|
|
28
|
-
|
|
29
|
-
Exit codes: 0 ok, 2 usage/validation error (e.g. missing grounding).
|
|
30
|
-
"""
|
|
31
|
-
|
|
32
|
-
import argparse
|
|
33
|
-
import datetime as _dt
|
|
34
|
-
import json
|
|
35
|
-
import os
|
|
36
|
-
import re
|
|
37
|
-
import sys
|
|
38
|
-
import unicodedata
|
|
39
|
-
import urllib.request
|
|
40
|
-
|
|
41
|
-
STORE_REL = os.path.join(".specs", "lessons.json")
|
|
42
|
-
RENDER_REL = os.path.join(".specs", "LESSONS.md")
|
|
43
|
-
OBS_REL = os.path.join(".specs", "observations.json")
|
|
44
|
-
|
|
45
|
-
SIGNALS = {
|
|
46
|
-
"ac_gap": "Acceptance criterion not covered / failed",
|
|
47
|
-
"surviving_mutant": "Discrimination sensor mutant survived (weak test)",
|
|
48
|
-
"spec_precision_gap": "Spec did not define a precise outcome",
|
|
49
|
-
"spec_deviation": "Implementation diverged from spec/design (SPEC_DEVIATION)",
|
|
50
|
-
"gate_fail": "Build-level gate check failed",
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
DEFAULTS = {"promote_threshold": 2, "window_days": 45, "quarantine_threshold": 2}
|
|
54
|
-
|
|
55
|
-
# massa-ai supported memory types (references/mcp-tools.md). `procedural` is a
|
|
56
|
-
# TAG, never a type. Lessons are procedural knowledge -> type `pattern`.
|
|
57
|
-
MASSA_AI_SUPPORTED_TYPES = ("critical", "conversation", "code", "decision", "pattern")
|
|
58
|
-
MASSA_AI_LESSON_TYPE = "pattern"
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
def _now():
|
|
62
|
-
return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
def _parse_date(s):
|
|
66
|
-
try:
|
|
67
|
-
return _dt.datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=_dt.timezone.utc)
|
|
68
|
-
except Exception:
|
|
69
|
-
return _dt.datetime.now(_dt.timezone.utc)
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
def _store_path(root):
|
|
73
|
-
return os.path.join(root, STORE_REL)
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
def _render_path(root):
|
|
77
|
-
return os.path.join(root, RENDER_REL)
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
def _load(root):
|
|
81
|
-
path = _store_path(root)
|
|
82
|
-
if not os.path.exists(path):
|
|
83
|
-
return {
|
|
84
|
-
"schema": 1,
|
|
85
|
-
"promote_threshold": DEFAULTS["promote_threshold"],
|
|
86
|
-
"window_days": DEFAULTS["window_days"],
|
|
87
|
-
"quarantine_threshold": DEFAULTS["quarantine_threshold"],
|
|
88
|
-
"next_id": 1,
|
|
89
|
-
"lessons": [],
|
|
90
|
-
}
|
|
91
|
-
with open(path, "r", encoding="utf-8") as f:
|
|
92
|
-
data = json.load(f)
|
|
93
|
-
for k, v in DEFAULTS.items():
|
|
94
|
-
data.setdefault(k, v)
|
|
95
|
-
data.setdefault("schema", 1)
|
|
96
|
-
data.setdefault("next_id", 1)
|
|
97
|
-
data.setdefault("lessons", [])
|
|
98
|
-
return data
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
def _save(root, data):
|
|
102
|
-
os.makedirs(os.path.join(root, ".specs"), exist_ok=True)
|
|
103
|
-
with open(_store_path(root), "w", encoding="utf-8") as f:
|
|
104
|
-
json.dump(data, f, indent=2, ensure_ascii=False)
|
|
105
|
-
f.write("\n")
|
|
106
|
-
_render(root, data)
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
def _confidence(lesson, data):
|
|
110
|
-
"""Deterministic 0-1 confidence from recurrence + signal + scope presence."""
|
|
111
|
-
rec_cap = min(lesson.get("recurrence", 1) / max(data["promote_threshold"], 1), 1.0)
|
|
112
|
-
sig_weight = 0.15
|
|
113
|
-
scope_weight = 0.10 if lesson.get("scope") else 0.0
|
|
114
|
-
return round(min(rec_cap * 0.75 + sig_weight + scope_weight, 1.0), 2)
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
def _obs_path(root):
|
|
118
|
-
return os.path.join(root, OBS_REL)
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
def _obs_load(root):
|
|
122
|
-
path = _obs_path(root)
|
|
123
|
-
if not os.path.exists(path):
|
|
124
|
-
return []
|
|
125
|
-
try:
|
|
126
|
-
with open(path, "r", encoding="utf-8") as f:
|
|
127
|
-
data = json.load(f)
|
|
128
|
-
return data if isinstance(data, list) else []
|
|
129
|
-
except (ValueError, OSError):
|
|
130
|
-
return []
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
def _obs_append(root, item):
|
|
134
|
-
os.makedirs(os.path.join(root, ".specs"), exist_ok=True)
|
|
135
|
-
items = _obs_load(root)
|
|
136
|
-
items.append(item)
|
|
137
|
-
with open(_obs_path(root), "w", encoding="utf-8") as f:
|
|
138
|
-
json.dump(items, f, indent=2, ensure_ascii=False)
|
|
139
|
-
f.write("\n")
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
def _remember_best_effort(root, content, tags, project_id="", session_id=""):
|
|
143
|
-
"""Best-effort massa-ai memory write via REST (urllib, stdlib only).
|
|
144
|
-
|
|
145
|
-
massa-ai MCP is agent-side only; a CLI subprocess cannot call MCP. massa-ai exposes
|
|
146
|
-
REST at MASSA_AI_API_URL. Type is always `pattern` (lessons are procedural
|
|
147
|
-
knowledge); `procedural` is a tag, not a type. Returns True on success,
|
|
148
|
-
False (silent) when unavailable — the file store remains source of truth.
|
|
149
|
-
"""
|
|
150
|
-
api_url = os.environ.get("MASSA_AI_API_URL")
|
|
151
|
-
if not api_url:
|
|
152
|
-
return False
|
|
153
|
-
path = os.environ.get("MASSA_AI_MEMORY_PATH", "/api/v1/memory")
|
|
154
|
-
url = api_url.rstrip("/") + path
|
|
155
|
-
body = json.dumps({
|
|
156
|
-
"content": content, "type": MASSA_AI_LESSON_TYPE, "importance": 0.6,
|
|
157
|
-
"projectId": project_id, "sessionId": session_id, "tags": list(tags),
|
|
158
|
-
}).encode("utf-8")
|
|
159
|
-
req = urllib.request.Request(url, data=body, method="POST",
|
|
160
|
-
headers={"Content-Type": "application/json"})
|
|
161
|
-
key = os.environ.get("MASSA_AI_API_KEY")
|
|
162
|
-
if key:
|
|
163
|
-
req.add_header("x-api-key", key)
|
|
164
|
-
try:
|
|
165
|
-
with urllib.request.urlopen(req, timeout=1.5) as resp:
|
|
166
|
-
return 200 <= resp.status < 300
|
|
167
|
-
except Exception:
|
|
168
|
-
return False
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
def _lesson_tags(lesson):
|
|
172
|
-
"""massa-ai persistence tag contract for a lesson's massa-ai memory."""
|
|
173
|
-
return [
|
|
174
|
-
"project:%s" % lesson.get("project", ""),
|
|
175
|
-
"session:%s" % lesson.get("session", ""),
|
|
176
|
-
"workflow:%s" % (lesson.get("workflow", "") or "unset"),
|
|
177
|
-
"entity:%s" % (lesson.get("entity", "") or "unset"),
|
|
178
|
-
"memory:procedural",
|
|
179
|
-
]
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
def _norm(text):
|
|
183
|
-
"""Normalized dedup key for lesson text.
|
|
184
|
-
|
|
185
|
-
- casefold + NFD, strip combining marks (so Portuguese diacritics match ASCII peers)
|
|
186
|
-
- keep characters where str.isalnum() is true (any script) and whitespace
|
|
187
|
-
- drop other punctuation, collapse whitespace
|
|
188
|
-
|
|
189
|
-
Exact-after-normalization only - no semantic matching (stdlib-only limitation).
|
|
190
|
-
Phrase lessons tersely and canonically so recurrences actually merge.
|
|
191
|
-
"""
|
|
192
|
-
t = unicodedata.normalize("NFD", text.casefold())
|
|
193
|
-
t = "".join(c for c in t if unicodedata.category(c) != "Mn")
|
|
194
|
-
t = "".join(c if (c.isalnum() or c.isspace()) else " " for c in t)
|
|
195
|
-
t = re.sub(r"\s+", " ", t).strip()
|
|
196
|
-
return t
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
def _selftest_norm():
|
|
200
|
-
"""Regressions for #158: Portuguese diacritics + distinct non-Latin text."""
|
|
201
|
-
failures = []
|
|
202
|
-
|
|
203
|
-
def check(cond, msg):
|
|
204
|
-
if not cond:
|
|
205
|
-
failures.append(msg)
|
|
206
|
-
|
|
207
|
-
a = _norm("Não use datas locais")
|
|
208
|
-
b = _norm("Nao use datas locais")
|
|
209
|
-
check(a == b == "nao use datas locais", f"PT diacritics: {a!r} vs {b!r}")
|
|
210
|
-
|
|
211
|
-
jp1 = _norm("日本語の文です")
|
|
212
|
-
jp2 = _norm("別の日本語文")
|
|
213
|
-
check(jp1 != "", f"JP1 empty: {jp1!r}")
|
|
214
|
-
check(jp2 != "", f"JP2 empty: {jp2!r}")
|
|
215
|
-
check(jp1 != jp2, f"JP sentences collapsed: {jp1!r} == {jp2!r}")
|
|
216
|
-
|
|
217
|
-
check(_norm("café") == _norm("cafe") == "cafe", f"cafe: {_norm('café')!r}")
|
|
218
|
-
|
|
219
|
-
if failures:
|
|
220
|
-
for f in failures:
|
|
221
|
-
print(f"FAIL: {f}", file=sys.stderr)
|
|
222
|
-
return 1
|
|
223
|
-
print("selftest_norm: ok")
|
|
224
|
-
return 0
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
def _key(signal, text):
|
|
228
|
-
return signal + "::" + _norm(text)
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
def _auto_prune(data):
|
|
232
|
-
"""Drop candidates that never recurred within the window. Mutates data."""
|
|
233
|
-
threshold = data["promote_threshold"]
|
|
234
|
-
window = data["window_days"]
|
|
235
|
-
now = _dt.datetime.now(_dt.timezone.utc)
|
|
236
|
-
kept = []
|
|
237
|
-
dropped = []
|
|
238
|
-
for l in data["lessons"]:
|
|
239
|
-
if l["status"] == "candidate" and l["recurrence"] < threshold:
|
|
240
|
-
age_days = (now - _parse_date(l.get("last_seen", l.get("created", _now())))).days
|
|
241
|
-
if age_days > window:
|
|
242
|
-
dropped.append(l["id"])
|
|
243
|
-
continue
|
|
244
|
-
kept.append(l)
|
|
245
|
-
data["lessons"] = kept
|
|
246
|
-
return dropped
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
def _find(data, signal, text):
|
|
250
|
-
k = _key(signal, text)
|
|
251
|
-
for l in data["lessons"]:
|
|
252
|
-
if l.get("key") == k:
|
|
253
|
-
return l
|
|
254
|
-
return None
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
def _render(root, data):
|
|
258
|
-
lines = []
|
|
259
|
-
lines.append("# LESSONS - auto-maintained by skills/massa-ai/scripts/lessons.py")
|
|
260
|
-
lines.append("")
|
|
261
|
-
lines.append("> Machine-owned. Do NOT hand-edit. Changes are overwritten on the next `lessons.py` write.")
|
|
262
|
-
lines.append("> Canonical state lives in `.specs/lessons.json`. Edit lessons only via the script.")
|
|
263
|
-
lines.append(f"> promote_threshold={data['promote_threshold']} distinct features | window_days={data['window_days']} | quarantine_threshold={data['quarantine_threshold']}")
|
|
264
|
-
lines.append("")
|
|
265
|
-
|
|
266
|
-
by_status = {"confirmed": [], "candidate": [], "quarantined": []}
|
|
267
|
-
for l in data["lessons"]:
|
|
268
|
-
by_status.get(l["status"], by_status["candidate"]).append(l)
|
|
269
|
-
|
|
270
|
-
def block(title, items, note):
|
|
271
|
-
out = [f"## {title}", ""]
|
|
272
|
-
if note:
|
|
273
|
-
out.append(note)
|
|
274
|
-
out.append("")
|
|
275
|
-
if not items:
|
|
276
|
-
out.append("_none_")
|
|
277
|
-
out.append("")
|
|
278
|
-
return out
|
|
279
|
-
for l in sorted(items, key=lambda x: x["id"]):
|
|
280
|
-
scope = f" | scope: `{l['scope']}`" if l.get("scope") else ""
|
|
281
|
-
conf = l.get("confidence", _confidence(l, data))
|
|
282
|
-
out.append(f"### {l['id']} - {l['text']}")
|
|
283
|
-
out.append(
|
|
284
|
-
f"- signal: `{l['signal']}` | recurrence: {l['recurrence']} feature(s){scope} | harmful: {l.get('harmful', 0)} | confidence: {conf}"
|
|
285
|
-
)
|
|
286
|
-
feats = ", ".join(l.get("features", [])) or "-"
|
|
287
|
-
out.append(f"- features: {feats}")
|
|
288
|
-
ctx = []
|
|
289
|
-
for k in ("project", "session", "workflow", "entity"):
|
|
290
|
-
if l.get(k):
|
|
291
|
-
ctx.append(f"{k}={l[k]}")
|
|
292
|
-
if ctx:
|
|
293
|
-
out.append(f"- context: {' '.join(ctx)}")
|
|
294
|
-
ev = l.get("evidence", [])
|
|
295
|
-
if ev:
|
|
296
|
-
out.append(f"- evidence: {ev[0]}" + (f" (+{len(ev) - 1} more)" if len(ev) > 1 else ""))
|
|
297
|
-
out.append(f"- last seen: {l.get('last_seen', '-')}")
|
|
298
|
-
out.append("")
|
|
299
|
-
return out
|
|
300
|
-
|
|
301
|
-
lines += block(
|
|
302
|
-
"Confirmed (load these at Specify/Design)",
|
|
303
|
-
by_status["confirmed"],
|
|
304
|
-
"Corroborated across multiple features. Safe to apply as guidance.",
|
|
305
|
-
)
|
|
306
|
-
lines += block(
|
|
307
|
-
"Candidates (under observation - do NOT load as guidance yet)",
|
|
308
|
-
by_status["candidate"],
|
|
309
|
-
"Seen once or not yet corroborated. Tracked, not trusted.",
|
|
310
|
-
)
|
|
311
|
-
lines += block(
|
|
312
|
-
"Quarantined (failed when applied - ignore)",
|
|
313
|
-
by_status["quarantined"],
|
|
314
|
-
"A confirmed lesson that recurred alongside failure. Kept for the maintainer to review.",
|
|
315
|
-
)
|
|
316
|
-
|
|
317
|
-
with open(_render_path(root), "w", encoding="utf-8") as f:
|
|
318
|
-
f.write("\n".join(lines).rstrip() + "\n")
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
# ----------------------------- commands -----------------------------
|
|
322
|
-
|
|
323
|
-
def cmd_init(root, args):
|
|
324
|
-
data = _load(root)
|
|
325
|
-
_save(root, data)
|
|
326
|
-
print(f"Initialized lessons store at {_store_path(root)} and {_render_path(root)}")
|
|
327
|
-
return 0
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
def cmd_add(root, args):
|
|
331
|
-
signal = args.signal
|
|
332
|
-
source = (args.source or "").strip()
|
|
333
|
-
text = (args.text or "").strip()
|
|
334
|
-
feature = (args.feature or "").strip()
|
|
335
|
-
|
|
336
|
-
# Grounding is enforced here, deterministically - not left to the prompt.
|
|
337
|
-
if signal not in SIGNALS:
|
|
338
|
-
print(f"ERROR: --signal must be one of {sorted(SIGNALS)}", file=sys.stderr)
|
|
339
|
-
return 2
|
|
340
|
-
if not feature:
|
|
341
|
-
print("ERROR: --feature is required (the feature the signal came from).", file=sys.stderr)
|
|
342
|
-
return 2
|
|
343
|
-
if not source:
|
|
344
|
-
print("ERROR: --source is required (file:line / AC id / mutant id / SPEC_DEVIATION ref).", file=sys.stderr)
|
|
345
|
-
print(" A lesson with no grounding in validation.md is an opinion, not a lesson. Refused.", file=sys.stderr)
|
|
346
|
-
return 2
|
|
347
|
-
if len(text) < 12:
|
|
348
|
-
print("ERROR: --text too short. State the actionable lesson in one terse sentence.", file=sys.stderr)
|
|
349
|
-
return 2
|
|
350
|
-
|
|
351
|
-
data = _load(root)
|
|
352
|
-
_auto_prune(data)
|
|
353
|
-
existing = _find(data, signal, text)
|
|
354
|
-
now = _now()
|
|
355
|
-
project = (getattr(args, "project", "") or "").strip()
|
|
356
|
-
session = (getattr(args, "session", "") or "").strip()
|
|
357
|
-
workflow = (getattr(args, "workflow", "") or "").strip()
|
|
358
|
-
entity = (getattr(args, "entity", "") or "").strip()
|
|
359
|
-
|
|
360
|
-
def _ctx(lesson):
|
|
361
|
-
if project:
|
|
362
|
-
lesson["project"] = project
|
|
363
|
-
if session:
|
|
364
|
-
lesson["session"] = session
|
|
365
|
-
if workflow:
|
|
366
|
-
lesson["workflow"] = workflow
|
|
367
|
-
if entity:
|
|
368
|
-
lesson["entity"] = entity
|
|
369
|
-
|
|
370
|
-
if existing:
|
|
371
|
-
if feature not in existing["features"]:
|
|
372
|
-
existing["features"].append(feature)
|
|
373
|
-
existing["recurrence"] = len(existing["features"])
|
|
374
|
-
existing["last_seen"] = now
|
|
375
|
-
_ctx(existing)
|
|
376
|
-
existing["confidence"] = _confidence(existing, data)
|
|
377
|
-
ev = source if not args.scope else f"{source} ({args.scope})"
|
|
378
|
-
if ev not in existing["evidence"]:
|
|
379
|
-
existing["evidence"].append(ev)
|
|
380
|
-
promoted = False
|
|
381
|
-
if existing["status"] == "candidate" and existing["recurrence"] >= data["promote_threshold"]:
|
|
382
|
-
existing["status"] = "confirmed"
|
|
383
|
-
promoted = True
|
|
384
|
-
_save(root, data)
|
|
385
|
-
_remember_best_effort(root, "%s [%s] %s" % (existing["id"], signal, text),
|
|
386
|
-
_lesson_tags(existing), project, session)
|
|
387
|
-
msg = f"UPDATED {existing['id']} (recurrence={existing['recurrence']}, status={existing['status']}, confidence={existing['confidence']})"
|
|
388
|
-
if promoted:
|
|
389
|
-
msg += " - PROMOTED to confirmed"
|
|
390
|
-
print(msg)
|
|
391
|
-
else:
|
|
392
|
-
lid = f"L-{data['next_id']:03d}"
|
|
393
|
-
data["next_id"] += 1
|
|
394
|
-
lesson = {
|
|
395
|
-
"id": lid,
|
|
396
|
-
"key": _key(signal, text),
|
|
397
|
-
"text": text,
|
|
398
|
-
"signal": signal,
|
|
399
|
-
"scope": (args.scope or "").strip(),
|
|
400
|
-
"status": "candidate",
|
|
401
|
-
"features": [feature],
|
|
402
|
-
"recurrence": 1,
|
|
403
|
-
"harmful": 0,
|
|
404
|
-
"evidence": [source if not args.scope else f"{source} ({args.scope})"],
|
|
405
|
-
"created": now,
|
|
406
|
-
"last_seen": now,
|
|
407
|
-
}
|
|
408
|
-
_ctx(lesson)
|
|
409
|
-
lesson["confidence"] = _confidence(lesson, data)
|
|
410
|
-
data["lessons"].append(lesson)
|
|
411
|
-
_save(root, data)
|
|
412
|
-
_remember_best_effort(root, "%s [%s] %s" % (lid, signal, text),
|
|
413
|
-
_lesson_tags(lesson), project, session)
|
|
414
|
-
print(f"ADDED {lid} (status=candidate, recurrence=1, confidence={lesson['confidence']})")
|
|
415
|
-
return 0
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
def cmd_penalize(root, args):
|
|
419
|
-
data = _load(root)
|
|
420
|
-
target = None
|
|
421
|
-
for l in data["lessons"]:
|
|
422
|
-
if l["id"].lower() == args.id.lower():
|
|
423
|
-
target = l
|
|
424
|
-
break
|
|
425
|
-
if not target:
|
|
426
|
-
print(f"ERROR: no lesson with id {args.id}", file=sys.stderr)
|
|
427
|
-
return 2
|
|
428
|
-
target["harmful"] = target.get("harmful", 0) + 1
|
|
429
|
-
target["last_seen"] = _now()
|
|
430
|
-
if target["harmful"] >= data["quarantine_threshold"]:
|
|
431
|
-
target["status"] = "quarantined"
|
|
432
|
-
_save(root, data)
|
|
433
|
-
print(f"PENALIZED {target['id']} (harmful={target['harmful']}, status={target['status']})")
|
|
434
|
-
return 0
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
def cmd_list(root, args):
|
|
438
|
-
data = _load(root)
|
|
439
|
-
if _auto_prune(data):
|
|
440
|
-
_save(root, data)
|
|
441
|
-
want = args.status
|
|
442
|
-
q = (args.query or "").lower().strip()
|
|
443
|
-
scope = (args.scope or "").lower().strip()
|
|
444
|
-
project = (getattr(args, "project", "") or "").lower().strip()
|
|
445
|
-
rows = []
|
|
446
|
-
for l in data["lessons"]:
|
|
447
|
-
if want != "all" and l["status"] != want:
|
|
448
|
-
continue
|
|
449
|
-
if q and q not in l["text"].lower():
|
|
450
|
-
continue
|
|
451
|
-
if scope and scope not in (l.get("scope", "").lower()):
|
|
452
|
-
continue
|
|
453
|
-
if project and project not in (l.get("project", "").lower()):
|
|
454
|
-
continue
|
|
455
|
-
rows.append(l)
|
|
456
|
-
if not rows:
|
|
457
|
-
flt = " ".join(f for f in (q, scope, project) if f)
|
|
458
|
-
print(f"(no {want} lessons" + (f" matching '{flt}'" if flt else "") + ")")
|
|
459
|
-
return 0
|
|
460
|
-
for l in sorted(rows, key=lambda x: x["id"]):
|
|
461
|
-
sc = f" [scope:{l['scope']}]" if l.get("scope") else ""
|
|
462
|
-
conf = l.get("confidence", _confidence(l, data))
|
|
463
|
-
print(f"{l['id']} ({l['status']}, x{l['recurrence']}, conf={conf}){sc}: {l['text']}")
|
|
464
|
-
return 0
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
def cmd_observe(root, args):
|
|
468
|
-
"""Ingest a JSON observation into the gitignored observations buffer.
|
|
469
|
-
|
|
470
|
-
Grounding is NOT enforced here; it is enforced when `add` consumes the
|
|
471
|
-
buffer. Observation fields: signal, text, source, feature, scope, project,
|
|
472
|
-
session, workflow, entity.
|
|
473
|
-
"""
|
|
474
|
-
raw = args.json if args.json else sys.stdin.read()
|
|
475
|
-
try:
|
|
476
|
-
item = json.loads(raw)
|
|
477
|
-
except (ValueError, TypeError) as exc:
|
|
478
|
-
print(f"ERROR: observation is not valid JSON: {exc}", file=sys.stderr)
|
|
479
|
-
return 2
|
|
480
|
-
if not isinstance(item, dict):
|
|
481
|
-
print("ERROR: observation must be a JSON object", file=sys.stderr)
|
|
482
|
-
return 2
|
|
483
|
-
item.setdefault("observed_at", _now())
|
|
484
|
-
_obs_append(root, item)
|
|
485
|
-
print(f"OBSERVED buffer=1 (total={len(_obs_load(root))})")
|
|
486
|
-
return 0
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
def cmd_export(root, args):
|
|
490
|
-
"""Export the lessons store as JSON (stdout or --out). Round-trips with import."""
|
|
491
|
-
data = _load(root)
|
|
492
|
-
text = json.dumps(data, indent=2, ensure_ascii=False) + "\n"
|
|
493
|
-
if args.out:
|
|
494
|
-
with open(args.out, "w", encoding="utf-8") as f:
|
|
495
|
-
f.write(text)
|
|
496
|
-
print(f"EXPORTED {len(data['lessons'])} lessons -> {args.out}")
|
|
497
|
-
else:
|
|
498
|
-
sys.stdout.write(text)
|
|
499
|
-
return 0
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
def cmd_import(root, args):
|
|
503
|
-
"""Import lessons from JSON (stdin or --in), merging by dedup key.
|
|
504
|
-
|
|
505
|
-
Re-emits massa-ai memory best-effort (type `pattern`, tag `memory:procedural`)
|
|
506
|
-
for each imported lesson so the file store and massa-ai memory stay consistent.
|
|
507
|
-
"""
|
|
508
|
-
raw = sys.stdin.read() if args.in_ is None else open(args.in_, "r", encoding="utf-8").read()
|
|
509
|
-
try:
|
|
510
|
-
incoming = json.loads(raw)
|
|
511
|
-
except (ValueError, TypeError) as exc:
|
|
512
|
-
print(f"ERROR: import payload is not valid JSON: {exc}", file=sys.stderr)
|
|
513
|
-
return 2
|
|
514
|
-
if not isinstance(incoming, dict) or not isinstance(incoming.get("lessons"), list):
|
|
515
|
-
print("ERROR: import payload must be a lessons store object with `lessons`", file=sys.stderr)
|
|
516
|
-
return 2
|
|
517
|
-
data = _load(root)
|
|
518
|
-
_auto_prune(data)
|
|
519
|
-
now = _now()
|
|
520
|
-
added = merged = 0
|
|
521
|
-
for l in incoming["lessons"]:
|
|
522
|
-
key = l.get("key") or _key(l.get("signal", ""), l.get("text", ""))
|
|
523
|
-
existing = next((x for x in data["lessons"] if x.get("key") == key), None)
|
|
524
|
-
if existing:
|
|
525
|
-
for f in l.get("features", []):
|
|
526
|
-
if f not in existing["features"]:
|
|
527
|
-
existing["features"].append(f)
|
|
528
|
-
existing["recurrence"] = len(existing["features"])
|
|
529
|
-
existing["last_seen"] = now
|
|
530
|
-
existing["confidence"] = _confidence(existing, data)
|
|
531
|
-
merged += 1
|
|
532
|
-
else:
|
|
533
|
-
lid = f"L-{data['next_id']:03d}"
|
|
534
|
-
data["next_id"] += 1
|
|
535
|
-
l.setdefault("id", lid)
|
|
536
|
-
l["id"] = lid
|
|
537
|
-
l["key"] = key
|
|
538
|
-
l.setdefault("status", "candidate")
|
|
539
|
-
l.setdefault("recurrence", len(l.get("features", [])) or 1)
|
|
540
|
-
l.setdefault("harmful", 0)
|
|
541
|
-
l.setdefault("created", now)
|
|
542
|
-
l["last_seen"] = now
|
|
543
|
-
l["confidence"] = _confidence(l, data)
|
|
544
|
-
data["lessons"].append(l)
|
|
545
|
-
added += 1
|
|
546
|
-
target = existing or l
|
|
547
|
-
_remember_best_effort(root, "%s [%s] %s" % (target.get("id"), target.get("signal", ""), target.get("text", "")),
|
|
548
|
-
_lesson_tags(target), target.get("project", ""), target.get("session", ""))
|
|
549
|
-
_save(root, data)
|
|
550
|
-
print(f"IMPORTED added={added} merged={merged} massa-ai=best-effort")
|
|
551
|
-
return 0
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
def cmd_prune(root, args):
|
|
555
|
-
data = _load(root)
|
|
556
|
-
dropped = _auto_prune(data)
|
|
557
|
-
_save(root, data)
|
|
558
|
-
print(f"Pruned {len(dropped)} stale candidate(s): {', '.join(dropped) if dropped else '-'}")
|
|
559
|
-
return 0
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
def cmd_status(root, args):
|
|
563
|
-
data = _load(root)
|
|
564
|
-
counts = {"confirmed": 0, "candidate": 0, "quarantined": 0}
|
|
565
|
-
for l in data["lessons"]:
|
|
566
|
-
counts[l["status"]] = counts.get(l["status"], 0) + 1
|
|
567
|
-
total = len(data["lessons"])
|
|
568
|
-
print(f"lessons: {total} total | confirmed={counts['confirmed']} candidate={counts['candidate']} quarantined={counts['quarantined']}")
|
|
569
|
-
return 0
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
def main(argv=None):
|
|
573
|
-
p = argparse.ArgumentParser(prog="lessons.py", description="Deterministic lessons bookkeeping for massa-ai spec-driven.")
|
|
574
|
-
p.add_argument("--root", default=".", help="Project root containing .specs/ (default: current dir)")
|
|
575
|
-
sub = p.add_subparsers(dest="cmd", required=True)
|
|
576
|
-
|
|
577
|
-
sp = sub.add_parser("init", help="Create empty store + rendered file")
|
|
578
|
-
sp.set_defaults(fn=cmd_init)
|
|
579
|
-
|
|
580
|
-
sp = sub.add_parser("add", help="Record a grounded lesson")
|
|
581
|
-
sp.add_argument("--feature", required=True)
|
|
582
|
-
sp.add_argument("--signal", required=True, choices=sorted(SIGNALS))
|
|
583
|
-
sp.add_argument("--source", required=True, help="file:line / AC id / mutant id / SPEC_DEVIATION ref")
|
|
584
|
-
sp.add_argument("--text", required=True, help="One terse, actionable sentence")
|
|
585
|
-
sp.add_argument("--scope", default="", help="Optional: path/layer/tag for retrieval filtering")
|
|
586
|
-
sp.add_argument("--project", default="", help="massa-ai projectId context")
|
|
587
|
-
sp.add_argument("--session", default="", help="massa-ai workflowSessionId context")
|
|
588
|
-
sp.add_argument("--workflow", default="", help="active massa-ai workflow type")
|
|
589
|
-
sp.add_argument("--entity", default="", help="active massa-ai entity")
|
|
590
|
-
sp.set_defaults(fn=cmd_add)
|
|
591
|
-
|
|
592
|
-
sp = sub.add_parser("penalize", help="Mark a confirmed lesson as failed-when-applied")
|
|
593
|
-
sp.add_argument("--id", required=True)
|
|
594
|
-
sp.set_defaults(fn=cmd_penalize)
|
|
595
|
-
|
|
596
|
-
sp = sub.add_parser("list", help="Print lessons for loading")
|
|
597
|
-
sp.add_argument("--status", default="confirmed", choices=["confirmed", "candidate", "quarantined", "all"])
|
|
598
|
-
sp.add_argument("--query", default="", help="Substring filter on lesson text")
|
|
599
|
-
sp.add_argument("--scope", default="", help="Substring filter on scope")
|
|
600
|
-
sp.add_argument("--project", default="", help="Substring filter on project")
|
|
601
|
-
sp.set_defaults(fn=cmd_list)
|
|
602
|
-
|
|
603
|
-
sp = sub.add_parser("observe", help="Ingest a JSON observation into the buffer")
|
|
604
|
-
sp.add_argument("--json", default="", help="Observation JSON (else read stdin)")
|
|
605
|
-
sp.set_defaults(fn=cmd_observe)
|
|
606
|
-
|
|
607
|
-
sp = sub.add_parser("export", help="Export lessons store as JSON")
|
|
608
|
-
sp.add_argument("--out", default="", help="Write to file (else stdout)")
|
|
609
|
-
sp.set_defaults(fn=cmd_export)
|
|
610
|
-
|
|
611
|
-
sp = sub.add_parser("import", help="Import lessons from JSON (merge by dedup key)")
|
|
612
|
-
sp.add_argument("--in", dest="in_", default=None, help="Read from file (else stdin)")
|
|
613
|
-
sp.set_defaults(fn=cmd_import)
|
|
614
|
-
|
|
615
|
-
sp = sub.add_parser("prune", help="Drop stale uncorroborated candidates")
|
|
616
|
-
sp.set_defaults(fn=cmd_prune)
|
|
617
|
-
|
|
618
|
-
sp = sub.add_parser("status", help="Print counts")
|
|
619
|
-
sp.set_defaults(fn=cmd_status)
|
|
620
|
-
|
|
621
|
-
sp = sub.add_parser("selftest", help="Run stdlib regressions (normalization)")
|
|
622
|
-
sp.set_defaults(fn=lambda root, args: _selftest_norm())
|
|
623
|
-
|
|
624
|
-
args = p.parse_args(argv)
|
|
625
|
-
root = os.path.abspath(args.root)
|
|
626
|
-
return args.fn(root, args)
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
if __name__ == "__main__":
|
|
630
|
-
raise SystemExit(main())
|