napkinstack 0.30.0__tar.gz → 0.31.0__tar.gz

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.
Files changed (41) hide show
  1. {napkinstack-0.30.0 → napkinstack-0.31.0}/PKG-INFO +5 -5
  2. {napkinstack-0.30.0 → napkinstack-0.31.0}/README.md +4 -4
  3. {napkinstack-0.30.0 → napkinstack-0.31.0}/pyproject.toml +1 -1
  4. {napkinstack-0.30.0 → napkinstack-0.31.0}/pyproject.toml.orig +1 -1
  5. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/board.py +39 -4
  6. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/cli.py +4 -3
  7. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/doctor.py +50 -3
  8. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/evidence.py +2 -1
  9. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/fitness/manifests.py +3 -3
  10. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/fitness/plan.py +20 -8
  11. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/modules.py +8 -4
  12. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/project.py +49 -0
  13. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/pull_request.py +77 -7
  14. {napkinstack-0.30.0 → napkinstack-0.31.0}/LICENSE +0 -0
  15. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/__init__.py +0 -0
  16. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/__main__.py +0 -0
  17. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/agent.py +0 -0
  18. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/assurance.py +0 -0
  19. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/attest.py +0 -0
  20. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/compat.py +0 -0
  21. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/discovery.py +0 -0
  22. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/fitness/__init__.py +0 -0
  23. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/fitness/boundaries.py +0 -0
  24. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/fitness/hygiene.py +0 -0
  25. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/fitness/pr_scope.py +0 -0
  26. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/hold.py +0 -0
  27. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/landed.py +0 -0
  28. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/owners.py +0 -0
  29. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/provenance.py +0 -0
  30. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/settings.py +0 -0
  31. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/skills.py +0 -0
  32. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/templates/contracts/AGENTS.md +0 -0
  33. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/templates/contracts/MANIFEST.yaml +0 -0
  34. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/templates/contracts/README.md +0 -0
  35. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/templates/contracts/docs/runbook.md +0 -0
  36. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/templates/contracts/tests/.gitkeep +0 -0
  37. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/templates/module/AGENTS.md +0 -0
  38. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/templates/module/MANIFEST.yaml +0 -0
  39. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/templates/module/README.md +0 -0
  40. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/templates/module/src/.gitkeep +0 -0
  41. {napkinstack-0.30.0 → napkinstack-0.31.0}/src/napkinstack/templates/module/tests/.gitkeep +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: napkinstack
3
- Version: 0.30.0
3
+ Version: 0.31.0
4
4
  Summary: Engineering framework for several teams and their agents working in one repository: modules, contracts, guardrails in CI.
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -22,7 +22,7 @@ modules, contracts, guardrails in CI. On the Django or Rails model, one command
22
22
  the project, which then receives new versions on demand; no application stack is imposed.
23
23
  Positioning and vocabulary: [`PRODUCT.md`](PRODUCT.md) §1.
24
24
 
