@solaqua/ghosts 0.4.32 → 0.4.34
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/README.md +13 -1
- package/experience/README.md +89 -0
- package/experience/skills/curate/SKILL.md +72 -0
- package/experience/skills/curate/references/candidate-contract.md +84 -0
- package/experience/skills/curate/templates/INDEX.md +11 -0
- package/experience/skills/curate/templates/knowledge.md +29 -0
- package/experience/skills/harvest/SKILL.md +60 -0
- package/experience/skills/harvest/assets/config.example.json +18 -0
- package/experience/skills/harvest/references/candidate-contract.md +84 -0
- package/experience/skills/harvest/references/sources.md +82 -0
- package/experience/skills/harvest/scripts/experience.py +544 -0
- package/experience/skills/harvest/templates/candidate.md +31 -0
- package/experience/skills/harvest/tests/EVALUATION.md +46 -0
- package/experience/skills/harvest/tests/test_experience.py +274 -0
- package/experience/skills/recall/SKILL.md +47 -0
- package/experience/skills/recall/library/INDEX.md +4 -0
- package/experience/skills/recall/library/engineering/INDEX.md +16 -0
- package/experience/skills/recall/library/engineering/entry-point-flow.md +30 -0
- package/experience/skills/recall/library/engineering/events-and-commands.md +29 -0
- package/experience/skills/recall/library/engineering/meaning-at-call-sites.md +64 -0
- package/experience/skills/recall/library/engineering/names-and-effects.md +39 -0
- package/experience/skills/recall/library/engineering/operational-signals.md +23 -0
- package/experience/skills/recall/library/engineering/public-contract.md +27 -0
- package/experience/skills/recall/library/engineering/purpose-docstrings.md +25 -0
- package/experience/skills/recall/library/engineering/responsibility-before-reuse.md +37 -0
- package/experience/skills/recall/library/engineering/single-source-state.md +52 -0
- package/experience/skills/recall/library/engineering/test-file-placement.md +42 -0
- package/experience/skills/recall/library/engineering/test-value.md +21 -0
- package/experience/skills/recall/library/engineering/visible-test-scenarios.md +67 -0
- package/experience/skills/recall/library/writing/INDEX.md +5 -0
- package/experience/skills/recall/library/writing/change-explanations.md +32 -0
- package/experience/skills/recall/library/writing/durable-guidance.md +28 -0
- package/experience/skills/recall/library/writing/reviewable-scope.md +40 -0
- package/package.json +2 -1
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Support engineering experience skills with local collection and validation."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import contextlib
|
|
6
|
+
import datetime as dt
|
|
7
|
+
import fcntl
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
import re
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
import tempfile
|
|
16
|
+
import time
|
|
17
|
+
from urllib.parse import unquote, urlsplit
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def main():
|
|
21
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
22
|
+
parser.add_argument("--config", default=None)
|
|
23
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
24
|
+
collect_parser = sub.add_parser("collect")
|
|
25
|
+
collect_parser.add_argument("--config", dest="sub_config", default=None)
|
|
26
|
+
collect_parser.add_argument("--days", type=int, choices=[7, 30])
|
|
27
|
+
collect_parser.add_argument("--start")
|
|
28
|
+
collect_parser.add_argument("--end")
|
|
29
|
+
collect_parser.add_argument("--sources", nargs="+")
|
|
30
|
+
collect_parser.add_argument("--dry-run", action="store_true")
|
|
31
|
+
save_parser = sub.add_parser("save")
|
|
32
|
+
save_parser.add_argument("--config", dest="sub_config", default=None)
|
|
33
|
+
save_parser.add_argument("--packet", required=True)
|
|
34
|
+
save_parser.add_argument("--decisions", required=True)
|
|
35
|
+
save_parser.add_argument("--dry-run", action="store_true")
|
|
36
|
+
validate_parser = sub.add_parser("validate")
|
|
37
|
+
validate_parser.add_argument("paths", nargs="+")
|
|
38
|
+
args = parser.parse_args()
|
|
39
|
+
try:
|
|
40
|
+
if args.command == "validate":
|
|
41
|
+
result = validate([Path(p).expanduser() for p in args.paths])
|
|
42
|
+
else:
|
|
43
|
+
config_path = args.config or getattr(args, "sub_config", None) or os.environ.get("EXPERIENCE_CONFIG")
|
|
44
|
+
if not config_path:
|
|
45
|
+
raise ValueError("Supply --config or EXPERIENCE_CONFIG")
|
|
46
|
+
config = json.loads(Path(config_path).expanduser().read_text())
|
|
47
|
+
if args.command == "collect":
|
|
48
|
+
end = timestamp(args.end) if args.end else dt.datetime.now(dt.timezone.utc)
|
|
49
|
+
start = timestamp(args.start) if args.start else end - dt.timedelta(
|
|
50
|
+
days=args.days or config.get("default_days", 7))
|
|
51
|
+
if start >= end:
|
|
52
|
+
raise ValueError("start must precede end (interval is [start, end))")
|
|
53
|
+
result = collect(config, start, end, args.sources)
|
|
54
|
+
else:
|
|
55
|
+
packet = json.loads(Path(args.packet).read_text())
|
|
56
|
+
decisions = json.loads(Path(args.decisions).read_text())
|
|
57
|
+
result = save(config, packet, decisions, args.dry_run)
|
|
58
|
+
print(json.dumps(scrub(result), ensure_ascii=False, indent=2))
|
|
59
|
+
return int(bool(result.get("errors")))
|
|
60
|
+
except (ValueError, OSError, KeyError, TypeError) as exc:
|
|
61
|
+
print(json.dumps({"errors": [redact(str(exc))]}))
|
|
62
|
+
return 1
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def collect(config, start, end, selected=None):
|
|
66
|
+
"""Collect changed source records without persisting source content."""
|
|
67
|
+
result = {"start": start.isoformat(), "end": end.isoformat(), "records": [],
|
|
68
|
+
"errors": [], "excluded": 0, "sources": {}}
|
|
69
|
+
checkpoint = load_state(notes_root(config) / ".harvest-state.json") if config.get("vault") else {}
|
|
70
|
+
for source in selected or config.get("sources", []):
|
|
71
|
+
count = 0
|
|
72
|
+
try:
|
|
73
|
+
if source == "github":
|
|
74
|
+
records = github_records(config, start, end, result)
|
|
75
|
+
elif source in {"codex", "claude", "agy"}:
|
|
76
|
+
records = session_records(config, source, start, end, result)
|
|
77
|
+
else:
|
|
78
|
+
raise ValueError(f"Unsupported source: {source}")
|
|
79
|
+
for record in records:
|
|
80
|
+
record = scrub(record)
|
|
81
|
+
record["revision"] = digest(record)
|
|
82
|
+
count += 1
|
|
83
|
+
if checkpoint.get(record["id"]) == record["revision"]:
|
|
84
|
+
result["excluded"] += 1
|
|
85
|
+
else:
|
|
86
|
+
result["records"].append(record)
|
|
87
|
+
except (OSError, ValueError, KeyError, TypeError) as exc:
|
|
88
|
+
result["errors"].append(f"{source}: {exc}")
|
|
89
|
+
result["sources"][source] = count
|
|
90
|
+
return result
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def session_records(config, source, start, end, report):
|
|
94
|
+
roots = config.get("session_roots", {}).get(source, [])
|
|
95
|
+
if not roots:
|
|
96
|
+
raise ValueError(f"No session_roots configured for {source}")
|
|
97
|
+
seen = set()
|
|
98
|
+
for raw_root in roots:
|
|
99
|
+
root = absolute(raw_root)
|
|
100
|
+
if not root.is_dir():
|
|
101
|
+
report["errors"].append(f"{source}: missing directory {root}")
|
|
102
|
+
continue
|
|
103
|
+
pattern = "brain/*/.system_generated/logs/transcript.jsonl" if source == "agy" else "**/*.jsonl"
|
|
104
|
+
files = sorted(root.glob(pattern))
|
|
105
|
+
if source == "agy":
|
|
106
|
+
supported = {p.parents[2].name for p in files}
|
|
107
|
+
for p in sorted((root / "conversations").glob("*")):
|
|
108
|
+
if p.is_file() and p.stem not in supported:
|
|
109
|
+
report["errors"].append(f"agy: unsupported conversation without transcript: {p.name}")
|
|
110
|
+
for path in files:
|
|
111
|
+
if path.resolve() in seen:
|
|
112
|
+
continue
|
|
113
|
+
seen.add(path.resolve())
|
|
114
|
+
try:
|
|
115
|
+
messages, session, repository = [], path.stem, None
|
|
116
|
+
recognized = False
|
|
117
|
+
for index, line in enumerate(path.read_text().splitlines(), 1):
|
|
118
|
+
row = json.loads(line)
|
|
119
|
+
if source == "codex":
|
|
120
|
+
recognized |= row.get("type") in {"session_meta", "response_item", "event_msg", "turn_context"}
|
|
121
|
+
elif source == "claude":
|
|
122
|
+
recognized |= row.get("type") in {"user", "assistant", "system", "file-history-snapshot"}
|
|
123
|
+
else:
|
|
124
|
+
recognized |= "step_index" in row and "created_at" in row
|
|
125
|
+
if source == "codex" and row.get("type") == "session_meta":
|
|
126
|
+
session = row["payload"].get("id", session)
|
|
127
|
+
session = row.get("sessionId", session)
|
|
128
|
+
when = row.get("timestamp") or row.get("created_at")
|
|
129
|
+
if not when or not start <= timestamp(when) < end:
|
|
130
|
+
continue
|
|
131
|
+
text, role = message_text(source, row)
|
|
132
|
+
if text.strip():
|
|
133
|
+
messages.append({"locator": f"line:{index}", "role": role,
|
|
134
|
+
"timestamp": when, "text": text})
|
|
135
|
+
if path.stat().st_size and not recognized:
|
|
136
|
+
raise ValueError("Unsupported session schema")
|
|
137
|
+
if messages:
|
|
138
|
+
rollout_id = re.search(r"([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})$", path.stem)
|
|
139
|
+
if source == "codex" and path.name.startswith("rollout-") and rollout_id:
|
|
140
|
+
session = rollout_id[1]
|
|
141
|
+
elif source == "agy":
|
|
142
|
+
session = path.parents[2].name
|
|
143
|
+
elif source == "claude" and "subagents" in path.parts:
|
|
144
|
+
session = f"{session}:{path.stem}"
|
|
145
|
+
yield {"id": f"{source}:{session}", "source": source,
|
|
146
|
+
"repository": repository, "source_refs": [path.resolve().as_uri()],
|
|
147
|
+
"messages": messages}
|
|
148
|
+
except (OSError, ValueError, KeyError, TypeError) as exc:
|
|
149
|
+
report["errors"].append(f"{source}: {path}: {exc}")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def message_text(source, row):
|
|
153
|
+
if source == "codex":
|
|
154
|
+
payload = row.get("payload", {})
|
|
155
|
+
if row.get("type") != "response_item":
|
|
156
|
+
return "", ""
|
|
157
|
+
kind, role = payload.get("type"), payload.get("role")
|
|
158
|
+
if kind == "function_call_output":
|
|
159
|
+
return str(payload.get("output", "")), "tool"
|
|
160
|
+
if kind != "message" or role not in {"user", "assistant"}:
|
|
161
|
+
return "", ""
|
|
162
|
+
return content_text(payload.get("content", [])), role
|
|
163
|
+
if source == "claude":
|
|
164
|
+
if row.get("type") not in {"user", "assistant"}:
|
|
165
|
+
return "", ""
|
|
166
|
+
return content_text(row.get("message", {}).get("content", [])), row["type"]
|
|
167
|
+
if row.get("source") not in {"USER_EXPLICIT", "MODEL"}:
|
|
168
|
+
return "", ""
|
|
169
|
+
return row.get("content", ""), row.get("source", "")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def content_text(content):
|
|
173
|
+
if isinstance(content, str):
|
|
174
|
+
return content
|
|
175
|
+
parts = []
|
|
176
|
+
for block in content:
|
|
177
|
+
if block.get("type") in {"text", "input_text", "output_text"}:
|
|
178
|
+
parts.append(block.get("text", ""))
|
|
179
|
+
elif block.get("type") == "tool_result":
|
|
180
|
+
parts.append(content_text(block.get("content", [])))
|
|
181
|
+
return "\n".join(parts)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def github_records(config, start, end, report):
|
|
185
|
+
login = config.get("github_login")
|
|
186
|
+
if not login:
|
|
187
|
+
raise ValueError("github_login is required; do not infer reviewer identity")
|
|
188
|
+
repos = set(config.get("github_repositories", []))
|
|
189
|
+
for org in config.get("github_organizations", []):
|
|
190
|
+
try:
|
|
191
|
+
repos.update(r["full_name"] for r in gh_pages(f"orgs/{org}/repos?per_page=100"))
|
|
192
|
+
except ValueError as exc:
|
|
193
|
+
report["errors"].append(f"github organization {org}: {exc}")
|
|
194
|
+
for repo in sorted(repos):
|
|
195
|
+
try:
|
|
196
|
+
if not re.fullmatch(r"[\w.-]+/[\w.-]+", repo):
|
|
197
|
+
raise ValueError("Invalid repository name")
|
|
198
|
+
since = start.astimezone(dt.timezone.utc).isoformat().replace("+00:00", "Z")
|
|
199
|
+
comments = gh_pages(f"repos/{repo}/pulls/comments?since={since}&per_page=100")
|
|
200
|
+
pulls = gh_pages(f"repos/{repo}/pulls?state=all&sort=updated&direction=desc&per_page=100")
|
|
201
|
+
relevant = {p["number"]: p for p in pulls if timestamp(p["updated_at"]) >= start}
|
|
202
|
+
for comment in comments:
|
|
203
|
+
if comment.get("user", {}).get("login", "").casefold() != login.casefold():
|
|
204
|
+
continue
|
|
205
|
+
number = int(comment["pull_request_url"].rsplit("/", 1)[1])
|
|
206
|
+
if number not in relevant:
|
|
207
|
+
relevant[number] = gh_one(f"repos/{repo}/pulls/{number}")
|
|
208
|
+
for number, pr in relevant.items():
|
|
209
|
+
if pr["user"]["login"].casefold() == login.casefold():
|
|
210
|
+
report["excluded"] += 1
|
|
211
|
+
continue
|
|
212
|
+
try:
|
|
213
|
+
reviews = gh_pages(f"repos/{repo}/pulls/{number}/reviews?per_page=100")
|
|
214
|
+
own = [c for c in comments if int(c["pull_request_url"].rsplit("/", 1)[1]) == number]
|
|
215
|
+
for kind, rows in [("comment", own), ("review", reviews)]:
|
|
216
|
+
for row in rows:
|
|
217
|
+
when = row.get("updated_at") or row.get("submitted_at") or row.get("created_at")
|
|
218
|
+
body = row.get("body") or ""
|
|
219
|
+
if (row.get("user", {}).get("login", "").casefold() != login.casefold()
|
|
220
|
+
or not when or not start <= timestamp(when) < end
|
|
221
|
+
or not body.strip()
|
|
222
|
+
or re.fullmatch(r"(?i)\s*(lgtm|approved?|thanks|👍)[.!\s]*", body)):
|
|
223
|
+
report["excluded"] += 1
|
|
224
|
+
continue
|
|
225
|
+
yield {"id": f"github:{repo}:{kind}:{row['id']}", "source": "github",
|
|
226
|
+
"repository": repo, "source_refs": [row["html_url"]],
|
|
227
|
+
"adoption": "unverified", "pr": number,
|
|
228
|
+
"head_sha": pr["head"]["sha"],
|
|
229
|
+
"messages": [{"role": "reviewer", "timestamp": when,
|
|
230
|
+
"text": body, "diff_hunk": row.get("diff_hunk"),
|
|
231
|
+
"commit_id": row.get("commit_id"),
|
|
232
|
+
"path": row.get("path")} ]}
|
|
233
|
+
except (ValueError, KeyError, TypeError) as exc:
|
|
234
|
+
report["errors"].append(f"github {repo} PR {number}: {exc}")
|
|
235
|
+
except (ValueError, KeyError, TypeError) as exc:
|
|
236
|
+
report["errors"].append(f"github {repo}: {exc}")
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def gh_pages(endpoint):
|
|
240
|
+
return [row for page in gh(endpoint, pages=True) for row in page]
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def gh_one(endpoint):
|
|
244
|
+
return gh(endpoint, pages=False)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def gh(endpoint, pages):
|
|
248
|
+
command = ["gh", "api", "--method", "GET", endpoint]
|
|
249
|
+
if pages:
|
|
250
|
+
command += ["--paginate", "--slurp"]
|
|
251
|
+
for attempt in range(3):
|
|
252
|
+
try:
|
|
253
|
+
result = subprocess.run(command, capture_output=True, text=True, timeout=30)
|
|
254
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
255
|
+
raise ValueError(f"GitHub request unavailable: {exc}") from exc
|
|
256
|
+
if result.returncode == 0:
|
|
257
|
+
return json.loads(result.stdout)
|
|
258
|
+
if not re.search(r"429|rate limit|HTTP 5\d\d", result.stderr, re.I) or attempt == 2:
|
|
259
|
+
raise ValueError(redact(result.stderr.strip()))
|
|
260
|
+
time.sleep(2 ** attempt)
|
|
261
|
+
raise ValueError("GitHub request failed")
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def save(config, packet, decisions, dry_run=False):
|
|
265
|
+
"""Save evaluated candidates and acknowledge only successful source revisions."""
|
|
266
|
+
root = notes_root(config)
|
|
267
|
+
records = {r["id"]: r for r in packet["records"]}
|
|
268
|
+
result = {"added": 0, "updated": 0, "skipped": 0, "errors": [], "source_ids": []}
|
|
269
|
+
if dry_run:
|
|
270
|
+
lock = contextlib.nullcontext()
|
|
271
|
+
else:
|
|
272
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
273
|
+
lock = file_lock(root / ".harvest.lock")
|
|
274
|
+
with lock:
|
|
275
|
+
state_path = root / ".harvest-state.json"
|
|
276
|
+
state = load_state(state_path)
|
|
277
|
+
for decision in decisions:
|
|
278
|
+
try:
|
|
279
|
+
record = records[decision["id"]]
|
|
280
|
+
if decision["revision"] != record["revision"]:
|
|
281
|
+
raise ValueError("Stale source revision")
|
|
282
|
+
if state.get(record["id"]) == record["revision"]:
|
|
283
|
+
result["skipped"] += 1
|
|
284
|
+
continue
|
|
285
|
+
for candidate in decision["candidates"]:
|
|
286
|
+
action = save_candidate(root, candidate, record, dry_run)
|
|
287
|
+
result[action] += 1
|
|
288
|
+
if not dry_run:
|
|
289
|
+
state[record["id"]] = record["revision"]
|
|
290
|
+
atomic_write(state_path, json.dumps(state, indent=2) + "\n")
|
|
291
|
+
result["source_ids"].append(record["id"])
|
|
292
|
+
except (ValueError, KeyError, TypeError, OSError) as exc:
|
|
293
|
+
result["errors"].append(f"{decision.get('id')}: {exc}")
|
|
294
|
+
return result
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def save_candidate(root, candidate, record, dry_run):
|
|
298
|
+
candidate = dict(candidate)
|
|
299
|
+
expected = candidate.pop("expected_sha256", None)
|
|
300
|
+
for reserved in {"id", "status", "captured_at", "updated_at", "source_refs", "source_ids"}:
|
|
301
|
+
candidate.pop(reserved, None)
|
|
302
|
+
body = candidate.pop("body")
|
|
303
|
+
now = dt.datetime.now(dt.timezone.utc).isoformat()
|
|
304
|
+
identity = [candidate.get("scope"), candidate.get("repository"), candidate.get("key")]
|
|
305
|
+
candidate.update(id="candidate-" + digest(identity)[:24], status="candidate",
|
|
306
|
+
captured_at=now, updated_at=now, source_refs=record["source_refs"],
|
|
307
|
+
source_ids=[record["id"]])
|
|
308
|
+
validate_candidate(candidate, body)
|
|
309
|
+
matches = list(root.glob(f"inbox/*/{candidate['id']}.md"))
|
|
310
|
+
target = root / "inbox" / now[:7] / f"{candidate['id']}.md"
|
|
311
|
+
action = "added"
|
|
312
|
+
if len(matches) > 1:
|
|
313
|
+
raise ValueError(f"Duplicate candidate ID: {candidate['id']}")
|
|
314
|
+
if matches:
|
|
315
|
+
target = matches[0]
|
|
316
|
+
original = target.read_text()
|
|
317
|
+
previous, previous_body = parse_note(original)
|
|
318
|
+
# A retry after a partial failure must not overwrite or duplicate a note.
|
|
319
|
+
same = (all(previous.get(k) == candidate.get(k) for k in
|
|
320
|
+
["key", "title", "summary", "type", "scope", "repository", "confidence"])
|
|
321
|
+
and previous_body.strip() == body.strip()
|
|
322
|
+
and record["id"] in previous.get("source_ids", [])
|
|
323
|
+
and set(record["source_refs"]).issubset(previous.get("source_refs", [])))
|
|
324
|
+
if same:
|
|
325
|
+
return "skipped"
|
|
326
|
+
if expected != hashlib.sha256(original.encode()).hexdigest():
|
|
327
|
+
raise ValueError(f"Read existing note and supply expected_sha256: {target}")
|
|
328
|
+
candidate = {**previous, **candidate, "captured_at": previous["captured_at"],
|
|
329
|
+
"status": previous["status"],
|
|
330
|
+
"source_ids": sorted(set(previous["source_ids"] + candidate["source_ids"])),
|
|
331
|
+
"source_refs": sorted(set(previous["source_refs"] + candidate["source_refs"]))}
|
|
332
|
+
action = "updated"
|
|
333
|
+
if not target.resolve().is_relative_to(root.resolve()):
|
|
334
|
+
raise ValueError("Candidate destination escapes the notes directory")
|
|
335
|
+
note = format_note(candidate, body)
|
|
336
|
+
if redact(note) != note:
|
|
337
|
+
raise ValueError("Potential sensitive information in candidate; remove it before saving")
|
|
338
|
+
if not dry_run:
|
|
339
|
+
atomic_write(target, note)
|
|
340
|
+
return action
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def validate(paths):
|
|
344
|
+
"""Check candidate contracts, navigation links and Markdown size."""
|
|
345
|
+
result = {"checked": 0, "errors": [], "warnings": []}
|
|
346
|
+
seen = {}
|
|
347
|
+
for path in paths:
|
|
348
|
+
if not path.exists():
|
|
349
|
+
result["errors"].append(f"Missing path: {path}")
|
|
350
|
+
continue
|
|
351
|
+
files = sorted(path.rglob("*.md")) if path.is_dir() else [path]
|
|
352
|
+
graph = {}
|
|
353
|
+
for file in files:
|
|
354
|
+
try:
|
|
355
|
+
text = file.read_text()
|
|
356
|
+
result["checked"] += 1
|
|
357
|
+
if len(text.splitlines()) > 100:
|
|
358
|
+
result["warnings"].append(f"{file}: exceeds 100 lines; consider a subindex or topic split")
|
|
359
|
+
if redact(text) != text:
|
|
360
|
+
raise ValueError("Potential sensitive information")
|
|
361
|
+
if text.startswith("---\n") and re.search(r"(?m)^id:", text.split("\n---\n", 1)[0]):
|
|
362
|
+
meta, body = parse_note(text)
|
|
363
|
+
if "id" in meta:
|
|
364
|
+
validate_candidate(meta, body)
|
|
365
|
+
if meta["id"] in seen:
|
|
366
|
+
raise ValueError(f"Duplicate ID also in {seen[meta['id']]}")
|
|
367
|
+
seen[meta["id"]] = str(file)
|
|
368
|
+
graph[file.resolve()] = []
|
|
369
|
+
for target in markdown_links(text):
|
|
370
|
+
target = target.strip("<>")
|
|
371
|
+
parsed = urlsplit(target)
|
|
372
|
+
if parsed.scheme or target.startswith("#"):
|
|
373
|
+
continue
|
|
374
|
+
if target.startswith("/"):
|
|
375
|
+
raise ValueError(f"Use relative navigation links: {target}")
|
|
376
|
+
destination = file.parent / unquote(parsed.path)
|
|
377
|
+
if not destination.is_file():
|
|
378
|
+
raise ValueError(f"Broken relative link: {target}")
|
|
379
|
+
graph[file.resolve()].append(destination.resolve())
|
|
380
|
+
except (OSError, ValueError, KeyError, TypeError) as exc:
|
|
381
|
+
result["errors"].append(f"{file}: {exc}")
|
|
382
|
+
entry = (path / "INDEX.md").resolve()
|
|
383
|
+
if path.is_dir() and entry in graph:
|
|
384
|
+
reached, pending = set(), [entry]
|
|
385
|
+
while pending:
|
|
386
|
+
current = pending.pop()
|
|
387
|
+
if current not in reached:
|
|
388
|
+
reached.add(current)
|
|
389
|
+
pending.extend(graph.get(current, []))
|
|
390
|
+
for orphan in sorted(set(graph) - reached):
|
|
391
|
+
result["warnings"].append(f"{orphan}: not reachable from root INDEX.md")
|
|
392
|
+
return result
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def markdown_links(text):
|
|
396
|
+
text = re.sub(r"(?ms)^(```|~~~).*?^\1[^\n]*$", "", text)
|
|
397
|
+
inline = re.findall(r"\[[^\]]*\]\(([^\s)]+)(?:\s+\"[^\"]*\")?\)", text)
|
|
398
|
+
references = re.findall(r"(?m)^\s{0,3}\[[^\]]+\]:\s+<?([^\s>]+)>?", text)
|
|
399
|
+
return inline + references
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def validate_candidate(meta, body):
|
|
403
|
+
required = ["id", "key", "title", "summary", "type", "scope", "repository", "status",
|
|
404
|
+
"confidence", "captured_at", "updated_at", "source_refs", "source_ids"]
|
|
405
|
+
if any(key not in meta for key in required):
|
|
406
|
+
raise ValueError("Missing candidate fields")
|
|
407
|
+
for key in ["key", "title", "summary"]:
|
|
408
|
+
if not isinstance(meta[key], str) or not meta[key].strip():
|
|
409
|
+
raise ValueError(f"Invalid {key}")
|
|
410
|
+
if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", meta["key"]):
|
|
411
|
+
raise ValueError("key must be a stable lowercase slug")
|
|
412
|
+
enums = {"type": {"principle", "decision", "pitfall", "playbook", "snippet"},
|
|
413
|
+
"scope": {"global", "repository"},
|
|
414
|
+
"status": {"candidate", "review", "proposed", "promoted", "skipped"},
|
|
415
|
+
"confidence": {"low", "medium", "high"}}
|
|
416
|
+
for key, values in enums.items():
|
|
417
|
+
if meta[key] not in values:
|
|
418
|
+
raise ValueError(f"Invalid {key}")
|
|
419
|
+
if meta["scope"] == "global" and meta["repository"] is not None:
|
|
420
|
+
raise ValueError("global scope requires repository: null")
|
|
421
|
+
if meta["scope"] == "repository" and not re.fullmatch(r"[\w.-]+/[\w.-]+", meta["repository"] or ""):
|
|
422
|
+
raise ValueError("repository scope requires owner/repo")
|
|
423
|
+
expected = "candidate-" + digest([meta["scope"], meta["repository"], meta["key"]])[:24]
|
|
424
|
+
if meta["id"] != expected:
|
|
425
|
+
raise ValueError("Candidate ID does not match scope/repository/key")
|
|
426
|
+
for key in ["captured_at", "updated_at"]:
|
|
427
|
+
timestamp(meta[key])
|
|
428
|
+
for key in ["source_refs", "source_ids"]:
|
|
429
|
+
if not isinstance(meta[key], list) or not meta[key] or not all(isinstance(v, str) and v for v in meta[key]):
|
|
430
|
+
raise ValueError(f"Invalid {key}")
|
|
431
|
+
if meta["status"] in {"proposed", "promoted"}:
|
|
432
|
+
targets = meta.get("targets")
|
|
433
|
+
if not isinstance(targets, list) or not targets:
|
|
434
|
+
raise ValueError("proposed/promoted requires targets")
|
|
435
|
+
for target in targets:
|
|
436
|
+
if not isinstance(target, str) or Path(target).is_absolute() or ".." in Path(target).parts:
|
|
437
|
+
raise ValueError("targets must stay inside the library")
|
|
438
|
+
for section in ["When", "Principle", "Why", "Limits", "Evidence", "Observation", "Inference"]:
|
|
439
|
+
match = re.search(rf"(?m)^## {section}\s*\n(.+?)(?=\n## |\Z)", body, re.S)
|
|
440
|
+
if not match or not match[1].strip():
|
|
441
|
+
raise ValueError(f"Missing or empty section: {section}")
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def parse_note(text):
|
|
445
|
+
if not text.startswith("---\n") or "\n---\n" not in text[4:]:
|
|
446
|
+
raise ValueError("Expected frontmatter with one JSON value per field")
|
|
447
|
+
header, body = text[4:].split("\n---\n", 1)
|
|
448
|
+
meta = {}
|
|
449
|
+
for line in header.splitlines():
|
|
450
|
+
key, value = line.split(":", 1)
|
|
451
|
+
if key in meta:
|
|
452
|
+
raise ValueError(f"Duplicate frontmatter field: {key}")
|
|
453
|
+
meta[key] = json.loads(value)
|
|
454
|
+
return meta, body
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def format_note(meta, body):
|
|
458
|
+
return "---\n" + "\n".join(f"{key}: {json.dumps(value, ensure_ascii=False)}"
|
|
459
|
+
for key, value in meta.items()) + "\n---\n" + body.strip() + "\n"
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def notes_root(config):
|
|
463
|
+
root = absolute(config["vault"])
|
|
464
|
+
relative = Path(config.get("notes_directory", "agent-notes"))
|
|
465
|
+
if relative.is_absolute() or ".." in relative.parts:
|
|
466
|
+
raise ValueError("notes_directory must stay inside the vault")
|
|
467
|
+
target = (root / relative).resolve()
|
|
468
|
+
if not target.is_relative_to(root.resolve()):
|
|
469
|
+
raise ValueError("notes_directory escapes the vault through a symlink")
|
|
470
|
+
return target
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def absolute(value):
|
|
474
|
+
path = Path(value).expanduser()
|
|
475
|
+
if not path.is_absolute():
|
|
476
|
+
raise ValueError(f"Expected an absolute or ~ path: {value}")
|
|
477
|
+
return path
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def timestamp(value):
|
|
481
|
+
parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
482
|
+
if parsed.tzinfo is None:
|
|
483
|
+
raise ValueError("Timestamps require an explicit timezone")
|
|
484
|
+
return parsed
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def digest(value):
|
|
488
|
+
return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def redact(text):
|
|
492
|
+
patterns = [r"(?i)\b(?:gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|sk-[A-Za-z0-9_-]{16,}|AKIA[A-Z0-9]{16})\b",
|
|
493
|
+
r"(?im)\b(?:api[_-]?key|access[_-]?token|password|secret)\s*[=:]\s*[\"']?[^\s\"',}]+",
|
|
494
|
+
r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH )?PRIVATE KEY-----",
|
|
495
|
+
r"(?i)Authorization[\"']?\s*[:=]\s*[\"']?(?:Bearer|Basic)\s+[^\s\"']+",
|
|
496
|
+
r"https?://[^\s/:]+:[^\s/@]+@[^\s]+"]
|
|
497
|
+
for pattern in patterns:
|
|
498
|
+
text = re.sub(pattern, "[REDACTED]", text)
|
|
499
|
+
return text
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def scrub(value):
|
|
503
|
+
if isinstance(value, str):
|
|
504
|
+
return redact(value)
|
|
505
|
+
if isinstance(value, list):
|
|
506
|
+
return [scrub(item) for item in value]
|
|
507
|
+
if isinstance(value, dict):
|
|
508
|
+
return {key: scrub(item) for key, item in value.items()}
|
|
509
|
+
return value
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def load_state(path):
|
|
513
|
+
return json.loads(path.read_text()) if path.exists() else {}
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
@contextlib.contextmanager
|
|
517
|
+
def file_lock(path):
|
|
518
|
+
with path.open("a") as handle:
|
|
519
|
+
os.chmod(path, 0o600)
|
|
520
|
+
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
521
|
+
try:
|
|
522
|
+
yield
|
|
523
|
+
finally:
|
|
524
|
+
fcntl.flock(handle, fcntl.LOCK_UN)
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def atomic_write(path, text):
|
|
528
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
529
|
+
if not path.resolve().is_relative_to(path.parent.resolve()):
|
|
530
|
+
raise ValueError(f"Refusing symlink outside destination: {path}")
|
|
531
|
+
fd, name = tempfile.mkstemp(dir=path.parent, prefix=".experience-")
|
|
532
|
+
try:
|
|
533
|
+
with os.fdopen(fd, "w") as handle:
|
|
534
|
+
handle.write(text)
|
|
535
|
+
handle.flush()
|
|
536
|
+
os.fsync(handle.fileno())
|
|
537
|
+
os.replace(name, path)
|
|
538
|
+
finally:
|
|
539
|
+
if os.path.exists(name):
|
|
540
|
+
os.unlink(name)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
if __name__ == "__main__":
|
|
544
|
+
sys.exit(main())
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: "candidate-<derived-by-save>"
|
|
3
|
+
key: "semantic-api-contracts"
|
|
4
|
+
title: "Semantic API contracts"
|
|
5
|
+
summary: "Check semantic guarantees when changing a boundary."
|
|
6
|
+
type: "principle"
|
|
7
|
+
scope: "global"
|
|
8
|
+
repository: null
|
|
9
|
+
status: "candidate"
|
|
10
|
+
confidence: "medium"
|
|
11
|
+
captured_at: "2026-11-06T00:00:00Z"
|
|
12
|
+
updated_at: "2026-11-06T00:00:00Z"
|
|
13
|
+
source_refs: ["<precise source reference>"]
|
|
14
|
+
source_ids: ["<collection record ID>"]
|
|
15
|
+
---
|
|
16
|
+
# Semantic API contracts
|
|
17
|
+
|
|
18
|
+
## When
|
|
19
|
+
Changing a system boundary.
|
|
20
|
+
## Principle
|
|
21
|
+
Check meaning and guarantees as well as data shape.
|
|
22
|
+
## Why
|
|
23
|
+
An unchanged shape can hide changed consistency or concurrency guarantees.
|
|
24
|
+
## Limits
|
|
25
|
+
Specify the observed constraints; do not claim universal applicability.
|
|
26
|
+
## Evidence
|
|
27
|
+
List at least two independent situations: task/PR, source ID, exact user passage/locator, rejected option and chosen option. Copies and handoffs count once.
|
|
28
|
+
## Observation
|
|
29
|
+
Describe the user choices directly observed across those situations.
|
|
30
|
+
## Inference
|
|
31
|
+
State the recurring decision criterion as an interpretation; include contrary choices and unresolved scope.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Validation
|
|
2
|
+
|
|
3
|
+
## Deterministic helper
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s experience/skills/harvest/tests -v
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
The suite covers source readers and time intervals, fork/subagent identities,
|
|
10
|
+
GitHub authorship and pagination, changed revisions, repeat execution, dry-run,
|
|
11
|
+
partial failures, edit conflicts, redaction, path safety and Markdown navigation.
|
|
12
|
+
GitHub responses are fixtures. These tests verify collection and persistence,
|
|
13
|
+
not the agent's extraction quality. Single-correction fixtures exercise storage;
|
|
14
|
+
they do not justify extracting a recurring judgment from one situation.
|
|
15
|
+
|
|
16
|
+
## Semantic checks
|
|
17
|
+
|
|
18
|
+
A targeted pass over real sessions and GitHub feedback produced four patterns:
|
|
19
|
+
return-value meaning, responsibility boundaries, test readability and test-file
|
|
20
|
+
placement. Original passages and independent contexts are retained in private
|
|
21
|
+
Obsidian candidates. One pattern includes a contrary choice limiting its scope.
|
|
22
|
+
|
|
23
|
+
The first search missed file-placement corrections because it started with a few
|
|
24
|
+
anticipated themes. Discovery now inventories direct corrections before grouping.
|
|
25
|
+
This addresses the known omission; it does not establish exhaustive coverage or
|
|
26
|
+
independent model evaluation.
|
|
27
|
+
|
|
28
|
+
Check these cases when evaluating future extraction runs:
|
|
29
|
+
|
|
30
|
+
- One isolated fix produces no recurring-pattern candidate.
|
|
31
|
+
- A correction copied to several agents still counts as one situation.
|
|
32
|
+
- Independent choices sharing a trade-off retain their original passages.
|
|
33
|
+
- Contrary choices qualify or defer an interpretation.
|
|
34
|
+
- Naming and placement corrections are compared before being dismissed as cosmetic.
|
|
35
|
+
|
|
36
|
+
For recall, a matching question should open only the relevant document; a near
|
|
37
|
+
miss should open none. Keep the original evidence in candidates and the reusable
|
|
38
|
+
criterion, conditions and examples in the library.
|
|
39
|
+
|
|
40
|
+
## Limits
|
|
41
|
+
|
|
42
|
+
Local sessions and selected live GitHub comments were read, but source access
|
|
43
|
+
alone does not prove complete collection. Opaque AGY conversations remain
|
|
44
|
+
unsupported; see [source limits](../references/sources.md).
|
|
45
|
+
Native skill discovery across all agents, remote PR creation and an unattended
|
|
46
|
+
scheduler run remain unverified. No scheduler was enabled by these checks.
|