@orion-qa/orion 3.4.0 → 3.5.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/agents/change-agent.md +1 -1
- package/.claude/agents/requirement-analyst.md +1 -1
- package/.claude/agents/test-reporter.md +1 -1
- package/.claude/skills/appium/templates/project-java/src/test/java/automation/pageObjects/BaseScreen.java +36 -2
- package/.claude/skills/appium/templates/project-java/src/test/java/automation/tests/unit/UtilsTest.java +10 -0
- package/.claude/skills/appium/templates/project-java/src/test/java/automation/utils/AutomationError.java +21 -0
- package/.claude/skills/automation-implementation/SKILL.md +2 -2
- package/.claude/skills/automation-implementation/references/patterns.md +14 -0
- package/.claude/skills/change-management/SKILL.md +1 -1
- package/.claude/skills/code-review/SKILL.md +1 -1
- package/.claude/skills/code-review/references/pattern-rules.md +4 -0
- package/.claude/skills/documentation/SKILL.md +2 -1
- package/.claude/skills/execution/SKILL.md +1 -0
- package/.claude/skills/failure-analysis/SKILL.md +1 -0
- package/.claude/skills/failure-analysis/references/bug-report-standard.md +27 -0
- package/.claude/skills/orion/SKILL.md +6 -3
- package/.claude/skills/orion/references/conversation.md +1 -1
- package/.claude/skills/orion/references/project-context-files.md +3 -1
- package/.claude/skills/orion/references/setup-card.md +3 -2
- package/.claude/skills/orion/scripts/browser_setup.mjs +4 -4
- package/.claude/skills/orion/scripts/case_check.mjs +69 -0
- package/.claude/skills/orion/scripts/cases_coverage.py +179 -0
- package/.claude/skills/orion/scripts/cases_export.py +3 -0
- package/.claude/skills/orion/scripts/cases_model.py +256 -0
- package/.claude/skills/orion/scripts/context_guard.mjs +172 -0
- package/.claude/skills/orion/scripts/graph.mjs +112 -22
- package/.claude/skills/orion/scripts/lib/scan.mjs +8 -2
- package/.claude/skills/orion/scripts/report_make.mjs +15 -11
- package/.claude/skills/orion/scripts/run_state.mjs +4 -0
- package/.claude/skills/orion/scripts/screen_map.mjs +392 -0
- package/.claude/skills/orion/scripts/suite_check.mjs +1 -1
- package/.claude/skills/playwright/templates/dotnet/PageObjects/BasePage.cs +46 -0
- package/.claude/skills/playwright/templates/dotnet/Tests/Unit/UtilsTests.cs +10 -0
- package/.claude/skills/playwright/templates/dotnet/Utils/AutomationError.cs +19 -1
- package/.claude/skills/playwright/templates/javascript/pageObjects/basePage.js +52 -0
- package/.claude/skills/playwright/templates/javascript/reporters/summaryReporter.js +18 -9
- package/.claude/skills/playwright/templates/javascript/tests/unit/basePage.test.js +51 -0
- package/.claude/skills/playwright/templates/javascript/utils/errors.js +9 -2
- package/.claude/skills/playwright/templates/project/pageObjects/basePage.ts +54 -1
- package/.claude/skills/playwright/templates/project/reporters/summaryReporter.ts +18 -9
- package/.claude/skills/playwright/templates/project/tests/unit/basePage.test.ts +52 -0
- package/.claude/skills/playwright/templates/project/utils/errors.ts +12 -2
- package/.claude/skills/playwright/templates/python/page_objects/base_page.py +43 -0
- package/.claude/skills/playwright/templates/python/tests/unit/test_fail_fast_helpers.py +57 -0
- package/.claude/skills/playwright/templates/python/utils/errors.py +7 -3
- package/.claude/skills/requests/templates/python-pytest/src/services/api_client.py +11 -1
- package/.claude/skills/requests/templates/python-pytest/tests/unit/test_api_client.py +16 -0
- package/.claude/skills/requirement-analysis/references/test-case-import.md +9 -1
- package/.claude/skills/requirement-analysis/scripts/tm.py +422 -2
- package/.claude/skills/rest-assured/templates/java-testng/src/test/java/automation/config/Flags.java +19 -0
- package/.claude/skills/rest-assured/templates/java-testng/src/test/java/automation/services/ApiSpec.java +10 -3
- package/.claude/skills/selenium/templates/csharp-nunit/PageObjects/BasePage.cs +89 -11
- package/.claude/skills/selenium/templates/csharp-nunit/Tests/Unit/UtilsTests.cs +10 -0
- package/.claude/skills/selenium/templates/csharp-nunit/Utils/AutomationError.cs +19 -1
- package/.claude/skills/selenium/templates/java-testng/src/test/java/automation/pageObjects/BasePage.java +65 -8
- package/.claude/skills/selenium/templates/java-testng/src/test/java/automation/tests/unit/UtilsTest.java +10 -0
- package/.claude/skills/selenium/templates/java-testng/src/test/java/automation/utils/AutomationError.java +21 -0
- package/.claude/skills/selenium/templates/python-pytest/page_objects/base_page.py +70 -11
- package/.claude/skills/selenium/templates/python-pytest/tests/unit/test_fail_fast_helpers.py +43 -0
- package/.claude/skills/selenium/templates/python-pytest/utils/errors.py +7 -3
- package/.claude/skills/test-design/SKILL.md +1 -0
- package/.claude/skills/test-design/references/test-case-standard.md +31 -0
- package/.claude/skills/test-reporting/SKILL.md +1 -0
- package/.claude/skills/ui-observation/SKILL.md +5 -2
- package/.claude-plugin/plugin.json +1 -1
- package/.cursor/rules/orion-quiet.mdc +13 -0
- package/AGENTS.md +1 -1
- package/README.md +2 -2
- package/bin/orion.mjs +5 -1
- package/hosts/gemini-extension/gemini-extension.json +1 -1
- package/package.json +2 -1
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Coverage of existing test cases against a story's acceptance criteria, and what to do about it: add, update or
|
|
3
|
+
keep. Read-only: it writes nothing anywhere except the report file you name.
|
|
4
|
+
|
|
5
|
+
python3 .claude/skills/orion/scripts/cases_coverage.py --cases cases.json --ac <ACs file> [--ui-map <map.md>]
|
|
6
|
+
[--json proposal.json]
|
|
7
|
+
|
|
8
|
+
--cases an orion-cases/1 record set (cases_model.py to-json, from TestRail, Zephyr, Xray, Azure, Jira, Excel, CSV)
|
|
9
|
+
--ac the story's criteria: a design.md / intent with an `| AC | Meaning |` table, or lines `AC-1: text`
|
|
10
|
+
--ui-map the explored page texts (optional): quoted expected texts found nowhere in the story or the map are flagged
|
|
11
|
+
|
|
12
|
+
Per case it decides, with the reason shown:
|
|
13
|
+
keep linked to a criterion and passes the test-case standard (case_check.mjs, the same rules as Orion's own cases)
|
|
14
|
+
update linked, but the standard finds problems (vague expected result, joined steps, no data …), or an expected
|
|
15
|
+
text the story and the app don't show (possibly outdated)
|
|
16
|
+
orphan covers no criterion (by link or by its words): listed, never deleted
|
|
17
|
+
duplicate says the same as another case for the same criterion: listed, never deleted
|
|
18
|
+
And per criterion with no case: add.
|
|
19
|
+
Exit: 0 every criterion covered and nothing to update · 1 something to add or update · 2 usage.
|
|
20
|
+
"""
|
|
21
|
+
import argparse
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import subprocess
|
|
26
|
+
import sys
|
|
27
|
+
import tempfile
|
|
28
|
+
|
|
29
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
30
|
+
STOP = set("a an the and or of to in on for with is are be by as at it its this that from into user users page "
|
|
31
|
+
"shows show shown can should must when then given".split())
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def words(text):
|
|
35
|
+
"""Content words of a text, lower-case."""
|
|
36
|
+
return {w for w in re.findall(r"[a-z0-9]+", (text or "").lower()) if w not in STOP and len(w) > 2}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def similarity(a, b):
|
|
40
|
+
"""Jaccard similarity of two word sets."""
|
|
41
|
+
return len(a & b) / len(a | b) if a and b else 0.0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def read_acs(path):
|
|
45
|
+
"""Criteria from an `| AC | Meaning |` table or `AC-1: text` lines → {"AC-1": "text"}."""
|
|
46
|
+
text = open(path, encoding="utf-8").read()
|
|
47
|
+
acs = {}
|
|
48
|
+
for m in re.finditer(r"^\|\s*(AC[-\s]?\d+)\s*\|\s*([^|\n]+?)\s*\|", text, re.M | re.I):
|
|
49
|
+
acs[re.sub(r"AC[-\s]?", "AC-", m.group(1).upper())] = m.group(2).strip()
|
|
50
|
+
if not acs:
|
|
51
|
+
for m in re.finditer(r"^\s*[-*]?\s*(AC[-\s]?\d+)\s*[:.)-]\s*(.+)$", text, re.M | re.I):
|
|
52
|
+
acs[re.sub(r"AC[-\s]?", "AC-", m.group(1).upper())] = m.group(2).strip()
|
|
53
|
+
return acs
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def standard_findings(cases):
|
|
57
|
+
"""case_check.mjs findings per case id, by writing the cases as a design table (one standard for all cases)."""
|
|
58
|
+
def cell(v):
|
|
59
|
+
return str(v or "").replace("|", "/").replace("\n", " ").strip()
|
|
60
|
+
rows = ["| ID | What it checks | Preconditions | Steps | Test data | Expected result | Postconditions |",
|
|
61
|
+
"|---|---|---|---|---|---|---|"]
|
|
62
|
+
alias = {}
|
|
63
|
+
for n, c in enumerate(cases, 1):
|
|
64
|
+
alias[f"TS-{n}"] = c["id"]
|
|
65
|
+
steps = " ".join(f"{i}. {s['action']}" for i, s in enumerate(c.get("steps", []), 1)) if len(c.get("steps", [])) > 1 \
|
|
66
|
+
else (c["steps"][0]["action"] if c.get("steps") else "")
|
|
67
|
+
expected = c.get("expected") or "; ".join(s["expected"] for s in c.get("steps", []) if s.get("expected"))
|
|
68
|
+
rows.append("| " + " | ".join(cell(x) for x in (f"TS-{n}",
|
|
69
|
+
c.get("title"), c.get("preconditions"), steps, c.get("data"),
|
|
70
|
+
expected, c.get("postconditions"))) + " |")
|
|
71
|
+
with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding="utf-8") as f:
|
|
72
|
+
f.write("\n".join(rows) + "\n")
|
|
73
|
+
try:
|
|
74
|
+
out = subprocess.run(["node", os.path.join(HERE, "case_check.mjs"), f.name], capture_output=True, text=True).stdout
|
|
75
|
+
finally:
|
|
76
|
+
os.unlink(f.name)
|
|
77
|
+
found = {}
|
|
78
|
+
for line in out.splitlines():
|
|
79
|
+
m = re.match(r"\s*-\s*(TS-\d+):\s*(.+)$", line)
|
|
80
|
+
if m and m.group(1) in alias:
|
|
81
|
+
found.setdefault(alias[m.group(1)], []).append(m.group(2).strip())
|
|
82
|
+
# A missing column is the source's format, not a case's fault: report it once, per field, below.
|
|
83
|
+
return found, [l.strip()[2:] for l in out.splitlines() if l.strip().startswith("- table:")]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def analyse(doc, acs, ui_text=""):
|
|
87
|
+
"""The proposal: per criterion, per case, and the summary counts."""
|
|
88
|
+
cases = doc.get("cases", [])
|
|
89
|
+
findings, table_notes = standard_findings(cases)
|
|
90
|
+
story_words = {k: words(v) for k, v in acs.items()}
|
|
91
|
+
known_text = " ".join(acs.values()) + " " + ui_text
|
|
92
|
+
rows, coverage = [], {k: [] for k in acs}
|
|
93
|
+
for c in cases:
|
|
94
|
+
linked = [a for a in c.get("ac", []) if a in acs]
|
|
95
|
+
how = "linked"
|
|
96
|
+
if not linked:
|
|
97
|
+
cw = words(c.get("title", "") + " " + " ".join(s["action"] for s in c.get("steps", [])))
|
|
98
|
+
best = max(acs, key=lambda k: similarity(cw, story_words[k]), default=None)
|
|
99
|
+
if best and similarity(cw, story_words[best]) >= 0.2:
|
|
100
|
+
linked, how = [best], "by its words"
|
|
101
|
+
for a in linked:
|
|
102
|
+
coverage[a].append(c["id"])
|
|
103
|
+
reasons = list(findings.get(c["id"], []))
|
|
104
|
+
if ui_text:
|
|
105
|
+
for q in re.findall(r"[\"“]([^\"”]{4,})[\"”]", c.get("expected", "") + " " + " ".join(s.get("expected", "") for s in c.get("steps", []))):
|
|
106
|
+
if q.lower() not in known_text.lower():
|
|
107
|
+
reasons.append(f'expects "{q}", which neither the story nor the app shows (possibly outdated)')
|
|
108
|
+
action = "orphan" if not linked else ("update" if reasons else "keep")
|
|
109
|
+
rows.append({"id": c["id"], "key": c.get("key", ""), "title": c.get("title", ""), "ac": linked, "linked": how,
|
|
110
|
+
"action": action, "reasons": reasons if linked else ["covers no criterion of this story"]})
|
|
111
|
+
# Duplicates: same criterion, nearly the same title and steps; the later one is flagged.
|
|
112
|
+
for a, ids in coverage.items():
|
|
113
|
+
for i, x in enumerate(ids):
|
|
114
|
+
for y in ids[i + 1:]:
|
|
115
|
+
cx = next(c for c in cases if c["id"] == x)
|
|
116
|
+
cy = next(c for c in cases if c["id"] == y)
|
|
117
|
+
wx = words(cx.get("title", "") + " " + " ".join(s["action"] for s in cx.get("steps", [])))
|
|
118
|
+
wy = words(cy.get("title", "") + " " + " ".join(s["action"] for s in cy.get("steps", [])))
|
|
119
|
+
rx = next(r for r in rows if r["id"] == x)
|
|
120
|
+
ry = next(r for r in rows if r["id"] == y)
|
|
121
|
+
if similarity(wx, wy) >= 0.8 and "duplicate" not in (rx["action"], ry["action"]):
|
|
122
|
+
# Keep the one with fewer problems; the other is the duplicate (with its own problems kept in view).
|
|
123
|
+
keep, dup = (rx, ry) if len(rx["reasons"]) <= len(ry["reasons"]) else (ry, rx)
|
|
124
|
+
dup["action"] = "duplicate"
|
|
125
|
+
dup["reasons"] = [f"says the same as {keep['id']} for {a}"] + dup["reasons"]
|
|
126
|
+
add = [{"ac": a, "meaning": acs[a]} for a, ids in coverage.items() if not ids]
|
|
127
|
+
count = {k: sum(1 for r in rows if r["action"] == k) for k in ("keep", "update", "orphan", "duplicate")}
|
|
128
|
+
return {"format": "orion-coverage/1", "criteria": {a: ids for a, ids in coverage.items()}, "cases": rows,
|
|
129
|
+
"add": add, "summary": {"add": len(add), **count}, "source_notes": table_notes}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def render(p):
|
|
133
|
+
"""The chat/report view: one summary line, the criteria table, then the cases to change."""
|
|
134
|
+
s = p["summary"]
|
|
135
|
+
out = [f"**Add {s['add']} · Update {s['update']} · Keep {s['keep']}**"
|
|
136
|
+
+ (f" · {s['duplicate']} duplicate" + ("s" if s['duplicate'] != 1 else "") if s["duplicate"] else "")
|
|
137
|
+
+ (f" · {s['orphan']} not linked to this story" if s["orphan"] else "") + " (nothing is deleted)", "",
|
|
138
|
+
"| Criterion | Covered by |", "|---|---|"]
|
|
139
|
+
for a, ids in p["criteria"].items():
|
|
140
|
+
out.append(f"| {a} | {', '.join(ids) if ids else '**none: add a case**'} |")
|
|
141
|
+
change = [r for r in p["cases"] if r["action"] != "keep"]
|
|
142
|
+
if change:
|
|
143
|
+
out += ["", "| Case | Do | Why |", "|---|---|---|"]
|
|
144
|
+
for r in change:
|
|
145
|
+
out.append(f"| {r['id']} {r['title'][:50]} | {r['action']} | {'; '.join(r['reasons'])[:160]} |")
|
|
146
|
+
if p["source_notes"]:
|
|
147
|
+
out += ["", "Fields this source doesn't have: " + "; ".join(n.replace("table: no column for ", "") for n in p["source_notes"])]
|
|
148
|
+
return "\n".join(out)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def main(argv=None):
|
|
152
|
+
"""Command line."""
|
|
153
|
+
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
|
154
|
+
ap.add_argument("--cases", required=True)
|
|
155
|
+
ap.add_argument("--ac", required=True)
|
|
156
|
+
ap.add_argument("--ui-map")
|
|
157
|
+
ap.add_argument("--json")
|
|
158
|
+
a = ap.parse_args(argv)
|
|
159
|
+
for f in (a.cases, a.ac, a.ui_map):
|
|
160
|
+
if f and not os.path.isfile(f):
|
|
161
|
+
print(f"cases_coverage: no such file: {f}")
|
|
162
|
+
return 2
|
|
163
|
+
acs = read_acs(a.ac)
|
|
164
|
+
if not acs:
|
|
165
|
+
print("cases_coverage: no acceptance criteria found (an `| AC | Meaning |` table or `AC-1: text` lines)")
|
|
166
|
+
return 2
|
|
167
|
+
doc = json.load(open(a.cases, encoding="utf-8"))
|
|
168
|
+
ui = open(a.ui_map, encoding="utf-8").read() if a.ui_map else ""
|
|
169
|
+
p = analyse(doc, acs, ui)
|
|
170
|
+
if a.json:
|
|
171
|
+
with open(a.json, "w", encoding="utf-8") as f:
|
|
172
|
+
json.dump(p, f, indent=1, ensure_ascii=False)
|
|
173
|
+
print(render(p))
|
|
174
|
+
s = p["summary"]
|
|
175
|
+
return 1 if s["add"] or s["update"] else 0
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
if __name__ == "__main__":
|
|
179
|
+
sys.exit(main())
|
|
@@ -715,6 +715,9 @@ def main():
|
|
|
715
715
|
return 3
|
|
716
716
|
raise
|
|
717
717
|
stories = sorted({c["Story"] for c in cases}, key=tc_sort)
|
|
718
|
+
untitled = [k for k in stories if not titles.get(k)]
|
|
719
|
+
if untitled:
|
|
720
|
+
print(f"note: no story title for {', '.join(untitled)}: pass --titles \"{untitled[0]}=<story title>\" so the summary's Title column isn't empty")
|
|
718
721
|
print(f"{', '.join(files)}: {len(cases)} test cases, {len(stories)} stor{'y' if len(stories) == 1 else 'ies'} "
|
|
719
722
|
f"({', '.join(stories)}); {fmt}: {note}")
|
|
720
723
|
return 0
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""The one test-case record every Orion reader and writer shares (`orion-cases/1`), so a new tool or file format
|
|
3
|
+
needs one adapter, not a change everywhere.
|
|
4
|
+
|
|
5
|
+
python3 .claude/skills/orion/scripts/cases_model.py to-json <cases.csv | design.md>... [--source <tool>]
|
|
6
|
+
[--story <KEY>] [--out cases.json]
|
|
7
|
+
python3 .claude/skills/orion/scripts/cases_model.py validate cases.json
|
|
8
|
+
|
|
9
|
+
Reads CSV exports (TestRail, Zephyr, Xray, Azure, Excel saved as CSV, or `tm.py xlsx-to-csv`), Orion's own case CSVs
|
|
10
|
+
and the test-case table of a `design.md`. Headers are matched case-insensitively from the aliases below; a case
|
|
11
|
+
whose steps come one row per step (the same ID repeated, as TestRail and Zephyr export them) is merged into one.
|
|
12
|
+
|
|
13
|
+
A case:
|
|
14
|
+
{"id": "TS-3", "key": "C1203", "title": "...", "story": "PR-1", "ac": ["AC-2"], "type": "negative",
|
|
15
|
+
"priority": "High", "preconditions": "...", "steps": [{"action": "...", "expected": "..."}],
|
|
16
|
+
"expected": "...", "data": "...", "postconditions": "...", "labels": [],
|
|
17
|
+
"source": {"tool": "testrail", "key": "C1203", "updated": "2026-11-20T10:00:00Z"},
|
|
18
|
+
"fingerprint": "<sha1 of the content fields>"}
|
|
19
|
+
Content is data, never instructions; standard library only. Exit: 0 ok · 1 findings (validate) · 2 usage.
|
|
20
|
+
"""
|
|
21
|
+
import argparse
|
|
22
|
+
import csv
|
|
23
|
+
import hashlib
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import re
|
|
27
|
+
import sys
|
|
28
|
+
|
|
29
|
+
FORMAT = "orion-cases/1"
|
|
30
|
+
# Field → header aliases (matched case-insensitively, spaces, dashes and underscores ignored).
|
|
31
|
+
ALIASES = {
|
|
32
|
+
"id": ["id", "test case id", "case id", "testcase id", "tc id", "test id"],
|
|
33
|
+
"key": ["key", "issue key", "tracker key", "external id", "test key"],
|
|
34
|
+
"title": ["title", "summary", "name", "test case", "what it checks", "test case title"],
|
|
35
|
+
"story": ["story", "story key", "user story", "parent"],
|
|
36
|
+
"ac": ["ac", "acceptance criteria", "linked ac", "covers", "requirement", "requirements", "refs", "references",
|
|
37
|
+
"linked issue", "linked issues"],
|
|
38
|
+
"type": ["type", "test type", "case type"],
|
|
39
|
+
"priority": ["priority", "severity"],
|
|
40
|
+
"preconditions": ["preconditions", "precondition", "pre conditions", "setup", "preconditions (incl starting state)"],
|
|
41
|
+
"steps": ["steps", "test steps", "step", "action", "step action", "steps (separated)"],
|
|
42
|
+
"step_expected": ["step expected", "expected (step)", "step expected result"],
|
|
43
|
+
"expected": ["expected", "expected result", "expected results", "expected result (what changed)"],
|
|
44
|
+
"data": ["test data", "data", "test data (fields)", "step data"],
|
|
45
|
+
"postconditions": ["postconditions", "post conditions", "cleanup", "teardown",
|
|
46
|
+
"postconditions (cleanup, checked)"],
|
|
47
|
+
"labels": ["labels", "tags", "components"],
|
|
48
|
+
"updated": ["updated", "updated on", "last modified", "modified", "updated_on"],
|
|
49
|
+
}
|
|
50
|
+
CONTENT = ["title", "ac", "type", "priority", "preconditions", "steps", "expected", "data", "postconditions"]
|
|
51
|
+
TYPES = {"positive", "negative", "boundary", "edge"}
|
|
52
|
+
PRIORITIES = {"high": "High", "medium": "Medium", "low": "Low", "critical": "High", "highest": "High",
|
|
53
|
+
"major": "High", "normal": "Medium", "minor": "Low", "lowest": "Low", "1": "High", "2": "Medium",
|
|
54
|
+
"3": "Low", "p1": "High", "p2": "Medium", "p3": "Low"}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _norm(h):
|
|
58
|
+
"""A header without case, punctuation or extra spaces."""
|
|
59
|
+
return re.sub(r"[\s_\-.:/]+", " ", re.sub(r"[*`]", "", h or "")).strip().lower()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def column_map(headers):
|
|
63
|
+
"""Map each field to the first header that matches one of its aliases (exact first, then prefix)."""
|
|
64
|
+
found = {}
|
|
65
|
+
normed = {h: _norm(h) for h in headers}
|
|
66
|
+
for field, names in ALIASES.items():
|
|
67
|
+
for h, n in normed.items():
|
|
68
|
+
if n in names and h not in found.values():
|
|
69
|
+
found[field] = h
|
|
70
|
+
break
|
|
71
|
+
else:
|
|
72
|
+
for h, n in normed.items():
|
|
73
|
+
if any(n.startswith(a) for a in names) and h not in found.values():
|
|
74
|
+
found[field] = h
|
|
75
|
+
break
|
|
76
|
+
return found
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def split_steps(text, expected_text=""):
|
|
80
|
+
"""Turn a steps cell into [{"action", "expected"}]: numbered (`1. … 2. …`), one per line, or `<br>`-separated.
|
|
81
|
+
A matching expected cell with the same numbering is paired step by step; otherwise expected stays empty."""
|
|
82
|
+
def parts(t):
|
|
83
|
+
t = (t or "").replace("<br>", "\n").replace("<br/>", "\n").strip()
|
|
84
|
+
if not t:
|
|
85
|
+
return []
|
|
86
|
+
numbered = re.split(r"(?:^|\s)(?=\d{1,2}[.)]\s)", t)
|
|
87
|
+
items = [re.sub(r"^\d{1,2}[.)]\s*", "", x).strip() for x in numbered if x.strip()]
|
|
88
|
+
if len(items) <= 1:
|
|
89
|
+
items = [x.strip(" -•\t") for x in t.split("\n") if x.strip(" -•\t")]
|
|
90
|
+
return items
|
|
91
|
+
acts, exps = parts(text), parts(expected_text)
|
|
92
|
+
if exps and len(exps) != len(acts):
|
|
93
|
+
exps = []
|
|
94
|
+
return [{"action": a, "expected": exps[i] if exps else ""} for i, a in enumerate(acts)]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def fingerprint(case):
|
|
98
|
+
"""A short hash of what a case says (not where it came from), to see whether it changed."""
|
|
99
|
+
body = json.dumps({k: case.get(k) for k in CONTENT}, sort_keys=True, ensure_ascii=False)
|
|
100
|
+
return hashlib.sha1(body.encode("utf-8")).hexdigest()[:12]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _case(get, source, story_default):
|
|
104
|
+
"""One case from a row reader `get(field) -> str`."""
|
|
105
|
+
ac_text = get("ac")
|
|
106
|
+
acs = re.findall(r"\bAC[-\s]?(\d+)\b", ac_text, re.I)
|
|
107
|
+
story = get("story") or next((t for t in re.findall(r"\b[A-Z][A-Z0-9]+-\d+\b", ac_text) if not t.upper().startswith("AC-")), "") \
|
|
108
|
+
or story_default
|
|
109
|
+
pr = get("priority").strip()
|
|
110
|
+
typ = get("type").strip().lower()
|
|
111
|
+
case = {
|
|
112
|
+
"id": get("id").strip(),
|
|
113
|
+
"key": get("key").strip(),
|
|
114
|
+
"title": get("title").strip(),
|
|
115
|
+
"story": story,
|
|
116
|
+
"ac": [f"AC-{n}" for n in dict.fromkeys(acs)],
|
|
117
|
+
"type": typ if typ in TYPES else (typ or ""),
|
|
118
|
+
"priority": PRIORITIES.get(pr.lower(), pr),
|
|
119
|
+
"preconditions": get("preconditions").strip(),
|
|
120
|
+
"steps": split_steps(get("steps"), get("step_expected")),
|
|
121
|
+
"expected": get("expected").strip(),
|
|
122
|
+
"data": get("data").strip(),
|
|
123
|
+
"postconditions": get("postconditions").strip(),
|
|
124
|
+
"labels": [x.strip() for x in re.split(r"[,;]", get("labels")) if x.strip()],
|
|
125
|
+
"source": {"tool": source, "key": get("key").strip() or get("id").strip(), "updated": get("updated").strip()},
|
|
126
|
+
}
|
|
127
|
+
return case
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _merge(cases):
|
|
131
|
+
"""Rows of one case (same ID, steps one per row) become one case; the first row's other fields win."""
|
|
132
|
+
out, by = [], {}
|
|
133
|
+
for c in cases:
|
|
134
|
+
k = c["id"] or c["key"]
|
|
135
|
+
if k and k in by:
|
|
136
|
+
first = by[k]
|
|
137
|
+
first["steps"] += c["steps"]
|
|
138
|
+
for f in ("expected", "data", "preconditions", "postconditions", "title"):
|
|
139
|
+
if not first[f] and c[f]:
|
|
140
|
+
first[f] = c[f]
|
|
141
|
+
continue
|
|
142
|
+
if k:
|
|
143
|
+
by[k] = c
|
|
144
|
+
out.append(c)
|
|
145
|
+
for i, c in enumerate(out, 1):
|
|
146
|
+
if not c["id"]:
|
|
147
|
+
c["id"] = c["key"] or f"IMP-{i}"
|
|
148
|
+
c["fingerprint"] = fingerprint(c)
|
|
149
|
+
return out
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def from_csv(path, source="csv", story=""):
|
|
153
|
+
"""Cases from a CSV file (UTF-8, with or without BOM)."""
|
|
154
|
+
with open(path, encoding="utf-8-sig", newline="") as f:
|
|
155
|
+
rows = list(csv.DictReader(f))
|
|
156
|
+
cmap = column_map(rows[0].keys() if rows else [])
|
|
157
|
+
base = os.path.splitext(os.path.basename(path))[0]
|
|
158
|
+
default = story or (base[: -len("-test-cases")] if base.endswith("-test-cases") else "")
|
|
159
|
+
cases = [_case(lambda fld, r=r: (r.get(cmap[fld]) or "") if fld in cmap else "", source, default)
|
|
160
|
+
for r in rows if any((v or "").strip() for v in r.values())]
|
|
161
|
+
return _merge(cases), cmap
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def from_design(path, source="orion", story=""):
|
|
165
|
+
"""Cases from the test-case table of a design.md (the first table with ID and Steps columns, or ID and What it checks)."""
|
|
166
|
+
with open(path, encoding="utf-8") as f:
|
|
167
|
+
lines = f.read().split("\n")
|
|
168
|
+
head, rows = None, []
|
|
169
|
+
for line in lines:
|
|
170
|
+
if not line.strip().startswith("|"):
|
|
171
|
+
if rows:
|
|
172
|
+
break
|
|
173
|
+
head = None
|
|
174
|
+
continue
|
|
175
|
+
cells = [c.strip() for c in line.strip().strip("|").split("|")]
|
|
176
|
+
if head is None:
|
|
177
|
+
if any(_norm(c) == "id" for c in cells) and any(_norm(c).startswith(("steps", "what it checks")) for c in cells):
|
|
178
|
+
head = cells
|
|
179
|
+
continue
|
|
180
|
+
if re.match(r"^[-:\s|]+$", line.strip()):
|
|
181
|
+
continue
|
|
182
|
+
rows.append(dict(zip(head, cells)))
|
|
183
|
+
cmap = column_map(head or [])
|
|
184
|
+
default = story or os.path.basename(os.path.dirname(os.path.abspath(path)))
|
|
185
|
+
cases = [_case(lambda fld, r=r: (r.get(cmap[fld]) or "") if fld in cmap else "", source, default)
|
|
186
|
+
for r in rows if re.match(r"^[A-Z]+-\d+", r.get(cmap.get("id", ""), "") or "")]
|
|
187
|
+
return _merge(cases), cmap
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def load(paths, source="csv", story=""):
|
|
191
|
+
"""Cases from any mix of CSV files and design.md files."""
|
|
192
|
+
cases, maps = [], {}
|
|
193
|
+
for p in paths:
|
|
194
|
+
got, cmap = (from_design if p.endswith(".md") else from_csv)(p, source if not p.endswith(".md") else "orion", story)
|
|
195
|
+
cases += got
|
|
196
|
+
maps[p] = (len(got), cmap)
|
|
197
|
+
return {"format": FORMAT, "cases": cases}, maps
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def validate(doc):
|
|
201
|
+
"""Structural problems of a record set (not quality: case_check judges that)."""
|
|
202
|
+
out = []
|
|
203
|
+
if doc.get("format") != FORMAT:
|
|
204
|
+
out.append(f"format is {doc.get('format')!r}, expected {FORMAT!r}")
|
|
205
|
+
seen = set()
|
|
206
|
+
for c in doc.get("cases", []):
|
|
207
|
+
cid = c.get("id") or "?"
|
|
208
|
+
for f in ("id", "title", "steps"):
|
|
209
|
+
if not c.get(f):
|
|
210
|
+
out.append(f"{cid}: {f} is empty")
|
|
211
|
+
if cid in seen:
|
|
212
|
+
out.append(f"{cid}: id used twice")
|
|
213
|
+
seen.add(cid)
|
|
214
|
+
if c.get("fingerprint") and c["fingerprint"] != fingerprint(c):
|
|
215
|
+
out.append(f"{cid}: fingerprint doesn't match its content")
|
|
216
|
+
return out
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def main(argv=None):
|
|
220
|
+
"""Command line: to-json, validate."""
|
|
221
|
+
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
|
222
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
223
|
+
t = sub.add_parser("to-json")
|
|
224
|
+
t.add_argument("files", nargs="+")
|
|
225
|
+
t.add_argument("--source", default="csv", help="the tool the files came from: testrail, zephyr, xray, azure, jira, excel, csv")
|
|
226
|
+
t.add_argument("--story", default="")
|
|
227
|
+
t.add_argument("--out")
|
|
228
|
+
v = sub.add_parser("validate")
|
|
229
|
+
v.add_argument("file")
|
|
230
|
+
a = ap.parse_args(argv)
|
|
231
|
+
if a.cmd == "to-json":
|
|
232
|
+
missing = [f for f in a.files if not os.path.isfile(f)]
|
|
233
|
+
if missing:
|
|
234
|
+
print(f"cases_model: no such file: {missing[0]}")
|
|
235
|
+
return 2
|
|
236
|
+
doc, maps = load(a.files, a.source, a.story)
|
|
237
|
+
text = json.dumps(doc, indent=1, ensure_ascii=False) + "\n"
|
|
238
|
+
if a.out:
|
|
239
|
+
with open(a.out, "w", encoding="utf-8") as f:
|
|
240
|
+
f.write(text)
|
|
241
|
+
else:
|
|
242
|
+
sys.stdout.write(text)
|
|
243
|
+
for p, (n, m) in maps.items():
|
|
244
|
+
print(f"{p}: {n} case(s) · mapping: " + ", ".join(f"{k}={v}" for k, v in m.items()), file=sys.stderr)
|
|
245
|
+
return 0
|
|
246
|
+
with open(a.file, encoding="utf-8") as f:
|
|
247
|
+
doc = json.load(f)
|
|
248
|
+
problems = validate(doc)
|
|
249
|
+
print(f"cases_model: {len(doc.get('cases', []))} case(s), {len(problems)} problem(s)")
|
|
250
|
+
for p in problems:
|
|
251
|
+
print(f" - {p}")
|
|
252
|
+
return 1 if problems else 0
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
if __name__ == "__main__":
|
|
256
|
+
sys.exit(main())
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Keeps project-context/ safe to commit with the code, so a clone anywhere (a teammate, a cloud session) starts with
|
|
4
|
+
* what earlier runs learned, and nothing private travels with it.
|
|
5
|
+
*
|
|
6
|
+
* node .claude/skills/orion/scripts/context_guard.mjs ensure [--context project-context]
|
|
7
|
+
* node .claude/skills/orion/scripts/context_guard.mjs check [--context project-context] [--allow-domain <d>]...
|
|
8
|
+
*
|
|
9
|
+
* ensure writes project-context/.gitignore for the local-only files (logs, the graph, which is rebuilt in seconds,
|
|
10
|
+
* tool backups, screenshots and traces), or adds the lines it lacks. The user's own lines are kept. Idempotent.
|
|
11
|
+
* check reads every file that would be committed and every tracked file, and reports, by file:line and kind only
|
|
12
|
+
* (never the value): secrets (password/token/key values, bearer tokens, JWTs, cloud and Git tokens, private
|
|
13
|
+
* keys, credentials in URLs), e-mail addresses outside test domains (example.com, *.test, *.example,
|
|
14
|
+
* *.invalid, *.localhost, no-reply addresses; more with --allow-domain or project-context/privacy-allow.txt,
|
|
15
|
+
* one domain per line), and images, videos, traces or archives. A local-only file that git already tracks is
|
|
16
|
+
* listed as a warning with the command that stops tracking it.
|
|
17
|
+
* Exit: 0 nothing to block · 1 findings (do not commit) · 2 usage.
|
|
18
|
+
*/
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { execFileSync } from 'node:child_process';
|
|
22
|
+
import { fileURLToPath } from 'node:url';
|
|
23
|
+
|
|
24
|
+
const MARK_START = '# --- Orion: local-only files, never committed (context_guard.mjs ensure keeps this block) ---';
|
|
25
|
+
const MARK_END = '# --- end of Orion block; your own lines go below ---';
|
|
26
|
+
export const LOCAL_ONLY = ['logs/', 'graph/', 'tm-backups/', '*.png', '*.jpg', '*.jpeg', '*.gif', '*.webp', '*.webm',
|
|
27
|
+
'*.mp4', '*.zip', '*.har', '*.trace', '.env', '.env.*'];
|
|
28
|
+
const BINARY = /\.(png|jpe?g|gif|webp|webm|mp4|zip|har|trace|pdf|xlsx|docx|pptx)$/i;
|
|
29
|
+
const DERIVED_DIRS = ['logs/', 'graph/', 'tm-backups/'];
|
|
30
|
+
const TEST_DOMAINS = [/(^|\.)example\.(com|org|net)$/, /\.(test|example|invalid|localhost)$/, /^users\.noreply\.github\.com$/];
|
|
31
|
+
const NO_REPLY = /^(no-?reply|donotreply)@/i;
|
|
32
|
+
|
|
33
|
+
/** Values that name where a secret comes from rather than holding one. */
|
|
34
|
+
const PLACEHOLDER = /^(<[^>]*>|\*+|\$\{?[\w.]+\}?|process\.env\b.*|os\.environ.*|env\(.*|\[?redacted\]?|masked|xxx+|\.\.\.|…|[A-Z][A-Z0-9_]{2,}|synthetic[-\w]*|dummy[-\w]*|placeholder[-\w]*)$/i;
|
|
35
|
+
|
|
36
|
+
const RULES = [
|
|
37
|
+
['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
|
|
38
|
+
['bearer token', /\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/],
|
|
39
|
+
['basic auth header', /\bBasic\s+[A-Za-z0-9+/]{16,}={0,2}(?![A-Za-z0-9+/=])/],
|
|
40
|
+
['JWT', /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\./],
|
|
41
|
+
['cloud key', /\b(AKIA|ASIA)[0-9A-Z]{16}\b|\bAIza[0-9A-Za-z_-]{35}\b/],
|
|
42
|
+
['git or chat token', /\b(ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}\b|\bgithub_pat_[A-Za-z0-9_]{40,}|\bglpat-[A-Za-z0-9_-]{20,}|\bxox[abpr]-[A-Za-z0-9-]{10,}/],
|
|
43
|
+
['API key', /\bsk-(ant-)?[A-Za-z0-9_-]{20,}\b/],
|
|
44
|
+
['credentials in a URL', /\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@'"`]+:[^\s/@'"`]{3,}@/i],
|
|
45
|
+
];
|
|
46
|
+
const NAMED = /\b(pass(word|wd)?|pwd|secret|client[_-]?secret|token|api[_-]?key|apikey|access[_-]?key)\b["'`]?\s*[:=]\s*["'`]?([^\s"'`,;|)]+)/gi;
|
|
47
|
+
// The domain ends in letters (`.com`, `.co.uk`), so a package version such as `mcp@0.0.83` is not an address.
|
|
48
|
+
const EMAIL = /\b[A-Za-z0-9._%+-]+@((?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,})\b(?![.@\w-]*\d)/g;
|
|
49
|
+
|
|
50
|
+
function die(code, msg) { console.error(msg); process.exit(code); }
|
|
51
|
+
|
|
52
|
+
function args(argv) {
|
|
53
|
+
const o = { context: 'project-context', allow: [] };
|
|
54
|
+
for (let i = 0; i < argv.length; i++) {
|
|
55
|
+
if (argv[i] === '--context') o.context = argv[++i];
|
|
56
|
+
else if (argv[i] === '--allow-domain') o.allow.push(String(argv[++i] || '').toLowerCase());
|
|
57
|
+
else die(2, `context_guard: unknown argument ${argv[i]}`);
|
|
58
|
+
}
|
|
59
|
+
if (!o.context) die(2, 'context_guard: --context needs a folder');
|
|
60
|
+
return o;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Write or complete the Orion block of <context>/.gitignore; returns what changed. */
|
|
64
|
+
export function ensure(context) {
|
|
65
|
+
fs.mkdirSync(context, { recursive: true });
|
|
66
|
+
const file = path.join(context, '.gitignore');
|
|
67
|
+
const had = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
|
|
68
|
+
const block = [MARK_START, ...LOCAL_ONLY, MARK_END].join('\n');
|
|
69
|
+
let text;
|
|
70
|
+
if (had.includes(MARK_START) && had.includes(MARK_END)) {
|
|
71
|
+
text = had.replace(new RegExp(`${escape(MARK_START)}[\\s\\S]*?${escape(MARK_END)}`), block);
|
|
72
|
+
} else {
|
|
73
|
+
text = `${block}\n${had ? `${had.replace(/\n*$/, '')}\n` : ''}`;
|
|
74
|
+
}
|
|
75
|
+
if (text === had) return 'unchanged';
|
|
76
|
+
fs.writeFileSync(file, text);
|
|
77
|
+
return had ? 'updated' : 'created';
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function escape(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
|
|
81
|
+
|
|
82
|
+
/** Files under the folder, relative to it, skipping VCS and dependency folders. */
|
|
83
|
+
function walk(dir, base = dir, out = []) {
|
|
84
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
85
|
+
if (e.name === '.git' || e.name === 'node_modules') continue;
|
|
86
|
+
const p = path.join(dir, e.name);
|
|
87
|
+
if (e.isDirectory()) walk(p, base, out);
|
|
88
|
+
else if (e.isFile()) out.push(path.relative(base, p).split(path.sep).join('/'));
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Does a pattern of the Orion block match this relative path? */
|
|
94
|
+
function localOnly(rel) {
|
|
95
|
+
return LOCAL_ONLY.some((p) => (p.endsWith('/') ? rel.startsWith(p) || rel.includes(`/${p}`)
|
|
96
|
+
: new RegExp(`(^|/)${p.split('*').map(escape).join('[^/]*')}$`).test(rel)));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Tracked files and ignore status from git, when the folder is in a git repository. */
|
|
100
|
+
function gitView(context, files) {
|
|
101
|
+
const run = (a, input) => execFileSync('git', a, { cwd: context, input, encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] });
|
|
102
|
+
try {
|
|
103
|
+
run(['rev-parse', '--is-inside-work-tree']);
|
|
104
|
+
} catch { return null; }
|
|
105
|
+
const tracked = new Set(run(['ls-files', '-z', '--', '.']).split('\0').filter(Boolean));
|
|
106
|
+
let ignored = new Set();
|
|
107
|
+
try {
|
|
108
|
+
ignored = new Set(run(['check-ignore', '--no-index', '-z', '--stdin'], files.join('\0')).split('\0').filter(Boolean));
|
|
109
|
+
} catch { /* exit 1: none ignored */ }
|
|
110
|
+
return { tracked, ignored };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function allowedDomain(domain, allow) {
|
|
114
|
+
const d = domain.toLowerCase();
|
|
115
|
+
return TEST_DOMAINS.some((r) => r.test(d)) || allow.some((a) => d === a || d.endsWith(`.${a}`));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Findings for one text: [{line, kind}] (never the value). */
|
|
119
|
+
export function scanText(text, allow = []) {
|
|
120
|
+
const out = [];
|
|
121
|
+
text.split(/\r?\n/).forEach((line, i) => {
|
|
122
|
+
for (const [kind, re] of RULES) if (re.test(line)) out.push({ line: i + 1, kind });
|
|
123
|
+
for (const m of line.matchAll(NAMED)) {
|
|
124
|
+
const v = m[3].replace(/^["'`]|["'`]$/g, '');
|
|
125
|
+
if (v.length >= 8 && !PLACEHOLDER.test(v) && /[0-9]/.test(v) && /[A-Za-z]/.test(v)) out.push({ line: i + 1, kind: `${m[1].toLowerCase()} value` });
|
|
126
|
+
}
|
|
127
|
+
for (const m of line.matchAll(EMAIL)) {
|
|
128
|
+
if (!NO_REPLY.test(m[0]) && !allowedDomain(m[1], allow)) out.push({ line: i + 1, kind: 'e-mail address (record a handle or role instead)' });
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function check(o) {
|
|
135
|
+
if (!fs.existsSync(o.context)) { console.log(`context_guard: no ${o.context} folder; nothing to check`); return 0; }
|
|
136
|
+
const allowFile = path.join(o.context, 'privacy-allow.txt');
|
|
137
|
+
const allow = [...o.allow, ...(fs.existsSync(allowFile) ? fs.readFileSync(allowFile, 'utf8').split(/\r?\n/)
|
|
138
|
+
.map((l) => l.trim().toLowerCase()).filter((l) => l && !l.startsWith('#')) : [])];
|
|
139
|
+
const files = walk(o.context);
|
|
140
|
+
const git = gitView(o.context, files);
|
|
141
|
+
const block = [];
|
|
142
|
+
const warn = [];
|
|
143
|
+
for (const rel of files) {
|
|
144
|
+
const tracked = git ? git.tracked.has(rel) : false;
|
|
145
|
+
const committed = tracked || (git ? !git.ignored.has(rel) : !localOnly(rel));
|
|
146
|
+
if (!committed) continue;
|
|
147
|
+
if (tracked && DERIVED_DIRS.some((d) => rel.startsWith(d))) {
|
|
148
|
+
warn.push(`${rel}: local-only, but git tracks it (stop with: git rm -r --cached ${path.posix.join(o.context.split(path.sep).join('/'), rel.split('/')[0])})`);
|
|
149
|
+
}
|
|
150
|
+
if (BINARY.test(rel)) { block.push(`${rel}: image, video, trace or archive (keep it local; screenshots can show account names and page data)`); continue; }
|
|
151
|
+
const full = path.join(o.context, rel);
|
|
152
|
+
if (fs.statSync(full).size > 5_000_000) { block.push(`${rel}: over 5 MB (not reviewable; keep it local)`); continue; }
|
|
153
|
+
const buf = fs.readFileSync(full);
|
|
154
|
+
if (buf.includes(0)) { block.push(`${rel}: binary file (keep it local)`); continue; }
|
|
155
|
+
for (const f of scanText(buf.toString('utf8'), allow)) block.push(`${rel}:${f.line}: ${f.kind}`);
|
|
156
|
+
}
|
|
157
|
+
const where = git ? 'files git would commit or already tracks' : 'files outside the local-only list (no git repository)';
|
|
158
|
+
console.log(`context_guard: ${files.length} file(s) in ${o.context}, ${block.length} finding(s), ${warn.length} warning(s) (${where})`);
|
|
159
|
+
for (const b of block) console.log(` - ${b}`);
|
|
160
|
+
for (const w of warn) console.log(` ! ${w}`);
|
|
161
|
+
if (block.length) console.log('Do not commit: remove the value (keep only the .env variable name, a handle or a role), then run this again.');
|
|
162
|
+
return block.length ? 1 : 0;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
166
|
+
if (isMain) {
|
|
167
|
+
const [cmd, ...rest] = process.argv.slice(2);
|
|
168
|
+
const o = args(rest);
|
|
169
|
+
if (cmd === 'ensure') console.log(`context_guard: ${path.join(o.context, '.gitignore')} ${ensure(o.context)}`);
|
|
170
|
+
else if (cmd === 'check') process.exit(check(o));
|
|
171
|
+
else die(2, 'usage: context_guard.mjs ensure|check [--context project-context] [--allow-domain <domain>]');
|
|
172
|
+
}
|