stead 0.5.0__py3-none-any.whl

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 (139) hide show
  1. ctx/__init__.py +7 -0
  2. ctx/__main__.py +9 -0
  3. ctx/_bundled_factories/context-maintenance/FACTORY.md +37 -0
  4. ctx/_bundled_factories/context-maintenance/evals/eval-maintenance-broken-relation.json +7 -0
  5. ctx/_bundled_factories/context-maintenance/evals/eval-maintenance-clean.json +7 -0
  6. ctx/_bundled_factories/context-maintenance/evals/eval-maintenance-duplicates.json +7 -0
  7. ctx/_bundled_factories/context-maintenance/evals/eval-maintenance-inbox.json +7 -0
  8. ctx/_bundled_factories/context-maintenance/evals/eval-maintenance-stale.json +7 -0
  9. ctx/_bundled_factories/context-maintenance/prompts/v1.md +19 -0
  10. ctx/_bundled_factories/feature-builder/FACTORY.md +160 -0
  11. ctx/_bundled_factories/feature-builder/evals/eval-feature-builtin-method.json +1 -0
  12. ctx/_bundled_factories/feature-builder/evals/eval-feature-clear-spec.json +1 -0
  13. ctx/_bundled_factories/feature-builder/evals/eval-feature-duplicate-work.json +1 -0
  14. ctx/_bundled_factories/feature-builder/evals/eval-feature-spec-kit-method.json +1 -0
  15. ctx/_bundled_factories/feature-builder/evals/eval-feature-spec-kit-vague.json +1 -0
  16. ctx/_bundled_factories/feature-builder/evals/eval-feature-vague-spec.json +1 -0
  17. ctx/_bundled_factories/feature-builder/evals/pipeline/pipeline-add-greeting-flag.json +16 -0
  18. ctx/_bundled_factories/feature-builder/evals/pipeline/pipeline-broken-check-detected.json +15 -0
  19. ctx/_bundled_factories/feature-builder/evals/pipeline/pipeline-js-slug-helper.json +16 -0
  20. ctx/_bundled_factories/feature-builder/prompts/v1.md +101 -0
  21. ctx/_bundled_factories/feature-builder/prompts/v2.md +177 -0
  22. ctx/_bundled_factories/weekly-contribution-digest/FACTORY.md +88 -0
  23. ctx/_bundled_factories/weekly-contribution-digest/evals/eval-digest-ci-failure.json +1 -0
  24. ctx/_bundled_factories/weekly-contribution-digest/evals/eval-digest-empty-cache.json +1 -0
  25. ctx/_bundled_factories/weekly-contribution-digest/evals/eval-digest-multi-repo.json +1 -0
  26. ctx/_bundled_factories/weekly-contribution-digest/prompts/v1.md +48 -0
  27. ctx/_bundled_factories/weekly-project-status/FACTORY.md +71 -0
  28. ctx/_bundled_factories/weekly-project-status/evals/eval-status-blocked-project.json +1 -0
  29. ctx/_bundled_factories/weekly-project-status/evals/eval-status-happy-path.json +1 -0
  30. ctx/_bundled_factories/weekly-project-status/evals/eval-status-thin-context.json +1 -0
  31. ctx/_bundled_factories/weekly-project-status/prompts/v1.md +32 -0
  32. ctx/accounts.py +350 -0
  33. ctx/acp_server.py +976 -0
  34. ctx/actors.py +64 -0
  35. ctx/agent.py +2344 -0
  36. ctx/agent_address.py +781 -0
  37. ctx/agent_exports.py +724 -0
  38. ctx/agent_git.py +704 -0
  39. ctx/agent_prompts.py +298 -0
  40. ctx/agent_tools.py +256 -0
  41. ctx/audit.py +97 -0
  42. ctx/autonomy.py +344 -0
  43. ctx/backup.py +387 -0
  44. ctx/bench.py +473 -0
  45. ctx/bundle.py +442 -0
  46. ctx/chatops.py +370 -0
  47. ctx/ci_hooks.py +128 -0
  48. ctx/cli.py +2018 -0
  49. ctx/cli_handlers.py +2248 -0
  50. ctx/cockpit/events_forms.js +835 -0
  51. ctx/cockpit/events_pipeline.js +1353 -0
  52. ctx/cockpit/events_ui.js +1302 -0
  53. ctx/cockpit/palette.js +146 -0
  54. ctx/cockpit/state.js +666 -0
  55. ctx/cockpit/styles.css +834 -0
  56. ctx/cockpit/views_core.js +661 -0
  57. ctx/cockpit/views_pipeline.js +1183 -0
  58. ctx/cockpit/views_spaces.js +1468 -0
  59. ctx/cockpit.html +61 -0
  60. ctx/commands.py +499 -0
  61. ctx/comment.py +233 -0
  62. ctx/config.py +563 -0
  63. ctx/context_bench.py +220 -0
  64. ctx/context_sync.py +235 -0
  65. ctx/db.py +519 -0
  66. ctx/deliver.py +105 -0
  67. ctx/demo.py +338 -0
  68. ctx/devcontainer.py +850 -0
  69. ctx/doctor.py +376 -0
  70. ctx/drift.py +565 -0
  71. ctx/events.py +142 -0
  72. ctx/executor.py +713 -0
  73. ctx/factory.py +1384 -0
  74. ctx/federation.py +397 -0
  75. ctx/forge.py +358 -0
  76. ctx/frontmatter.py +157 -0
  77. ctx/gc.py +275 -0
  78. ctx/graph.py +434 -0
  79. ctx/inbox_import.py +341 -0
  80. ctx/integrations.py +214 -0
  81. ctx/isolation.py +665 -0
  82. ctx/issue_file.py +228 -0
  83. ctx/local_review.py +205 -0
  84. ctx/lsp.py +493 -0
  85. ctx/mcp_server.py +1806 -0
  86. ctx/merge.py +286 -0
  87. ctx/metrics.py +232 -0
  88. ctx/model_evals.py +431 -0
  89. ctx/models.py +953 -0
  90. ctx/notify.py +304 -0
  91. ctx/objects.py +111 -0
  92. ctx/onboard.py +419 -0
  93. ctx/otel.py +397 -0
  94. ctx/output_compress.py +180 -0
  95. ctx/patch.py +407 -0
  96. ctx/pipeline_eval.py +586 -0
  97. ctx/plan_paths.py +200 -0
  98. ctx/pr_triage.py +625 -0
  99. ctx/proof.py +90 -0
  100. ctx/publish.py +270 -0
  101. ctx/repair.py +250 -0
  102. ctx/repo_map.py +1320 -0
  103. ctx/review.py +672 -0
  104. ctx/safety.py +667 -0
  105. ctx/sarif.py +175 -0
  106. ctx/scaffold.py +199 -0
  107. ctx/schedule.py +590 -0
  108. ctx/schema.sql +180 -0
  109. ctx/search.py +249 -0
  110. ctx/semantic.py +1007 -0
  111. ctx/sessions.py +265 -0
  112. ctx/slop.py +725 -0
  113. ctx/spec.py +1528 -0
  114. ctx/spec_split.py +588 -0
  115. ctx/spend.py +200 -0
  116. ctx/stack.py +719 -0
  117. ctx/stead_publish.py +578 -0
  118. ctx/steer.py +151 -0
  119. ctx/sync.py +628 -0
  120. ctx/task_query.py +36 -0
  121. ctx/tasks.py +449 -0
  122. ctx/test_quality.py +1007 -0
  123. ctx/tracker.py +1063 -0
  124. ctx/ui.py +1761 -0
  125. ctx/ui_routes.py +2427 -0
  126. ctx/ui_server.py +1333 -0
  127. ctx/ui_snapshot.py +1238 -0
  128. ctx/util.py +132 -0
  129. ctx/wiki.py +492 -0
  130. ctx/wiki_store.py +169 -0
  131. ctx/writeback.py +1403 -0
  132. stead/__init__.py +5 -0
  133. stead/__main__.py +6 -0
  134. stead-0.5.0.dist-info/METADATA +204 -0
  135. stead-0.5.0.dist-info/RECORD +139 -0
  136. stead-0.5.0.dist-info/WHEEL +5 -0
  137. stead-0.5.0.dist-info/entry_points.txt +2 -0
  138. stead-0.5.0.dist-info/licenses/LICENSE +201 -0
  139. stead-0.5.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,88 @@
