Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

build: lint every commit and CI run, and allow no code comments but TODO, FIXME, MARK, tool directives and licenses

wquguruade2bf5084c9
diff --git a/.githooks/pre-commit b/.githooks/pre-commit
index 76b77d0..43d0eca 100755
--- a/.githooks/pre-commit
+++ b/.githooks/pre-commit
@@ -1,5 +1,2 @@
#!/bin/bash
-# Enabled with `git config core.hooksPath .githooks`.
-if git diff --cached --name-only | grep -qx 'AGENTS.md'; then
- exec python3 "$(git rev-parse --show-toplevel)/scripts/check-agents.py"
-fi
+exec python3 "$(git rev-parse --show-toplevel)/scripts/lint.py" --staged
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 46353e5..984dcc7 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -12,6 +12,7 @@ jobs:
runs-on: macos-26
steps:
- uses: actions/checkout@v4
+ - run: python3 scripts/lint.py
- run: scripts/test.sh
- run: scripts/package.sh
- uses: actions/upload-artifact@v4
diff --git a/AGENTS.md b/AGENTS.md
index 26fbb66..a0b1485 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -29,7 +29,7 @@ Cicada (知了, formerly Live Subs) turns what a computer plays into live transl
## Layout
-- `Sources/Cicada`: the app, one concern per file. Engines are UI-free (`ListenEngine`, `SpeakEngine`, `Notes`, `Translator`, `Ling`, `VirtualMic`, `SessionStore`…); `AppModel` wires them and holds the debug commands. Settings keys: `AppSettings` in `Settings.swift`.
+- `Sources/Cicada`: the app, one concern per file. Engines are UI-free (`ListenEngine`, `SpeakEngine`, `Notes`, `Ling`…); `AppModel` wires them and holds the debug commands. Settings keys: `AppSettings` in `Settings.swift`.
- `Sources/CicadaIcon`: renders the icon set. `site/`: the website, built by `scripts/site.py`. `server/`: the Worker on cicada.indaloop.app (site, shared meetings); `node --test server/test/*.mjs` against `wrangler dev`.
- The site is Chinese at `/`, English / Japanese / Korean under `/en/` `/ja/` `/ko/`; every `{{t.key}}` comes from `site/i18n/<lang>.json`. `start.html` is the setup page; its `img/start/` shots come from the app per language. `tools/`: test helpers. `Tests/CicadaTests`: unit tests for the pure parts.
@@ -37,6 +37,7 @@ Cicada (知了, formerly Live Subs) turns what a computer plays into live transl
```bash
scripts/test.sh # AGENTS.md check + unit tests
+python3 scripts/lint.py # lint (on commit: git config core.hooksPath .githooks)
scripts/build.sh && open build/Cicada.app # dev build: own bundle id, settings, log
RELEASE=1 scripts/build.sh # release build
scripts/package.sh # DMG + zip + checksums
@@ -46,15 +47,15 @@ scripts/deploy-site.sh # deploy the site and server/ (cicada.ind
## Verifying
-- Run the app and check the behaviour, not just the build; check the English UI too.
+- Run the app and check the behaviour, not just the build, in English too.
- Drive the dev build with `tools/lsctl` (`tools/README.md`; source of truth: `AppModel.debugCommand`). Use `afplay Resources/sample/sample.m4a` or `say -o` clips as input and read `/tmp/livesubs-dev-debug.log`.
- Real sound (room mic, 同声传译): `.claude/skills/audio-test`. A real voice, the BlackHole install, Input Monitoring and a Mac without permissions need a person.
## Conventions
-- Match the existing naming and comment density; comments say why.
-- Commits are English Conventional Commits (`feat:` `fix:` `docs:` `build:` `refactor:` `test:` `chore:`). `feat:` and `fix:` subjects are the release notes (`scripts/changelog.py`), one line each linked to the commit: say what the user gets in one plain sentence, one change per commit. The scope picks the platform: `(windows)` `(android)` `(linux)` `(site)`, anything else is Mac.
+- Match existing naming. No comments but TODO, FIXME, MARK, tool directives and licenses (`scripts/comments.py`).
+- Commits are English Conventional Commits (`feat:` `fix:` `docs:` `build:` `refactor:` `test:` `chore:`). `feat:` and `fix:` subjects are the release notes (`scripts/changelog.py`): say what the user gets in one plain sentence, one change per commit. The scope picks the platform: `(windows)` `(android)` `(linux)` `(site)`, anything else is Mac.
- Release notes have no Chinese but the brand: name UI in English (Listen to › Room).
-- Every user-visible change also gets a Chinese item in `site/changelog.json`, the website's changelog; keep `README.md` (English) and `README.{zh-CN,ja,ko}.md` in step.
+- Every user-visible change also gets a Chinese item in `site/changelog.json`; keep `README.md` (English) and `README.{zh-CN,ja,ko}.md` in step.
- One semver version for every platform, in `VERSION`; every build reads it. Patch for fixes only, minor for features, major only when users of any platform must grant permissions again. Every release ships all four platforms.
-- This file stays under 6 KB with these sections; `scripts/check-agents.py` enforces it. Implementation detail belongs in code comments, not here.
+- This file stays under 6 KB with these sections (`scripts/check-agents.py`); implementation detail belongs in code and tests.
diff --git a/scripts/check-agents.py b/scripts/check-agents.py
index 572e7ce..1379bf0 100755
--- a/scripts/check-agents.py
+++ b/scripts/check-agents.py
@@ -1,11 +1,9 @@
#!/usr/bin/env python3
-"""Keeps AGENTS.md (read by every agent session) small and in shape. Run by scripts/test.sh,
-CI and the pre-commit hook. Budgets sit below where the file had grown to (27 KB), on purpose."""
import re, sys
from pathlib import Path
MAX_BYTES = 6 * 1024
-MAX_LINE = 400 # long lines are how it grew last time while the line count stood still
+MAX_LINE = 400
SECTIONS = ["Scope", "Hard rules", "Design", "Layout", "Commands", "Verifying", "Conventions"]
path = Path(__file__).resolve().parent.parent / "AGENTS.md"
@@ -13,7 +11,7 @@ text = path.read_text(encoding="utf-8")
errors = []
size = len(text.encode("utf-8"))
if size > MAX_BYTES:
- errors.append(f"{size} bytes, budget {MAX_BYTES}: move detail to code comments or tools/README.md")
+ errors.append(f"{size} bytes, budget {MAX_BYTES}: move detail to code, tests or tools/README.md")
for n, line in enumerate(text.splitlines(), 1):
if len(line) > MAX_LINE:
errors.append(f"line {n} is {len(line)} chars (max {MAX_LINE})")
diff --git a/scripts/comments.py b/scripts/comments.py
new file mode 100755
index 0000000..c515545
--- /dev/null
+++ b/scripts/comments.py
@@ -0,0 +1,536 @@
+#!/usr/bin/env python3
+"""Usage: comments.py check|strip|list [files...]
+
+check: fail on comments outside KEEP. strip: remove them in place. list: print them.
+No files: every tracked source file."""
+import ast, io, re, subprocess, sys, tokenize
+from pathlib import Path
+
+KEEP = re.compile(
+ r"^\s*(?:"
+ r"TODO|FIXME|MARK\b|"
+ r"swift-tools-version|swift-format-ignore|swiftlint:|sourcery:|"
+ r"noqa|type:|pragma\b|pylint:|fmt:|-\*-|coding[:=]|"
+ r"requires\b|shellcheck\s|eslint|@ts-|prettier-ignore|istanbul\s|c8\s|"
+ r"ktlint|noinspection|language=|ReSharper\s|<auto-generated|"
+ r"SPDX-|Copyright\b)"
+ r"|\b(?:CC BY|GPL|Apache License|MIT License|SPDX)\b"
+)
+
+C_LIKE = {".swift": "swift", ".kt": "kotlin", ".kts": "kotlin", ".cs": "csharp",
+ ".c": "c", ".h": "c", ".js": "js", ".mjs": "js"}
+HASH = {".sh": "sh", ".py": "py", ".ps1": "ps1"}
+MARKUP = (".html", ".css")
+REASON = re.compile(r"^(#\s*noqa\b[^-]*?)\s+-\s.*$", re.S)
+
+def body(text):
+ t = re.sub(r"^(//+|/\*+|#+)", "", text.strip())
+ return re.sub(r"\*+/$", "", t)
+
+def kept(text):
+ return any(KEEP.search(re.sub(r"^\s*\*\s?", "", line)) for line in body(text).splitlines() or [""])
+
+class CLike:
+
+ def __init__(self, src, lang):
+ self.s, self.lang, self.out = src, lang, []
+ self.nested = lang in ("swift", "kotlin")
+
+ def run(self):
+ self.code(0, None)
+ return self.out
+
+ def code(self, i, close):
+ s, depth = self.s, 0
+ prev = ""
+ while i < len(s):
+ c = s[i]
+ if s.startswith("//", i):
+ j = s.find("\n", i)
+ j = len(s) if j < 0 else j
+ self.out.append((i, j))
+ i = j
+ continue
+ if s.startswith("/*", i):
+ j = self.block(i)
+ self.out.append((i, j))
+ i = j
+ continue
+ if close and c in "({[":
+ depth += 1
+ elif close and c in ")}]":
+ if depth == 0 and c == close:
+ return i + 1
+ depth -= 1
+ if c == '"' or (c == "#" and self.lang == "swift" and re.match(r'#+"', s[i:])):
+ i = self.string(i)
+ prev = '"'
+ continue
+ if c in "@$" and self.lang == "csharp" and re.match(r'[@$]+"', s[i:]):
+ i = self.string(i)
+ prev = '"'
+ continue
+ if c == "'" and self.lang in ("kotlin", "csharp", "c"):
+ i = self.char(i)
+ continue
+ if c in "'`" and self.lang == "js":
+ i = self.jsquote(i, c)
+ continue
+ if c == "/" and self.lang == "js" and self.regex_ok(prev):
+ i = self.jsregex(i)
+ prev = "r"
+ continue
+ if not c.isspace():
+ prev = c
+ i += 1
+ return i
+
+ def block(self, i):
+ s, depth, j = self.s, 0, i
+ while j < len(s):
+ if s.startswith("/*", j):
+ depth += 1 if (self.nested or depth == 0) else 0
+ j += 2
+ elif s.startswith("*/", j):
+ depth -= 1
+ j += 2
+ if depth == 0:
+ return j
+ else:
+ j += 1
+ raise SyntaxError("unterminated block comment")
+
+ def char(self, i):
+ s, j = self.s, i + 1
+ while j < len(s) and s[j] != "'":
+ j += 2 if s[j] == "\\" else 1
+ return j + 1
+
+ def string(self, i):
+ s, lang = self.s, self.lang
+ m = re.match(r'(#*)', s[i:]) if lang == "swift" else re.match(r'([@$]*)', s[i:])
+ pre = m.group(1)
+ j = i + len(pre)
+ triple = s.startswith('"""', j)
+ q = '"""' if triple else '"'
+ j += len(q)
+ if lang == "swift":
+ end, interp, esc = q + pre, "\\" + pre + "(", "\\" + pre
+ elif lang == "kotlin":
+ end, interp, esc = q, "${", None if triple else "\\"
+ elif lang == "csharp":
+ verbatim, dollars = "@" in pre, pre.count("$")
+ end = q
+ interp = "{" * max(dollars, 1) if dollars else None
+ esc = None if (verbatim or triple) else "\\"
+ else:
+ end, interp, esc = q, None, "\\"
+ while j < len(s):
+ if lang == "csharp" and not triple and "@" in pre and s.startswith('""', j):
+ j += 2
+ continue
+ if interp and s.startswith(interp, j):
+ if lang == "csharp" and not triple and s.startswith(interp + "{", j) and pre.count("$") == 1:
+ j += 2
+ continue
+ j = self.code(j + len(interp), ")" if lang == "swift" else "}")
+ continue
+ if esc and s.startswith(esc, j):
+ j += len(esc) + 1
+ continue
+ if s.startswith(end, j):
+ j += len(end)
+ if triple:
+ while j < len(s) and s[j] == '"':
+ j += 1
+ return j
+ j += 1
+ raise SyntaxError(f"unterminated string at {i}")
+
+ def jsquote(self, i, q):
+ s, j = self.s, i + 1
+ while j < len(s):
+ if s[j] == "\\":
+ j += 2
+ continue
+ if q == "`" and s.startswith("${", j):
+ j = self.code(j + 2, "}")
+ continue
+ if s[j] == q:
+ return j + 1
+ j += 1
+ raise SyntaxError("unterminated js string")
+
+ def regex_ok(self, prev):
+ return prev == "" or prev in "(,=:[!&|?{};+-*%<>~^" or prev == "\n"
+
+ def jsregex(self, i):
+ s, j, cls = self.s, i + 1, False
+ if s.startswith("//", i) or s.startswith("/*", i):
+ return i
+ while j < len(s) and s[j] != "\n":
+ if s[j] == "\\":
+ j += 2
+ continue
+ if s[j] == "[":
+ cls = True
+ elif s[j] == "]":
+ cls = False
+ elif s[j] == "/" and not cls:
+ j += 1
+ while j < len(s) and s[j].isalpha():
+ j += 1
+ return j
+ j += 1
+ return i + 1
+
+class Sh:
+
+ def __init__(self, src):
+ self.s, self.out, self.heredocs = src, [], []
+
+ def run(self):
+ self.code(0, None)
+ return self.out
+
+ def code(self, i, close):
+ s, n, depth, word = self.s, len(self.s), 0, True
+ while i < n:
+ c = s[i]
+ if c == "\n":
+ i = self.newline(i)
+ word = True
+ continue
+ if c == "\\":
+ i, word = i + 2, False
+ continue
+ if c == "#" and word:
+ j = s.find("\n", i)
+ j = n if j < 0 else j
+ self.out.append((i, j))
+ i = j
+ continue
+ if c in "'\"`$":
+ i, word = self.quoted(i), False
+ continue
+ m = re.match(r"<<(-?)\s*(['\"]?)([A-Za-z_]\w*)\2", s[i:])
+ if m:
+ self.heredocs.append((m.group(3), bool(m.group(1))))
+ i, word = i + m.end(), False
+ continue
+ if close:
+ if c == "(":
+ depth += 1
+ elif c == ")":
+ if depth == 0 and close == ")":
+ return i + 1
+ depth -= 1
+ word = c in " \t;|&()"
+ i += 1
+ return i
+
+ def newline(self, i):
+ s, n = self.s, len(self.s)
+ i += 1
+ for tag, dash in self.heredocs:
+ while i < n:
+ j = s.find("\n", i)
+ j = n if j < 0 else j
+ line = s[i:j]
+ i = j + 1
+ if (line.lstrip("\t") if dash else line) == tag:
+ break
+ self.heredocs = []
+ return i
+
+ def quoted(self, i):
+ s = self.s
+ c = s[i]
+ if c == "'":
+ return s.index("'", i + 1) + 1
+ if c == "`":
+ j = i + 1
+ while s[j] != "`":
+ j += 2 if s[j] == "\\" else 1
+ return j + 1
+ if c == '"':
+ j = i + 1
+ while s[j] != '"':
+ if s[j] == "\\":
+ j += 2
+ elif s[j] in "$`":
+ j = self.quoted(j)
+ else:
+ j += 1
+ return j + 1
+ nxt = s[i + 1:i + 2]
+ if nxt == "'":
+ j = i + 2
+ while s[j] != "'":
+ j += 2 if s[j] == "\\" else 1
+ return j + 1
+ if nxt == "(":
+ return self.code(i + 2, ")")
+ if nxt == "{":
+ j, depth = i + 2, 1
+ while depth:
+ if s[j] in "'\"`" or (s[j] == "$" and s[j + 1:j + 2] in "({"):
+ j = self.quoted(j)
+ continue
+ if s[j] == "\\":
+ j += 2
+ continue
+ depth += {"{": 1, "}": -1}.get(s[j], 0)
+ j += 1
+ return j
+ return i + 2 if nxt else i + 1
+
+class Ps:
+
+ def __init__(self, src):
+ self.s, self.out = src, []
+
+ def run(self):
+ self.code(0, None)
+ return self.out
+
+ def code(self, i, close):
+ s, n, depth, word = self.s, len(self.s), 0, True
+ while i < n:
+ c = s[i]
+ if s.startswith("<#", i):
+ j = s.index("#>", i + 2) + 2
+ self.out.append((i, j))
+ i = j
+ continue
+ if c == "#" and word:
+ j = s.find("\n", i)
+ j = n if j < 0 else j
+ self.out.append((i, j))
+ i = j
+ continue
+ if c == "`":
+ i, word = i + 2, False
+ continue
+ m = re.match(r"@(['\"])[ \t]*\r?\n", s[i:])
+ if m:
+ q = m.group(1)
+ j = re.compile(r"\n" + q + "@").search(s, i + m.end() - 1)
+ i, word = j.end(), False
+ continue
+ if c == "'":
+ j = i + 1
+ while not (s[j] == "'" and s[j + 1:j + 2] != "'"):
+ j += 2 if s[j] == "'" else 1
+ i, word = j + 1, False
+ continue
+ if c == '"':
+ j = i + 1
+ while not (s[j] == '"' and s[j + 1:j + 2] != '"'):
+ if s[j] == "`" or s[j:j + 2] == '""':
+ j += 2
+ elif s.startswith("$(", j):
+ j = self.code(j + 2, ")")
+ else:
+ j += 1
+ i, word = j + 1, False
+ continue
+ if s.startswith("${", i):
+ i, word = s.index("}", i) + 1, False
+ continue
+ if close:
+ if c in "({":
+ depth += 1
+ elif c in ")}":
+ if depth == 0:
+ return i + 1
+ depth -= 1
+ word = c in " \t\n;|&(){}=,"
+ i += 1
+ return i
+
+
+def css_spans(s, base=0):
+ out, i = [], 0
+ while i < len(s):
+ c = s[i]
+ if c in "'\"":
+ j = i + 1
+ while s[j] != c:
+ j += 2 if s[j] == "\\" else 1
+ i = j + 1
+ elif s.startswith("/*", i):
+ j = s.index("*/", i + 2) + 2
+ out.append((base + i, base + j))
+ i = j
+ else:
+ i += 1
+ return out
+
+
+def html_spans(s):
+ out, i = [], 0
+ while True:
+ m = re.compile(r"<!--|<script\b[^>]*>|<style\b[^>]*>", re.I).search(s, i)
+ if not m:
+ return out
+ if m.group(0) == "<!--":
+ j = s.index("-->", m.end()) + 3
+ out.append((m.start(), j))
+ i = j
+ continue
+ tag = "script" if m.group(0).lower().startswith("<script") else "style"
+ end = s.lower().index("</" + tag, m.end())
+ inner = s[m.end():end]
+ if tag == "style":
+ out += css_spans(inner, m.end())
+ elif "src=" not in m.group(0) and "json" not in m.group(0):
+ out += [(m.end() + a, m.end() + b) for a, b in CLike(inner, "js").run()]
+ i = end
+
+
+def offsets(src):
+ starts, pos = [0], 0
+ for line in src.splitlines(keepends=True):
+ pos += len(line)
+ starts.append(pos)
+ return starts
+
+def py_spans(src, path):
+ tree = ast.parse(src)
+ usage = "__doc__" in src
+ starts = offsets(src)
+ lines = src.splitlines(keepends=True)
+ at = lambda line, col: starts[line - 1] + len(lines[line - 1].encode()[:col].decode())
+ spans, holders = [], []
+ for node in ast.walk(tree):
+ if isinstance(node, (ast.Module, ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and node.body:
+ first = node.body[0]
+ if isinstance(first, ast.Expr) and isinstance(first.value, ast.Constant) and isinstance(first.value.value, str):
+ if usage and isinstance(node, ast.Module):
+ continue
+ a, b = at(first.lineno, first.col_offset), at(first.end_lineno, first.end_col_offset)
+ spans.append((a, b, "doc", len(node.body) == 1))
+ for tok in tokenize.generate_tokens(io.StringIO(src).readline):
+ if tok.type == tokenize.COMMENT:
+ a = starts[tok.start[0] - 1] + tok.start[1]
+ spans.append((a, a + len(tok.string), "#", False))
+ return spans
+
+def spans_for(path, src):
+ ext = path.suffix
+ if ext in C_LIKE:
+ return [(a, b, None, False) for a, b in CLike(src, C_LIKE[ext]).run()]
+ if ext == ".py":
+ return py_spans(src, path)
+ if ext == ".ps1":
+ return [(a, b, None, False) for a, b in Ps(src).run()]
+ if ext == ".css":
+ return [(a, b, None, False) for a, b in css_spans(src)]
+ if ext == ".html":
+ return [(a, b, None, False) for a, b in html_spans(src)]
+ if ext == ".sh" or (ext == "" and src.startswith("#!") and "sh" in src.split("\n", 1)[0]):
+ return [(a, b, None, False) for a, b in Sh(src).run()]
+ return []
+
+CUT = "\x00"
+
+
+def drop(src, spans):
+ spans = [sp for sp in spans if not (sp[0] == 0 and src.startswith("#!"))]
+ spans = [sp for sp in spans if not kept(src[sp[0]:sp[1]]) or sp[2] == "doc"]
+ if not spans:
+ return src
+ out, last = [], 0
+ for a, b, kind, only in sorted(spans):
+ ls = src.rfind("\n", 0, a) + 1
+ le = src.find("\n", b)
+ le = len(src) if le < 0 else le
+ before, after = src[ls:a], src[b:le]
+ if not before.strip() and not after.strip():
+ if only:
+ out.append(src[last:a] + "pass")
+ last = b
+ else:
+ out.append(src[last:ls] + CUT)
+ last = le + 1
+ else:
+ seg = src[last:a]
+ nxt = src[b:b + 1]
+ if not after.strip():
+ seg = seg.rstrip(" \t")
+ elif seg[-1:].isspace() and (nxt.isspace() or nxt in ",;)]}"):
+ seg = seg.rstrip(" \t")
+ elif seg[-1:] and not seg[-1:].isspace() and nxt and not nxt.isspace() and seg[-1] not in "([{" and nxt not in ")]},;":
+ seg += " "
+ if only:
+ seg += "pass"
+ out.append(seg)
+ last = b
+ out.append(src[last:])
+ return tidy("".join(out))
+
+
+def tidy(text):
+ lines, res = text.split("\n"), []
+ for line in lines:
+ if not line.startswith(CUT):
+ res.append(line)
+ continue
+ line = line.lstrip(CUT)
+ prev = res[-1] if res else None
+ blank = not line.strip()
+ if blank and (prev is None or not prev.strip() or prev.rstrip().endswith(("{", "(", "[", ":")) or prev.startswith("#!")):
+ continue
+ if prev is not None and not prev.strip() and line.lstrip().startswith(("}", ")", "]")):
+ res.pop()
+ res.append(line)
+ return "\n".join(res)
+
+def tracked():
+ files = subprocess.run(["git", "ls-files"], capture_output=True, text=True, check=True).stdout.split()
+ files = [f for f in files if not f.startswith("docs/")]
+ return [f for f in files if Path(f).suffix in C_LIKE or Path(f).suffix in HASH or Path(f).suffix in MARKUP or
+ (Path(f).suffix == "" and Path(f).is_file() and Path(f).read_bytes()[:2] == b"#!" and b"sh" in Path(f).read_bytes().split(b"\n", 1)[0])]
+
+def main():
+ if len(sys.argv) < 2 or sys.argv[1] not in ("check", "strip", "list"):
+ sys.exit(__doc__)
+ mode, files = sys.argv[1], sys.argv[2:] or tracked()
+ bad = 0
+ for f in files:
+ p = Path(f)
+ if not p.is_file():
+ continue
+ src = p.read_text(encoding="utf-8")
+ try:
+ spans = spans_for(p, src)
+ except (SyntaxError, ValueError, IndexError) as e:
+ print(f"{f}: cannot scan: {e}", file=sys.stderr)
+ bad += 1
+ continue
+ if mode == "strip":
+ new = src
+ for a, b, kind, _ in sorted(spans, reverse=True):
+ m = kind != "doc" and REASON.match(src[a:b])
+ if m:
+ new = new[:a] + m.group(1) + new[b:]
+ new = drop(new, spans_for(p, new))
+ if new != src:
+ p.write_text(new, encoding="utf-8")
+ continue
+ for a, b, kind, _ in spans:
+ text = src[a:b]
+ if (a == 0 and text.startswith("#!")) or (kind != "doc" and kept(text) and not REASON.match(text)):
+ continue
+ bad += 1
+ if mode == "list" or bad <= 20:
+ line = src.count("\n", 0, a) + 1
+ print(f"{f}:{line}: {text.splitlines()[0][:100]}")
+ if mode == "check" and bad:
+ print(f"{bad} comments: only TODO, FIXME, MARK, tool directives and license lines are allowed "
+ f"(scripts/comments.py strip <file> removes the rest)", file=sys.stderr)
+ sys.exit(1 if bad and mode != "list" else 0)
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/lint-baseline.txt b/scripts/lint-baseline.txt
new file mode 100644
index 0000000..88e9c2d
--- /dev/null
+++ b/scripts/lint-baseline.txt
@@ -0,0 +1,26 @@
+.claude/skills/audio-test/scripts/room-round.sh: error: ShellCheck only supports sh/bash/dash/ksh/'busybox sh' scripts. Sorry! [SC1071]
+.claude/skills/audio-test/scripts/speak-round.sh: error: ShellCheck only supports sh/bash/dash/ksh/'busybox sh' scripts. Sorry! [SC1071]
+Sources/Cicada/AppModel.swift: warning: unnecessary check for 'macOS'; enclosing scope ensures guard will always be true
+Sources/Cicada/Diagnostics.swift: warning: 'appendInterpolation' is deprecated: Localized string interpolation produces an unlocalized, debug description for this type of value. Use String(describing:) to make this explicit and silence this warning or provide a different value that has built-in support or conforms to CustomLocalizedStringResourceConvertible.
+Sources/Cicada/DiagnosticsView.swift: warning: cannot use enum 'Publishers' in a property declaration member of a type not marked '@_implementationOnly'; 'Combine' was not imported by this file
+Sources/Cicada/DiagnosticsView.swift: warning: cannot use generic class 'Autoconnect' in a property declaration member of a type not marked '@_implementationOnly'; 'Combine' was not imported by this file
+Sources/Cicada/ListenPill.swift: warning: cannot use enum 'Publishers' in a property declaration member of a type not marked '@_implementationOnly'; 'Combine' was not imported by this file
+Sources/Cicada/ListenPill.swift: warning: cannot use generic class 'Autoconnect' in a property declaration member of a type not marked '@_implementationOnly'; 'Combine' was not imported by this file
+Sources/Cicada/LocalNetwork.swift: warning: concurrently-executed local function 'finish' must be marked as '@Sendable'; this is an error in the Swift 6 language mode
+Sources/Cicada/NotesViews.swift: warning: cannot use enum 'Publishers' in a property declaration member of a type not marked '@_implementationOnly'; 'Combine' was not imported by this file
+Sources/Cicada/NotesViews.swift: warning: cannot use generic class 'Autoconnect' in a property declaration member of a type not marked '@_implementationOnly'; 'Combine' was not imported by this file
+Sources/Cicada/SpeakEngine.swift: warning: add '@preconcurrency' to suppress 'Sendable'-related warnings from module 'AVFAudio'
+Sources/Cicada/SpeakEngine.swift: warning: capture of 'buf' with non-Sendable type 'AVAudioPCMBuffer' in a '@Sendable' closure
+Sources/Cicada/SpeakEngine.swift: warning: capture of 'conv' with non-Sendable type 'PCMConverter' in a '@Sendable' closure
+Sources/Cicada/SpeakEngine.swift: warning: capture of 's' with non-Sendable type '[AVAudioPCMBuffer]' in a '@Sendable' closure
+Sources/Cicada/SpeakEngine.swift: warning: consider using asynchronous alternative function
+Sources/Cicada/Updates.swift: warning: 'weak' ownership of capture 'self' differs from implicitly-captured strong reference in outer scope
+Sources/Cicada/VirtualMic.swift: warning: 'weak' ownership of capture 'self' differs from implicitly-captured strong reference in outer scope
+ios/scripts/build.sh: warning: Quote this to prevent word splitting. [SC2046]
+ios/scripts/host-recognizer.sh: warning: Prefer mapfile or read -a to split command output (or quote to avoid splitting). [SC2207]
+ios/scripts/host-recognizer.sh: warning: Prefer mapfile or read -a to split command output (or quote to avoid splitting). [SC2207]
+tools/audio-probe/clips.sh: error: ShellCheck only supports sh/bash/dash/ksh/'busybox sh' scripts. Sorry! [SC1071]
+tools/macos-vm/vm.sh: warning: Tilde does not expand in quotes. Use $HOME. [SC2088]
+windows/scripts/build.sh: warning: Don't use ls | grep. Use a glob or a for loop with a condition to allow non-alphanumeric filenames. [SC2010]
+windows/vm/run.sh: warning: Use spaces, not commas, to separate array elements. [SC2054]
+windows/vm/run.sh: warning: Use spaces, not commas, to separate array elements. [SC2054]
diff --git a/scripts/lint.py b/scripts/lint.py
new file mode 100755
index 0000000..5a0ce16
--- /dev/null
+++ b/scripts/lint.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python3
+"""Usage: lint.py [--staged] [--update-baseline]
+
+--staged: only the files about to be committed, and no Swift build (the pre-commit hook).
+--update-baseline: accept today's compiler and shellcheck warnings into scripts/lint-baseline.txt."""
+import collections, re, shutil, subprocess, sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+BASELINE = ROOT / "scripts/lint-baseline.txt"
+ANSI = re.compile(r"\x1b\[[0-9;]*m|\x1b\]8;;[^\x1b]*\x1b\\")
+
+
+def git(*args):
+ return subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True, check=True).stdout.split("\n")
+
+
+def files(staged):
+ names = git("diff", "--cached", "--name-only", "--diff-filter=ACMR") if staged else git("ls-files")
+ return [n for n in names if n and (ROOT / n).is_file()]
+
+
+def is_shell(name):
+ p = ROOT / name
+ if p.suffix == ".sh":
+ return True
+ if p.suffix:
+ return False
+ head = p.read_bytes()[:64].split(b"\n", 1)[0]
+ return head.startswith(b"#!") and b"sh" in head and b"python" not in head
+
+
+def shellcheck(names):
+ if not names or not shutil.which("shellcheck"):
+ return []
+ out = subprocess.run(["shellcheck", "-S", "warning", "-f", "gcc", *names], cwd=ROOT,
+ capture_output=True, text=True).stdout
+ return [re.sub(r":\d+:\d+:", ":", line) for line in out.splitlines() if line]
+
+
+def swift_warnings():
+ for d in ("Sources/Cicada", "Sources/CicadaIcon"):
+ for f in (ROOT / d).glob("*.swift"):
+ f.touch()
+ out = subprocess.run(["swift", "build", "--build-path", ".build/lint"], cwd=ROOT,
+ capture_output=True, text=True)
+ text = ANSI.sub("", out.stdout + out.stderr)
+ if out.returncode:
+ print(text[-4000:], file=sys.stderr)
+ sys.exit("lint: swift build failed")
+ found = set()
+ for m in re.finditer(r"^(/\S+?):\d+:\d+: warning: (.+?)(?: \[#\w+\])?$", text, re.M):
+ found.add(f"{Path(m.group(1)).relative_to(ROOT)}: warning: {m.group(2)}")
+ return sorted(found)
+
+
+def main():
+ if set(sys.argv[1:]) - {"--staged", "--update-baseline"}:
+ sys.exit(__doc__)
+ staged = "--staged" in sys.argv
+ if staged and "--update-baseline" in sys.argv:
+ sys.exit("lint: --update-baseline needs the full run")
+ names = files(staged)
+ errors = []
+
+ if not staged or "AGENTS.md" in names:
+ if subprocess.run([sys.executable, "scripts/check-agents.py"], cwd=ROOT).returncode:
+ errors.append("AGENTS.md")
+
+ source = [n for n in names if Path(n).suffix in (".swift", ".kt", ".kts", ".cs", ".c", ".h", ".js", ".mjs", ".py", ".ps1", ".html", ".css") or is_shell(n)]
+ source = [n for n in source if not n.startswith("docs/")]
+ if source and subprocess.run([sys.executable, "scripts/comments.py", "check", *source], cwd=ROOT).returncode:
+ errors.append("comments")
+
+ for n in names:
+ if n.endswith(".py"):
+ try:
+ compile((ROOT / n).read_bytes(), n, "exec")
+ except SyntaxError as e:
+ print(f"{n}:{e.lineno}: {e.msg}", file=sys.stderr)
+ errors.append(n)
+ elif n.endswith((".js", ".mjs")) and shutil.which("node"):
+ if subprocess.run(["node", "--check", n], cwd=ROOT).returncode:
+ errors.append(n)
+ shells = [n for n in names if is_shell(n)]
+ for n in shells:
+ if subprocess.run(["bash", "-n", n], cwd=ROOT).returncode:
+ errors.append(n)
+
+ warnings = shellcheck(shells)
+ if not staged:
+ warnings += swift_warnings()
+ if "--update-baseline" in sys.argv:
+ BASELINE.write_text("".join(w + "\n" for w in sorted(warnings)), encoding="utf-8")
+ print(f"lint: {len(warnings)} warnings in the baseline")
+ else:
+ known = collections.Counter(BASELINE.read_text(encoding="utf-8").splitlines()) if BASELINE.exists() else collections.Counter()
+ new = collections.Counter(warnings) - known
+ for w in sorted(new.elements()):
+ print(w, file=sys.stderr)
+ if new:
+ errors.append(f"{sum(new.values())} new warnings (fix them; scripts/lint.py --update-baseline only for ones that must stay)")
+
+ if errors:
+ sys.exit("lint failed: " + ", ".join(errors))
+ print("lint ok")
+
+
+if __name__ == "__main__":
+ main()