@chrono-meta/fh-gate 3.26.2 → 3.28.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/.claude-plugin/marketplace.json +4 -4
- package/AGENTS.md +2 -1
- package/CLAUDE.md +84 -1329
- package/README.ja.md +2 -4
- package/README.ko.md +2 -4
- package/README.md +19 -19
- package/README.zh.md +2 -4
- package/knowledge/shared/dialogue/memory_intent_recall.md +35 -0
- package/knowledge/shared/harness-core/builtin_capability_map.md +70 -0
- package/knowledge/shared/harness-core/claude_md_full_reference.md +1277 -0
- package/knowledge/shared/harness-core/fh_module_contract.md +97 -0
- package/knowledge/shared/harness-core/multi_model_sidecar_strategy.md +64 -0
- package/knowledge/shared/learnings/subagent_invocations_log.yaml +145 -0
- package/package.json +14 -1
- package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
- package/plugins/fh-commons/skills/ko-tech-writer/SKILL.md +84 -4
- package/plugins/fh-commons/skills/ko-tech-writer/fh-module.yaml +19 -0
- package/plugins/fh-commons/skills/ko-tech-writer/fixtures/known_negative.md +73 -1
- package/plugins/fh-commons/skills/ko-tech-writer/fixtures/known_positive.md +39 -1
- package/plugins/fh-commons/skills/ko-tech-writer/fixtures/known_unclosed.md +6 -0
- package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
- package/plugins/fh-meta/CHANGELOG.md +23 -0
- package/plugins/fh-meta/skills/context-doctor/SKILL.md +1 -1
- package/plugins/fh-meta/skills/frontier-digest/SKILL.md +14 -10
- package/plugins/fh-meta/skills/frontier-digest/SKILL_detail.md +17 -1
- package/plugins/fh-meta/skills/install-doctor/SKILL.md +1 -1
- package/plugins/fh-preprep/.claude-plugin/plugin.json +1 -1
- package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
- package/scripts/fh_env_delta_scan.sh +20 -4
- package/scripts/fh_module_check.py +686 -0
- package/scripts/fixtures/frontier_digest_recall.tsv +5 -0
- package/scripts/ko_tech_writer_calibrate.py +288 -15
- package/scripts/memory_gc_report.py +270 -0
- package/scripts/probe_live_eval.sh +19 -1
- package/scripts/probe_live_eval_lib.py +174 -5
- package/scripts/resident_cost.py +1 -1
- package/scripts/selfcheck.sh +34 -1
- package/scripts/session_checklist.py +66 -0
- package/scripts/session_close_check.sh +44 -0
- package/scripts/sim_isolated_run.sh +31 -0
- package/scripts/test_claude_md_size_lanes.sh +22 -7
- package/scripts/test_env_delta_worktree_lanes.sh +61 -0
- package/scripts/test_fh_module_check_lanes.sh +581 -0
- package/scripts/test_frontier_digest_recall.sh +26 -0
- package/scripts/test_frontier_digest_recall_negctl.sh +15 -0
- package/scripts/test_ko_tech_writer_lanes.sh +1 -1
- package/scripts/test_memory_gc_report_lanes.sh +210 -0
- package/scripts/test_probe_live_eval_lanes.sh +116 -0
- package/scripts/test_regression_guard_sibling_lanes.sh +193 -0
- package/scripts/test_resident_cost_lanes.sh +1 -1
- package/scripts/test_session_checklist_lanes.sh +29 -0
- package/scripts/test_sim_isolated_run_lanes.sh +51 -0
- package/scripts/test_utterance_checklist_hook_lanes.sh +175 -0
- package/scripts/utterance_checklist_hook.py +193 -0
- package/scripts/utterance_checklist_hook.sh +31 -0
- package/templates/regression_guard.sh +30 -12
|
@@ -0,0 +1,686 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""fh_module_check.py - FH module contract v0 checker (spec: knowledge/shared/harness-core/fh_module_contract.md).
|
|
3
|
+
|
|
4
|
+
Subcommands
|
|
5
|
+
check <manifest> [--repo DIR] [--installed DIR] install-time check
|
|
6
|
+
merge <manifest> <manifest>... strictest-wins merge of constraints
|
|
7
|
+
remove <id> --installed DIR removal plan (refused while a dependant exists)
|
|
8
|
+
export <manifest> --out DIR [--repo DIR] copy only what the module declares into DIR, then run its
|
|
9
|
+
calibration THERE: rc 0 = it runs standalone (no FH around it)
|
|
10
|
+
|
|
11
|
+
Exit codes: 0 OK . 1 BLOCK . 2 UNMEASURED (unreadable / tooling down / empty core list) .
|
|
12
|
+
3 OK-but-UNCALIBRATED (valid, no verdict entry points, calibration declared UNCALIBRATED; never a clean pass).
|
|
13
|
+
Fail closed: nothing unreadable, unknown or empty ever exits 0.
|
|
14
|
+
"""
|
|
15
|
+
import argparse, glob, hashlib, json, os, re, shutil, subprocess, sys
|
|
16
|
+
|
|
17
|
+
OK, BLOCK, UNMEASURED, UNCAL = 0, 1, 2, 3
|
|
18
|
+
|
|
19
|
+
# ---- closed enums (spec section 2) ------------------------------------------------------------
|
|
20
|
+
IRREVERSIBLE = ["none", "publish", "delete", "history"]
|
|
21
|
+
DATA_CLASS = ["public", "private", "company"] # permissive -> strictest (residency axis)
|
|
22
|
+
# permission axes of capability_composition_contract.md, permissive -> strictest
|
|
23
|
+
AXES = {
|
|
24
|
+
"approval": ["auto", "notify", "ask", "ask-per-item", "forbidden"],
|
|
25
|
+
"reversibility": ["reversible", "unknown", "irreversible"],
|
|
26
|
+
"residency": ["public", "operator-private", "company"],
|
|
27
|
+
"degrade": ["advisory", "fail-closed"],
|
|
28
|
+
}
|
|
29
|
+
HOOK_EVENTS = ["PreToolUse", "PermissionRequest", "PostToolUse", "SessionStart", "SessionEnd", "Stop",
|
|
30
|
+
"SubagentStop", "UserPromptSubmit", "PreCompact", "git-pre-commit", "git-pre-push"]
|
|
31
|
+
# Added hooks may only OBSERVE. v0 opens only events whose output cannot steer the session: a text scan of the
|
|
32
|
+
# hook body cannot prove a PreToolUse/PermissionRequest hook never emits a decision (decision.behavior, a key built
|
|
33
|
+
# from pieces) nor that a PostToolUse hook never injects additionalContext — so those are closed, not scanned.
|
|
34
|
+
GATING_EVENTS = {"PreToolUse", "PermissionRequest"}
|
|
35
|
+
OBSERVE_ONLY_EVENTS = {"SessionEnd"}
|
|
36
|
+
INTERPRETERS = {"bash", "sh", "python3", "node"}
|
|
37
|
+
CMD_FORBID = re.compile(r"[$`;&|<>\\\n\r(){}*?!\"'~]")
|
|
38
|
+
CMD_ARG = re.compile(r"^[A-Za-z0-9_./=:,@%+-]+$")
|
|
39
|
+
CORE_DISABLING = [r"hooksPath", r"core\.hooks", r"GIT_CONFIG_\w+", r"GIT_DIR[^\n]*hooks",
|
|
40
|
+
r"\.git/hooks", r"\bhooks?/(pre|post)-", r"settings[\w.-]*\.json",
|
|
41
|
+
r"permissionDecision", r"updatedInput", r"\bbehavior\b", r"additionalContext", r"\bchmod\b[^\n]*hook", r"\brm\b[^\n]*hook"]
|
|
42
|
+
IRREVERSIBLE_VERBS = [r"\bgit\b[^\n]*\bpush\b", r"\brm\b[^\n]*(\s-\w*r|--recursive)",
|
|
43
|
+
r"\bgit\b[^\n]*\bbranch\b[^\n]*\s-D", r"\bgit\b[^\n]*\breset\b[^\n]*--hard",
|
|
44
|
+
r"\bnpm\b[^\n]*\bpublish\b", r"\btwine\b[^\n]*\bupload\b",
|
|
45
|
+
r"\bgh\b[^\n]*\b(repo|release)\b", r"--visibility",
|
|
46
|
+
r"\bgit\b[^\n]*\b(filter-branch|filter-repo|rebase)\b",
|
|
47
|
+
r"\brm\b[^\n]*\s-\w*f", r"\b(rmtree|rmSync|rmdirSync|unlinkSync|os\.remove|os\.unlink)\b", r"\bgit\b[^\n]*\bclean\b[^\n]*-\w*f",
|
|
48
|
+
r"\bfind\b[^\n]*-delete", r"\bgit\b[^\n]*\btag\b[^\n]*\s-d", r"\bgh\b[^\n]*\bapi\b[^\n]*(DELETE|PATCH|PUT|POST)",
|
|
49
|
+
r"--amend", r"\breflog\b[^\n]*expire", r"\bupdate-ref\b[^\n]*-d"]
|
|
50
|
+
DATA_TO_RESIDENCY = {"public": "public", "private": "operator-private", "company": "company"}
|
|
51
|
+
# merge never lands below the core floor
|
|
52
|
+
# approval=ask is a FLOOR here, not a default: merge never emits less than ask, because the core
|
|
53
|
+
# irreversible gates are ask-level. reversibility=irreversible is seeded too (assume the worst).
|
|
54
|
+
CORE_FLOOR = {"approval": "ask", "degrade": "fail-closed", "reversibility": "irreversible"}
|
|
55
|
+
HOOK_ACTIONS = ["add"] # override / disable / reorder are known words, never allowed
|
|
56
|
+
HOOK_ACTIONS_KNOWN = ["add", "override", "disable", "reorder"]
|
|
57
|
+
HOOK_ORDER = ["append"] # prepend is a reorder
|
|
58
|
+
HOOK_ORDER_KNOWN = ["append", "prepend"]
|
|
59
|
+
# irreversible class -> (core gate name, repo-relative file that must exist)
|
|
60
|
+
CORE_GATES = {
|
|
61
|
+
"publish": {"pre-publish": "templates/PRE-PUBLISH-CHECKLIST.md",
|
|
62
|
+
"public-surface-audit": "templates/PRE-PUBLISH-CHECKLIST.md"},
|
|
63
|
+
"delete": {"destructive-op": "templates/predelete_check.sh"},
|
|
64
|
+
"history": {"destructive-op": "templates/predelete_check.sh"},
|
|
65
|
+
}
|
|
66
|
+
TOP_KEYS = {"id", "version", "provides", "adds_constraints", "touches_irreversible", "core_route",
|
|
67
|
+
"data_class", "requires", "calibration", "records", "files"}
|
|
68
|
+
PROVIDES_KEYS = {"skills", "agents", "hooks", "verdicts"}
|
|
69
|
+
HOOK_KEYS = {"event", "matcher", "command", "action", "order", "target"}
|
|
70
|
+
VERDICT_KEYS = {"entry", "command", "exit_codes"}
|
|
71
|
+
EXIT_KEYS = {"pass", "block", "unmeasured"}
|
|
72
|
+
REQ_KEYS = {"modules", "core_min"}
|
|
73
|
+
SEMVER = re.compile(r"^\d+\.\d+\.\d+$")
|
|
74
|
+
SLUG = re.compile(r"^[a-z][a-z0-9-]{0,62}$")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Verdict:
|
|
78
|
+
def __init__(self):
|
|
79
|
+
self.blocks, self.unmeasured, self.notes = [], [], []
|
|
80
|
+
self.uncal = False
|
|
81
|
+
def block(self, m): self.blocks.append(m)
|
|
82
|
+
def unm(self, m): self.unmeasured.append(m)
|
|
83
|
+
def code(self):
|
|
84
|
+
if self.blocks: return BLOCK
|
|
85
|
+
if self.unmeasured: return UNMEASURED
|
|
86
|
+
return UNCAL if self.uncal else OK
|
|
87
|
+
def report(self):
|
|
88
|
+
for m in self.blocks: print("BLOCK: " + m)
|
|
89
|
+
for m in self.unmeasured: print("UNMEASURED: " + m)
|
|
90
|
+
for m in self.notes: print("NOTE: " + m)
|
|
91
|
+
print({OK: "RESULT: OK", UNCAL: "RESULT: OK (UNCALIBRATED)", BLOCK: "RESULT: BLOCK", UNMEASURED: "RESULT: UNMEASURED"}[self.code()])
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def load_yaml(path):
|
|
95
|
+
"""Return (data, err). err set on any unreadable / unparsable / non-mapping input."""
|
|
96
|
+
try:
|
|
97
|
+
import yaml
|
|
98
|
+
except Exception as e:
|
|
99
|
+
return None, "PyYAML unavailable (%s)" % e
|
|
100
|
+
class Strict(yaml.SafeLoader):
|
|
101
|
+
pass
|
|
102
|
+
def cm(loader, node, deep=False):
|
|
103
|
+
seen = set()
|
|
104
|
+
for k, _ in node.value:
|
|
105
|
+
kk = loader.construct_object(k, deep=True)
|
|
106
|
+
if kk in seen:
|
|
107
|
+
raise ValueError("duplicate key %r" % (kk,))
|
|
108
|
+
seen.add(kk)
|
|
109
|
+
return yaml.SafeLoader.construct_mapping(loader, node, deep)
|
|
110
|
+
Strict.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, cm)
|
|
111
|
+
try:
|
|
112
|
+
with open(path, encoding="utf-8") as f:
|
|
113
|
+
data = yaml.load(f, Loader=Strict)
|
|
114
|
+
except UnicodeDecodeError as e:
|
|
115
|
+
return None, "cannot read %s (not UTF-8)" % path
|
|
116
|
+
except ValueError as e:
|
|
117
|
+
return None, "duplicate key in %s (%s)" % (path, e)
|
|
118
|
+
except Exception as e:
|
|
119
|
+
return None, "cannot read %s (%s)" % (path, type(e).__name__)
|
|
120
|
+
if not isinstance(data, dict) or not data:
|
|
121
|
+
return None, "%s is empty or not a mapping" % path
|
|
122
|
+
return data, None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def default_repo():
|
|
126
|
+
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def core_hooks(repo):
|
|
130
|
+
"""Core hook identifiers = script basenames wired in tracked settings snippets + git hook names."""
|
|
131
|
+
names = set()
|
|
132
|
+
for f in sorted(glob.glob(os.path.join(repo, "templates", "settings.*.snippet.json"))):
|
|
133
|
+
try:
|
|
134
|
+
d = json.load(open(f, encoding="utf-8"))
|
|
135
|
+
except Exception:
|
|
136
|
+
return None, "unreadable core hook config %s" % f
|
|
137
|
+
stack = [d.get("project_settings_json", {})]
|
|
138
|
+
while stack:
|
|
139
|
+
x = stack.pop()
|
|
140
|
+
if isinstance(x, dict):
|
|
141
|
+
if isinstance(x.get("command"), str):
|
|
142
|
+
for tok in re.findall(r"[\w./$\"{}-]+\.(?:sh|py)", x["command"]):
|
|
143
|
+
names.add(os.path.basename(tok.strip('"')))
|
|
144
|
+
stack.extend(x.values())
|
|
145
|
+
elif isinstance(x, list):
|
|
146
|
+
stack.extend(x)
|
|
147
|
+
for f in glob.glob(os.path.join(repo, "templates", ".git-hooks", "*")):
|
|
148
|
+
names.add(os.path.basename(f))
|
|
149
|
+
if not names:
|
|
150
|
+
return None, "core hook list is empty (a gate list that is empty passes everything)"
|
|
151
|
+
return names, None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def resolve_cmd(cmd, repo):
|
|
155
|
+
"""Command-shape allowlist: exactly `bash|sh|python3|node <repo-relative file> [simple args]`.
|
|
156
|
+
Returns (abs_path, kind, msg); kind in (None, 'block', 'unm')."""
|
|
157
|
+
if not isinstance(cmd, str) or not cmd.strip():
|
|
158
|
+
return None, "block", "command missing"
|
|
159
|
+
if CMD_FORBID.search(cmd):
|
|
160
|
+
return None, "block", "command contains a shell metacharacter"
|
|
161
|
+
if re.search(r"\b(eval|base64)\b", cmd, re.I):
|
|
162
|
+
return None, "block", "command mentions eval/base64"
|
|
163
|
+
t = cmd.split()
|
|
164
|
+
if t[0] not in INTERPRETERS or len(t) < 2:
|
|
165
|
+
return None, "block", "command must be `%s <repo-relative file> [args]`" % "|".join(sorted(INTERPRETERS))
|
|
166
|
+
if "-c" in t:
|
|
167
|
+
return None, "block", "command uses -c"
|
|
168
|
+
f = t[1]
|
|
169
|
+
if f.startswith("/") or f.startswith("-") or ".." in f.split("/") or not CMD_ARG.match(f):
|
|
170
|
+
return None, "block", "command file must be a plain repo-relative path (got %r)" % f
|
|
171
|
+
if not all(CMD_ARG.match(x) for x in t[2:]):
|
|
172
|
+
return None, "block", "command args must be simple tokens"
|
|
173
|
+
for x in t[2:]:
|
|
174
|
+
v = x.split("=", 1)[1] if x.startswith("-") and "=" in x else x
|
|
175
|
+
if v.startswith("/") or ".." in v.split("/"):
|
|
176
|
+
return None, "block", "command args must not name absolute paths or .. (got %r)" % x
|
|
177
|
+
full = os.path.join(repo, f)
|
|
178
|
+
rr = os.path.realpath(repo)
|
|
179
|
+
if os.path.commonpath([rr, os.path.realpath(full)]) != rr:
|
|
180
|
+
return None, "block", "command file resolves outside the repo"
|
|
181
|
+
if not os.path.isfile(full):
|
|
182
|
+
return None, "unm", "referenced file %s does not exist" % f
|
|
183
|
+
return full, None, ""
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def scan_text(text, where, vd, irrev):
|
|
187
|
+
text = re.sub(r"\\\r?\n", " ", text) # a line continuation (git \ ⏎ push) is one command
|
|
188
|
+
for pat in CORE_DISABLING:
|
|
189
|
+
if re.search(pat, text, re.I | re.M):
|
|
190
|
+
vd.block("%s matches core-disabling pattern /%s/ (added hooks may only observe)" % (where, pat))
|
|
191
|
+
if irrev:
|
|
192
|
+
for pat in IRREVERSIBLE_VERBS:
|
|
193
|
+
if re.search(pat, text, re.I | re.M):
|
|
194
|
+
vd.block("%s contains an irreversible verb /%s/ but touches_irreversible=none" % (where, pat))
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def check_command(cmd, where, vd, repo, irrev):
|
|
198
|
+
"""Shape allowlist, then open the one referenced file and run the same lexical scans (case-insensitive)."""
|
|
199
|
+
full, kind, msg = resolve_cmd(cmd, repo)
|
|
200
|
+
if kind == "block":
|
|
201
|
+
vd.block("%s: %s" % (where, msg)); return
|
|
202
|
+
if kind == "unm":
|
|
203
|
+
vd.unm("%s: %s" % (where, msg)); return
|
|
204
|
+
try:
|
|
205
|
+
raw = open(full, "rb").read()
|
|
206
|
+
except Exception as e:
|
|
207
|
+
vd.unm("%s: cannot read %s (%s)" % (where, full, type(e).__name__)); return
|
|
208
|
+
vd.notes.append("sha256 %s %s" % (os.path.relpath(full, repo), hashlib.sha256(raw).hexdigest()))
|
|
209
|
+
scan_text(cmd, where + ".command", vd, irrev)
|
|
210
|
+
scan_text(raw.decode("utf-8", "replace"), where + " file " + os.path.relpath(full, repo), vd, irrev)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def is_list_of_str(v):
|
|
214
|
+
return isinstance(v, list) and all(isinstance(i, str) and i for i in v)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def unknown_keys(d, allowed, where, vd):
|
|
218
|
+
for k in d:
|
|
219
|
+
if k not in allowed:
|
|
220
|
+
vd.block("unknown key '%s' in %s" % (k, where))
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def validate(m, vd, repo_core, repo):
|
|
224
|
+
if not isinstance(m, dict):
|
|
225
|
+
vd.block("manifest is not a mapping"); return
|
|
226
|
+
unknown_keys(m, TOP_KEYS, "manifest", vd)
|
|
227
|
+
for req in ("id", "version", "touches_irreversible", "data_class", "requires", "calibration"):
|
|
228
|
+
if req not in m:
|
|
229
|
+
vd.block("missing required field '%s'" % req)
|
|
230
|
+
if "id" in m and not (isinstance(m["id"], str) and SLUG.fullmatch(m["id"])):
|
|
231
|
+
vd.block("id must be a lowercase slug")
|
|
232
|
+
if "version" in m and not (isinstance(m["version"], str) and SEMVER.fullmatch(m["version"])):
|
|
233
|
+
vd.block("version must be a MAJOR.MINOR.PATCH string")
|
|
234
|
+
ti = m.get("touches_irreversible")
|
|
235
|
+
if "touches_irreversible" in m and ti not in IRREVERSIBLE:
|
|
236
|
+
vd.block("touches_irreversible=%r not in %s" % (ti, IRREVERSIBLE))
|
|
237
|
+
if "data_class" in m and m["data_class"] not in DATA_CLASS:
|
|
238
|
+
vd.block("data_class=%r not in %s" % (m["data_class"], DATA_CLASS))
|
|
239
|
+
|
|
240
|
+
# provides
|
|
241
|
+
pv = m.get("provides", {})
|
|
242
|
+
if pv is None: pv = {}
|
|
243
|
+
if not isinstance(pv, dict):
|
|
244
|
+
vd.block("provides must be a mapping"); pv = {}
|
|
245
|
+
unknown_keys(pv, PROVIDES_KEYS, "provides", vd)
|
|
246
|
+
for k in ("skills", "agents"):
|
|
247
|
+
if k in pv and not is_list_of_str(pv[k]):
|
|
248
|
+
vd.block("provides.%s must be a list of non-empty strings" % k)
|
|
249
|
+
elif k in pv and any(not SLUG.fullmatch(x) for x in pv[k]):
|
|
250
|
+
vd.block("provides.%s names must be plain slugs (no paths, no globs)" % k)
|
|
251
|
+
hooks = pv.get("hooks", [])
|
|
252
|
+
if hooks is None: hooks = []
|
|
253
|
+
if not isinstance(hooks, list):
|
|
254
|
+
vd.block("provides.hooks must be a list"); hooks = []
|
|
255
|
+
for i, h in enumerate(hooks):
|
|
256
|
+
w = "provides.hooks[%d]" % i
|
|
257
|
+
if not isinstance(h, dict):
|
|
258
|
+
vd.block(w + " is not a mapping"); continue
|
|
259
|
+
unknown_keys(h, HOOK_KEYS, w, vd)
|
|
260
|
+
if not isinstance(h.get("event"), str) or h.get("event") not in HOOK_EVENTS:
|
|
261
|
+
vd.block("%s.event=%r not in enum" % (w, h.get("event")))
|
|
262
|
+
if not (isinstance(h.get("command"), str) and h["command"]):
|
|
263
|
+
vd.block(w + ".command missing")
|
|
264
|
+
if "matcher" in h and not isinstance(h["matcher"], str):
|
|
265
|
+
vd.block("%s.matcher must be a string" % w)
|
|
266
|
+
act = h.get("action", "add")
|
|
267
|
+
if not isinstance(act, str) or act not in HOOK_ACTIONS_KNOWN:
|
|
268
|
+
vd.block("%s.action=%r not in enum" % (w, act))
|
|
269
|
+
elif act not in HOOK_ACTIONS:
|
|
270
|
+
vd.block("%s.action=%s: a module may add hooks, never %s a core hook" % (w, act, act))
|
|
271
|
+
order = h.get("order", "append")
|
|
272
|
+
if not isinstance(order, str) or order not in HOOK_ORDER_KNOWN:
|
|
273
|
+
vd.block("%s.order=%r not in enum" % (w, order))
|
|
274
|
+
elif order not in HOOK_ORDER:
|
|
275
|
+
vd.block("%s.order=%s reorders core hooks" % (w, order))
|
|
276
|
+
if "target" in h:
|
|
277
|
+
vd.block("%s.target: a hook that names a core hook as its target is an override" % w)
|
|
278
|
+
if repo_core is not None and isinstance(h.get("command"), str):
|
|
279
|
+
for b in repo_core:
|
|
280
|
+
if re.search(r"(?<![\w.-])" + re.escape(b) + r"(?![\w.-])", h["command"]):
|
|
281
|
+
vd.block("%s.command shadows core hook %s" % (w, b))
|
|
282
|
+
verdicts = pv.get("verdicts", [])
|
|
283
|
+
if verdicts is None: verdicts = []
|
|
284
|
+
if not isinstance(verdicts, list):
|
|
285
|
+
vd.block("provides.verdicts must be a list"); verdicts = []
|
|
286
|
+
for i, v in enumerate(verdicts):
|
|
287
|
+
w = "provides.verdicts[%d]" % i
|
|
288
|
+
if not isinstance(v, dict):
|
|
289
|
+
vd.block(w + " is not a mapping"); continue
|
|
290
|
+
unknown_keys(v, VERDICT_KEYS, w, vd)
|
|
291
|
+
if not (isinstance(v.get("entry"), str) and isinstance(v.get("command"), str)):
|
|
292
|
+
vd.block(w + " needs entry and command")
|
|
293
|
+
ec = v.get("exit_codes")
|
|
294
|
+
if not isinstance(ec, dict) or set(ec) != EXIT_KEYS or not all(isinstance(x, int) and not isinstance(x, bool) for x in ec.values()):
|
|
295
|
+
vd.block(w + ".exit_codes must map exactly pass/block/unmeasured to ints")
|
|
296
|
+
elif (ec["pass"], ec["block"], ec["unmeasured"]) != (0, 1, 2):
|
|
297
|
+
vd.block(w + ".exit_codes must be pass 0 · block 1 · unmeasured 2 (the caller reads 0 as proceed; any other mapping can turn a block into a pass)")
|
|
298
|
+
|
|
299
|
+
# A1/A2: command scans over hook + verdict command strings
|
|
300
|
+
cmds = [("provides.hooks[%d]" % i, h.get("command")) for i, h in enumerate(hooks) if isinstance(h, dict)]
|
|
301
|
+
cmds += [("provides.verdicts[%d]" % i, v.get("command")) for i, v in enumerate(verdicts) if isinstance(v, dict)]
|
|
302
|
+
for w, cmd in cmds:
|
|
303
|
+
check_command(cmd, w, vd, repo, ti == "none")
|
|
304
|
+
for i, h in enumerate(hooks):
|
|
305
|
+
ev = h.get("event") if isinstance(h, dict) else None
|
|
306
|
+
if isinstance(ev, str) and ev in HOOK_EVENTS and ev not in OBSERVE_ONLY_EVENTS:
|
|
307
|
+
why = "can return a permission decision" if ev in GATING_EVENTS else "can inject context or block"
|
|
308
|
+
vd.block("provides.hooks[%d]: event %s %s; closed to modules in v0 (open: %s)" % (i, ev, why, sorted(OBSERVE_ONLY_EVENTS)))
|
|
309
|
+
|
|
310
|
+
# constraints
|
|
311
|
+
for i, c in enumerate(m.get("adds_constraints", []) or []):
|
|
312
|
+
w = "adds_constraints[%d]" % i
|
|
313
|
+
if not isinstance(c, dict) or set(c) != {"axis", "value"}:
|
|
314
|
+
vd.block(w + " must be {axis, value}"); continue
|
|
315
|
+
if not isinstance(c["axis"], str) or c["axis"] not in AXES:
|
|
316
|
+
vd.block("%s.axis=%r not in %s" % (w, c["axis"], sorted(AXES)))
|
|
317
|
+
elif not isinstance(c["value"], str) or c["value"] not in AXES[c["axis"]]:
|
|
318
|
+
vd.block("%s.value=%r not in %s" % (w, c["value"], AXES[c["axis"]]))
|
|
319
|
+
elif c["axis"] in CORE_FLOOR and AXES[c["axis"]].index(c["value"]) < AXES[c["axis"]].index(CORE_FLOOR[c["axis"]]):
|
|
320
|
+
vd.block("%s: %s=%s is below the core floor %s (a module can only add constraints, never weaken them)" % (w, c["axis"], c["value"], CORE_FLOOR[c["axis"]]))
|
|
321
|
+
if "adds_constraints" in m and not isinstance(m["adds_constraints"], list):
|
|
322
|
+
vd.block("adds_constraints must be a list")
|
|
323
|
+
|
|
324
|
+
# irreversible routing
|
|
325
|
+
route = m.get("core_route")
|
|
326
|
+
if ti in ("publish", "delete", "history"):
|
|
327
|
+
gates = CORE_GATES[ti]
|
|
328
|
+
if route not in gates:
|
|
329
|
+
vd.block("touches_irreversible=%s requires core_route in %s (got %r)" % (ti, sorted(gates), route))
|
|
330
|
+
else:
|
|
331
|
+
p = os.path.join(repo, gates[route])
|
|
332
|
+
if not os.path.isfile(p):
|
|
333
|
+
vd.unm("core gate file %s missing: routing cannot be verified" % gates[route])
|
|
334
|
+
elif ti == "none" and "core_route" in m:
|
|
335
|
+
vd.block("core_route set while touches_irreversible=none")
|
|
336
|
+
|
|
337
|
+
# requires
|
|
338
|
+
rq = m.get("requires")
|
|
339
|
+
if "requires" in m:
|
|
340
|
+
if not isinstance(rq, dict):
|
|
341
|
+
vd.block("requires must be a mapping")
|
|
342
|
+
else:
|
|
343
|
+
unknown_keys(rq, REQ_KEYS, "requires", vd)
|
|
344
|
+
if not (isinstance(rq.get("core_min"), str) and SEMVER.fullmatch(rq["core_min"])):
|
|
345
|
+
vd.block("requires.core_min must be MAJOR.MINOR.PATCH")
|
|
346
|
+
mods = rq.get("modules", [])
|
|
347
|
+
if mods is None: mods = []
|
|
348
|
+
if not is_list_of_str(mods):
|
|
349
|
+
vd.block("requires.modules must be a list of module ids")
|
|
350
|
+
elif m.get("id") in mods:
|
|
351
|
+
vd.block("module requires itself")
|
|
352
|
+
|
|
353
|
+
# calibration
|
|
354
|
+
cal = m.get("calibration")
|
|
355
|
+
if "calibration" in m:
|
|
356
|
+
if cal == "UNCALIBRATED":
|
|
357
|
+
if verdicts:
|
|
358
|
+
vd.block("calibration=UNCALIBRATED but provides.verdicts is non-empty: a verdict needs a known-pair test")
|
|
359
|
+
else:
|
|
360
|
+
vd.uncal = True
|
|
361
|
+
vd.notes.append("calibration=UNCALIBRATED: no verdict from this module may be trusted as a number")
|
|
362
|
+
elif isinstance(cal, dict) and set(cal) == {"command"} and isinstance(cal["command"], str) and cal["command"].strip():
|
|
363
|
+
check_command(cal["command"], "calibration", vd, repo, False) # irreversible-verb scan skipped: test code
|
|
364
|
+
else:
|
|
365
|
+
vd.block("calibration must be {command: <known-pair test>} or the literal UNCALIBRATED")
|
|
366
|
+
|
|
367
|
+
rec = m.get("records")
|
|
368
|
+
if rec is not None and not is_list_of_str(rec):
|
|
369
|
+
vd.block("records must be a list of paths")
|
|
370
|
+
|
|
371
|
+
# files the module ships beyond its skill/agent folders and command files (export copies exactly these)
|
|
372
|
+
if "files" in m:
|
|
373
|
+
fl = m["files"]
|
|
374
|
+
if not is_list_of_str(fl):
|
|
375
|
+
vd.block("files must be a list of repo-relative paths")
|
|
376
|
+
else:
|
|
377
|
+
rr = os.path.realpath(repo)
|
|
378
|
+
for f in fl:
|
|
379
|
+
if f.startswith("/") or ".." in f.split("/") or not CMD_ARG.match(f):
|
|
380
|
+
vd.block("files: %r must be a plain repo-relative path" % f)
|
|
381
|
+
elif not os.path.exists(os.path.join(repo, f)):
|
|
382
|
+
vd.unm("files: %s does not exist" % f)
|
|
383
|
+
elif os.path.commonpath([rr, os.path.realpath(os.path.join(repo, f))]) != rr:
|
|
384
|
+
vd.block("files: %s resolves outside the repo" % f)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def load_installed(d):
|
|
388
|
+
mods, errs, dups = {}, [], []
|
|
389
|
+
if not os.path.isdir(d):
|
|
390
|
+
return mods, ["installed dir %s missing or not a directory" % d], dups
|
|
391
|
+
files = []
|
|
392
|
+
for pat in ("*/fh-module.yaml", "*/fh-module.yml", "*.yaml", "*.yml"):
|
|
393
|
+
files += glob.glob(os.path.join(d, pat))
|
|
394
|
+
for f in sorted(files):
|
|
395
|
+
data, err = load_yaml(f)
|
|
396
|
+
if err or not isinstance(data.get("id"), str):
|
|
397
|
+
errs.append("%s: %s" % (f, err or "no id")); continue
|
|
398
|
+
rq = data.get("requires")
|
|
399
|
+
if rq is not None and not (isinstance(rq, dict) and (rq.get("modules") is None or is_list_of_str(rq.get("modules")))):
|
|
400
|
+
errs.append("%s: malformed requires" % f); continue
|
|
401
|
+
if data["id"] in mods:
|
|
402
|
+
dups.append(data["id"])
|
|
403
|
+
mods[data["id"]] = data
|
|
404
|
+
if not files:
|
|
405
|
+
errs.append("no installed manifests found in %s (an empty registry cannot clear anything)" % d)
|
|
406
|
+
return mods, errs, dups
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def cmd_check(a):
|
|
410
|
+
vd = Verdict()
|
|
411
|
+
repo = os.path.abspath(a.repo) if a.repo else default_repo()
|
|
412
|
+
m, err = load_yaml(a.manifest)
|
|
413
|
+
if err:
|
|
414
|
+
(vd.block if err.startswith("duplicate key") else vd.unm)(err); vd.report(); return vd.code()
|
|
415
|
+
core, cerr = core_hooks(repo)
|
|
416
|
+
if cerr:
|
|
417
|
+
vd.unm(cerr)
|
|
418
|
+
validate(m, vd, core, repo)
|
|
419
|
+
if a.installed:
|
|
420
|
+
inst, errs, dups = load_installed(a.installed)
|
|
421
|
+
for e in errs: vd.unm("installed registry unreadable: " + e)
|
|
422
|
+
for d in dups: vd.block("duplicate installed module id %s" % d)
|
|
423
|
+
if m.get("id") in inst:
|
|
424
|
+
vd.block("module id %s already installed" % m.get("id"))
|
|
425
|
+
rq = m.get("requires")
|
|
426
|
+
if not errs and isinstance(rq, dict) and is_list_of_str(rq.get("modules", []) or []): # an unreadable registry proves nothing either way
|
|
427
|
+
for r in rq.get("modules", []) or []:
|
|
428
|
+
if r not in inst:
|
|
429
|
+
vd.block("required module %s is not installed" % r)
|
|
430
|
+
vd.report()
|
|
431
|
+
return vd.code()
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def cmd_merge(a):
|
|
435
|
+
vd = Verdict()
|
|
436
|
+
repo = os.path.abspath(a.repo) if a.repo else default_repo()
|
|
437
|
+
core, cerr = core_hooks(repo)
|
|
438
|
+
if cerr:
|
|
439
|
+
vd.unm(cerr)
|
|
440
|
+
# seed with the core-floor pseudo-manifest: nothing merges below it
|
|
441
|
+
merged = {ax: AXES[ax].index(v) for ax, v in CORE_FLOOR.items()}
|
|
442
|
+
srcs, dclass, irr = [], 0, 0
|
|
443
|
+
irr_rank = {k: i for i, k in enumerate(IRREVERSIBLE)}
|
|
444
|
+
for p in a.manifests:
|
|
445
|
+
m, err = load_yaml(p)
|
|
446
|
+
if err:
|
|
447
|
+
(vd.block if err.startswith("duplicate key") else vd.unm)(err); continue
|
|
448
|
+
sub = Verdict()
|
|
449
|
+
validate(m, sub, core, repo)
|
|
450
|
+
for x in sub.blocks: vd.block("%s: %s" % (p, x))
|
|
451
|
+
for x in sub.unmeasured: vd.unm("%s: %s" % (p, x))
|
|
452
|
+
vd.notes += sub.notes
|
|
453
|
+
if sub.uncal: vd.uncal = True
|
|
454
|
+
if sub.blocks or sub.unmeasured:
|
|
455
|
+
continue # an invalid member contributes nothing and the merge is refused
|
|
456
|
+
for c in m.get("adds_constraints", []) or []:
|
|
457
|
+
idx = AXES[c["axis"]].index(c["value"])
|
|
458
|
+
merged[c["axis"]] = max(merged.get(c["axis"], 0), idx) # permission axes: strictest wins
|
|
459
|
+
dc = DATA_CLASS.index(m["data_class"])
|
|
460
|
+
dclass = max(dclass, dc)
|
|
461
|
+
# residency floor derived from data_class
|
|
462
|
+
res = AXES["residency"].index(DATA_TO_RESIDENCY[m["data_class"]])
|
|
463
|
+
merged["residency"] = max(merged.get("residency", 0), res)
|
|
464
|
+
irr = max(irr, irr_rank[m["touches_irreversible"]]) # any irreversible member taints the set
|
|
465
|
+
srcs.append(p)
|
|
466
|
+
if not srcs and not vd.blocks and not vd.unmeasured:
|
|
467
|
+
vd.unm("nothing merged")
|
|
468
|
+
code = vd.code()
|
|
469
|
+
if code in (OK, UNCAL):
|
|
470
|
+
out = {ax: AXES[ax][i] for ax, i in sorted(merged.items())}
|
|
471
|
+
print(json.dumps({"verdict": "OK" if code == OK else "OK-UNCALIBRATED", "constraints": out,
|
|
472
|
+
"data_class": DATA_CLASS[dclass],
|
|
473
|
+
"touches_irreversible": "none" if irr == 0 else "irreversible-present",
|
|
474
|
+
"members": len(srcs)}, sort_keys=True))
|
|
475
|
+
else:
|
|
476
|
+
print(json.dumps({"verdict": "BLOCK" if code == BLOCK else "UNMEASURED"}))
|
|
477
|
+
vd.report()
|
|
478
|
+
return code
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def cmd_remove(a):
|
|
482
|
+
vd = Verdict()
|
|
483
|
+
inst, errs, dups = load_installed(a.installed)
|
|
484
|
+
for e in errs: vd.unm("installed registry unreadable: " + e)
|
|
485
|
+
for d in dups: vd.block("duplicate installed module id %s" % d)
|
|
486
|
+
if vd.unmeasured or vd.blocks:
|
|
487
|
+
vd.report(); return vd.code() # cannot see all dependants -> cannot clear removal
|
|
488
|
+
if a.id not in inst:
|
|
489
|
+
vd.block("module %s is not installed" % a.id); vd.report(); return vd.code()
|
|
490
|
+
deps = sorted(i for i, m in inst.items() if i != a.id and isinstance(m.get("requires"), dict)
|
|
491
|
+
and a.id in (m["requires"].get("modules") or []))
|
|
492
|
+
if deps:
|
|
493
|
+
vd.block("removal of %s refused: required by %s" % (a.id, ", ".join(deps)))
|
|
494
|
+
else:
|
|
495
|
+
recs = inst[a.id].get("records") or []
|
|
496
|
+
print("PLAN: unregister %s; ARCHIVE (not delete) %d record path(s): %s" % (a.id, len(recs), ", ".join(recs) or "-"))
|
|
497
|
+
vd.report()
|
|
498
|
+
return vd.code()
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
RESERVED_EXPORT = {"fh-module.yaml", "MODULE.md", ".fh-export"}
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def tracked(repo):
|
|
505
|
+
"""Repo-relative paths git tracks (None if not a git checkout). Export copies only these: an untracked or ignored
|
|
506
|
+
local file would make STANDALONE true on this machine and false for everyone else."""
|
|
507
|
+
try:
|
|
508
|
+
r = subprocess.run(["git", "-C", repo, "ls-files", "-z"], capture_output=True, timeout=60)
|
|
509
|
+
except Exception:
|
|
510
|
+
return None
|
|
511
|
+
if r.returncode != 0:
|
|
512
|
+
return None
|
|
513
|
+
return set(x for x in r.stdout.decode("utf-8", "replace").split("\0") if x)
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def module_paths(m, repo):
|
|
517
|
+
"""Everything export copies, repo-relative: skill and agent folders, every command file, the declared files.
|
|
518
|
+
-> (paths, problems). Names are literal slugs; a skill/agent that does not resolve to exactly one place is a problem."""
|
|
519
|
+
out, prob = [], []
|
|
520
|
+
pv = m.get("provides") or {}
|
|
521
|
+
for s_ in pv.get("skills") or []:
|
|
522
|
+
if not SLUG.fullmatch(str(s_)):
|
|
523
|
+
prob.append("skill name %r is not a plain slug" % s_); continue
|
|
524
|
+
hits = sorted(glob.glob(os.path.join(repo, "plugins", "*", "skills", glob.escape(s_))))
|
|
525
|
+
if len(hits) != 1: prob.append("skill %s resolves to %d folders" % (s_, len(hits)))
|
|
526
|
+
else: out.append(os.path.relpath(hits[0], repo))
|
|
527
|
+
for ag in pv.get("agents") or []:
|
|
528
|
+
if not SLUG.fullmatch(str(ag)):
|
|
529
|
+
prob.append("agent name %r is not a plain slug" % ag); continue
|
|
530
|
+
hits = sorted(glob.glob(os.path.join(repo, "plugins", "*", "agents", glob.escape(ag) + ".md")))
|
|
531
|
+
if len(hits) != 1: prob.append("agent %s resolves to %d files" % (ag, len(hits)))
|
|
532
|
+
else: out.append(os.path.relpath(hits[0], repo))
|
|
533
|
+
cmds = [h.get("command") for h in pv.get("hooks") or [] if isinstance(h, dict)]
|
|
534
|
+
cmds += [v.get("command") for v in pv.get("verdicts") or [] if isinstance(v, dict)]
|
|
535
|
+
cal = m.get("calibration")
|
|
536
|
+
if isinstance(cal, dict): cmds.append(cal.get("command"))
|
|
537
|
+
for c in cmds:
|
|
538
|
+
full, kind, msg = resolve_cmd(c, repo)
|
|
539
|
+
if kind: prob.append(msg)
|
|
540
|
+
else: out.append(os.path.relpath(full, repo))
|
|
541
|
+
out += list(m.get("files") or [])
|
|
542
|
+
return sorted(set(out)), prob
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def expand_tracked(rels, repo, trk):
|
|
546
|
+
"""Declared paths -> the tracked files under them. Symlinks anywhere are refused (a link can point outside the repo
|
|
547
|
+
or at an undeclared file and turn a non-standalone module into STANDALONE)."""
|
|
548
|
+
files, prob = [], []
|
|
549
|
+
rr = os.path.realpath(repo)
|
|
550
|
+
for rel in rels:
|
|
551
|
+
top = rel.split("/")[0]
|
|
552
|
+
if rel in (".", "") or ".git" in rel.split("/") or rel in RESERVED_EXPORT:
|
|
553
|
+
prob.append("export: %s cannot be exported" % rel); continue
|
|
554
|
+
src = os.path.join(repo, rel)
|
|
555
|
+
if os.path.islink(src):
|
|
556
|
+
prob.append("export: %s is a symlink" % rel); continue
|
|
557
|
+
if os.path.isdir(src):
|
|
558
|
+
for d, dirs, fs in os.walk(src):
|
|
559
|
+
for n in dirs + fs:
|
|
560
|
+
if os.path.islink(os.path.join(d, n)):
|
|
561
|
+
prob.append("export: %s is a symlink" % os.path.relpath(os.path.join(d, n), repo))
|
|
562
|
+
for n in fs:
|
|
563
|
+
r_ = os.path.relpath(os.path.join(d, n), repo)
|
|
564
|
+
if trk is None or r_ in trk: files.append(r_)
|
|
565
|
+
elif trk is None or rel in trk:
|
|
566
|
+
files.append(rel)
|
|
567
|
+
else:
|
|
568
|
+
prob.append("export: %s is not tracked by git (it would not exist for anyone else)" % rel)
|
|
569
|
+
if os.path.commonpath([rr, os.path.realpath(src)]) != rr:
|
|
570
|
+
prob.append("export: %s resolves outside the repo" % rel)
|
|
571
|
+
return sorted(set(files)), prob
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def trusted_path(repo):
|
|
575
|
+
"""PATH for the calibration run: the system dirs plus where the allowed interpreters live, never a dir inside the repo."""
|
|
576
|
+
rr = os.path.realpath(repo)
|
|
577
|
+
dirs = ["/usr/bin", "/bin", "/usr/sbin", "/sbin"]
|
|
578
|
+
for it in sorted(INTERPRETERS):
|
|
579
|
+
w = shutil.which(it)
|
|
580
|
+
if w:
|
|
581
|
+
d = os.path.dirname(os.path.realpath(w))
|
|
582
|
+
if os.path.commonpath([rr, d]) != rr and d not in dirs: dirs.append(d)
|
|
583
|
+
return ":".join(dirs)
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def cmd_export(a):
|
|
587
|
+
"""Copy only what the module declares (git-tracked, no symlinks) into an empty folder outside the repo, run its
|
|
588
|
+
calibration in a scratch copy of that folder. rc 0 = STANDALONE. The calibration's own rc 2 (or a missing
|
|
589
|
+
interpreter, or a signal) is UNMEASURED, not a dependency failure."""
|
|
590
|
+
import tempfile, signal
|
|
591
|
+
vd = Verdict()
|
|
592
|
+
repo = os.path.abspath(a.repo) if a.repo else default_repo()
|
|
593
|
+
m, err = load_yaml(a.manifest)
|
|
594
|
+
if err:
|
|
595
|
+
(vd.block if err.startswith("duplicate key") else vd.unm)(err); vd.report(); return vd.code()
|
|
596
|
+
core, cerr = core_hooks(repo)
|
|
597
|
+
if cerr: vd.unm(cerr)
|
|
598
|
+
validate(m, vd, core, repo)
|
|
599
|
+
if vd.blocks or vd.unmeasured:
|
|
600
|
+
print("export refused: the manifest does not pass check"); vd.report(); return vd.code()
|
|
601
|
+
cal = m.get("calibration")
|
|
602
|
+
if not isinstance(cal, dict):
|
|
603
|
+
vd.unm("calibration is UNCALIBRATED: a standalone run cannot be proven"); vd.report(); return vd.code()
|
|
604
|
+
out = os.path.realpath(os.path.abspath(a.out))
|
|
605
|
+
rr = os.path.realpath(repo)
|
|
606
|
+
if os.path.commonpath([rr, out]) == rr:
|
|
607
|
+
vd.unm("--out %s is inside the repo: the run could reach the repo it is meant to stand without" % out); vd.report(); return vd.code()
|
|
608
|
+
if os.path.exists(out) and (not os.path.isdir(out) or os.listdir(out)):
|
|
609
|
+
vd.unm("--out %s exists and is not an empty folder" % out); vd.report(); return vd.code()
|
|
610
|
+
rels, prob = module_paths(m, repo)
|
|
611
|
+
trk = tracked(repo)
|
|
612
|
+
files, prob2 = expand_tracked(rels, repo, trk)
|
|
613
|
+
for p_ in prob + prob2:
|
|
614
|
+
(vd.block if ("symlink" in p_ or "outside" in p_ or "cannot be exported" in p_ or "slug" in p_) else vd.unm)(p_)
|
|
615
|
+
if vd.blocks or vd.unmeasured:
|
|
616
|
+
vd.report(); return vd.code()
|
|
617
|
+
parent = os.path.dirname(out) or "."
|
|
618
|
+
os.makedirs(parent, exist_ok=True)
|
|
619
|
+
stage = tempfile.mkdtemp(prefix=".fh-export-", dir=parent)
|
|
620
|
+
scratch = tempfile.mkdtemp(prefix="fh-export-run-")
|
|
621
|
+
try:
|
|
622
|
+
for rel in files:
|
|
623
|
+
dst = os.path.join(stage, rel)
|
|
624
|
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
|
625
|
+
shutil.copy2(os.path.join(repo, rel), dst, follow_symlinks=False)
|
|
626
|
+
os.makedirs(os.path.join(stage, ".fh-export"))
|
|
627
|
+
shutil.copy2(a.manifest, os.path.join(stage, ".fh-export", "fh-module.yaml"))
|
|
628
|
+
with open(os.path.join(stage, ".fh-export", "MODULE.md"), "w", encoding="utf-8") as fh:
|
|
629
|
+
fh.write("# %s %s (standalone export)\n\nFiles: %d git-tracked files.\nRun its known-pair test from this folder: `%s`\n"
|
|
630
|
+
% (m.get("id"), m.get("version"), len(files), cal["command"]))
|
|
631
|
+
run_dir = os.path.join(scratch, "m")
|
|
632
|
+
shutil.copytree(stage, run_dir, symlinks=True)
|
|
633
|
+
home = os.path.join(scratch, "home"); tmp = os.path.join(scratch, "tmp")
|
|
634
|
+
os.makedirs(home); os.makedirs(tmp)
|
|
635
|
+
env = {"PATH": trusted_path(repo), "HOME": home, "TMPDIR": tmp, "LANG": os.environ.get("LANG", "C.UTF-8"),
|
|
636
|
+
"XDG_CONFIG_HOME": os.path.join(home, ".config"), "XDG_CACHE_HOME": os.path.join(home, ".cache")}
|
|
637
|
+
pr = subprocess.Popen(cal["command"].split(), cwd=run_dir, env=env, stdin=subprocess.DEVNULL,
|
|
638
|
+
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=True)
|
|
639
|
+
try:
|
|
640
|
+
outb, _ = pr.communicate(timeout=int(getattr(a, "timeout", 600) or 600))
|
|
641
|
+
except subprocess.TimeoutExpired:
|
|
642
|
+
try: os.killpg(pr.pid, signal.SIGKILL)
|
|
643
|
+
except Exception: pass
|
|
644
|
+
pr.communicate()
|
|
645
|
+
vd.unm("calibration timed out inside the export (process group killed)"); vd.report(); return vd.code()
|
|
646
|
+
rc = pr.returncode
|
|
647
|
+
tail = "\n".join(outb.decode("utf-8", "replace").strip().splitlines()[-8:])
|
|
648
|
+
print("calibration rc=%d inside a scratch copy of the export (%d files)" % (rc, len(files)))
|
|
649
|
+
if rc == 0:
|
|
650
|
+
os.rename(stage, out) if not os.path.exists(out) else (os.rmdir(out), os.rename(stage, out))
|
|
651
|
+
stage = None
|
|
652
|
+
print("STANDALONE: the module's own known-pair test passes with only its declared, git-tracked files -> %s" % out)
|
|
653
|
+
elif re.search(r"No such file|can't open file|cannot find module|Cannot find module|ModuleNotFoundError|missing .*\.(py|sh|js|md)", tail):
|
|
654
|
+
# a file the run reached for is not in the export — an undeclared dependency, whatever the rc (python exits 2 here)
|
|
655
|
+
vd.block("not standalone: the calibration reached for a file the export does not have:\n" + tail)
|
|
656
|
+
elif rc == 2 or rc in (126, 127) or rc < 0:
|
|
657
|
+
vd.unm("calibration could not measure inside the export (rc=%d: its own UNMEASURED, a missing interpreter or a signal):\n%s" % (rc, tail))
|
|
658
|
+
else:
|
|
659
|
+
vd.block("not standalone: calibration fails inside the export (an undeclared dependency?):\n" + tail)
|
|
660
|
+
finally:
|
|
661
|
+
if stage and os.path.isdir(stage): shutil.rmtree(stage, ignore_errors=True)
|
|
662
|
+
shutil.rmtree(scratch, ignore_errors=True)
|
|
663
|
+
vd.report()
|
|
664
|
+
return vd.code()
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def main(argv):
|
|
668
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
669
|
+
sub = ap.add_subparsers(dest="cmd")
|
|
670
|
+
c = sub.add_parser("check"); c.add_argument("manifest"); c.add_argument("--repo"); c.add_argument("--installed")
|
|
671
|
+
g = sub.add_parser("merge"); g.add_argument("manifests", nargs="+"); g.add_argument("--repo")
|
|
672
|
+
r = sub.add_parser("remove"); r.add_argument("id"); r.add_argument("--installed", required=True)
|
|
673
|
+
x = sub.add_parser("export"); x.add_argument("manifest"); x.add_argument("--out", required=True); x.add_argument("--repo"); x.add_argument("--timeout", type=int, default=600)
|
|
674
|
+
try:
|
|
675
|
+
a = ap.parse_args(argv)
|
|
676
|
+
except SystemExit:
|
|
677
|
+
return UNMEASURED
|
|
678
|
+
try:
|
|
679
|
+
return {"check": cmd_check, "merge": cmd_merge, "remove": cmd_remove, "export": cmd_export}[a.cmd](a)
|
|
680
|
+
except Exception as e: # fail closed: an internal error is never a pass
|
|
681
|
+
print("UNMEASURED: checker error %s: %s" % (type(e).__name__, e))
|
|
682
|
+
return UNMEASURED
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
if __name__ == "__main__":
|
|
686
|
+
sys.exit(main(sys.argv[1:]))
|