1
+ # FACTORY: weekly-contribution-digest
2
+
3
+ The **first factory** of the unified cockpit (own projects + OSS contributions).
4
+ **Specific** (one job: a weekly digest of your GitHub contributions in flight),
5
+ **shared** (any agent/human runs it via the CLI), **scrutinized** (versioned
6
+ prompts, evals, run logs, human verdicts).
7
+
8
+ > **NEVER auto-post.** This factory drafts locally. Nothing it produces is ever
9
+ > posted to GitHub (no comments, reviews, issues, PRs, labels, pushes). All
10
+ > `gh` usage in this system is READ-ONLY (`gh search`, `gh pr view`,
11
+ > `gh api user` GET). Publishing anything is a human action, outside the factory.
12
+
13
+ ## Trigger
14
+
15
+ - **Scheduled (target):** weekly, e.g. Friday afternoon, after a fresh
16
+ `python -m stead sync github`. Scheduler-agnostic: any cron / Windows Task
17
+ Scheduler / Hermes cron job invokes:
18
+ `python -m stead factory run --factory weekly-contribution-digest --shadow`
19
+ (equivalently: `python -m stead digest`).
20
+ - **Event-driven:** `stead sync github --digest` assembles the digest only
21
+ when the cache changed. It still does not post.
22
+ - **Manual:** `stead digest` works fully offline from the cached files.
23
+
24
+ ## Inputs
25
+
26
+ Cached contributions — no network at assembly time:
27
+
28
+ 1. `context/contributions/*.md` — issues/PRs you're involved with
29
+ (flat frontmatter: `repo`, `kind`, `number`, `role`, `state`, `ci`, `review`,
30
+ `visibility: public`), populated by `stead sync github` or by hand.
31
+ 2. `context/repos/*.md` — repo metadata (own vs oss, url) for grouping.
32
+
33
+ Private notes/strategy (`context/documents/`) are deliberately NOT inputs:
34
+ GitHub-derived data is public; the digest stays public-safe.
35
+
36
+ ## Stages
37
+
38
+ 1. **Sync (explicit, read-only):** `stead sync github [--author @me] [--limit N]`
39
+ shells out to `gh` (subprocess), caches results as markdown + index.
40
+ `--offline` re-indexes the cache without network.
41
+ 2. **Assemble** (`stead factory run` / `stead digest`): deterministically group
42
+ contributions by repo; compute counts (PRs in flight, reviews awaiting
43
+ reply, claimed issues, CI flags); write `bundle.md`, `prompt.md`, `run.json`;
44
+ insert a `runs` row. **No LLM call.**
45
+ 3. **Generate** (pluggable): any agent or human reads `prompt.md` and drafts the
46
+ digest. No provider is hardwired; no API key is required by this repo.
47
+ 4. **Review** (human, mandatory in shadow mode): accuracy vs the bundle,
48
+ completeness, tone; confirm nothing private leaked into the draft.
49
+ 5. **Record**: `stead run log --factory weekly-contribution-digest
50
+ --task contributions --prompt-version <v> --output <draft>
51
+ --verdict approved|rejected`.
52
+ 6. **File** (only after approval, later phases): the approved digest becomes a
53
+ document in `context/documents/` (private notes stay private). Never posted
54
+ to GitHub by the system.
55
+
56
+ ## Outputs
57
+
58
+ - `runs/<timestamp>-digest/bundle.md` — deterministic contribution bundle
59
+ - `runs/<timestamp>-digest/prompt.md` — assembled prompt (the emit)
60
+ - `runs/<timestamp>-digest/run.json` — run metadata
61
+ - `runs` row in state.db (verdict starts `pending`)
62
+ - After review: a drafted weekly digest + verdict in the run ledger
63
+
64
+ ## Tools
65
+
66
+ Python 3.11+ standard library only (`python -m stead`). External open-source
67
+ tools invoked via subprocess: `gh` (read-only sync), `git` (audit trail).
68
+ Generation step: any LLM/agent the operator chooses. Assembly is offline.
69
+
70
+ ## Risk level & incremental rollout
71
+
72
+ **Low risk, shadow-first.**
73
+
74
+ 1. **Shadow (current):** drafts only; a human reviews before anything is filed
75
+ or acted on. Default mode. Never auto-posts, in any mode.
76
+ 2. **Low volume (next):** after 3–5 reviewed shadow runs with mostly `approved`
77
+ verdicts, schedule the weekly sync + digest.
78
+ 3. **Consequential (filed):** `stead run file --run ID` writes an approved
79
+ digest into `context/documents/`. The human approval is the gate. Posting to
80
+ GitHub remains out of scope, permanently.
81
+
82
+ ## Scrutiny
83
+
84
+ - Prompts are versioned (`prompts/v1.md`, ...); `stead prompt list` shows
85
+ testing/production/retired. Promote only after evals pass (`stead prompt
86
+ promote`); old production is retired, never deleted.
87
+ - Evals live in `evals/*.json` (loaded into state.db by `stead init`).
88
+ - Review run logs weekly; fix **real observed failures**, not imagined ones.
@@ -0,0 +1 @@
1
+ {"id": "eval-digest-ci-failure", "factory": "weekly-contribution-digest", "title": "Failing CI on the user's own open PR", "input": "Bundle with one oss repo: an open author PR with ci fail and review changes, plus an open author PR with ci pending.", "pass_criteria": "CI flags lists the failing PR first and the pending PR second; PRs in flight states the change requests and failing CI explicitly; This week's focus ranks fixing the failing CI first with a bundle-traceable justification; no invented fix details or root causes; 150-400 words; output is draft-only with no posting actions."}
@@ -0,0 +1 @@
1
+ {"id": "eval-digest-empty-cache", "factory": "weekly-contribution-digest", "title": "Empty or stale contribution cache", "input": "Bundle with zero contributions (or only closed/merged items) and the 'No contributions cached' notice.", "pass_criteria": "Digest explicitly states the cache is empty or too thin to report instead of inventing activity; recommends running `stead sync github` (read-only) to refresh; no fabricated PRs, issues, or CI states; header and summary still present; no suggestion to post anything to GitHub."}
@@ -0,0 +1 @@
1
+ {"id": "eval-digest-multi-repo", "factory": "weekly-contribution-digest", "title": "Healthy multi-repo week: own PR, owed review, claimed issue", "input": "Bundle with two repos (one own, one oss): an open author PR with ci pass and review requested, an open reviewer PR awaiting reply, and one open assigned issue; no CI failures.", "pass_criteria": "Digest grouped by repo with own/oss marked; PRs in flight lists the author PR by number+title with ci pass noted; Reviews awaiting reply lists the reviewer PR; Claimed issues lists the assigned issue; CI flags says 'None.'; This week's focus puts the owed review ahead of the awaiting-review PR; 150-400 words; no facts absent from the bundle; no suggestion to post anything to GitHub."}
@@ -0,0 +1,48 @@
1
+ # Prompt v1 — weekly-contribution-digest (production)
2
+
3
+ You are drafting a **weekly contribution digest** for one person who works on
4
+ their own projects and contributes to open-source repos. The context bundle
5
+ below the `---` separator is the complete, authoritative input: a read-only
6
+ local cache of their public GitHub contributions (PRs, review requests,
7
+ assigned issues) grouped by repo, with CI and review state. Do not invent facts
8
+ that are not in the bundle. Do not fetch anything from the network.
9
+
10
+ ## Instructions
11
+
12
+ Write the digest in Markdown, **grouped by repo** (one section per repo that
13
+ has contributions; use the repo title, mark own vs oss). Within each repo
14
+ section use exactly these subsections, omitting any that are empty:
15
+
16
+ 1. **PRs in flight** — open PRs where the user is the author (`role: author`).
17
+ One bullet each: PR number + title, review state, CI state, and the single
18
+ next action implied by the bundle (e.g. "awaiting review", "address change
19
+ requests"). If CI is `fail` or `pending`, say so explicitly.
20
+ 2. **Reviews awaiting reply** — open PRs where the user is a requested reviewer
21
+ (`role: reviewer`). One bullet each: PR number + title, how long it has been
22
+ waiting if `updated` suggests staleness, and that a reply is owed.
23
+ 3. **Claimed issues** — open issues assigned to the user (`role: assignee`).
24
+ One bullet each: issue number + title and current state.
25
+ 4. **CI flags** — any open contribution with `ci: fail` (first) or `ci: pending`
26
+ that needs attention. If none, write "None."
27
+
28
+ Then close with:
29
+
30
+ 5. **This week's focus** — 2–4 bullets recommending what to tackle first,
31
+ ordered by: failing CI on your own PRs > reviews you owe > your PRs awaiting
32
+ review > claimed issues. Justify each pick from bundle facts only.
33
+
34
+ Start the digest with a one-line header: `# Weekly contribution digest — <date>`
35
+ (use the bundle's `created` timestamp date) and a one-sentence summary with the
36
+ bundle's Summary counts.
37
+
38
+ ## Rules
39
+
40
+ - Be factual and concise: the whole digest should be 150–400 words.
41
+ - Every claim must be traceable to the bundle. If the cache looks stale or thin,
42
+ say so explicitly and suggest `stead sync github` instead of guessing.
43
+ - Reference PRs/issues by number and title, and link the url from the bundle.
44
+ - Plain professional tone; no marketing language, no emoji.
45
+ - **Never post anything.** Output only the digest Markdown; a human reviews it.
46
+ Do not suggest automated comments/reviews/posts to GitHub.
47
+ - Do not include or infer private strategy notes; the bundle is public data only.
48
+ - This is a shadow run: a human will review your draft before it is filed.
@@ -0,0 +1,71 @@
1
+ # FACTORY: weekly-project-status
2
+
3
+ The first factory. **Specific** (one task type: draft a weekly status update
4
+ for one project), **shared** (any agent/human can run it via the CLI),
5
+ **scrutinized** (versioned prompts, evals, run logs, human verdicts).
6
+
7
+ ## Trigger
8
+
9
+ - **Scheduled (target):** weekly, e.g. Friday afternoon. Scheduler-agnostic:
10
+ any cron / Windows Task Scheduler / Hermes cron job invokes:
11
+ `python -m stead factory run --factory weekly-project-status --project <P> --shadow`
12
+ - **Event-driven (scheduled):** `stead schedule show --project P` adds this
13
+ project to the Friday local job. `stead factory run --project P` is the
14
+ manual trigger.
15
+ - **Now (Phase 1–2):** manual invocation only.
16
+
17
+ ## Inputs
18
+
19
+ One project id. The runner deterministically gathers (no LLM involved):
20
+
21
+ 1. `context/projects/<slug>.md` — the project object
22
+ 2. All tasks with `project: <id>` (any status)
23
+ 3. All documents with `project: <id>`
24
+ 4. All meetings with `project: <id>`
25
+
26
+ ## Stages
27
+
28
+ 1. **Assemble** (`stead factory run`): build `bundle.md`, emit `prompt.md`
29
+ (production prompt + bundle), write `run.json`, insert a `runs` row.
30
+ 2. **Generate** (pluggable): any agent or human reads `prompt.md` and drafts
31
+ the status update. No provider is hardwired; no API key is required by
32
+ this repo.
33
+ 3. **Review** (human, mandatory in shadow mode): check accuracy against the
34
+ bundle, completeness, tone.
35
+ 4. **Record**: `stead run log --factory weekly-project-status --task <project-id>
36
+ --prompt-version <v> --output <draft> --verdict approved|rejected`.
37
+ 5. **File** (only after approval, and only in later phases): the approved
38
+ update becomes a document in `context/documents/` linked to the project.
39
+
40
+ ## Outputs
41
+
42
+ - `runs/<timestamp>-<project>/bundle.md` — deterministic context bundle
43
+ - `runs/<timestamp>-<project>/prompt.md` — assembled prompt (the emit)
44
+ - `runs/<timestamp>-<project>/run.json` — run metadata
45
+ - `runs` row in state.db (verdict starts `pending`)
46
+ - After review: a drafted status update + verdict in the run ledger
47
+
48
+ ## Tools
49
+
50
+ Python 3.11+ standard library only (`python -m stead`). Generation step: any
51
+ LLM/agent the operator chooses. No network dependency in the runner.
52
+
53
+ ## Risk level & incremental rollout
54
+
55
+ **Low risk, shadow-first.**
56
+
57
+ 1. **Shadow (current):** drafts only; nothing is filed or acted on without
58
+ human approval. Default mode of `factory run`.
59
+ 2. **Low volume (next):** after 3–5 reviewed shadow runs with mostly
60
+ `approved` verdicts, schedule one project weekly.
61
+ 3. **Consequential (filed):** `stead run file --run ID` writes an approved
62
+ status update into `context/documents/`. The human approval is the gate.
63
+ Nothing is posted.
64
+
65
+ ## Scrutiny
66
+
67
+ - Prompts are versioned (`prompts/v1.md`, ...); `stead prompt list` shows
68
+ testing/production/retired. Promote only after evals pass (`stead prompt
69
+ promote`); old production is retired, never deleted.
70
+ - Evals live in `evals/*.json` (loaded into state.db by `stead init`).
71
+ - Review run logs weekly; fix **real observed failures**, not imagined ones.
@@ -0,0 +1 @@
1
+ {"id": "eval-status-blocked-project", "factory": "weekly-project-status", "title": "Project with a blocked task and a risk in meeting notes", "input": "Bundle for an active project with 1 blocked task (waiting on an external decision), 1 doing task, and a meeting note recording a deadline slip.", "pass_criteria": "Health judged at-risk or blocked (not on-track); Risks & blockers names the blocked task AND the deadline slip from the meeting note; Asks requests the external decision; no invented mitigation claims; 150-350 words."}
@@ -0,0 +1 @@
1
+ {"id": "eval-status-happy-path", "factory": "weekly-project-status", "title": "Healthy project with mixed task statuses", "input": "Bundle for an active project with 1 done task, 1 doing task, 2 to-do tasks, no blocked tasks, one decision document and one recent meeting note.", "pass_criteria": "Output has all six required sections (Header, Summary, Progress, Next up, Risks & blockers, Asks); health judged on-track; Progress lists the done+doing tasks by title; Next up lists both to-do tasks; Risks says 'None identified.'; 150-350 words; no facts absent from the bundle."}
@@ -0,0 +1 @@
1
+ {"id": "eval-status-thin-context", "factory": "weekly-project-status", "title": "Thin bundle: project file only, no tasks or documents", "input": "Bundle containing only a project markdown file with a goal statement; zero tasks, documents, or meetings linked.", "pass_criteria": "Output explicitly states the context is too thin to judge health instead of guessing; Progress/Next up/Risks sections present and honestly empty or 'None identified.'; no fabricated accomplishments; all six sections still present."}
@@ -0,0 +1,32 @@
1
+ # Prompt v1 — weekly-project-status (production)
2
+
3
+ You are drafting a **weekly project status update** for the project described
4
+ in the context bundle below the `---` separator. The bundle is the complete,
5
+ authoritative context: the project file, its tasks, linked documents, and
6
+ meeting notes. Do not invent facts that are not in the bundle.
7
+
8
+ ## Instructions
9
+
10
+ Write a status update in Markdown with exactly these sections:
11
+
12
+ 1. **Header** — project title, report date (use the bundle's `created`
13
+ timestamp date), and one sentence stating the project's goal.
14
+ 2. **Summary** — 2–4 sentences: overall health (on-track / at-risk / blocked)
15
+ and the single most important thing that happened since the last update.
16
+ Judge health from task statuses and recent meeting/document content.
17
+ 3. **Progress** — bullet list of tasks with status `done` (recently completed
18
+ work) and `doing` (in flight). Reference task titles, not ids.
19
+ 4. **Next up** — bullet list of `to-do` tasks, in a sensible order.
20
+ 5. **Risks & blockers** — bullet list of `blocked` tasks and any risks evident
21
+ from documents/meetings. If none, write "None identified."
22
+ 6. **Asks** — decisions or help needed from the human owner, if any; otherwise
23
+ "None."
24
+
25
+ ## Rules
26
+
27
+ - Be factual and concise: the whole update should be 150–350 words.
28
+ - Every claim must be traceable to the bundle. If the bundle is too thin to
29
+ judge health, say so explicitly instead of guessing.
30
+ - Plain professional tone; no marketing language, no emoji.
31
+ - Do not modify any files. Output only the status update Markdown.
32
+ - This is a shadow run: a human will review your draft before it is filed.
ctx/accounts.py ADDED
@@ -0,0 +1,350 @@
1
+ """Per-person sign-in for a shared server. Not a login on this computer.
2
+
3
+ Passwords are scrypt hashes in gitignored private/accounts.json. They are
4
+ never written into context markdown, and they are never returned by a list.
5
+ A session is a random cookie, not the password.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import re
13
+ import secrets
14
+ from pathlib import Path
15
+
16
+ from ctx import objects
17
+
18
+ _NAME = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$")
19
+ _SCRYPT = {"n": 2**14, "r": 8, "p": 1, "dklen": 32}
20
+ ROLES = ("viewer", "editor", "admin")
21
+ DEFAULT_ROLE = "admin"
22
+
23
+
24
+ def _role(role: str | None) -> str:
25
+ value = (role or DEFAULT_ROLE).strip().lower()
26
+ if value not in ROLES:
27
+ raise AccountError(f"role must be one of: {', '.join(ROLES)}")
28
+ return value
29
+
30
+
31
+ class AccountError(Exception):
32
+ def __init__(self, message: str):
33
+ super().__init__(message)
34
+
35
+
36
+ def accounts_path(root: Path) -> Path:
37
+ return root / "private" / "accounts.json"
38
+
39
+
40
+ def load(root: Path) -> list[dict]:
41
+ path = accounts_path(root)
42
+ if not path.is_file():
43
+ return []
44
+ try:
45
+ data = json.loads(path.read_text(encoding="utf-8"))
46
+ except (OSError, json.JSONDecodeError) as exc:
47
+ raise AccountError(f"could not read accounts: {exc}") from exc
48
+ accounts = data.get("accounts") if isinstance(data, dict) else None
49
+ if not isinstance(accounts, list):
50
+ raise AccountError("accounts file is not valid")
51
+ return accounts
52
+
53
+
54
+ def count(root: Path) -> int:
55
+ return len(load(root))
56
+
57
+
58
+ def _acct_lock(root: Path):
59
+ from ctx.util import file_lock
60
+ return file_lock(accounts_path(root).parent / ".accounts.lock")
61
+
62
+
63
+ def public_list(root: Path) -> list[dict]:
64
+ """Names, actors, and roles only. Never salts or hashes."""
65
+ out: list[dict] = []
66
+ for item in load(root):
67
+ entry: dict = {
68
+ "name": item.get("name") or "",
69
+ "actor": item.get("actor") or "",
70
+ "role": (item.get("role") or DEFAULT_ROLE).strip().lower(),
71
+ }
72
+ if item.get("disabled"):
73
+ entry["disabled"] = True
74
+ repos = item.get("allowed_repos")
75
+ if isinstance(repos, list) and repos:
76
+ entry["allowed_repos"] = [str(r) for r in repos if str(r).strip()]
77
+ out.append(entry)
78
+ return out
79
+
80
+
81
+ def _normalize_repos(repos: list[str] | str | None) -> list[str]:
82
+ if repos is None:
83
+ return []
84
+ raw_items = repos.split(",") if isinstance(repos, str) else list(repos)
85
+ out: list[str] = []
86
+ seen: set[str] = set()
87
+ for item in raw_items:
88
+ val = str(item or "").strip()
89
+ if not val:
90
+ continue
91
+ if not val.startswith("repo-"):
92
+ val = f"repo-{val}"
93
+ if val not in seen:
94
+ seen.add(val)
95
+ out.append(val)
96
+ return out
97
+
98
+
99
+ def allowed_repos_for(root: Path, name: str) -> set[str] | None:
100
+ """Return restricted repo IDs for ``name``, or ``None`` if unrestricted."""
101
+ wanted = (name or "").strip().lower()
102
+ if not wanted:
103
+ return None
104
+ for item in load(root):
105
+ if item.get("name") == wanted:
106
+ repos = item.get("allowed_repos")
107
+ if isinstance(repos, list) and repos:
108
+ cleaned = {str(r).strip() for r in repos if str(r).strip()}
109
+ return cleaned or None
110
+ return None
111
+ return None
112
+
113
+
114
+ def set_allowed_repos(root: Path, name: str, repos: list[str] | str | None) -> dict:
115
+ """Set (or with empty list, clear) per-repo ACL scoping for an account."""
116
+ name = _name(name)
117
+ cleaned = _normalize_repos(repos)
118
+ with _acct_lock(root):
119
+ accounts = load(root)
120
+ found = next((item for item in accounts if item.get("name") == name), None)
121
+ if found is None:
122
+ raise AccountError(f"account not found: {name}")
123
+ if cleaned:
124
+ found["allowed_repos"] = cleaned
125
+ else:
126
+ found.pop("allowed_repos", None)
127
+ _save(root, accounts)
128
+ return {"name": name, "allowed_repos": cleaned}
129
+
130
+
131
+ def _active_admin_count(accounts: list[dict]) -> int:
132
+ return sum(
133
+ 1 for item in accounts
134
+ if not item.get("disabled")
135
+ and (item.get("role") or DEFAULT_ROLE).strip().lower() == "admin"
136
+ )
137
+
138
+
139
+ def find_active(root: Path, name: str) -> dict | None:
140
+ """Return ``{name, actor, role}`` for an active (non-disabled) account, or None."""
141
+ wanted = (name or "").strip().lower()
142
+ if not wanted:
143
+ return None
144
+ for item in load(root):
145
+ if item.get("name") != wanted:
146
+ continue
147
+ if item.get("disabled"):
148
+ return None
149
+ return {
150
+ "name": wanted,
151
+ "actor": item.get("actor") or "",
152
+ "role": (item.get("role") or DEFAULT_ROLE).strip().lower(),
153
+ }
154
+ return None
155
+
156
+
157
+ def is_disabled(root: Path, name: str) -> bool:
158
+ """Return True if ``name`` is disabled or no longer exists."""
159
+ wanted = (name or "").strip().lower()
160
+ if not wanted:
161
+ return True
162
+ for item in load(root):
163
+ if item.get("name") == wanted:
164
+ return bool(item.get("disabled"))
165
+ return True
166
+
167
+
168
+ def add(root: Path, name: str, actor_id: str, password: str | None = None,
169
+ role: str = DEFAULT_ROLE) -> str:
170
+ """Create an account. Returns the password once. Stores only the hash."""
171
+ name = _name(name)
172
+ chosen_role = _role(role)
173
+ actor_id = (actor_id or "").strip()
174
+ if objects.find(root, "actor", actor_id) is None:
175
+ raise AccountError(f"actor not found: {actor_id}")
176
+ shown = password if password else secrets.token_urlsafe(18)
177
+ if len(shown) < 12:
178
+ raise AccountError("password must be at least 12 characters")
179
+ salt, digest = _hash(shown)
180
+ with _acct_lock(root):
181
+ accounts = load(root)
182
+ if any(item.get("name") == name for item in accounts):
183
+ raise AccountError(f"account already exists: {name}")
184
+ accounts.append({
185
+ "name": name, "actor": actor_id, "role": chosen_role,
186
+ "salt": salt, "hash": digest,
187
+ })
188
+ _save(root, accounts)
189
+ return shown
190
+
191
+
192
+ def set_role(root: Path, name: str, role: str) -> dict:
193
+ """Change an existing account's role (viewer, editor, admin)."""
194
+ name = _name(name)
195
+ chosen_role = _role(role)
196
+ with _acct_lock(root):
197
+ accounts = load(root)
198
+ found = next((item for item in accounts if item.get("name") == name), None)
199
+ if found is None:
200
+ raise AccountError(f"account not found: {name}")
201
+ current_role = (found.get("role") or DEFAULT_ROLE).strip().lower()
202
+ if current_role == "admin" and chosen_role != "admin" and not found.get("disabled"):
203
+ if _active_admin_count(accounts) <= 1:
204
+ raise AccountError("cannot demote the last active admin account")
205
+ found["role"] = chosen_role
206
+ _save(root, accounts)
207
+ return {"name": name, "actor": found.get("actor") or "", "role": chosen_role}
208
+
209
+
210
+ def set_disabled(root: Path, name: str, disabled: bool) -> dict:
211
+ """Disable or re-enable an existing shared-server account."""
212
+ name = _name(name)
213
+ with _acct_lock(root):
214
+ accounts = load(root)
215
+ found = next((item for item in accounts if item.get("name") == name), None)
216
+ if found is None:
217
+ raise AccountError(f"account not found: {name}")
218
+ if disabled and not found.get("disabled"):
219
+ cur_role = (found.get("role") or DEFAULT_ROLE).strip().lower()
220
+ if cur_role == "admin" and _active_admin_count(accounts) <= 1:
221
+ raise AccountError("cannot disable the last active admin account")
222
+ if disabled:
223
+ found["disabled"] = True
224
+ else:
225
+ found.pop("disabled", None)
226
+ _save(root, accounts)
227
+ return {
228
+ "name": name,
229
+ "actor": found.get("actor") or "",
230
+ "role": (found.get("role") or DEFAULT_ROLE).strip().lower(),
231
+ "disabled": bool(disabled),
232
+ }
233
+
234
+
235
+ def delete(root: Path, name: str) -> dict:
236
+ """Remove a shared-server account."""
237
+ name = _name(name)
238
+ with _acct_lock(root):
239
+ accounts = load(root)
240
+ found = next((item for item in accounts if item.get("name") == name), None)
241
+ if found is None:
242
+ raise AccountError(f"account not found: {name}")
243
+ cur_role = (found.get("role") or DEFAULT_ROLE).strip().lower()
244
+ if (cur_role == "admin" and not found.get("disabled")
245
+ and len(accounts) > 1 and _active_admin_count(accounts) <= 1):
246
+ raise AccountError("cannot delete the last active admin account while other accounts exist")
247
+ remaining = [item for item in accounts if item.get("name") != name]
248
+ _save(root, remaining)
249
+ return {"name": name, "actor": found.get("actor") or "", "deleted": True}
250
+
251
+
252
+ def change_password(root: Path, name: str, current_password: str, new_password: str) -> dict:
253
+ """Self-service password change: verifies ``current_password`` before replacing."""
254
+ name = _name(name)
255
+ if not current_password or not new_password:
256
+ raise AccountError("current password and new password are required")
257
+ if len(new_password) < 12:
258
+ raise AccountError("new password must be at least 12 characters")
259
+ verified = verify(root, name, current_password)
260
+ if verified is None:
261
+ raise AccountError("current password is incorrect")
262
+ salt, digest = _hash(new_password)
263
+ with _acct_lock(root):
264
+ accounts = load(root)
265
+ found = next((item for item in accounts if item.get("name") == name), None)
266
+ if found is None:
267
+ raise AccountError(f"account not found: {name}")
268
+ found["salt"] = salt
269
+ found["hash"] = digest
270
+ _save(root, accounts)
271
+ return {"name": name, "actor": found.get("actor") or "", "changed": True}
272
+
273
+
274
+ def role_for(root: Path, name: str) -> str:
275
+ """Return the current stored role for ``name``, or ``'viewer'`` if missing."""
276
+ wanted = (name or "").strip().lower()
277
+ if not wanted:
278
+ return "viewer"
279
+ for item in load(root):
280
+ if item.get("name") == wanted:
281
+ return (item.get("role") or DEFAULT_ROLE).strip().lower()
282
+ return "viewer"
283
+
284
+
285
+ def reset(root: Path, name: str) -> str:
286
+ """Replace the password. Returns the new one once."""
287
+ name = _name(name)
288
+ shown = secrets.token_urlsafe(18)
289
+ salt, digest = _hash(shown)
290
+ with _acct_lock(root):
291
+ accounts = load(root)
292
+ found = next((item for item in accounts if item.get("name") == name), None)
293
+ if found is None:
294
+ raise AccountError(f"account not found: {name}")
295
+ found["salt"] = salt
296
+ found["hash"] = digest
297
+ _save(root, accounts)
298
+ return shown
299
+
300
+
301
+ _DUMMY_SALT = b"stead-dummy-salt"
302
+
303
+
304
+ def verify(root: Path, name: str, password: str) -> dict | None:
305
+ """Return {name, actor} or None. Does not say which part was wrong."""
306
+ wanted = (name or "").strip().lower()
307
+ if not wanted or not password:
308
+ return None
309
+ for item in load(root):
310
+ if item.get("name") != wanted:
311
+ continue
312
+ if item.get("disabled"):
313
+ _hash(password, _DUMMY_SALT)
314
+ return None
315
+ salt = item.get("salt") or ""
316
+ expected = item.get("hash") or ""
317
+ if not salt or not expected:
318
+ return None
319
+ try:
320
+ _salt, digest = _hash(password, bytes.fromhex(salt))
321
+ except ValueError:
322
+ return None
323
+ if secrets.compare_digest(digest, expected):
324
+ return {
325
+ "name": wanted,
326
+ "actor": item.get("actor") or "",
327
+ "role": (item.get("role") or DEFAULT_ROLE).strip().lower(),
328
+ }
329
+ return None
330
+ # Equalize timing when the username does not exist.
331
+ _hash(password, _DUMMY_SALT)
332
+ return None
333
+
334
+
335
+ def _name(name: str) -> str:
336
+ name = (name or "").strip().lower()
337
+ if not _NAME.match(name):
338
+ raise AccountError("name must be letters, numbers, and hyphens")
339
+ return name
340
+
341
+
342
+ def _hash(password: str, salt: bytes | None = None) -> tuple[str, str]:
343
+ salt = salt or secrets.token_bytes(16)
344
+ digest = hashlib.scrypt(password.encode("utf-8"), salt=salt, **_SCRYPT)
345
+ return salt.hex(), digest.hex()
346
+
347
+
348
+ def _save(root: Path, accounts: list[dict]) -> None:
349
+ from ctx.util import atomic_write_json
350
+ atomic_write_json(accounts_path(root), {"accounts": accounts}, mode=0o600, prefix=".accounts-")