25
- > **Status: v0.30.0, published** on [PyPI](https://pypi.org/project/napkinstack/).
25
+ > **Status: v0.31.0, published** on [PyPI](https://pypi.org/project/napkinstack/).
26
26
  > What each version changes, engine and project apart: [`CHANGELOG.md`](CHANGELOG.md).
27
27
  > What is open: [`docs/governance/workstreams.md`](docs/governance/workstreams.md).
28
28
 
@@ -86,8 +86,8 @@ To try it without installing anything, or to install it from this repository ins
86
86
  registry — always pinned to a release tag:
87
87
 
88
88
  ```bash
89
- uvx --from "git+https://github.com/NapkinStack/engineering-os@v0.30.0" nstack init my-project
90
- uv tool install "napkinstack @ git+https://github.com/NapkinStack/engineering-os@v0.30.0"
89
+ uvx --from "git+https://github.com/NapkinStack/engineering-os@v0.31.0" nstack init my-project
90
+ uv tool install "napkinstack @ git+https://github.com/NapkinStack/engineering-os@v0.31.0"
91
91
  ```
92
92
 
93
93
  **Two channels, one published artefact.** The registry publishes: the PyPI artefact of a
@@ -117,7 +117,7 @@ Each project then pins its version and changes it through `nstack update`.
117
117
  | `nstack claim <deliverable or '#issue'> [--take-over]`; `nstack unclaim …` | Takes a ready deliverable — or an issue no cycle plans — for a session before its first change, on a branch of its own the shared remote refuses to a second taker; gives it back ([ADR-0007](docs/adr/0007-hold-a-deliverable-on-a-branch-of-its-own.md)) |
118
118
  | `nstack deliver <deliverable> --held [N=]#PR` | Records that a merged deliverable is delivered, criterion by criterion, with no pull request; refused with no merge of it; `--write-states` writes the states at a closure ([PDR-0022](docs/pdr/0022-agents-deliver-alone-a-person-is-asked-only-where-it-matters.md)) |
119
119
  | `nstack agent add <name>`; `nstack agent run <name> -- <command>`; `nstack agent status` | Gives an agent its own GitHub App and a clone that commits as it and runs the project's hooks — `add` is a person's, two clicks at the forge; starts the agent there without the person's credentials, says what it keeps of them, gives Claude Code settings of its own; `status` tells an agent who it is, a person this project's agents (`--all`: every project's) ([ADR-0004](docs/adr/0004-give-agents-their-own-github-identity.md)) |
120
- | `nstack board [--dry-run]` | Shows the cycles and their deliverables on the forge, one way: milestones and issues ([ADR-0008](docs/adr/0008-show-the-plan-as-milestones-and-issues-applied-by-ci.md)) |
120
+ | `nstack board [--dry-run]` | Shows the cycles and their deliverables on the forge, one way: milestones and issues ([ADR-0008](docs/adr/0008-show-the-plan-as-milestones-and-issues-applied-by-ci.md)); a dry run also previews what a proposed cycle's acceptance would create |
121
121
  | `nstack fitness` | Manifests, boundaries between modules, skills, plan, hygiene — each also runs alone: `manifests`, `boundaries`, `skills`, `plan`, `hygiene` |
122
122
  | `nstack pr-scope` | One PR = one module, review budget |
123
123
  | `nstack modules [--changed-since <base>]` | The project's modules, or those with a file changed since a base |
@@ -5,7 +5,7 @@ modules, contracts, guardrails in CI. On the Django or Rails model, one command
5
5
  the project, which then receives new versions on demand; no application stack is imposed.
6
6
  Positioning and vocabulary: [`PRODUCT.md`](PRODUCT.md) §1.
7
7
 
8
- > **Status: v0.30.0, published** on [PyPI](https://pypi.org/project/napkinstack/).
8
+ > **Status: v0.31.0, published** on [PyPI](https://pypi.org/project/napkinstack/).
9
9
  > What each version changes, engine and project apart: [`CHANGELOG.md`](CHANGELOG.md).
10
10
  > What is open: [`docs/governance/workstreams.md`](docs/governance/workstreams.md).
11
11
 
@@ -69,8 +69,8 @@ To try it without installing anything, or to install it from this repository ins
69
69
  registry — always pinned to a release tag:
70
70
 
71
71
  ```bash
72
- uvx --from "git+https://github.com/NapkinStack/engineering-os@v0.30.0" nstack init my-project
73
- uv tool install "napkinstack @ git+https://github.com/NapkinStack/engineering-os@v0.30.0"
72
+ uvx --from "git+https://github.com/NapkinStack/engineering-os@v0.31.0" nstack init my-project
73
+ uv tool install "napkinstack @ git+https://github.com/NapkinStack/engineering-os@v0.31.0"
74
74
  ```
75
75
 
76
76
  **Two channels, one published artefact.** The registry publishes: the PyPI artefact of a
@@ -100,7 +100,7 @@ Each project then pins its version and changes it through `nstack update`.
100
100
  | `nstack claim <deliverable or '#issue'> [--take-over]`; `nstack unclaim …` | Takes a ready deliverable — or an issue no cycle plans — for a session before its first change, on a branch of its own the shared remote refuses to a second taker; gives it back ([ADR-0007](docs/adr/0007-hold-a-deliverable-on-a-branch-of-its-own.md)) |
101
101
  | `nstack deliver <deliverable> --held [N=]#PR` | Records that a merged deliverable is delivered, criterion by criterion, with no pull request; refused with no merge of it; `--write-states` writes the states at a closure ([PDR-0022](docs/pdr/0022-agents-deliver-alone-a-person-is-asked-only-where-it-matters.md)) |
102
102
  | `nstack agent add <name>`; `nstack agent run <name> -- <command>`; `nstack agent status` | Gives an agent its own GitHub App and a clone that commits as it and runs the project's hooks — `add` is a person's, two clicks at the forge; starts the agent there without the person's credentials, says what it keeps of them, gives Claude Code settings of its own; `status` tells an agent who it is, a person this project's agents (`--all`: every project's) ([ADR-0004](docs/adr/0004-give-agents-their-own-github-identity.md)) |
103
- | `nstack board [--dry-run]` | Shows the cycles and their deliverables on the forge, one way: milestones and issues ([ADR-0008](docs/adr/0008-show-the-plan-as-milestones-and-issues-applied-by-ci.md)) |
103
+ | `nstack board [--dry-run]` | Shows the cycles and their deliverables on the forge, one way: milestones and issues ([ADR-0008](docs/adr/0008-show-the-plan-as-milestones-and-issues-applied-by-ci.md)); a dry run also previews what a proposed cycle's acceptance would create |
104
104
  | `nstack fitness` | Manifests, boundaries between modules, skills, plan, hygiene — each also runs alone: `manifests`, `boundaries`, `skills`, `plan`, `hygiene` |
105
105
  | `nstack pr-scope` | One PR = one module, review budget |
106
106
  | `nstack modules [--changed-since <base>]` | The project's modules, or those with a file changed since a base |
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "napkinstack"
3
- version = "0.30.0"
3
+ version = "0.31.0"
4
4
  description = "Engineering framework for several teams and their agents working in one repository: modules, contracts, guardrails in CI."
5
5
  requires-python = ">=3.12"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "napkinstack"
3
- version = "0.30.0"
3
+ version = "0.31.0"
4
4
  description = "Engineering framework for several teams and their agents working in one repository: modules, contracts, guardrails in CI."
5
5
  requires-python = ">=3.12"
6
6
  license = "MIT"
@@ -2,7 +2,8 @@
2
2
  The plan shown on the forge, one way (PDR-0016, ADR-0008).
3
3
 
4
4
  The cycle files are the plan; this command shows them on GitHub — a milestone per accepted,
5
- closed or stopped cycle, an issue per deliverable — and keeps the display equal to them. Its own
5
+ closed or stopped cycle, an issue per deliverable — and keeps the display equal to them. A dry
6
+ run also previews what a proposed cycle's acceptance would create, and makes none of it. Its own
6
7
  objects carry a marker in their body; an object without one is never touched. What the forge
7
8
  holds decides nothing but whether the display must be rewritten.
8
9
 
@@ -72,7 +73,8 @@ def _reason(state: str) -> str:
72
73
 
73
74
 
74
75
  def desired(root: Path, holders: dict[str, str] | None = None, pulls: dict[str, list[int]] | None = None,
75
- today: datetime.date | None = None, delivered: set[str] | None = None) -> tuple[list[Shown], list[str]]:
76
+ today: datetime.date | None = None, delivered: set[str] | None = None,
77
+ statuses: set[str] = SHOWN) -> tuple[list[Shown], list[str]]:
76
78
  """The display the cycle files call for, and what cannot be shown and why. `holders`:
77
79
  deliverable identifier to the hold's person; `pulls`: identifier to the pull requests whose
78
80
  description names it."""
@@ -81,7 +83,7 @@ def desired(root: Path, holders: dict[str, str] | None = None, pulls: dict[str,
81
83
  for path in plan.cycle_files(root):
82
84
  data = plan.read_front_matter(path)[0]
83
85
  found = NUMBER.match(path.stem)
84
- if data and plan.one_of(data.get("status"), SHOWN) and found:
86
+ if data and plan.one_of(data.get("status"), statuses) and found:
85
87
  cycles.setdefault(found[1], []).append((path, data))
86
88
  said = [f"cycle {number} not shown: {len(files)} cycle files carry its number "
87
89
  f"({', '.join(path.name for path, _ in files)})" for number, files in cycles.items() if len(files) > 1]
@@ -99,7 +101,7 @@ def desired(root: Path, holders: dict[str, str] | None = None, pulls: dict[str,
99
101
  continue
100
102
  path, data = files[0]
101
103
  relative = path.relative_to(root).as_posix()
102
- closed = data.get("status") != "accepted"
104
+ closed = data.get("status") not in ("accepted", "proposed") # proposed: only ever previewed
103
105
  text = path.read_text(encoding="utf-8", errors="replace")
104
106
  front = plan.FRONT_MATTER.match(text)
105
107
  heading = HEADING.search(text[front.end():] if front else text)
@@ -206,6 +208,8 @@ def _clean(text) -> str:
206
208
  def run(root: Path, dry_run: bool = False, today: datetime.date | None = None) -> int:
207
209
  from napkinstack import hold
208
210
 
211
+ if dry_run:
212
+ _preview(root, today)
209
213
  first, said = desired(root, today=today)
210
214
  if not first:
211
215
  _tell(said, "Plan on the forge: nothing to show — no accepted, closed or stopped cycle")
@@ -240,6 +244,37 @@ def run(root: Path, dry_run: bool = False, today: datetime.date | None = None) -
240
244
  return 0
241
245
 
242
246
 
247
+ def _preview(root: Path, today: datetime.date | None) -> None:
248
+ """What a proposed cycle's acceptance would create, said on a dry run and never made (#372): the
249
+ decider reviews the breakdown as the board will show it, before the acceptance decides it."""
250
+ numbers, idents = set(), set()
251
+ for path in plan.cycle_files(root):
252
+ data = plan.read_front_matter(path)[0]
253
+ found = NUMBER.match(path.stem)
254
+ if data and data.get("status") == "proposed" and found:
255
+ numbers.add(found[1])
256
+ items = data.get("deliverables")
257
+ idents |= {str(item["id"]) for item in items if isinstance(item, dict) and item.get("id")} \
258
+ if isinstance(items, list) else set()
259
+ if not numbers:
260
+ return
261
+ # Read beside the cycles already shown: what their acceptance would collide with is said too.
262
+ every, said = desired(root, today=today, statuses=SHOWN | {"proposed"})
263
+ for number in sorted(numbers):
264
+ cycle = next((item for item in every if item.kind == "cycle" and item.key == number), None)
265
+ if cycle is None:
266
+ continue
267
+ print(f"On acceptance of cycle {number} — previewed, nothing made:\n"
268
+ f" milestone {cycle.title}, ends {cycle.due or 'with no end date'}")
269
+ for item in every:
270
+ if item.kind == "deliverable" and item.cycle == number:
271
+ state = item.labels[-1].removeprefix("state: ") if item.labels else ""
272
+ print(f" issue {item.title} — {state}" + (", shown closed" if item.state == "closed" else ""))
273
+ for line in said:
274
+ if any(re.search(rf"\b{re.escape(key)}\b", line) for key in numbers | idents):
275
+ print(f" NOTE on acceptance: {line}")
276
+
277
+
243
278
  def _tell(lines: list[str], head: str) -> None:
244
279
  """Said in the output; in GitHub Actions, also in the job's summary, and what was not shown as
245
280
  a warning a person sees on the run."""
@@ -121,7 +121,7 @@ def build_parser() -> argparse.ArgumentParser:
121
121
  lambda a: modules.create(a.root, a.name, a.owner, a.criticality, a.user_facing))
122
122
  nm.add_argument("name", help="module name, kebab-case")
123
123
  nm.add_argument("owner", help="GitHub team, organisation/team, or a user when the project has "
124
- "no organisation")
124
+ "no organisation — on GitHub, never an organisation's name alone")
125
125
  nm.add_argument("criticality", choices=list(assurance.CRITICALITIES),
126
126
  help="what a failure of this module costs — prototype: nothing, it is "
127
127
  "thrown away and nothing depends on it · standard: real code, no "
@@ -209,7 +209,7 @@ def build_parser() -> argparse.ArgumentParser:
209
209
  dl.add_argument("--write-states", action="store_true", help="at a closure: writes the records' states in the cycle file, for its one pull request")
210
210
  bd = _add(sub, "board", "shows the cycles and their deliverables on the forge, one way: milestones and issues",
211
211
  lambda a: board.run(a.root, a.dry_run))
212
- bd.add_argument("--dry-run", action="store_true", help="say what would change, change nothing")
212
+ bd.add_argument("--dry-run", action="store_true", help="say what would change, change nothing — and preview what a proposed cycle's acceptance would create")
213
213
  ds = _add(sub, "discover", "starts a discovery from an idea file, for the team's agent",
214
214
  lambda a: discovery.run(a.root, a.idea))
215
215
  ds.add_argument("idea", type=Path, help="the idea, a .md or .txt file")
@@ -252,7 +252,8 @@ def build_parser() -> argparse.ArgumentParser:
252
252
  ini.add_argument("--repository", help="the repository's path at another forge, group/name or "
253
253
  "group/subgroup/name (asked when absent)")
254
254
  ini.add_argument("--owner-team", help="owner of the foundation: organisation/team, or a user "
255
- "when the project has no organisation (asked when absent)")
255
+ "when the project has no organisation — on GitHub, never an "
256
+ "organisation's name alone (asked when absent)")
256
257
  ini.add_argument("--source", help="template: URL or path (default: the NapkinStack repository)")
257
258
  ini.add_argument("--ref", help="skeleton version: a tag vX.Y.Z, or a commit (default: the one of nstack)")
258
259
  ini.set_defaults(func=_init)
@@ -12,7 +12,8 @@ either: whether its default branch holds that commit (GITHUB_API_URL, otherwise
12
12
  https://api.github.com). No answer leaves L1 as it is.
13
13
 
14
14
  GitHub is read with a token supplied by a human (GH_TOKEN, otherwise GITHUB_TOKEN):
15
- fine-grained, limited to the repository, Administration: read permission (Actions: read for N2). Without a token,
15
+ fine-grained, limited to the repository, Administration: read permission (Actions: read for N2,
16
+ Contents: read for L10 on a private repository). Without a token,
16
17
  or when the API refuses a read, the setting is "not verified", never compliant. No write.
17
18
 
18
19
  Rules:
@@ -35,6 +36,10 @@ Rules:
35
36
  L9 the `forge` answer is the one the project's files were written for — never changed by
36
37
  hand, which Copier would misread; `nstack update --forge` changes it. A remote on another
37
38
  known public forge is said, never judged: a mirror is a choice
39
+ L10 on GitHub, every owner the code owners file names is one GitHub knows, read from GitHub's
40
+ own validation of the default branch's file (#382): an organisation by its bare name, a
41
+ deleted user or a team without access is no owner. Unread — a private repository and a token
42
+ without Contents: read — it is said, never counted
38
43
  N1 information, never a gap (D91): a published version newer than the project's, read from
39
44
  the registry — the one place a project learns of it. Elsewhere, only `nstack update` asks
40
45
  it, whether the version it lays is published yet (D201)
@@ -59,6 +64,7 @@ Output: 0 when everything is verified and compliant; 1 when a setting is missin
59
64
  from __future__ import annotations
60
65
 
61
66
  import fnmatch
67
+ import http.client
62
68
  import json
63
69
  import os
64
70
  import re
@@ -79,6 +85,7 @@ from napkinstack.project import ANSWERS
79
85
  OK, GAP, UNKNOWN, NOT_APPLICABLE = "OK", "FAIL", "NOT VERIFIED", "NOT APPLICABLE"
80
86
  SOURCES = "SOURCES" # a contributor's checkout holding the project's version: said, not a gap (D136)
81
87
  OUT_OF_REACH = "OUT OF REACH" # the plan forbids it: a state, not a fault (PDR-0006)
88
+ NOT_READ = "NOT READ" # an optional read that did not answer: said, never counted (L10)
82
89
  # The settings that make the forge refuse a merge. A repository is guarded when they are
83
90
  # all in force; the others matter and none of them stops a merge.
84
91
  BLOCKING = ("G1", "G2", "G3", "G4", "G12", "G13", "G21")
@@ -390,6 +397,40 @@ def _default_owner(root: Path) -> tuple[str, str]:
390
397
  "its first rule: the code owner review then covers every path (.nstack/handbook/07-governance.md §7).")
391
398
 
392
399
 
400
+ SHOWN_ERRORS = 5 # lines of GitHub's validation said one by one; the rest counted
401
+
402
+
403
+ def _owners_known(repo: str) -> tuple[str, str]:
404
+ """L10: the ownership file as GitHub validates it on the default branch (#382). An owner GitHub
405
+ does not know — an organisation by its bare name, a deleted user, a team without access — is
406
+ no owner: the paths it names have none. GitHub's own reading, not a second one: no syntax check
407
+ tells a user from an organisation. Unread, it is said and counted neither as a gap nor as
408
+ not verified: the token doctor asks for reads settings, not contents."""
409
+ api = (os.environ.get("GITHUB_API_URL") or "https://api.github.com").rstrip("/")
410
+ token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")
411
+ headers = {"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": API_VERSION,
412
+ "User-Agent": f"nstack/{__version__}"}
413
+ if token:
414
+ headers["Authorization"] = f"Bearer {token}"
415
+ request = urllib.request.Request(f"{api}/repos/{repo}/codeowners/errors", headers=headers)
416
+ try:
417
+ with urllib.request.urlopen(request, timeout=10) as response:
418
+ errors = json.load(response)["errors"]
419
+ lines = [f"line {error['line']}: {error['kind']} — {str(error['source']).strip()}" for error in errors]
420
+ except (OSError, ValueError, KeyError, TypeError, http.client.HTTPException) as error:
421
+ said = f"HTTP {error.code}" if isinstance(error, urllib.error.HTTPError) else type(error).__name__
422
+ return NOT_READ, (f"Reason: GitHub's validation of the file did not answer ({said}): no file on the "
423
+ "default branch, or a private repository out of the token's reach.\nTo read it: a "
424
+ "token that may also read the repository's contents (Contents: read).")
425
+ if not lines:
426
+ return OK, ""
427
+ more = f"\n…and {len(lines) - SHOWN_ERRORS} more" if len(lines) > SHOWN_ERRORS else ""
428
+ return GAP, ("GitHub reads no valid owner on these lines of the default branch's file:\n"
429
+ + "\n".join(lines[:SHOWN_ERRORS]) + more
430
+ + "\nAction: name a user, or a team written organisation/team, with write access to the "
431
+ "repository — never an organisation by its name (.nstack/handbook/07-governance.md §7).")
432
+
433
+
393
434
  def _kept_for_a_human(root: Path, shown: str, text: str) -> tuple[str, str]:
394
435
  """L6 on `approval: agent`: no default owner, and every path a human must approve ends on a
395
436
  rule with an owner (`owners.py`; in CI, rule M13)."""
@@ -522,14 +563,18 @@ def _workstation(root: Path, answers: dict) -> list[tuple[str, str, str, str]]:
522
563
  if answers.get("approval") == "agent" else "CODEOWNERS starts with a default owner",
523
564
  *_default_owner(root)))
524
565
 
566
+ from napkinstack.project import forge, remote_forge, written_for
567
+
568
+ if forge(root) == "github":
569
+ results.append(("L10", "Every owner CODEOWNERS names is one GitHub knows",
570
+ *_owners_known(str(answers.get("github_repo") or ""))))
571
+
525
572
  source = str(answers.get("_src_path") or "")
526
573
  local = not REMOTE.match(source)
527
574
  results.append(("L7", "Template source reachable by anyone", GAP if local else OK,
528
575
  f"The project was generated from '{source}', a path on one machine: nobody else can "
529
576
  "update it.\nAction: nstack update, from the published source." if local else ""))
530
577
 
531
- from napkinstack.project import forge, remote_forge, written_for
532
-
533
578
  name = forge(root)
534
579
  written, remote = written_for(root), remote_forge(root)
535
580
  if written is not None:
@@ -798,6 +843,8 @@ def run(root: Path) -> int:
798
843
  suffix = f", {skipped} not applicable" if skipped else ""
799
844
  if not gaps and not unknown:
800
845
  reach = f"; {out_of_reach} setting(s) out of reach on this plan" if out_of_reach else ""
846
+ unread = [rule for rule, _, status, _ in results if status == NOT_READ]
847
+ reach += f"; {', '.join(unread)} not read" if unread else ""
801
848
  print(f"\nnstack doctor: compliant{suffix}{reach}.")
802
849
  return 0
803
850
  print(f"\nnstack doctor: {gaps} gap(s), {unknown} not verified{suffix}.\nWorkflows inform; "
@@ -271,7 +271,8 @@ WAIT_SAID_EVERY = 60.0 # seconds between two lines of a run that waits: a long
271
271
 
272
272
  def sealed(manifest: Path) -> bool:
273
273
  """Whether the module declares its end-to-end run sealed, `evidence.sealed: true` (#402): its own
274
- session, sound server and ports — nothing of the machine's that another run reads."""
274
+ session, devices, ports, the files it writes and its processes, and timings that hold whatever the load
275
+ (#419) — nothing another run shares."""
275
276
  try:
276
277
  data = yaml.safe_load(manifest.read_text(encoding="utf-8")) or {}
277
278
  except (OSError, yaml.YAMLError):
@@ -411,9 +411,9 @@ def declared_evidence(manifests: list[Path], root: Path) -> None:
411
411
  if not isinstance(item["scenario"], str) or not item["scenario"].strip():
412
412
  fail(name, "M12", f"the declaration of {item['pattern']!r} names no scenario: say which provokes it.\n{action}", at)
413
413
  if "sealed" in section and not isinstance(section["sealed"], bool):
414
- fail(name, "M12", "evidence.sealed must be true or false: true when the module's end-to-end run brings its "
415
- "own session, sound server and ports, and reads nothing of the machine's another run "
416
- "reads.\n Action: evidence.sealed: true or false, or no key: the run then waits "
414
+ fail(name, "M12", "evidence.sealed must be true or false: true when the module's end-to-end run shares "
415
+ "nothing with another run — session, devices, ports, files it writes, processes — and "
416
+ "passes whatever the machine's load.\n Action: evidence.sealed: true or false, or no key: the run then waits "
417
417
  "its turn (.nstack/playbooks/tests.md).", at)
418
418
  if "levels" in section and not isinstance(section["levels"], str):
419
419
  fail(name, "M12", "evidence.levels must be text, a regular expression.\n"
@@ -9,7 +9,7 @@ Rules:
9
9
  C1 front matter readable: a YAML mapping at the top of the file
10
10
  C2 charter: status proposed or accepted, a decider who is one named person, at least
11
11
  one success criterion
12
- C3 cycle: a goal, a known status, appetite_weeks, start and end, end = start + appetite;
12
+ C3 cycle: a goal, a known status, appetite_weeks or appetite_days, start and end, end = start + appetite;
13
13
  accepted_on, when written, a date: the next cycle's acceptance while another runs
14
14
  C4 deliverables: ids D1, D2… unique, a title, a known state, acceptance criteria once ready
15
15
  C5 at most one accepted cycle, and only under an accepted charter
@@ -621,6 +621,9 @@ def _check_success(path: Path, data: dict, status, numbers: list[int] | None, fa
621
621
  fail("C6", path, f"{where}: observing since when? {action}")
622
622
 
623
623
 
624
+ APPETITES = {"appetite_weeks": "weeks", "appetite_days": "days"} # a cycle's key, and its unit
625
+
626
+
624
627
  def _check_cycle(path: Path, fail, numbers: list[int] | None = None) -> str | None:
625
628
  data, reason = read_front_matter(path)
626
629
  if data is None:
@@ -631,16 +634,25 @@ def _check_cycle(path: Path, fail, numbers: list[int] | None = None) -> str | No
631
634
  status = data.get("status")
632
635
  if not one_of(status, CYCLE_STATUSES):
633
636
  fail("C3", path, f"status '{status}': expected one of {sorted(CYCLE_STATUSES)}")
634
- weeks = data.get("appetite_weeks")
635
- if isinstance(weeks, bool) or not isinstance(weeks, int) or weeks < 1:
636
- fail("C3", path, "appetite_weeks: a whole number of weeks, decided rather than estimated")
637
- weeks = None
637
+ # The appetite in weeks, or in days for an engagement shorter than one (#370): one or the
638
+ # other, never both — one decision, and the one date it sets.
639
+ given = [unit for unit in APPETITES if data.get(unit) is not None] # a key left empty is no appetite
640
+ unit = given[0] if len(given) == 1 else None
641
+ amount = data.get(unit) if unit else None
642
+ if len(given) > 1:
643
+ fail("C3", path, "appetite_weeks and appetite_days both set: the appetite is one decision.\n"
644
+ " Action: keep one — appetite_days for a cycle shorter than a week")
645
+ amount = None
646
+ elif isinstance(amount, bool) or not isinstance(amount, int) or amount < 1:
647
+ fail("C3", path, "appetite_weeks, or appetite_days for a cycle counted in days: a whole number of at "
648
+ "least 1, decided rather than estimated")
649
+ amount = None
638
650
  start, end = as_date(data.get("start")), as_date(data.get("end"))
639
651
  if start is None or end is None:
640
652
  fail("C3", path, "start and end: dates, YYYY-MM-DD")
641
- elif weeks is not None and end != start + datetime.timedelta(weeks=weeks):
642
- fail("C3", path, f"end {end}: the appetite sets it, start + {weeks} week(s) = "
643
- f"{start + datetime.timedelta(weeks=weeks)}")
653
+ elif amount is not None and end != start + datetime.timedelta(**{APPETITES[unit]: amount}):
654
+ fail("C3", path, f"end {end}: the appetite sets it, start + {amount} {APPETITES[unit][:-1]}(s) = "
655
+ f"{start + datetime.timedelta(**{APPETITES[unit]: amount})}")
644
656
  if "accepted_on" in data and as_date(data.get("accepted_on")) is None:
645
657
  fail("C3", path, "accepted_on: the day the decider accepted this cycle, YYYY-MM-DD")
646
658
  _check_deliverables(path, data.get("deliverables"), fail)
@@ -20,7 +20,7 @@ from pathlib import Path
20
20
  import yaml
21
21
 
22
22
  from napkinstack import assurance
23
- from napkinstack.project import answer, forge, ownership
23
+ from napkinstack.project import answer, forge, organisation_owner, ownership
24
24
  from napkinstack.fitness.manifests import (changed_files, contract_entries, find_manifests,
25
25
  module_content)
26
26
 
@@ -73,6 +73,8 @@ def create(root: Path, name: str, owner: str, criticality: str, user_facing: boo
73
73
  "GitLab group/subgroup off GitHub — or a user when the project has no organisation, for "
74
74
  "example acme/billing (CODEOWNERS, .nstack/handbook/07-governance.md §7).")
75
75
  return 1
76
+ if forge(root) == "github" and organisation_owner(owner, "new-module", f"{owner}/<team>"):
77
+ return 1
76
78
  folder = root / "modules" / name
77
79
  if folder.exists():
78
80
  print(f"FAIL [new-module] modules/{name} already exists.")
@@ -160,18 +162,20 @@ def create_contract(root: Path, name: str, owner: str | None = None) -> int:
160
162
  except (OSError, yaml.YAMLError):
161
163
  answers = {}
162
164
  owner = owner or str(answers.get("owner_team") or "")
163
- if not owner_valid(root, owner):
165
+ module, folder = root / "contracts", root / "contracts" / name
166
+ created = not (module / "MANIFEST.yaml").is_file() # the owner is written only with the module
167
+ if created and not owner_valid(root, owner):
164
168
  print(f"FAIL [new-contract] no valid owner for the contracts module ('{owner}').\n"
165
169
  " Action: pass --owner organisation/team — a boundary is never orphaned "
166
170
  "(.nstack/handbook/03-contracts.md §2).")
167
171
  return 1
168
- module, folder = root / "contracts", root / "contracts" / name
172
+ if created and forge(root) == "github" and organisation_owner(owner, "new-contract", f"--owner {owner}/<team>"):
173
+ return 1
169
174
  if folder.exists():
170
175
  print(f"FAIL [new-contract] contracts/{name} already exists.\n Action: a change to it is a new "
171
176
  "version beside the first, never an edit of it (.nstack/handbook/03-contracts.md §4).")
172
177
  return 1
173
178
 
174
- created = not (module / "MANIFEST.yaml").is_file()
175
179
  if created:
176
180
  shutil.copytree(CONTRACTS, module, dirs_exist_ok=True)
177
181
  # The contact: the project's discussions on GitHub; elsewhere, the module's owner (ADR-0010).
@@ -12,11 +12,14 @@ hook and CI reject any remaining marker.
12
12
 
13
13
  from __future__ import annotations
14
14
 
15
+ import json
15
16
  import os
16
17
  import re
17
18
  import subprocess
18
19
  import sys
19
20
  import tempfile
21
+ import urllib.parse
22
+ import urllib.request
20
23
  from pathlib import Path
21
24
 
22
25
  import yaml
@@ -30,6 +33,47 @@ DOWNGRADE = re.compile(r"You are downgrading from (\S+) to (\S+)\.")
30
33
  GITHUB = re.compile(r"^(?:https://github\.com/|git@github\.com:|gh:)(?P<repo>[^/]+/[^/]+?)(?:\.git)?/?$")
31
34
 
32
35
 
36
+ def organisation_owner(owner: str, command: str, instead: str) -> bool:
37
+ """True, with the refusal printed, when a bare handle written as a code owner on GitHub names an
38
+ organisation (#382): GitHub takes a user, or a team as organisation/team — never an organisation
39
+ by its name, and every CODEOWNERS line naming it would have no valid owner. A team needs no
40
+ asking; a forge that does not answer lets the owner pass, said: `nstack doctor` reads the file as
41
+ GitHub validates it (L10). A token is sent when there is one: a server in private mode answers
42
+ no one without it."""
43
+ import http.client
44
+ import urllib.error
45
+
46
+ if "/" in owner:
47
+ return False
48
+ api = (os.environ.get("GITHUB_API_URL") or "https://api.github.com").rstrip("/")
49
+ headers = {"Accept": "application/vnd.github+json", "User-Agent": f"nstack/{__version__}"}
50
+ if token := os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN"):
51
+ headers["Authorization"] = f"Bearer {token}"
52
+ request = urllib.request.Request(f"{api}/users/{urllib.parse.quote(owner, safe='')}", headers=headers)
53
+ try:
54
+ with urllib.request.urlopen(request, timeout=5) as response:
55
+ kind = (json.load(response) or {}).get("type")
56
+ except urllib.error.HTTPError as error:
57
+ kind = "unknown" if error.code == 404 else None
58
+ except (OSError, ValueError, AttributeError, http.client.HTTPException):
59
+ kind = None
60
+ if kind == "unknown":
61
+ print(f"NOTE [{command}] GitHub knows no user or organisation '{owner}': written as given — check the "
62
+ "spelling; nstack doctor reads the file as GitHub validates it.")
63
+ return False
64
+ if kind == "Organization":
65
+ print(f"FAIL [{command}] '{owner}' is an organisation: GitHub takes as a code owner a user, or a team "
66
+ f"written organisation/team — never an organisation by its name. Every CODEOWNERS line naming "
67
+ f"it would name no valid owner.\n Action: pass {instead} — a team of {owner} with write "
68
+ "access to the repository — or a user (.nstack/handbook/07-governance.md §7).")
69
+ return True
70
+ if kind is None:
71
+ print(f"NOTE [{command}] GitHub did not say what '{owner}' names: written as given. A code owner is a "
72
+ "user or organisation/team, never an organisation's name; nstack doctor reads the file as GitHub "
73
+ "validates it.")
74
+ return False
75
+
76
+
33
77
  def default_ref() -> str:
34
78
  """The skeleton of the engine version: they move up together (PDR-0001 R2)."""
35
79
  return f"v{__version__}"
@@ -233,6 +277,11 @@ def init(destination: Path, answers: dict[str, str | None], source: str, ref: st
233
277
  # Not asked at init (Copier would ask): a project on GitHub starts on its CI; elsewhere no CI
234
278
  # is shipped, and its checks are attested (PDR-0018) — settled after the copy when the forge
235
279
  # was asked by Copier itself.
280
+ # Asked by Copier instead — the owner, or the forge —, the owner is read by nstack doctor (L10):
281
+ # a prompt cannot ask the forge.
282
+ owner = str(data.get("owner_team") or "")
283
+ if data.get("forge") == "github" and owner and organisation_owner(owner, "init", f"--owner-team {owner}/<team>"):
284
+ return 1
236
285
  data.setdefault("checks", "forge" if named == "github" else "attested")
237
286
  data.setdefault("hold_days", 7) # a hold goes stale after a week without work (ADR-0007)
238
287
  data.setdefault("approval", "human") # a code owner approves, until the decider says otherwise (PDR-0021)
@@ -278,11 +278,10 @@ TRACES = """query($owner: String!, $name: String!, $number: Int!) {
278
278
  userContentEdits(first: 100) { totalCount nodes { editor { login } } } } } }"""
279
279
 
280
280
 
281
- def traces(root: Path) -> set[str] | str | None:
282
- """The accounts whose hand is on the pull request — its description's editors, its reviewers,
283
- its commenters —, lower case and without `[bot]`; why they are not read; None with no pull
284
- request number, on a workstation, and while `nstack attest` records the head: the hand is
285
- judged on the forge's run, which an edit of the description starts again."""
281
+ def _pull_request(root: Path, query: str) -> dict | str | None:
282
+ """The pull request as one GraphQL query reads it; why it is not read; None with no pull
283
+ request number, on a workstation, and while `nstack attest` records the head: what the forge
284
+ holds is judged on the forge's own run."""
286
285
  number = os.environ.get("PR_NUMBER", "").strip()
287
286
  if not re.fullmatch(r"[0-9]+", number) or os.environ.get("NSTACK_ATTESTING"):
288
287
  return None
@@ -293,7 +292,7 @@ def traces(root: Path) -> set[str] | str | None:
293
292
  owner, name = repository.split("/", 1)
294
293
  request = urllib.request.Request(
295
294
  os.environ.get("GITHUB_GRAPHQL_URL") or "https://api.github.com/graphql",
296
- data=json.dumps({"query": TRACES, "variables": {"owner": owner, "name": name, "number": int(number)}}).encode(),
295
+ data=json.dumps({"query": query, "variables": {"owner": owner, "name": name, "number": int(number)}}).encode(),
297
296
  headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json", "User-Agent": "nstack"})
298
297
  try:
299
298
  with urllib.request.urlopen(request, timeout=10) as response:
@@ -301,16 +300,85 @@ def traces(root: Path) -> set[str] | str | None:
301
300
  if answer.get("errors"): # a field refused leaves the rest of the answer partial
302
301
  return f"the forge refused part of the query ({answer['errors'][0].get('type', 'error')})"
303
302
  found = answer["data"]["repository"]["pullRequest"]
303
+ return found if isinstance(found, dict) else "the forge did not answer (no pull request)"
304
+ except (OSError, ValueError, KeyError, TypeError, AttributeError, IndexError) as error:
305
+ return f"the forge did not answer ({type(error).__name__})"
306
+
307
+
308
+ def traces(root: Path) -> set[str] | str | None:
309
+ """The accounts whose hand is on the pull request — its description's editors, its reviewers,
310
+ its commenters —, lower case and without `[bot]`; why they are not read; None where the pull
311
+ request is not read (`_pull_request`): the hand is judged on the forge's run, which an edit of
312
+ the description starts again."""
313
+ found = _pull_request(root, TRACES)
314
+ if not isinstance(found, dict):
315
+ return found
316
+ try:
304
317
  hands = [(found[kind], key) for kind, key in (("reviews", "author"), ("comments", "author"),
305
318
  ("userContentEdits", "editor"))]
306
319
  if any(connection["totalCount"] > len(connection["nodes"]) for connection, _ in hands):
307
320
  return "more traces than one page"
308
321
  return {node[key]["login"].lower().removesuffix("[bot]") for connection, key in hands
309
322
  for node in connection["nodes"] if node and node.get(key)}
310
- except (OSError, ValueError, KeyError, TypeError, AttributeError, IndexError) as error:
323
+ except (KeyError, TypeError, AttributeError) as error:
324
+ return f"the forge did not answer ({type(error).__name__})"
325
+
326
+
327
+ # Each reviewer's latest review that approved or asked for changes: a dismissed one is not APPROVED,
328
+ # so where the forge dismisses stale approvals (G13) none is ever read here as covering the head.
329
+ APPROVALS = """query($owner: String!, $name: String!, $number: Int!) {
330
+ repository(owner: $owner, name: $name) { pullRequest(number: $number) {
331
+ latestOpinionatedReviews(first: 100) { totalCount nodes { state author { login } commit { oid } } } } } }"""
332
+
333
+
334
+ def approvals(root: Path) -> list[tuple[str, str]] | str | None:
335
+ """Each approving reviewer's login and the commit their approval was given on; why they are not
336
+ read; None where the pull request is not read (`_pull_request`)."""
337
+ found = _pull_request(root, APPROVALS)
338
+ if not isinstance(found, dict):
339
+ return found
340
+ try:
341
+ reviews = found["latestOpinionatedReviews"]
342
+ if reviews["totalCount"] > len(reviews["nodes"]):
343
+ return "more reviewers than one page"
344
+ return [(node["author"]["login"] if node.get("author") else "a deleted account",
345
+ str((node.get("commit") or {}).get("oid") or "").lower())
346
+ for node in reviews["nodes"] if node and node.get("state") == "APPROVED"]
347
+ except (KeyError, TypeError, AttributeError) as error:
311
348
  return f"the forge did not answer ({type(error).__name__})"
312
349
 
313
350
 
351
+ def check_approvals(root: Path, base: str, head: str, found: list[tuple[str, str]] | str | None,
352
+ warn: Callable[[str], None]) -> None:
353
+ """R1 (#377): where the forge keeps an approval once new commits are pushed — no ruleset, or
354
+ stale approvals not dismissed —, "approved" no longer says the head was read. An approval on
355
+ an earlier commit covers the head when only the base branch was merged in since; otherwise it
356
+ is said, with whom and which commits. A warning, never a failure: a review starts no run (D218),
357
+ so a check failed on it would stay red after the approver read the head and approved again."""
358
+ if isinstance(found, str):
359
+ warn(f"[R1] whether each approval covers the head is not read: {found}.")
360
+ return
361
+ for login, commit in found or []:
362
+ if commit == head:
363
+ continue
364
+ known = bool(commit) and not _git(root, "merge-base", "--is-ancestor", commit, head).returncode
365
+ since = _git(root, "rev-list", f"{commit}..{head}", f"^{base}").stdout.split() if known else []
366
+ # A merge counts when it carries content of its own — a conflict resolved, an edit made
367
+ # while merging —: what a clean merge of the base would not have written.
368
+ since = [one for one in since if _git(root, "rev-list", "--no-walk", "--merges", one).stdout.strip() == ""
369
+ or _git(root, "show", "--remerge-diff", "--format=", one).stdout.strip()]
370
+ if known and not since:
371
+ continue # only the base branch merged in: nothing the approver has not read
372
+ what = (f"{len(since)} commit(s) pushed since" if known
373
+ else "a commit this branch does not hold — rewritten since, or not found here")
374
+ line = (f"[R1] @{login} approved {commit[:7] or 'an unknown commit'}, not the head {head[:7]}, at this run: "
375
+ f"{what}, which the approval does not cover.")
376
+ warn(f"{line}\n Action: @{login} reads them and approves again before the merge; where the forge "
377
+ "dismisses stale approvals on push, it does this itself (.nstack/handbook/07-governance.md §7).")
378
+ if os.environ.get("GITHUB_ACTIONS") == "true": # seen on the check, not only in its log
379
+ print(f"::warning title=R1 approval behind the head::{line.removeprefix('[R1] ')}")
380
+
381
+
314
382
  def check_verifier(verifier: str, authorship: tuple[set[str], set[str], list[str]], fail: Fail,
315
383
  hands: set[str] | None = None) -> None:
316
384
  """T2: the verifier is named — people as @handle anywhere on the line, an agent session as
@@ -865,6 +933,8 @@ def run(root: Path, base: str, body_file: Path | None = None, labels_given: str
865
933
  check_cycle(root, body, labels, datetime.date.today(), fail, warnings.append)
866
934
  check_hold(root, body, labels, authorship, fail, warnings.append, identities(root, base, head))
867
935
  checks = check_attested(root, head, fail, warnings.append)
936
+ if forge == "github":
937
+ check_approvals(root, base, head, approvals(root), warnings.append)
868
938
  if carried and reasons:
869
939
  check_moved(body, recorded_rows(root, fork, head), fail, warnings.append,
870
940
  lambda one, other: bool(tree_of(one)) and tree_of(one) == tree_of(other))
File without changes