120 Commits

Author SHA1 Message Date
Danilo Reyes
788ea5ad26 rules fixup 2026-02-06 06:59:59 -06:00
Danilo Reyes
1fd29a5f4f nat table 2026-02-06 06:44:47 -06:00
Danilo Reyes
a15db616b4 removed windows_vm key 2026-02-06 06:12:10 -06:00
Danilo Reyes
7cedfba30d dont even remember 2026-02-06 05:21:51 -06:00
Danilo Reyes
c50c98e7b2 firewall tweaks 2026-02-05 18:25:45 -06:00
Danilo Reyes
6079e6446c working version firewall 2026-02-05 17:49:11 -06:00
Danilo Reyes
afbffaa203 ip declarations 2026-02-05 17:02:20 -06:00
Danilo Reyes
c09268891e firewall migration 2026-02-05 12:45:39 -06:00
Danilo Reyes
e1f7c2291a testing on lebubu 2026-02-05 12:06:28 -06:00
Danilo Reyes
9e64325f5e nextcloud uses different proxy 2026-02-05 11:12:37 -06:00
Danilo Reyes
6603fac1c4 nextcloud nginx split 2026-02-05 10:58:35 -06:00
Danilo Reyes
cb1776d670 fixing 2026-02-05 10:41:29 -06:00
Danilo Reyes
3517e394c6 nextcloud proxy logic attempt 2026-02-05 06:54:14 -06:00
Danilo Reyes
81f9025dc9 documentation update 2026-02-05 06:36:09 -06:00
Danilo Reyes
2ef113bc0e synapse cert logic 2026-02-05 06:30:45 -06:00
Danilo Reyes
d14a7ba395 private certificate fix 2026-02-05 06:26:40 -06:00
Danilo Reyes
eddef549e7 hmmm 2026-02-05 06:18:42 -06:00
Danilo Reyes
4ba0fa0dd5 nextcloud nginx logic needs to exists in two place 2026-02-05 06:04:42 -06:00
Danilo Reyes
08cc3379ad use merge to segment the complex nginx proxy settings 2026-02-05 05:32:46 -06:00
Danilo Reyes
2a290f2fe2 it was the nginx module... 2026-02-05 05:16:43 -06:00
Danilo Reyes
0c7e745e55 plausible actually ran on server im dumb 2026-02-05 05:06:43 -06:00
Danilo Reyes
caf7fbc590 nginx ip fix attempt 2026-02-05 04:58:41 -06:00
Danilo Reyes
ee11d72de8 domain sandbox 2026-02-05 04:16:21 -06:00
Danilo Reyes
dce2142794 proper ip assignation for nginx 2026-02-05 03:39:27 -06:00
Danilo Reyes
237e120124 working 2026-02-04 19:16:04 -06:00
Danilo Reyes
afdb5bfd99 chichis 2026-02-04 15:03:46 -06:00
Danilo Reyes
d7f9ea971c vps keys fix 2026-02-04 12:39:33 -06:00
Danilo Reyes
f01817a15f iptables 2026-02-04 11:42:39 -06:00
Danilo Reyes
917e741b7f rg_filter 2026-02-04 11:21:35 -06:00
Danilo Reyes
0997fad0c6 plausible + other fixes 2026-02-04 11:16:45 -06:00
Danilo Reyes
ba4cf6c86b root logic 2026-02-04 06:34:40 -06:00
Danilo Reyes
3f13527e51 "fixes" 2026-02-04 06:31:41 -06:00
Danilo Reyes
efe5cb0f99 remediations 2 2026-02-03 20:44:09 -06:00
Danilo Reyes
86557548db remediations 2026-02-03 20:43:25 -06:00
Danilo Reyes
a74adc7f95 init 2026-02-03 20:35:44 -06:00
b5e358ee22 Merge pull request '003-vps-image-migration' (#4) from 003-vps-image-migration into main
Some checks failed
MCP Tests / mcp-tests (push) Failing after 6s
Reviewed-on: #4
2026-02-03 19:54:21 -06:00
Danilo Reyes
f845699845 meh
Some checks failed
MCP Tests / mcp-tests (pull_request) Failing after 8s
2026-02-03 19:53:15 -06:00
Danilo Reyes
47910ab3a0 vps hardware 2026-02-03 17:53:00 -06:00
Danilo Reyes
26dcef64ca new sops 2026-02-03 17:43:14 -06:00
Danilo Reyes
d99da36f3e syncthing function parameters 2026-02-03 17:35:42 -06:00
Danilo Reyes
a90eb89af2 hmmm 2026-02-03 17:29:14 -06:00
Danilo Reyes
59c8234d3c fix? 2026-02-03 17:24:05 -06:00
Danilo Reyes
b07d867d78 linode-image imports 2026-02-03 17:21:29 -06:00
Danilo Reyes
2f535cc91a linode setup 2026-02-03 17:02:16 -06:00
Danilo Reyes
42b39513a1 finish linode image 2026-02-03 16:28:26 -06:00
Danilo Reyes
592eb04e66 vps ssh keys 2026-02-03 16:21:55 -06:00
Danilo Reyes
dbd3af3d0f new hosts vps 2026-02-03 15:31:47 -06:00
Danilo Reyes
f6b1a01438 removed nixos-generators 2026-02-03 15:17:18 -06:00
Danilo Reyes
979bb915a6 init 2026-02-03 15:13:56 -06:00
Danilo Reyes
da352265f6 whitelist syncthing 2026-02-03 15:09:04 -06:00
Danilo Reyes
d2f8e279d1 branch fixes
Some checks failed
MCP Tests / mcp-tests (push) Failing after 8s
2026-02-03 13:41:25 -06:00
Danilo Reyes
6fcb1b50b4 yamtrack apis 2026-02-03 13:25:10 -06:00
NixOS Builder Bot
51bf9eae26 Weekly flake update: 2026-02-02 10:19 UTC 2026-02-02 04:19:05 -06:00
Danilo Reyes
657986cf15 sops patches
All checks were successful
Weekly NixOS Build & Cache / build-and-cache (push) Successful in 48m15s
2026-02-01 20:48:17 -06:00
Danilo Reyes
da4ae90c11 pipeline fix
Some checks are pending
MCP Tests / mcp-tests (push) Waiting to run
2026-02-01 20:22:40 -06:00
Danilo Reyes
6bdef87118 ryot > yamtrack 2026-02-01 19:56:53 -06:00
Danilo Reyes
6389b9f012 homepage adjustments 2026-02-01 16:59:55 -06:00
Danilo Reyes
32545e4fec linkwarden 2026-02-01 16:07:19 -06:00
Danilo Reyes
b7eab2dd94 exec pipeline as bash
Some checks failed
MCP Tests / mcp-tests (push) Failing after 4s
2026-02-01 12:09:17 -06:00
Danilo Reyes
f0d28b4a1e sync-docs
Some checks failed
MCP Tests / mcp-tests (push) Failing after 6s
2026-02-01 11:31:48 -06:00
a29aa773fc Merge pull request '001-mcp-server' (#3) from 001-mcp-server into main
Some checks failed
MCP Tests / mcp-tests (push) Failing after 3s
Reviewed-on: #3
2026-02-01 10:38:13 -06:00
Danilo Reyes
8946ade5e8 mcp server done
Some checks failed
MCP Tests / mcp-tests (pull_request) Failing after 4s
2026-02-01 10:36:54 -06:00
Danilo Reyes
ecf058aacf codex dotfiles 2026-02-01 10:05:56 -06:00
Danilo Reyes
703723b368 mcp dev environment 2026-01-31 17:39:52 -06:00
Danilo Reyes
97053901c0 mcp 2026-01-30 23:17:02 -06:00
Danilo Reyes
527fad8da0 init 2026-01-30 22:48:02 -06:00
2a418c4394 Merge pull request '001-ai-docs' (#2) from 001-ai-docs into main
Reviewed-on: #2
2026-01-30 22:20:12 -06:00
Danilo Reyes
56177eab30 constitution update 2026-01-30 22:19:06 -06:00
Danilo Reyes
d448e0f6c8 reviewing 2026-01-30 16:42:29 -06:00
Danilo Reyes
5da9abf1b7 init 2026-01-30 16:31:02 -06:00
NixOS Builder Bot
93411591ef Weekly flake update: 2026-01-30 09:47 UTC 2026-01-30 03:47:10 -06:00
Danilo Reyes
832054d987 prem2resolve
All checks were successful
Weekly NixOS Build & Cache / build-and-cache (push) Successful in 16m28s
2026-01-28 06:30:10 -06:00
NixOS Builder Bot
524859e737 Weekly flake update: 2026-01-26 10:20 UTC 2026-01-26 04:20:53 -06:00
Danilo Reyes
487fb1c294 registration secret
All checks were successful
Weekly NixOS Build & Cache / build-and-cache (push) Successful in 50m10s
2026-01-25 09:47:56 -06:00
Danilo Reyes
02b234ba6e proper syncthing id 2026-01-24 20:40:27 -06:00
Danilo Reyes
0e97d8c0c3 syncthing test friend 2026-01-24 18:53:49 -06:00
Danilo Reyes
94649363bb new vps wireguard friends 2026-01-24 18:13:26 -06:00
NixOS Builder Bot
c969158d00 Weekly flake update: 2026-01-24 00:22 UTC 2026-01-23 18:22:11 -06:00
Danilo Reyes
a45c33db1e ryot v10 2026-01-23 13:31:54 -06:00
Danilo Reyes
ef20380003 ryot upgrade to 6.0 2026-01-23 13:29:48 -06:00
Danilo Reyes
f3ae6163d0 derek configs 2026-01-23 13:29:41 -06:00
Danilo Reyes
0f65ad5217 selectively picked cudaSupport
Some checks failed
Weekly NixOS Build & Cache / build-and-cache (push) Failing after 2h0m53s
2026-01-18 17:58:33 -06:00
Danilo Reyes
4f87fec66e global cuda support 2026-01-18 17:20:33 -06:00
Danilo Reyes
8c539ca436 theme change 2026-01-18 17:20:24 -06:00
Danilo Reyes
845e027272 toggle both users for gnome 2026-01-18 17:20:11 -06:00
Danilo Reyes
1f173fa3c9 gnome extensions multi-user 2026-01-18 17:20:00 -06:00
Danilo Reyes
72d97655af blender cuda support 2026-01-17 16:58:58 -06:00
Danilo Reyes
253123c09b typo fixes uid gid 2026-01-17 16:57:18 -06:00
Danilo Reyes
20c8d082eb wip uid/gid mapping 2026-01-17 13:36:51 -06:00
Danilo Reyes
1b76039f49 parsec gone 2026-01-17 10:44:15 -06:00
Danilo Reyes
09bed16ffc antivirus 2026-01-17 06:19:57 -06:00
Danilo Reyes
d146fa68f7 not auto start sunshine 2026-01-17 06:00:00 -06:00
Danilo Reyes
c87a446a26 oops 2026-01-16 17:08:27 -06:00
Danilo Reyes
8aa95491cf parsec 2026-01-16 17:07:15 -06:00
Danilo Reyes
797963dc8b jawz scripts flake update 2026-01-16 15:30:28 -06:00
Danilo Reyes
19bc6f13d0 linting 2026-01-16 15:18:31 -06:00
Danilo Reyes
7368c914b5 mkforce 2026-01-16 15:03:07 -06:00
Danilo Reyes
ba51fce5f8 stash unprivated users 2026-01-16 14:56:51 -06:00
Danilo Reyes
25d22d0983 Update org-hugo-base-dir path in Doom Emacs configuration
Changed the org-hugo-base-dir from an absolute path to a relative path using the home directory shortcut. This adjustment improves portability of the configuration across different environments.
2026-01-16 14:07:43 -06:00
Danilo Reyes
0559d212fe Add user-specific configurations for Emacs and Stylix across multiple hosts
Updated the configuration files for miniserver, server, and workstation to include user-specific settings for Emacs and Stylix. This change enhances user management consistency and aligns with the recent refactor for multi-user support in the configuration.
2026-01-16 14:06:42 -06:00
Danilo Reyes
fa19c92b1e Update color scheme polarity for 'paul' to dark in schemes.nix
Some checks failed
Build All Color Schemes / build-schemes (push) Failing after 38m58s
2026-01-16 13:47:51 -06:00
Danilo Reyes
5e96618d8a Refactor user management in configuration files for enhanced consistency
Updated multiple configuration files to implement a unified approach for user management across applications and services. Introduced `mkEnabledWithUsers` to streamline user configuration, improving maintainability and flexibility in multi-user setups.
2026-01-16 13:47:17 -06:00
Danilo Reyes
6573392c3b Refactor user option types across modules for consistency
Updated multiple configuration files to replace the user option type with a unified `usersOptionType`, enhancing consistency in user management across applications and services. This change simplifies the user configuration process and improves maintainability.
2026-01-16 13:40:44 -06:00
Danilo Reyes
f1e6015d39 Add multi-user support for package installations across various modules
Updated multiple configuration files to include a `merge` option for user management, enhancing the ability to handle multi-user setups for applications and services. This change improves flexibility in managing user-specific package installations, ensuring a more streamlined configuration process.
2026-01-16 13:38:49 -06:00
Danilo Reyes
cceb4da041 Add custom font management and multimedia video editing support
Enhanced the configuration by introducing a custom font management system, allowing for the installation of additional fonts. Updated multimedia settings to include video editing applications, enabling users to manage multimedia and video editing packages more effectively. Removed the deprecated fonts module to streamline the configuration.
2026-01-16 13:28:18 -06:00
Danilo Reyes
cbe7c25812 Add multi-user support for various applications and services
Enhanced the configuration files to support multi-user management by introducing user options for multiple applications, including art, gaming, multimedia, and development tools. Updated existing modules to utilize these new user options, improving flexibility and maintainability in user package installations.
2026-01-16 13:07:56 -06:00
Danilo Reyes
2893487ffc format 2026-01-16 11:47:15 -06:00
Danilo Reyes
9629493d02 paul rosolie <3 2026-01-16 11:46:58 -06:00
Danilo Reyes
495f6e2e25 Refactor user management functions to use inputs
Removed the `lib.nix` file and refactored various modules to utilize `inputs.self.lib` for user package and attribute management. This change enhances consistency and maintainability across the configuration files.
2026-01-16 10:55:15 -06:00
Danilo Reyes
b89d193445 Add helper functions for multi-user toggle support
Introduced a new file `lib.nix` containing helper functions to streamline user package management and attributes for multi-user configurations. Updated various modules to utilize these functions, enhancing code maintainability and readability.
2026-01-16 10:36:02 -06:00
Danilo Reyes
4e835aca1b multi-user toggle init 2026-01-16 10:19:36 -06:00
Danilo Reyes
597f9ee5b8 new control groups 2026-01-16 09:53:02 -06:00
Danilo Reyes
d4c7ea8742 derek user 2026-01-16 09:53:02 -06:00
Danilo Reyes
f630e1483b webref migrated to module 2026-01-16 09:53:02 -06:00
NixOS Builder Bot
983e271075 Weekly flake update: 2026-01-16 10:47 UTC 2026-01-16 04:47:04 -06:00
NixOS Builder Bot
7aed2c9a65 Weekly flake update: 2026-01-10 15:39 UTC 2026-01-10 09:39:57 -06:00
Danilo Reyes
9cf2b7df40 metube update
All checks were successful
Weekly NixOS Build & Cache / build-and-cache (push) Successful in 57m27s
2026-01-06 07:51:30 -06:00
NixOS Builder Bot
2a793a3dec Weekly flake update: 2026-01-05 10:14 UTC 2026-01-05 04:14:54 -06:00
NixOS Builder Bot
89c3c0badc Weekly flake update: 2026-01-02 09:58 UTC 2026-01-02 03:58:50 -06:00
Danilo Reyes
43294b20c0 torrent port
All checks were successful
Weekly NixOS Build & Cache / build-and-cache (push) Successful in 28m19s
2026-01-01 23:45:35 -06:00
189 changed files with 10684 additions and 1306 deletions

16
.codex/config.toml Normal file
View File

@@ -0,0 +1,16 @@
version = 1
model = "gpt-5.2-codex"
[projects."/home/jawz/Development/NixOS"]
workspace = "/home/jawz/Development/NixOS"
trust_level = "trusted"
[notice]
"hide_gpt-5.1-codex-max_migration_prompt" = true
[notice.model_migrations]
"gpt-5.1-codex-max" = "gpt-5.2-codex"
[mcp_servers.nixos-mcp]
command = "nixos-mcp"
cwd = "/home/jawz/Development/NixOS"

View File

@@ -0,0 +1,184 @@
---
description: Perform a non-destructive cross-artifact consistency and quality analysis across spec.md, plan.md, and tasks.md after task generation.
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Goal
Identify inconsistencies, duplications, ambiguities, and underspecified items across the three core artifacts (`spec.md`, `plan.md`, `tasks.md`) before implementation. This command MUST run only after `/speckit.tasks` has successfully produced a complete `tasks.md`.
## Operating Constraints
**STRICTLY READ-ONLY**: Do **not** modify any files. Output a structured analysis report. Offer an optional remediation plan (user must explicitly approve before any follow-up editing commands would be invoked manually).
**Constitution Authority**: The project constitution (`.specify/memory/constitution.md`) is **non-negotiable** within this analysis scope. Constitution conflicts are automatically CRITICAL and require adjustment of the spec, plan, or tasks—not dilution, reinterpretation, or silent ignoring of the principle. If a principle itself needs to change, that must occur in a separate, explicit constitution update outside `/speckit.analyze`.
## Execution Steps
### 1. Initialize Analysis Context
Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` once from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS. Derive absolute paths:
- SPEC = FEATURE_DIR/spec.md
- PLAN = FEATURE_DIR/plan.md
- TASKS = FEATURE_DIR/tasks.md
Abort with an error message if any required file is missing (instruct the user to run missing prerequisite command).
For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
### 2. Load Artifacts (Progressive Disclosure)
Load only the minimal necessary context from each artifact:
**From spec.md:**
- Overview/Context
- Functional Requirements
- Non-Functional Requirements
- User Stories
- Edge Cases (if present)
**From plan.md:**
- Architecture/stack choices
- Data Model references
- Phases
- Technical constraints
**From tasks.md:**
- Task IDs
- Descriptions
- Phase grouping
- Parallel markers [P]
- Referenced file paths
**From constitution:**
- Load `.specify/memory/constitution.md` for principle validation
### 3. Build Semantic Models
Create internal representations (do not include raw artifacts in output):
- **Requirements inventory**: Each functional + non-functional requirement with a stable key (derive slug based on imperative phrase; e.g., "User can upload file" → `user-can-upload-file`)
- **User story/action inventory**: Discrete user actions with acceptance criteria
- **Task coverage mapping**: Map each task to one or more requirements or stories (inference by keyword / explicit reference patterns like IDs or key phrases)
- **Constitution rule set**: Extract principle names and MUST/SHOULD normative statements
### 4. Detection Passes (Token-Efficient Analysis)
Focus on high-signal findings. Limit to 50 findings total; aggregate remainder in overflow summary.
#### A. Duplication Detection
- Identify near-duplicate requirements
- Mark lower-quality phrasing for consolidation
#### B. Ambiguity Detection
- Flag vague adjectives (fast, scalable, secure, intuitive, robust) lacking measurable criteria
- Flag unresolved placeholders (TODO, TKTK, ???, `<placeholder>`, etc.)
#### C. Underspecification
- Requirements with verbs but missing object or measurable outcome
- User stories missing acceptance criteria alignment
- Tasks referencing files or components not defined in spec/plan
#### D. Constitution Alignment
- Any requirement or plan element conflicting with a MUST principle
- Missing mandated sections or quality gates from constitution
#### E. Coverage Gaps
- Requirements with zero associated tasks
- Tasks with no mapped requirement/story
- Non-functional requirements not reflected in tasks (e.g., performance, security)
#### F. Inconsistency
- Terminology drift (same concept named differently across files)
- Data entities referenced in plan but absent in spec (or vice versa)
- Task ordering contradictions (e.g., integration tasks before foundational setup tasks without dependency note)
- Conflicting requirements (e.g., one requires Next.js while other specifies Vue)
### 5. Severity Assignment
Use this heuristic to prioritize findings:
- **CRITICAL**: Violates constitution MUST, missing core spec artifact, or requirement with zero coverage that blocks baseline functionality
- **HIGH**: Duplicate or conflicting requirement, ambiguous security/performance attribute, untestable acceptance criterion
- **MEDIUM**: Terminology drift, missing non-functional task coverage, underspecified edge case
- **LOW**: Style/wording improvements, minor redundancy not affecting execution order
### 6. Produce Compact Analysis Report
Output a Markdown report (no file writes) with the following structure:
## Specification Analysis Report
| ID | Category | Severity | Location(s) | Summary | Recommendation |
|----|----------|----------|-------------|---------|----------------|
| A1 | Duplication | HIGH | spec.md:L120-134 | Two similar requirements ... | Merge phrasing; keep clearer version |
(Add one row per finding; generate stable IDs prefixed by category initial.)
**Coverage Summary Table:**
| Requirement Key | Has Task? | Task IDs | Notes |
|-----------------|-----------|----------|-------|
**Constitution Alignment Issues:** (if any)
**Unmapped Tasks:** (if any)
**Metrics:**
- Total Requirements
- Total Tasks
- Coverage % (requirements with >=1 task)
- Ambiguity Count
- Duplication Count
- Critical Issues Count
### 7. Provide Next Actions
At end of report, output a concise Next Actions block:
- If CRITICAL issues exist: Recommend resolving before `/speckit.implement`
- If only LOW/MEDIUM: User may proceed, but provide improvement suggestions
- Provide explicit command suggestions: e.g., "Run /speckit.specify with refinement", "Run /speckit.plan to adjust architecture", "Manually edit tasks.md to add coverage for 'performance-metrics'"
### 8. Offer Remediation
Ask the user: "Would you like me to suggest concrete remediation edits for the top N issues?" (Do NOT apply them automatically.)
## Operating Principles
### Context Efficiency
- **Minimal high-signal tokens**: Focus on actionable findings, not exhaustive documentation
- **Progressive disclosure**: Load artifacts incrementally; don't dump all content into analysis
- **Token-efficient output**: Limit findings table to 50 rows; summarize overflow
- **Deterministic results**: Rerunning without changes should produce consistent IDs and counts
### Analysis Guidelines
- **NEVER modify files** (this is read-only analysis)
- **NEVER hallucinate missing sections** (if absent, report them accurately)
- **Prioritize constitution violations** (these are always CRITICAL)
- **Use examples over exhaustive rules** (cite specific instances, not generic patterns)
- **Report zero issues gracefully** (emit success report with coverage statistics)
## Context
$ARGUMENTS

View File

@@ -0,0 +1,294 @@
---
description: Generate a custom checklist for the current feature based on user requirements.
---
## Checklist Purpose: "Unit Tests for English"
**CRITICAL CONCEPT**: Checklists are **UNIT TESTS FOR REQUIREMENTS WRITING** - they validate the quality, clarity, and completeness of requirements in a given domain.
**NOT for verification/testing**:
- ❌ NOT "Verify the button clicks correctly"
- ❌ NOT "Test error handling works"
- ❌ NOT "Confirm the API returns 200"
- ❌ NOT checking if code/implementation matches the spec
**FOR requirements quality validation**:
- ✅ "Are visual hierarchy requirements defined for all card types?" (completeness)
- ✅ "Is 'prominent display' quantified with specific sizing/positioning?" (clarity)
- ✅ "Are hover state requirements consistent across all interactive elements?" (consistency)
- ✅ "Are accessibility requirements defined for keyboard navigation?" (coverage)
- ✅ "Does the spec define what happens when logo image fails to load?" (edge cases)
**Metaphor**: If your spec is code written in English, the checklist is its unit test suite. You're testing whether the requirements are well-written, complete, unambiguous, and ready for implementation - NOT whether the implementation works.
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Execution Steps
1. **Setup**: Run `.specify/scripts/bash/check-prerequisites.sh --json` from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS list.
- All file paths must be absolute.
- For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **Clarify intent (dynamic)**: Derive up to THREE initial contextual clarifying questions (no pre-baked catalog). They MUST:
- Be generated from the user's phrasing + extracted signals from spec/plan/tasks
- Only ask about information that materially changes checklist content
- Be skipped individually if already unambiguous in `$ARGUMENTS`
- Prefer precision over breadth
Generation algorithm:
1. Extract signals: feature domain keywords (e.g., auth, latency, UX, API), risk indicators ("critical", "must", "compliance"), stakeholder hints ("QA", "review", "security team"), and explicit deliverables ("a11y", "rollback", "contracts").
2. Cluster signals into candidate focus areas (max 4) ranked by relevance.
3. Identify probable audience & timing (author, reviewer, QA, release) if not explicit.
4. Detect missing dimensions: scope breadth, depth/rigor, risk emphasis, exclusion boundaries, measurable acceptance criteria.
5. Formulate questions chosen from these archetypes:
- Scope refinement (e.g., "Should this include integration touchpoints with X and Y or stay limited to local module correctness?")
- Risk prioritization (e.g., "Which of these potential risk areas should receive mandatory gating checks?")
- Depth calibration (e.g., "Is this a lightweight pre-commit sanity list or a formal release gate?")
- Audience framing (e.g., "Will this be used by the author only or peers during PR review?")
- Boundary exclusion (e.g., "Should we explicitly exclude performance tuning items this round?")
- Scenario class gap (e.g., "No recovery flows detected—are rollback / partial failure paths in scope?")
Question formatting rules:
- If presenting options, generate a compact table with columns: Option | Candidate | Why It Matters
- Limit to AE options maximum; omit table if a free-form answer is clearer
- Never ask the user to restate what they already said
- Avoid speculative categories (no hallucination). If uncertain, ask explicitly: "Confirm whether X belongs in scope."
Defaults when interaction impossible:
- Depth: Standard
- Audience: Reviewer (PR) if code-related; Author otherwise
- Focus: Top 2 relevance clusters
Output the questions (label Q1/Q2/Q3). After answers: if ≥2 scenario classes (Alternate / Exception / Recovery / Non-Functional domain) remain unclear, you MAY ask up to TWO more targeted followups (Q4/Q5) with a one-line justification each (e.g., "Unresolved recovery path risk"). Do not exceed five total questions. Skip escalation if user explicitly declines more.
3. **Understand user request**: Combine `$ARGUMENTS` + clarifying answers:
- Derive checklist theme (e.g., security, review, deploy, ux)
- Consolidate explicit must-have items mentioned by user
- Map focus selections to category scaffolding
- Infer any missing context from spec/plan/tasks (do NOT hallucinate)
4. **Load feature context**: Read from FEATURE_DIR:
- spec.md: Feature requirements and scope
- plan.md (if exists): Technical details, dependencies
- tasks.md (if exists): Implementation tasks
**Context Loading Strategy**:
- Load only necessary portions relevant to active focus areas (avoid full-file dumping)
- Prefer summarizing long sections into concise scenario/requirement bullets
- Use progressive disclosure: add follow-on retrieval only if gaps detected
- If source docs are large, generate interim summary items instead of embedding raw text
5. **Generate checklist** - Create "Unit Tests for Requirements":
- Create `FEATURE_DIR/checklists/` directory if it doesn't exist
- Generate unique checklist filename:
- Use short, descriptive name based on domain (e.g., `ux.md`, `api.md`, `security.md`)
- Format: `[domain].md`
- If file exists, append to existing file
- Number items sequentially starting from CHK001
- Each `/speckit.checklist` run creates a NEW file (never overwrites existing checklists)
**CORE PRINCIPLE - Test the Requirements, Not the Implementation**:
Every checklist item MUST evaluate the REQUIREMENTS THEMSELVES for:
- **Completeness**: Are all necessary requirements present?
- **Clarity**: Are requirements unambiguous and specific?
- **Consistency**: Do requirements align with each other?
- **Measurability**: Can requirements be objectively verified?
- **Coverage**: Are all scenarios/edge cases addressed?
**Category Structure** - Group items by requirement quality dimensions:
- **Requirement Completeness** (Are all necessary requirements documented?)
- **Requirement Clarity** (Are requirements specific and unambiguous?)
- **Requirement Consistency** (Do requirements align without conflicts?)
- **Acceptance Criteria Quality** (Are success criteria measurable?)
- **Scenario Coverage** (Are all flows/cases addressed?)
- **Edge Case Coverage** (Are boundary conditions defined?)
- **Non-Functional Requirements** (Performance, Security, Accessibility, etc. - are they specified?)
- **Dependencies & Assumptions** (Are they documented and validated?)
- **Ambiguities & Conflicts** (What needs clarification?)
**HOW TO WRITE CHECKLIST ITEMS - "Unit Tests for English"**:
**WRONG** (Testing implementation):
- "Verify landing page displays 3 episode cards"
- "Test hover states work on desktop"
- "Confirm logo click navigates home"
**CORRECT** (Testing requirements quality):
- "Are the exact number and layout of featured episodes specified?" [Completeness]
- "Is 'prominent display' quantified with specific sizing/positioning?" [Clarity]
- "Are hover state requirements consistent across all interactive elements?" [Consistency]
- "Are keyboard navigation requirements defined for all interactive UI?" [Coverage]
- "Is the fallback behavior specified when logo image fails to load?" [Edge Cases]
- "Are loading states defined for asynchronous episode data?" [Completeness]
- "Does the spec define visual hierarchy for competing UI elements?" [Clarity]
**ITEM STRUCTURE**:
Each item should follow this pattern:
- Question format asking about requirement quality
- Focus on what's WRITTEN (or not written) in the spec/plan
- Include quality dimension in brackets [Completeness/Clarity/Consistency/etc.]
- Reference spec section `[Spec §X.Y]` when checking existing requirements
- Use `[Gap]` marker when checking for missing requirements
**EXAMPLES BY QUALITY DIMENSION**:
Completeness:
- "Are error handling requirements defined for all API failure modes? [Gap]"
- "Are accessibility requirements specified for all interactive elements? [Completeness]"
- "Are mobile breakpoint requirements defined for responsive layouts? [Gap]"
Clarity:
- "Is 'fast loading' quantified with specific timing thresholds? [Clarity, Spec §NFR-2]"
- "Are 'related episodes' selection criteria explicitly defined? [Clarity, Spec §FR-5]"
- "Is 'prominent' defined with measurable visual properties? [Ambiguity, Spec §FR-4]"
Consistency:
- "Do navigation requirements align across all pages? [Consistency, Spec §FR-10]"
- "Are card component requirements consistent between landing and detail pages? [Consistency]"
Coverage:
- "Are requirements defined for zero-state scenarios (no episodes)? [Coverage, Edge Case]"
- "Are concurrent user interaction scenarios addressed? [Coverage, Gap]"
- "Are requirements specified for partial data loading failures? [Coverage, Exception Flow]"
Measurability:
- "Are visual hierarchy requirements measurable/testable? [Acceptance Criteria, Spec §FR-1]"
- "Can 'balanced visual weight' be objectively verified? [Measurability, Spec §FR-2]"
**Scenario Classification & Coverage** (Requirements Quality Focus):
- Check if requirements exist for: Primary, Alternate, Exception/Error, Recovery, Non-Functional scenarios
- For each scenario class, ask: "Are [scenario type] requirements complete, clear, and consistent?"
- If scenario class missing: "Are [scenario type] requirements intentionally excluded or missing? [Gap]"
- Include resilience/rollback when state mutation occurs: "Are rollback requirements defined for migration failures? [Gap]"
**Traceability Requirements**:
- MINIMUM: ≥80% of items MUST include at least one traceability reference
- Each item should reference: spec section `[Spec §X.Y]`, or use markers: `[Gap]`, `[Ambiguity]`, `[Conflict]`, `[Assumption]`
- If no ID system exists: "Is a requirement & acceptance criteria ID scheme established? [Traceability]"
**Surface & Resolve Issues** (Requirements Quality Problems):
Ask questions about the requirements themselves:
- Ambiguities: "Is the term 'fast' quantified with specific metrics? [Ambiguity, Spec §NFR-1]"
- Conflicts: "Do navigation requirements conflict between §FR-10 and §FR-10a? [Conflict]"
- Assumptions: "Is the assumption of 'always available podcast API' validated? [Assumption]"
- Dependencies: "Are external podcast API requirements documented? [Dependency, Gap]"
- Missing definitions: "Is 'visual hierarchy' defined with measurable criteria? [Gap]"
**Content Consolidation**:
- Soft cap: If raw candidate items > 40, prioritize by risk/impact
- Merge near-duplicates checking the same requirement aspect
- If >5 low-impact edge cases, create one item: "Are edge cases X, Y, Z addressed in requirements? [Coverage]"
**🚫 ABSOLUTELY PROHIBITED** - These make it an implementation test, not a requirements test:
- ❌ Any item starting with "Verify", "Test", "Confirm", "Check" + implementation behavior
- ❌ References to code execution, user actions, system behavior
- ❌ "Displays correctly", "works properly", "functions as expected"
- ❌ "Click", "navigate", "render", "load", "execute"
- ❌ Test cases, test plans, QA procedures
- ❌ Implementation details (frameworks, APIs, algorithms)
**✅ REQUIRED PATTERNS** - These test requirements quality:
- ✅ "Are [requirement type] defined/specified/documented for [scenario]?"
- ✅ "Is [vague term] quantified/clarified with specific criteria?"
- ✅ "Are requirements consistent between [section A] and [section B]?"
- ✅ "Can [requirement] be objectively measured/verified?"
- ✅ "Are [edge cases/scenarios] addressed in requirements?"
- ✅ "Does the spec define [missing aspect]?"
6. **Structure Reference**: Generate the checklist following the canonical template in `.specify/templates/checklist-template.md` for title, meta section, category headings, and ID formatting. If template is unavailable, use: H1 title, purpose/created meta lines, `##` category sections containing `- [ ] CHK### <requirement item>` lines with globally incrementing IDs starting at CHK001.
7. **Report**: Output full path to created checklist, item count, and remind user that each run creates a new file. Summarize:
- Focus areas selected
- Depth level
- Actor/timing
- Any explicit user-specified must-have items incorporated
**Important**: Each `/speckit.checklist` command invocation creates a checklist file using short, descriptive names unless file already exists. This allows:
- Multiple checklists of different types (e.g., `ux.md`, `test.md`, `security.md`)
- Simple, memorable filenames that indicate checklist purpose
- Easy identification and navigation in the `checklists/` folder
To avoid clutter, use descriptive types and clean up obsolete checklists when done.
## Example Checklist Types & Sample Items
**UX Requirements Quality:** `ux.md`
Sample items (testing the requirements, NOT the implementation):
- "Are visual hierarchy requirements defined with measurable criteria? [Clarity, Spec §FR-1]"
- "Is the number and positioning of UI elements explicitly specified? [Completeness, Spec §FR-1]"
- "Are interaction state requirements (hover, focus, active) consistently defined? [Consistency]"
- "Are accessibility requirements specified for all interactive elements? [Coverage, Gap]"
- "Is fallback behavior defined when images fail to load? [Edge Case, Gap]"
- "Can 'prominent display' be objectively measured? [Measurability, Spec §FR-4]"
**API Requirements Quality:** `api.md`
Sample items:
- "Are error response formats specified for all failure scenarios? [Completeness]"
- "Are rate limiting requirements quantified with specific thresholds? [Clarity]"
- "Are authentication requirements consistent across all endpoints? [Consistency]"
- "Are retry/timeout requirements defined for external dependencies? [Coverage, Gap]"
- "Is versioning strategy documented in requirements? [Gap]"
**Performance Requirements Quality:** `performance.md`
Sample items:
- "Are performance requirements quantified with specific metrics? [Clarity]"
- "Are performance targets defined for all critical user journeys? [Coverage]"
- "Are performance requirements under different load conditions specified? [Completeness]"
- "Can performance requirements be objectively measured? [Measurability]"
- "Are degradation requirements defined for high-load scenarios? [Edge Case, Gap]"
**Security Requirements Quality:** `security.md`
Sample items:
- "Are authentication requirements specified for all protected resources? [Coverage]"
- "Are data protection requirements defined for sensitive information? [Completeness]"
- "Is the threat model documented and requirements aligned to it? [Traceability]"
- "Are security requirements consistent with compliance obligations? [Consistency]"
- "Are security failure/breach response requirements defined? [Gap, Exception Flow]"
## Anti-Examples: What NOT To Do
**❌ WRONG - These test implementation, not requirements:**
```markdown
- [ ] CHK001 - Verify landing page displays 3 episode cards [Spec §FR-001]
- [ ] CHK002 - Test hover states work correctly on desktop [Spec §FR-003]
- [ ] CHK003 - Confirm logo click navigates to home page [Spec §FR-010]
- [ ] CHK004 - Check that related episodes section shows 3-5 items [Spec §FR-005]
```
**✅ CORRECT - These test requirements quality:**
```markdown
- [ ] CHK001 - Are the number and layout of featured episodes explicitly specified? [Completeness, Spec §FR-001]
- [ ] CHK002 - Are hover state requirements consistently defined for all interactive elements? [Consistency, Spec §FR-003]
- [ ] CHK003 - Are navigation requirements clear for all clickable brand elements? [Clarity, Spec §FR-010]
- [ ] CHK004 - Is the selection criteria for related episodes documented? [Gap, Spec §FR-005]
- [ ] CHK005 - Are loading state requirements defined for asynchronous episode data? [Gap]
- [ ] CHK006 - Can "visual hierarchy" requirements be objectively measured? [Measurability, Spec §FR-001]
```
**Key Differences:**
- Wrong: Tests if the system works correctly
- Correct: Tests if the requirements are written correctly
- Wrong: Verification of behavior
- Correct: Validation of requirement quality
- Wrong: "Does it do X?"
- Correct: "Is X clearly specified?"

View File

@@ -0,0 +1,181 @@
---
description: Identify underspecified areas in the current feature spec by asking up to 5 highly targeted clarification questions and encoding answers back into the spec.
handoffs:
- label: Build Technical Plan
agent: speckit.plan
prompt: Create a plan for the spec. I am building with...
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Outline
Goal: Detect and reduce ambiguity or missing decision points in the active feature specification and record the clarifications directly in the spec file.
Note: This clarification workflow is expected to run (and be completed) BEFORE invoking `/speckit.plan`. If the user explicitly states they are skipping clarification (e.g., exploratory spike), you may proceed, but must warn that downstream rework risk increases.
Execution steps:
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --paths-only` from repo root **once** (combined `--json --paths-only` mode / `-Json -PathsOnly`). Parse minimal JSON payload fields:
- `FEATURE_DIR`
- `FEATURE_SPEC`
- (Optionally capture `IMPL_PLAN`, `TASKS` for future chained flows.)
- If JSON parsing fails, abort and instruct user to re-run `/speckit.specify` or verify feature branch environment.
- For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. Load the current spec file. Perform a structured ambiguity & coverage scan using this taxonomy. For each category, mark status: Clear / Partial / Missing. Produce an internal coverage map used for prioritization (do not output raw map unless no questions will be asked).
Functional Scope & Behavior:
- Core user goals & success criteria
- Explicit out-of-scope declarations
- User roles / personas differentiation
Domain & Data Model:
- Entities, attributes, relationships
- Identity & uniqueness rules
- Lifecycle/state transitions
- Data volume / scale assumptions
Interaction & UX Flow:
- Critical user journeys / sequences
- Error/empty/loading states
- Accessibility or localization notes
Non-Functional Quality Attributes:
- Performance (latency, throughput targets)
- Scalability (horizontal/vertical, limits)
- Reliability & availability (uptime, recovery expectations)
- Observability (logging, metrics, tracing signals)
- Security & privacy (authN/Z, data protection, threat assumptions)
- Compliance / regulatory constraints (if any)
Integration & External Dependencies:
- External services/APIs and failure modes
- Data import/export formats
- Protocol/versioning assumptions
Edge Cases & Failure Handling:
- Negative scenarios
- Rate limiting / throttling
- Conflict resolution (e.g., concurrent edits)
Constraints & Tradeoffs:
- Technical constraints (language, storage, hosting)
- Explicit tradeoffs or rejected alternatives
Terminology & Consistency:
- Canonical glossary terms
- Avoided synonyms / deprecated terms
Completion Signals:
- Acceptance criteria testability
- Measurable Definition of Done style indicators
Misc / Placeholders:
- TODO markers / unresolved decisions
- Ambiguous adjectives ("robust", "intuitive") lacking quantification
For each category with Partial or Missing status, add a candidate question opportunity unless:
- Clarification would not materially change implementation or validation strategy
- Information is better deferred to planning phase (note internally)
3. Generate (internally) a prioritized queue of candidate clarification questions (maximum 5). Do NOT output them all at once. Apply these constraints:
- Maximum of 10 total questions across the whole session.
- Each question must be answerable with EITHER:
- A short multiplechoice selection (25 distinct, mutually exclusive options), OR
- A one-word / shortphrase answer (explicitly constrain: "Answer in <=5 words").
- Only include questions whose answers materially impact architecture, data modeling, task decomposition, test design, UX behavior, operational readiness, or compliance validation.
- Ensure category coverage balance: attempt to cover the highest impact unresolved categories first; avoid asking two low-impact questions when a single high-impact area (e.g., security posture) is unresolved.
- Exclude questions already answered, trivial stylistic preferences, or plan-level execution details (unless blocking correctness).
- Favor clarifications that reduce downstream rework risk or prevent misaligned acceptance tests.
- If more than 5 categories remain unresolved, select the top 5 by (Impact * Uncertainty) heuristic.
4. Sequential questioning loop (interactive):
- Present EXACTLY ONE question at a time.
- For multiplechoice questions:
- **Analyze all options** and determine the **most suitable option** based on:
- Best practices for the project type
- Common patterns in similar implementations
- Risk reduction (security, performance, maintainability)
- Alignment with any explicit project goals or constraints visible in the spec
- Present your **recommended option prominently** at the top with clear reasoning (1-2 sentences explaining why this is the best choice).
- Format as: `**Recommended:** Option [X] - <reasoning>`
- Then render all options as a Markdown table:
| Option | Description |
|--------|-------------|
| A | <Option A description> |
| B | <Option B description> |
| C | <Option C description> (add D/E as needed up to 5) |
| Short | Provide a different short answer (<=5 words) (Include only if free-form alternative is appropriate) |
- After the table, add: `You can reply with the option letter (e.g., "A"), accept the recommendation by saying "yes" or "recommended", or provide your own short answer.`
- For shortanswer style (no meaningful discrete options):
- Provide your **suggested answer** based on best practices and context.
- Format as: `**Suggested:** <your proposed answer> - <brief reasoning>`
- Then output: `Format: Short answer (<=5 words). You can accept the suggestion by saying "yes" or "suggested", or provide your own answer.`
- After the user answers:
- If the user replies with "yes", "recommended", or "suggested", use your previously stated recommendation/suggestion as the answer.
- Otherwise, validate the answer maps to one option or fits the <=5 word constraint.
- If ambiguous, ask for a quick disambiguation (count still belongs to same question; do not advance).
- Once satisfactory, record it in working memory (do not yet write to disk) and move to the next queued question.
- Stop asking further questions when:
- All critical ambiguities resolved early (remaining queued items become unnecessary), OR
- User signals completion ("done", "good", "no more"), OR
- You reach 5 asked questions.
- Never reveal future queued questions in advance.
- If no valid questions exist at start, immediately report no critical ambiguities.
5. Integration after EACH accepted answer (incremental update approach):
- Maintain in-memory representation of the spec (loaded once at start) plus the raw file contents.
- For the first integrated answer in this session:
- Ensure a `## Clarifications` section exists (create it just after the highest-level contextual/overview section per the spec template if missing).
- Under it, create (if not present) a `### Session YYYY-MM-DD` subheading for today.
- Append a bullet line immediately after acceptance: `- Q: <question> → A: <final answer>`.
- Then immediately apply the clarification to the most appropriate section(s):
- Functional ambiguity → Update or add a bullet in Functional Requirements.
- User interaction / actor distinction → Update User Stories or Actors subsection (if present) with clarified role, constraint, or scenario.
- Data shape / entities → Update Data Model (add fields, types, relationships) preserving ordering; note added constraints succinctly.
- Non-functional constraint → Add/modify measurable criteria in Non-Functional / Quality Attributes section (convert vague adjective to metric or explicit target).
- Edge case / negative flow → Add a new bullet under Edge Cases / Error Handling (or create such subsection if template provides placeholder for it).
- Terminology conflict → Normalize term across spec; retain original only if necessary by adding `(formerly referred to as "X")` once.
- If the clarification invalidates an earlier ambiguous statement, replace that statement instead of duplicating; leave no obsolete contradictory text.
- Save the spec file AFTER each integration to minimize risk of context loss (atomic overwrite).
- Preserve formatting: do not reorder unrelated sections; keep heading hierarchy intact.
- Keep each inserted clarification minimal and testable (avoid narrative drift).
6. Validation (performed after EACH write plus final pass):
- Clarifications session contains exactly one bullet per accepted answer (no duplicates).
- Total asked (accepted) questions ≤ 5.
- Updated sections contain no lingering vague placeholders the new answer was meant to resolve.
- No contradictory earlier statement remains (scan for now-invalid alternative choices removed).
- Markdown structure valid; only allowed new headings: `## Clarifications`, `### Session YYYY-MM-DD`.
- Terminology consistency: same canonical term used across all updated sections.
7. Write the updated spec back to `FEATURE_SPEC`.
8. Report completion (after questioning loop ends or early termination):
- Number of questions asked & answered.
- Path to updated spec.
- Sections touched (list names).
- Coverage summary table listing each taxonomy category with Status: Resolved (was Partial/Missing and addressed), Deferred (exceeds question quota or better suited for planning), Clear (already sufficient), Outstanding (still Partial/Missing but low impact).
- If any Outstanding or Deferred remain, recommend whether to proceed to `/speckit.plan` or run `/speckit.clarify` again later post-plan.
- Suggested next command.
Behavior rules:
- If no meaningful ambiguities found (or all potential questions would be low-impact), respond: "No critical ambiguities detected worth formal clarification." and suggest proceeding.
- If spec file missing, instruct user to run `/speckit.specify` first (do not create a new spec here).
- Never exceed 5 total asked questions (clarification retries for a single question do not count as new questions).
- Avoid speculative tech stack questions unless the absence blocks functional clarity.
- Respect user early termination signals ("stop", "done", "proceed").
- If no questions asked due to full coverage, output a compact coverage summary (all categories Clear) then suggest advancing.
- If quota reached with unresolved high-impact categories remaining, explicitly flag them under Deferred with rationale.
Context for prioritization: $ARGUMENTS

View File

@@ -0,0 +1,82 @@
---
description: Create or update the project constitution from interactive or provided principle inputs, ensuring all dependent templates stay in sync.
handoffs:
- label: Build Specification
agent: speckit.specify
prompt: Implement the feature specification based on the updated constitution. I want to build...
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Outline
You are updating the project constitution at `.specify/memory/constitution.md`. This file is a TEMPLATE containing placeholder tokens in square brackets (e.g. `[PROJECT_NAME]`, `[PRINCIPLE_1_NAME]`). Your job is to (a) collect/derive concrete values, (b) fill the template precisely, and (c) propagate any amendments across dependent artifacts.
Follow this execution flow:
1. Load the existing constitution template at `.specify/memory/constitution.md`.
- Identify every placeholder token of the form `[ALL_CAPS_IDENTIFIER]`.
**IMPORTANT**: The user might require less or more principles than the ones used in the template. If a number is specified, respect that - follow the general template. You will update the doc accordingly.
2. Collect/derive values for placeholders:
- If user input (conversation) supplies a value, use it.
- Otherwise infer from existing repo context (README, docs, prior constitution versions if embedded).
- For governance dates: `RATIFICATION_DATE` is the original adoption date (if unknown ask or mark TODO), `LAST_AMENDED_DATE` is today if changes are made, otherwise keep previous.
- `CONSTITUTION_VERSION` must increment according to semantic versioning rules:
- MAJOR: Backward incompatible governance/principle removals or redefinitions.
- MINOR: New principle/section added or materially expanded guidance.
- PATCH: Clarifications, wording, typo fixes, non-semantic refinements.
- If version bump type ambiguous, propose reasoning before finalizing.
3. Draft the updated constitution content:
- Replace every placeholder with concrete text (no bracketed tokens left except intentionally retained template slots that the project has chosen not to define yet—explicitly justify any left).
- Preserve heading hierarchy and comments can be removed once replaced unless they still add clarifying guidance.
- Ensure each Principle section: succinct name line, paragraph (or bullet list) capturing nonnegotiable rules, explicit rationale if not obvious.
- Ensure Governance section lists amendment procedure, versioning policy, and compliance review expectations.
4. Consistency propagation checklist (convert prior checklist into active validations):
- Read `.specify/templates/plan-template.md` and ensure any "Constitution Check" or rules align with updated principles.
- Read `.specify/templates/spec-template.md` for scope/requirements alignment—update if constitution adds/removes mandatory sections or constraints.
- Read `.specify/templates/tasks-template.md` and ensure task categorization reflects new or removed principle-driven task types (e.g., observability, versioning, testing discipline).
- Read each command file in `.specify/templates/commands/*.md` (including this one) to verify no outdated references (agent-specific names like CLAUDE only) remain when generic guidance is required.
- Read any runtime guidance docs (e.g., `README.md`, `docs/quickstart.md`, or agent-specific guidance files if present). Update references to principles changed.
5. Produce a Sync Impact Report (prepend as an HTML comment at top of the constitution file after update):
- Version change: old → new
- List of modified principles (old title → new title if renamed)
- Added sections
- Removed sections
- Templates requiring updates (✅ updated / ⚠ pending) with file paths
- Follow-up TODOs if any placeholders intentionally deferred.
6. Validation before final output:
- No remaining unexplained bracket tokens.
- Version line matches report.
- Dates ISO format YYYY-MM-DD.
- Principles are declarative, testable, and free of vague language ("should" → replace with MUST/SHOULD rationale where appropriate).
7. Write the completed constitution back to `.specify/memory/constitution.md` (overwrite).
8. Output a final summary to the user with:
- New version and bump rationale.
- Any files flagged for manual follow-up.
- Suggested commit message (e.g., `docs: amend constitution to vX.Y.Z (principle additions + governance update)`).
Formatting & Style Requirements:
- Use Markdown headings exactly as in the template (do not demote/promote levels).
- Wrap long rationale lines to keep readability (<100 chars ideally) but do not hard enforce with awkward breaks.
- Keep a single blank line between sections.
- Avoid trailing whitespace.
If the user supplies partial updates (e.g., only one principle revision), still perform validation and version decision steps.
If critical info missing (e.g., ratification date truly unknown), insert `TODO(<FIELD_NAME>): explanation` and include in the Sync Impact Report under deferred items.
Do not create a new template; always operate on the existing `.specify/memory/constitution.md` file.

View File

@@ -0,0 +1,135 @@
---
description: Execute the implementation plan by processing and executing all tasks defined in tasks.md
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Outline
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **Check checklists status** (if FEATURE_DIR/checklists/ exists):
- Scan all checklist files in the checklists/ directory
- For each checklist, count:
- Total items: All lines matching `- [ ]` or `- [X]` or `- [x]`
- Completed items: Lines matching `- [X]` or `- [x]`
- Incomplete items: Lines matching `- [ ]`
- Create a status table:
```text
| Checklist | Total | Completed | Incomplete | Status |
|-----------|-------|-----------|------------|--------|
| ux.md | 12 | 12 | 0 | ✓ PASS |
| test.md | 8 | 5 | 3 | ✗ FAIL |
| security.md | 6 | 6 | 0 | ✓ PASS |
```
- Calculate overall status:
- **PASS**: All checklists have 0 incomplete items
- **FAIL**: One or more checklists have incomplete items
- **If any checklist is incomplete**:
- Display the table with incomplete item counts
- **STOP** and ask: "Some checklists are incomplete. Do you want to proceed with implementation anyway? (yes/no)"
- Wait for user response before continuing
- If user says "no" or "wait" or "stop", halt execution
- If user says "yes" or "proceed" or "continue", proceed to step 3
- **If all checklists are complete**:
- Display the table showing all checklists passed
- Automatically proceed to step 3
3. Load and analyze the implementation context:
- **REQUIRED**: Read tasks.md for the complete task list and execution plan
- **REQUIRED**: Read plan.md for tech stack, architecture, and file structure
- **IF EXISTS**: Read data-model.md for entities and relationships
- **IF EXISTS**: Read contracts/ for API specifications and test requirements
- **IF EXISTS**: Read research.md for technical decisions and constraints
- **IF EXISTS**: Read quickstart.md for integration scenarios
4. **Project Setup Verification**:
- **REQUIRED**: Create/verify ignore files based on actual project setup:
**Detection & Creation Logic**:
- Check if the following command succeeds to determine if the repository is a git repo (create/verify .gitignore if so):
```sh
git rev-parse --git-dir 2>/dev/null
```
- Check if Dockerfile* exists or Docker in plan.md → create/verify .dockerignore
- Check if .eslintrc* exists → create/verify .eslintignore
- Check if eslint.config.* exists → ensure the config's `ignores` entries cover required patterns
- Check if .prettierrc* exists → create/verify .prettierignore
- Check if .npmrc or package.json exists → create/verify .npmignore (if publishing)
- Check if terraform files (*.tf) exist → create/verify .terraformignore
- Check if .helmignore needed (helm charts present) → create/verify .helmignore
**If ignore file already exists**: Verify it contains essential patterns, append missing critical patterns only
**If ignore file missing**: Create with full pattern set for detected technology
**Common Patterns by Technology** (from plan.md tech stack):
- **Node.js/JavaScript/TypeScript**: `node_modules/`, `dist/`, `build/`, `*.log`, `.env*`
- **Python**: `__pycache__/`, `*.pyc`, `.venv/`, `venv/`, `dist/`, `*.egg-info/`
- **Java**: `target/`, `*.class`, `*.jar`, `.gradle/`, `build/`
- **C#/.NET**: `bin/`, `obj/`, `*.user`, `*.suo`, `packages/`
- **Go**: `*.exe`, `*.test`, `vendor/`, `*.out`
- **Ruby**: `.bundle/`, `log/`, `tmp/`, `*.gem`, `vendor/bundle/`
- **PHP**: `vendor/`, `*.log`, `*.cache`, `*.env`
- **Rust**: `target/`, `debug/`, `release/`, `*.rs.bk`, `*.rlib`, `*.prof*`, `.idea/`, `*.log`, `.env*`
- **Kotlin**: `build/`, `out/`, `.gradle/`, `.idea/`, `*.class`, `*.jar`, `*.iml`, `*.log`, `.env*`
- **C++**: `build/`, `bin/`, `obj/`, `out/`, `*.o`, `*.so`, `*.a`, `*.exe`, `*.dll`, `.idea/`, `*.log`, `.env*`
- **C**: `build/`, `bin/`, `obj/`, `out/`, `*.o`, `*.a`, `*.so`, `*.exe`, `Makefile`, `config.log`, `.idea/`, `*.log`, `.env*`
- **Swift**: `.build/`, `DerivedData/`, `*.swiftpm/`, `Packages/`
- **R**: `.Rproj.user/`, `.Rhistory`, `.RData`, `.Ruserdata`, `*.Rproj`, `packrat/`, `renv/`
- **Universal**: `.DS_Store`, `Thumbs.db`, `*.tmp`, `*.swp`, `.vscode/`, `.idea/`
**Tool-Specific Patterns**:
- **Docker**: `node_modules/`, `.git/`, `Dockerfile*`, `.dockerignore`, `*.log*`, `.env*`, `coverage/`
- **ESLint**: `node_modules/`, `dist/`, `build/`, `coverage/`, `*.min.js`
- **Prettier**: `node_modules/`, `dist/`, `build/`, `coverage/`, `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`
- **Terraform**: `.terraform/`, `*.tfstate*`, `*.tfvars`, `.terraform.lock.hcl`
- **Kubernetes/k8s**: `*.secret.yaml`, `secrets/`, `.kube/`, `kubeconfig*`, `*.key`, `*.crt`
5. Parse tasks.md structure and extract:
- **Task phases**: Setup, Tests, Core, Integration, Polish
- **Task dependencies**: Sequential vs parallel execution rules
- **Task details**: ID, description, file paths, parallel markers [P]
- **Execution flow**: Order and dependency requirements
6. Execute implementation following the task plan:
- **Phase-by-phase execution**: Complete each phase before moving to the next
- **Respect dependencies**: Run sequential tasks in order, parallel tasks [P] can run together
- **Follow TDD approach**: Execute test tasks before their corresponding implementation tasks
- **File-based coordination**: Tasks affecting the same files must run sequentially
- **Validation checkpoints**: Verify each phase completion before proceeding
7. Implementation execution rules:
- **Setup first**: Initialize project structure, dependencies, configuration
- **Tests before code**: If you need to write tests for contracts, entities, and integration scenarios
- **Core development**: Implement models, services, CLI commands, endpoints
- **Integration work**: Database connections, middleware, logging, external services
- **Polish and validation**: Unit tests, performance optimization, documentation
8. Progress tracking and error handling:
- Report progress after each completed task
- Halt execution if any non-parallel task fails
- For parallel tasks [P], continue with successful tasks, report failed ones
- Provide clear error messages with context for debugging
- Suggest next steps if implementation cannot proceed
- **IMPORTANT** For completed tasks, make sure to mark the task off as [X] in the tasks file.
9. Completion validation:
- Verify all required tasks are completed
- Check that implemented features match the original specification
- Validate that tests pass and coverage meets requirements
- Confirm the implementation follows the technical plan
- Report final status with summary of completed work
Note: This command assumes a complete task breakdown exists in tasks.md. If tasks are incomplete or missing, suggest running `/speckit.tasks` first to regenerate the task list.

View File

@@ -0,0 +1,89 @@
---
description: Execute the implementation planning workflow using the plan template to generate design artifacts.
handoffs:
- label: Create Tasks
agent: speckit.tasks
prompt: Break the plan into tasks
send: true
- label: Create Checklist
agent: speckit.checklist
prompt: Create a checklist for the following domain...
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Outline
1. **Setup**: Run `.specify/scripts/bash/setup-plan.sh --json` from repo root and parse JSON for FEATURE_SPEC, IMPL_PLAN, SPECS_DIR, BRANCH. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **Load context**: Read FEATURE_SPEC and `.specify/memory/constitution.md`. Load IMPL_PLAN template (already copied).
3. **Execute plan workflow**: Follow the structure in IMPL_PLAN template to:
- Fill Technical Context (mark unknowns as "NEEDS CLARIFICATION")
- Fill Constitution Check section from constitution
- Evaluate gates (ERROR if violations unjustified)
- Phase 0: Generate research.md (resolve all NEEDS CLARIFICATION)
- Phase 1: Generate data-model.md, contracts/, quickstart.md
- Phase 1: Update agent context by running the agent script
- Re-evaluate Constitution Check post-design
4. **Stop and report**: Command ends after Phase 2 planning. Report branch, IMPL_PLAN path, and generated artifacts.
## Phases
### Phase 0: Outline & Research
1. **Extract unknowns from Technical Context** above:
- For each NEEDS CLARIFICATION → research task
- For each dependency → best practices task
- For each integration → patterns task
2. **Generate and dispatch research agents**:
```text
For each unknown in Technical Context:
Task: "Research {unknown} for {feature context}"
For each technology choice:
Task: "Find best practices for {tech} in {domain}"
```
3. **Consolidate findings** in `research.md` using format:
- Decision: [what was chosen]
- Rationale: [why chosen]
- Alternatives considered: [what else evaluated]
**Output**: research.md with all NEEDS CLARIFICATION resolved
### Phase 1: Design & Contracts
**Prerequisites:** `research.md` complete
1. **Extract entities from feature spec** → `data-model.md`:
- Entity name, fields, relationships
- Validation rules from requirements
- State transitions if applicable
2. **Generate API contracts** from functional requirements:
- For each user action → endpoint
- Use standard REST/GraphQL patterns
- Output OpenAPI/GraphQL schema to `/contracts/`
3. **Agent context update**:
- Run `.specify/scripts/bash/update-agent-context.sh codex`
- These scripts detect which AI agent is in use
- Update the appropriate agent-specific context file
- Add only new technology from current plan
- Preserve manual additions between markers
**Output**: data-model.md, /contracts/*, quickstart.md, agent-specific file
## Key rules
- Use absolute paths
- ERROR on gate failures or unresolved clarifications

View File

@@ -0,0 +1,258 @@
---
description: Create or update the feature specification from a natural language feature description.
handoffs:
- label: Build Technical Plan
agent: speckit.plan
prompt: Create a plan for the spec. I am building with...
- label: Clarify Spec Requirements
agent: speckit.clarify
prompt: Clarify specification requirements
send: true
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Outline
The text the user typed after `/speckit.specify` in the triggering message **is** the feature description. Assume you always have it available in this conversation even if `$ARGUMENTS` appears literally below. Do not ask the user to repeat it unless they provided an empty command.
Given that feature description, do this:
1. **Generate a concise short name** (2-4 words) for the branch:
- Analyze the feature description and extract the most meaningful keywords
- Create a 2-4 word short name that captures the essence of the feature
- Use action-noun format when possible (e.g., "add-user-auth", "fix-payment-bug")
- Preserve technical terms and acronyms (OAuth2, API, JWT, etc.)
- Keep it concise but descriptive enough to understand the feature at a glance
- Examples:
- "I want to add user authentication" → "user-auth"
- "Implement OAuth2 integration for the API" → "oauth2-api-integration"
- "Create a dashboard for analytics" → "analytics-dashboard"
- "Fix payment processing timeout bug" → "fix-payment-timeout"
2. **Check for existing branches before creating new one**:
a. First, fetch all remote branches to ensure we have the latest information:
```bash
git fetch --all --prune
```
b. Find the highest feature number across all sources for the short-name:
- Remote branches: `git ls-remote --heads origin | grep -E 'refs/heads/[0-9]+-<short-name>$'`
- Local branches: `git branch | grep -E '^[* ]*[0-9]+-<short-name>$'`
- Specs directories: Check for directories matching `specs/[0-9]+-<short-name>`
c. Determine the next available number:
- Extract all numbers from all three sources
- Find the highest number N
- Use N+1 for the new branch number
d. Run the script `.specify/scripts/bash/create-new-feature.sh --json "$ARGUMENTS"` with the calculated number and short-name:
- Pass `--number N+1` and `--short-name "your-short-name"` along with the feature description
- Bash example: `.specify/scripts/bash/create-new-feature.sh --json "$ARGUMENTS" --json --number 5 --short-name "user-auth" "Add user authentication"`
- PowerShell example: `.specify/scripts/bash/create-new-feature.sh --json "$ARGUMENTS" -Json -Number 5 -ShortName "user-auth" "Add user authentication"`
**IMPORTANT**:
- Check all three sources (remote branches, local branches, specs directories) to find the highest number
- Only match branches/directories with the exact short-name pattern
- If no existing branches/directories found with this short-name, start with number 1
- You must only ever run this script once per feature
- The JSON is provided in the terminal as output - always refer to it to get the actual content you're looking for
- The JSON output will contain BRANCH_NAME and SPEC_FILE paths
- For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot")
3. Load `.specify/templates/spec-template.md` to understand required sections.
4. Follow this execution flow:
1. Parse user description from Input
If empty: ERROR "No feature description provided"
2. Extract key concepts from description
Identify: actors, actions, data, constraints
3. For unclear aspects:
- Make informed guesses based on context and industry standards
- Only mark with [NEEDS CLARIFICATION: specific question] if:
- The choice significantly impacts feature scope or user experience
- Multiple reasonable interpretations exist with different implications
- No reasonable default exists
- **LIMIT: Maximum 3 [NEEDS CLARIFICATION] markers total**
- Prioritize clarifications by impact: scope > security/privacy > user experience > technical details
4. Fill User Scenarios & Testing section
If no clear user flow: ERROR "Cannot determine user scenarios"
5. Generate Functional Requirements
Each requirement must be testable
Use reasonable defaults for unspecified details (document assumptions in Assumptions section)
6. Define Success Criteria
Create measurable, technology-agnostic outcomes
Include both quantitative metrics (time, performance, volume) and qualitative measures (user satisfaction, task completion)
Each criterion must be verifiable without implementation details
7. Identify Key Entities (if data involved)
8. Return: SUCCESS (spec ready for planning)
5. Write the specification to SPEC_FILE using the template structure, replacing placeholders with concrete details derived from the feature description (arguments) while preserving section order and headings.
6. **Specification Quality Validation**: After writing the initial spec, validate it against quality criteria:
a. **Create Spec Quality Checklist**: Generate a checklist file at `FEATURE_DIR/checklists/requirements.md` using the checklist template structure with these validation items:
```markdown
# Specification Quality Checklist: [FEATURE NAME]
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: [DATE]
**Feature**: [Link to spec.md]
## Content Quality
- [ ] No implementation details (languages, frameworks, APIs)
- [ ] Focused on user value and business needs
- [ ] Written for non-technical stakeholders
- [ ] All mandatory sections completed
## Requirement Completeness
- [ ] No [NEEDS CLARIFICATION] markers remain
- [ ] Requirements are testable and unambiguous
- [ ] Success criteria are measurable
- [ ] Success criteria are technology-agnostic (no implementation details)
- [ ] All acceptance scenarios are defined
- [ ] Edge cases are identified
- [ ] Scope is clearly bounded
- [ ] Dependencies and assumptions identified
## Feature Readiness
- [ ] All functional requirements have clear acceptance criteria
- [ ] User scenarios cover primary flows
- [ ] Feature meets measurable outcomes defined in Success Criteria
- [ ] No implementation details leak into specification
## Notes
- Items marked incomplete require spec updates before `/speckit.clarify` or `/speckit.plan`
```
b. **Run Validation Check**: Review the spec against each checklist item:
- For each item, determine if it passes or fails
- Document specific issues found (quote relevant spec sections)
c. **Handle Validation Results**:
- **If all items pass**: Mark checklist complete and proceed to step 6
- **If items fail (excluding [NEEDS CLARIFICATION])**:
1. List the failing items and specific issues
2. Update the spec to address each issue
3. Re-run validation until all items pass (max 3 iterations)
4. If still failing after 3 iterations, document remaining issues in checklist notes and warn user
- **If [NEEDS CLARIFICATION] markers remain**:
1. Extract all [NEEDS CLARIFICATION: ...] markers from the spec
2. **LIMIT CHECK**: If more than 3 markers exist, keep only the 3 most critical (by scope/security/UX impact) and make informed guesses for the rest
3. For each clarification needed (max 3), present options to user in this format:
```markdown
## Question [N]: [Topic]
**Context**: [Quote relevant spec section]
**What we need to know**: [Specific question from NEEDS CLARIFICATION marker]
**Suggested Answers**:
| Option | Answer | Implications |
|--------|--------|--------------|
| A | [First suggested answer] | [What this means for the feature] |
| B | [Second suggested answer] | [What this means for the feature] |
| C | [Third suggested answer] | [What this means for the feature] |
| Custom | Provide your own answer | [Explain how to provide custom input] |
**Your choice**: _[Wait for user response]_
```
4. **CRITICAL - Table Formatting**: Ensure markdown tables are properly formatted:
- Use consistent spacing with pipes aligned
- Each cell should have spaces around content: `| Content |` not `|Content|`
- Header separator must have at least 3 dashes: `|--------|`
- Test that the table renders correctly in markdown preview
5. Number questions sequentially (Q1, Q2, Q3 - max 3 total)
6. Present all questions together before waiting for responses
7. Wait for user to respond with their choices for all questions (e.g., "Q1: A, Q2: Custom - [details], Q3: B")
8. Update the spec by replacing each [NEEDS CLARIFICATION] marker with the user's selected or provided answer
9. Re-run validation after all clarifications are resolved
d. **Update Checklist**: After each validation iteration, update the checklist file with current pass/fail status
7. Report completion with branch name, spec file path, checklist results, and readiness for the next phase (`/speckit.clarify` or `/speckit.plan`).
**NOTE:** The script creates and checks out the new branch and initializes the spec file before writing.
## General Guidelines
## Quick Guidelines
- Focus on **WHAT** users need and **WHY**.
- Avoid HOW to implement (no tech stack, APIs, code structure).
- Written for business stakeholders, not developers.
- DO NOT create any checklists that are embedded in the spec. That will be a separate command.
### Section Requirements
- **Mandatory sections**: Must be completed for every feature
- **Optional sections**: Include only when relevant to the feature
- When a section doesn't apply, remove it entirely (don't leave as "N/A")
### For AI Generation
When creating this spec from a user prompt:
1. **Make informed guesses**: Use context, industry standards, and common patterns to fill gaps
2. **Document assumptions**: Record reasonable defaults in the Assumptions section
3. **Limit clarifications**: Maximum 3 [NEEDS CLARIFICATION] markers - use only for critical decisions that:
- Significantly impact feature scope or user experience
- Have multiple reasonable interpretations with different implications
- Lack any reasonable default
4. **Prioritize clarifications**: scope > security/privacy > user experience > technical details
5. **Think like a tester**: Every vague requirement should fail the "testable and unambiguous" checklist item
6. **Common areas needing clarification** (only if no reasonable default exists):
- Feature scope and boundaries (include/exclude specific use cases)
- User types and permissions (if multiple conflicting interpretations possible)
- Security/compliance requirements (when legally/financially significant)
**Examples of reasonable defaults** (don't ask about these):
- Data retention: Industry-standard practices for the domain
- Performance targets: Standard web/mobile app expectations unless specified
- Error handling: User-friendly messages with appropriate fallbacks
- Authentication method: Standard session-based or OAuth2 for web apps
- Integration patterns: RESTful APIs unless specified otherwise
### Success Criteria Guidelines
Success criteria must be:
1. **Measurable**: Include specific metrics (time, percentage, count, rate)
2. **Technology-agnostic**: No mention of frameworks, languages, databases, or tools
3. **User-focused**: Describe outcomes from user/business perspective, not system internals
4. **Verifiable**: Can be tested/validated without knowing implementation details
**Good examples**:
- "Users can complete checkout in under 3 minutes"
- "System supports 10,000 concurrent users"
- "95% of searches return results in under 1 second"
- "Task completion rate improves by 40%"
**Bad examples** (implementation-focused):
- "API response time is under 200ms" (too technical, use "Users see results instantly")
- "Database can handle 1000 TPS" (implementation detail, use user-facing metric)
- "React components render efficiently" (framework-specific)
- "Redis cache hit rate above 80%" (technology-specific)

View File

@@ -0,0 +1,137 @@
---
description: Generate an actionable, dependency-ordered tasks.md for the feature based on available design artifacts.
handoffs:
- label: Analyze For Consistency
agent: speckit.analyze
prompt: Run a project analysis for consistency
send: true
- label: Implement Project
agent: speckit.implement
prompt: Start the implementation in phases
send: true
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Outline
1. **Setup**: Run `.specify/scripts/bash/check-prerequisites.sh --json` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **Load design documents**: Read from FEATURE_DIR:
- **Required**: plan.md (tech stack, libraries, structure), spec.md (user stories with priorities)
- **Optional**: data-model.md (entities), contracts/ (API endpoints), research.md (decisions), quickstart.md (test scenarios)
- Note: Not all projects have all documents. Generate tasks based on what's available.
3. **Execute task generation workflow**:
- Load plan.md and extract tech stack, libraries, project structure
- Load spec.md and extract user stories with their priorities (P1, P2, P3, etc.)
- If data-model.md exists: Extract entities and map to user stories
- If contracts/ exists: Map endpoints to user stories
- If research.md exists: Extract decisions for setup tasks
- Generate tasks organized by user story (see Task Generation Rules below)
- Generate dependency graph showing user story completion order
- Create parallel execution examples per user story
- Validate task completeness (each user story has all needed tasks, independently testable)
4. **Generate tasks.md**: Use `.specify/templates/tasks-template.md` as structure, fill with:
- Correct feature name from plan.md
- Phase 1: Setup tasks (project initialization)
- Phase 2: Foundational tasks (blocking prerequisites for all user stories)
- Phase 3+: One phase per user story (in priority order from spec.md)
- Each phase includes: story goal, independent test criteria, tests (if requested), implementation tasks
- Final Phase: Polish & cross-cutting concerns
- All tasks must follow the strict checklist format (see Task Generation Rules below)
- Clear file paths for each task
- Dependencies section showing story completion order
- Parallel execution examples per story
- Implementation strategy section (MVP first, incremental delivery)
5. **Report**: Output path to generated tasks.md and summary:
- Total task count
- Task count per user story
- Parallel opportunities identified
- Independent test criteria for each story
- Suggested MVP scope (typically just User Story 1)
- Format validation: Confirm ALL tasks follow the checklist format (checkbox, ID, labels, file paths)
Context for task generation: $ARGUMENTS
The tasks.md should be immediately executable - each task must be specific enough that an LLM can complete it without additional context.
## Task Generation Rules
**CRITICAL**: Tasks MUST be organized by user story to enable independent implementation and testing.
**Tests are OPTIONAL**: Only generate test tasks if explicitly requested in the feature specification or if user requests TDD approach.
### Checklist Format (REQUIRED)
Every task MUST strictly follow this format:
```text
- [ ] [TaskID] [P?] [Story?] Description with file path
```
**Format Components**:
1. **Checkbox**: ALWAYS start with `- [ ]` (markdown checkbox)
2. **Task ID**: Sequential number (T001, T002, T003...) in execution order
3. **[P] marker**: Include ONLY if task is parallelizable (different files, no dependencies on incomplete tasks)
4. **[Story] label**: REQUIRED for user story phase tasks only
- Format: [US1], [US2], [US3], etc. (maps to user stories from spec.md)
- Setup phase: NO story label
- Foundational phase: NO story label
- User Story phases: MUST have story label
- Polish phase: NO story label
5. **Description**: Clear action with exact file path
**Examples**:
- ✅ CORRECT: `- [ ] T001 Create project structure per implementation plan`
- ✅ CORRECT: `- [ ] T005 [P] Implement authentication middleware in src/middleware/auth.py`
- ✅ CORRECT: `- [ ] T012 [P] [US1] Create User model in src/models/user.py`
- ✅ CORRECT: `- [ ] T014 [US1] Implement UserService in src/services/user_service.py`
- ❌ WRONG: `- [ ] Create User model` (missing ID and Story label)
- ❌ WRONG: `T001 [US1] Create model` (missing checkbox)
- ❌ WRONG: `- [ ] [US1] Create User model` (missing Task ID)
- ❌ WRONG: `- [ ] T001 [US1] Create model` (missing file path)
### Task Organization
1. **From User Stories (spec.md)** - PRIMARY ORGANIZATION:
- Each user story (P1, P2, P3...) gets its own phase
- Map all related components to their story:
- Models needed for that story
- Services needed for that story
- Endpoints/UI needed for that story
- If tests requested: Tests specific to that story
- Mark story dependencies (most stories should be independent)
2. **From Contracts**:
- Map each contract/endpoint → to the user story it serves
- If tests requested: Each contract → contract test task [P] before implementation in that story's phase
3. **From Data Model**:
- Map each entity to the user story(ies) that need it
- If entity serves multiple stories: Put in earliest story or Setup phase
- Relationships → service layer tasks in appropriate story phase
4. **From Setup/Infrastructure**:
- Shared infrastructure → Setup phase (Phase 1)
- Foundational/blocking tasks → Foundational phase (Phase 2)
- Story-specific setup → within that story's phase
### Phase Structure
- **Phase 1**: Setup (project initialization)
- **Phase 2**: Foundational (blocking prerequisites - MUST complete before user stories)
- **Phase 3+**: User Stories in priority order (P1, P2, P3...)
- Within each story: Tests (if requested) → Models → Services → Endpoints → Integration
- Each phase should be a complete, independently testable increment
- **Final Phase**: Polish & Cross-Cutting Concerns

View File

@@ -0,0 +1,30 @@
---
description: Convert existing tasks into actionable, dependency-ordered GitHub issues for the feature based on available design artifacts.
tools: ['github/github-mcp-server/issue_write']
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Outline
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
1. From the executed script, extract the path to **tasks**.
1. Get the Git remote by running:
```bash
git config --get remote.origin.url
```
> [!CAUTION]
> ONLY PROCEED TO NEXT STEPS IF THE REMOTE IS A GITHUB URL
1. For each task in the list, use the GitHub MCP server to create a new issue in the repository that is representative of the Git remote.
> [!CAUTION]
> UNDER NO CIRCUMSTANCES EVER CREATE ISSUES IN REPOSITORIES THAT DO NOT MATCH THE REMOTE URL

2
.codex/requirements.toml Normal file
View File

@@ -0,0 +1,2 @@
[mcp_servers.nixos-mcp.identity]
command = "nixos-mcp"

View File

@@ -0,0 +1 @@
821f2ce8d073b28f

View File

@@ -0,0 +1,375 @@
---
name: skill-creator
description: Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Codex's capabilities with specialized knowledge, workflows, or tool integrations.
metadata:
short-description: Create or update a skill
---
# Skill Creator
This skill provides guidance for creating effective skills.
## About Skills
Skills are modular, self-contained packages that extend Codex's capabilities by providing
specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific
domains or tasks—they transform Codex from a general-purpose agent into a specialized agent
equipped with procedural knowledge that no model can fully possess.
### What Skills Provide
1. Specialized workflows - Multi-step procedures for specific domains
2. Tool integrations - Instructions for working with specific file formats or APIs
3. Domain expertise - Company-specific knowledge, schemas, business logic
4. Bundled resources - Scripts, references, and assets for complex and repetitive tasks
## Core Principles
### Concise is Key
The context window is a public good. Skills share the context window with everything else Codex needs: system prompt, conversation history, other Skills' metadata, and the actual user request.
**Default assumption: Codex is already very smart.** Only add context Codex doesn't already have. Challenge each piece of information: "Does Codex really need this explanation?" and "Does this paragraph justify its token cost?"
Prefer concise examples over verbose explanations.
### Set Appropriate Degrees of Freedom
Match the level of specificity to the task's fragility and variability:
**High freedom (text-based instructions)**: Use when multiple approaches are valid, decisions depend on context, or heuristics guide the approach.
**Medium freedom (pseudocode or scripts with parameters)**: Use when a preferred pattern exists, some variation is acceptable, or configuration affects behavior.
**Low freedom (specific scripts, few parameters)**: Use when operations are fragile and error-prone, consistency is critical, or a specific sequence must be followed.
Think of Codex as exploring a path: a narrow bridge with cliffs needs specific guardrails (low freedom), while an open field allows many routes (high freedom).
### Anatomy of a Skill
Every skill consists of a required SKILL.md file and optional bundled resources:
```
skill-name/
├── SKILL.md (required)
│ ├── YAML frontmatter metadata (required)
│ │ ├── name: (required)
│ │ └── description: (required)
│ └── Markdown instructions (required)
└── Bundled Resources (optional)
├── scripts/ - Executable code (Python/Bash/etc.)
├── references/ - Documentation intended to be loaded into context as needed
└── assets/ - Files used in output (templates, icons, fonts, etc.)
```
#### SKILL.md (required)
Every SKILL.md consists of:
- **Frontmatter** (YAML): Contains `name` and `description` fields. These are the only fields that Codex reads to determine when the skill gets used, thus it is very important to be clear and comprehensive in describing what the skill is, and when it should be used.
- **Body** (Markdown): Instructions and guidance for using the skill. Only loaded AFTER the skill triggers (if at all).
#### Bundled Resources (optional)
##### Scripts (`scripts/`)
Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten.
- **When to include**: When the same code is being rewritten repeatedly or deterministic reliability is needed
- **Example**: `scripts/rotate_pdf.py` for PDF rotation tasks
- **Benefits**: Token efficient, deterministic, may be executed without loading into context
- **Note**: Scripts may still need to be read by Codex for patching or environment-specific adjustments
##### References (`references/`)
Documentation and reference material intended to be loaded as needed into context to inform Codex's process and thinking.
- **When to include**: For documentation that Codex should reference while working
- **Examples**: `references/finance.md` for financial schemas, `references/mnda.md` for company NDA template, `references/policies.md` for company policies, `references/api_docs.md` for API specifications
- **Use cases**: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides
- **Benefits**: Keeps SKILL.md lean, loaded only when Codex determines it's needed
- **Best practice**: If files are large (>10k words), include grep search patterns in SKILL.md
- **Avoid duplication**: Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files.
##### Assets (`assets/`)
Files not intended to be loaded into context, but rather used within the output Codex produces.
- **When to include**: When the skill needs files that will be used in the final output
- **Examples**: `assets/logo.png` for brand assets, `assets/slides.pptx` for PowerPoint templates, `assets/frontend-template/` for HTML/React boilerplate, `assets/font.ttf` for typography
- **Use cases**: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified
- **Benefits**: Separates output resources from documentation, enables Codex to use files without loading them into context
#### What to Not Include in a Skill
A skill should only contain essential files that directly support its functionality. Do NOT create extraneous documentation or auxiliary files, including:
- README.md
- INSTALLATION_GUIDE.md
- QUICK_REFERENCE.md
- CHANGELOG.md
- etc.
The skill should only contain the information needed for an AI agent to do the job at hand. It should not contain auxiliary context about the process that went into creating it, setup and testing procedures, user-facing documentation, etc. Creating additional documentation files just adds clutter and confusion.
### Progressive Disclosure Design Principle
Skills use a three-level loading system to manage context efficiently:
1. **Metadata (name + description)** - Always in context (~100 words)
2. **SKILL.md body** - When skill triggers (<5k words)
3. **Bundled resources** - As needed by Codex (Unlimited because scripts can be executed without reading into context window)
#### Progressive Disclosure Patterns
Keep SKILL.md body to the essentials and under 500 lines to minimize context bloat. Split content into separate files when approaching this limit. When splitting out content into other files, it is very important to reference them from SKILL.md and describe clearly when to read them, to ensure the reader of the skill knows they exist and when to use them.
**Key principle:** When a skill supports multiple variations, frameworks, or options, keep only the core workflow and selection guidance in SKILL.md. Move variant-specific details (patterns, examples, configuration) into separate reference files.
**Pattern 1: High-level guide with references**
```markdown
# PDF Processing
## Quick start
Extract text with pdfplumber:
[code example]
## Advanced features
- **Form filling**: See [FORMS.md](FORMS.md) for complete guide
- **API reference**: See [REFERENCE.md](REFERENCE.md) for all methods
- **Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns
```
Codex loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.
**Pattern 2: Domain-specific organization**
For Skills with multiple domains, organize content by domain to avoid loading irrelevant context:
```
bigquery-skill/
├── SKILL.md (overview and navigation)
└── reference/
├── finance.md (revenue, billing metrics)
├── sales.md (opportunities, pipeline)
├── product.md (API usage, features)
└── marketing.md (campaigns, attribution)
```
When a user asks about sales metrics, Codex only reads sales.md.
Similarly, for skills supporting multiple frameworks or variants, organize by variant:
```
cloud-deploy/
├── SKILL.md (workflow + provider selection)
└── references/
├── aws.md (AWS deployment patterns)
├── gcp.md (GCP deployment patterns)
└── azure.md (Azure deployment patterns)
```
When the user chooses AWS, Codex only reads aws.md.
**Pattern 3: Conditional details**
Show basic content, link to advanced content:
```markdown
# DOCX Processing
## Creating documents
Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).
## Editing documents
For simple edits, modify the XML directly.
**For tracked changes**: See [REDLINING.md](REDLINING.md)
**For OOXML details**: See [OOXML.md](OOXML.md)
```
Codex reads REDLINING.md or OOXML.md only when the user needs those features.
**Important guidelines:**
- **Avoid deeply nested references** - Keep references one level deep from SKILL.md. All reference files should link directly from SKILL.md.
- **Structure longer reference files** - For files longer than 100 lines, include a table of contents at the top so Codex can see the full scope when previewing.
## Skill Creation Process
Skill creation involves these steps:
1. Understand the skill with concrete examples
2. Plan reusable skill contents (scripts, references, assets)
3. Initialize the skill (run init_skill.py)
4. Edit the skill (implement resources and write SKILL.md)
5. Package the skill (run package_skill.py)
6. Iterate based on real usage
Follow these steps in order, skipping only if there is a clear reason why they are not applicable.
### Skill Naming
- Use lowercase letters, digits, and hyphens only; normalize user-provided titles to hyphen-case (e.g., "Plan Mode" -> `plan-mode`).
- When generating names, generate a name under 64 characters (letters, digits, hyphens).
- Prefer short, verb-led phrases that describe the action.
- Namespace by tool when it improves clarity or triggering (e.g., `gh-address-comments`, `linear-address-issue`).
- Name the skill folder exactly after the skill name.
### Step 1: Understanding the Skill with Concrete Examples
Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill.
To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback.
For example, when building an image-editor skill, relevant questions include:
- "What functionality should the image-editor skill support? Editing, rotating, anything else?"
- "Can you give some examples of how this skill would be used?"
- "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?"
- "What would a user say that should trigger this skill?"
To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness.
Conclude this step when there is a clear sense of the functionality the skill should support.
### Step 2: Planning the Reusable Skill Contents
To turn concrete examples into an effective skill, analyze each example by:
1. Considering how to execute on the example from scratch
2. Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly
Example: When building a `pdf-editor` skill to handle queries like "Help me rotate this PDF," the analysis shows:
1. Rotating a PDF requires re-writing the same code each time
2. A `scripts/rotate_pdf.py` script would be helpful to store in the skill
Example: When designing a `frontend-webapp-builder` skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows:
1. Writing a frontend webapp requires the same boilerplate HTML/React each time
2. An `assets/hello-world/` template containing the boilerplate HTML/React project files would be helpful to store in the skill
Example: When building a `big-query` skill to handle queries like "How many users have logged in today?" the analysis shows:
1. Querying BigQuery requires re-discovering the table schemas and relationships each time
2. A `references/schema.md` file documenting the table schemas would be helpful to store in the skill
To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets.
### Step 3: Initializing the Skill
At this point, it is time to actually create the skill.
Skip this step only if the skill being developed already exists, and iteration or packaging is needed. In this case, continue to the next step.
When creating a new skill from scratch, always run the `init_skill.py` script. The script conveniently generates a new template skill directory that automatically includes everything a skill requires, making the skill creation process much more efficient and reliable.
Usage:
```bash
scripts/init_skill.py <skill-name> --path <output-directory> [--resources scripts,references,assets] [--examples]
```
Examples:
```bash
scripts/init_skill.py my-skill --path skills/public
scripts/init_skill.py my-skill --path skills/public --resources scripts,references
scripts/init_skill.py my-skill --path skills/public --resources scripts --examples
```
The script:
- Creates the skill directory at the specified path
- Generates a SKILL.md template with proper frontmatter and TODO placeholders
- Optionally creates resource directories based on `--resources`
- Optionally adds example files when `--examples` is set
After initialization, customize the SKILL.md and add resources as needed. If you used `--examples`, replace or delete placeholder files.
### Step 4: Edit the Skill
When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of Codex to use. Include information that would be beneficial and non-obvious to Codex. Consider what procedural knowledge, domain-specific details, or reusable assets would help another Codex instance execute these tasks more effectively.
#### Learn Proven Design Patterns
Consult these helpful guides based on your skill's needs:
- **Multi-step processes**: See references/workflows.md for sequential workflows and conditional logic
- **Specific output formats or quality standards**: See references/output-patterns.md for template and example patterns
These files contain established best practices for effective skill design.
#### Start with Reusable Skill Contents
To begin implementation, start with the reusable resources identified above: `scripts/`, `references/`, and `assets/` files. Note that this step may require user input. For example, when implementing a `brand-guidelines` skill, the user may need to provide brand assets or templates to store in `assets/`, or documentation to store in `references/`.
Added scripts must be tested by actually running them to ensure there are no bugs and that the output matches what is expected. If there are many similar scripts, only a representative sample needs to be tested to ensure confidence that they all work while balancing time to completion.
If you used `--examples`, delete any placeholder files that are not needed for the skill. Only create resource directories that are actually required.
#### Update SKILL.md
**Writing Guidelines:** Always use imperative/infinitive form.
##### Frontmatter
Write the YAML frontmatter with `name` and `description`:
- `name`: The skill name
- `description`: This is the primary triggering mechanism for your skill, and helps Codex understand when to use the skill.
- Include both what the Skill does and specific triggers/contexts for when to use it.
- Include all "when to use" information here - Not in the body. The body is only loaded after triggering, so "When to Use This Skill" sections in the body are not helpful to Codex.
- Example description for a `docx` skill: "Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. Use when Codex needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks"
Ensure the frontmatter is valid YAML. Keep `name` and `description` as single-line scalars. If either could be interpreted as YAML syntax, wrap it in quotes.
Do not include any other fields in YAML frontmatter.
##### Body
Write instructions for using the skill and its bundled resources.
### Step 5: Packaging a Skill
Once development of the skill is complete, it must be packaged into a distributable .skill file that gets shared with the user. The packaging process automatically validates the skill first to ensure it meets all requirements:
```bash
scripts/package_skill.py <path/to/skill-folder>
```
Optional output directory specification:
```bash
scripts/package_skill.py <path/to/skill-folder> ./dist
```
The packaging script will:
1. **Validate** the skill automatically, checking:
- YAML frontmatter format and required fields
- Skill naming conventions and directory structure
- Description completeness and quality
- File organization and resource references
2. **Package** the skill if validation passes, creating a .skill file named after the skill (e.g., `my-skill.skill`) that includes all files and maintains the proper directory structure for distribution. The .skill file is a zip file with a .skill extension.
If validation fails, the script will report the errors and exit without creating a package. Fix any validation errors and run the packaging command again.
### Step 6: Iterate
After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.
**Iteration workflow:**
1. Use the skill on real tasks
2. Notice struggles or inefficiencies
3. Identify how SKILL.md or bundled resources should be updated
4. Implement changes and test again

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,378 @@
#!/usr/bin/env python3
"""
Skill Initializer - Creates a new skill from template
Usage:
init_skill.py <skill-name> --path <path> [--resources scripts,references,assets] [--examples]
Examples:
init_skill.py my-new-skill --path skills/public
init_skill.py my-new-skill --path skills/public --resources scripts,references
init_skill.py my-api-helper --path skills/private --resources scripts --examples
init_skill.py custom-skill --path /custom/location
"""
import argparse
import re
import sys
from pathlib import Path
MAX_SKILL_NAME_LENGTH = 64
ALLOWED_RESOURCES = {"scripts", "references", "assets"}
SKILL_TEMPLATE = """---
name: {skill_name}
description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.]
---
# {skill_title}
## Overview
[TODO: 1-2 sentences explaining what this skill enables]
## Structuring This Skill
[TODO: Choose the structure that best fits this skill's purpose. Common patterns:
**1. Workflow-Based** (best for sequential processes)
- Works well when there are clear step-by-step procedures
- Example: DOCX skill with "Workflow Decision Tree" -> "Reading" -> "Creating" -> "Editing"
- Structure: ## Overview -> ## Workflow Decision Tree -> ## Step 1 -> ## Step 2...
**2. Task-Based** (best for tool collections)
- Works well when the skill offers different operations/capabilities
- Example: PDF skill with "Quick Start" -> "Merge PDFs" -> "Split PDFs" -> "Extract Text"
- Structure: ## Overview -> ## Quick Start -> ## Task Category 1 -> ## Task Category 2...
**3. Reference/Guidelines** (best for standards or specifications)
- Works well for brand guidelines, coding standards, or requirements
- Example: Brand styling with "Brand Guidelines" -> "Colors" -> "Typography" -> "Features"
- Structure: ## Overview -> ## Guidelines -> ## Specifications -> ## Usage...
**4. Capabilities-Based** (best for integrated systems)
- Works well when the skill provides multiple interrelated features
- Example: Product Management with "Core Capabilities" -> numbered capability list
- Structure: ## Overview -> ## Core Capabilities -> ### 1. Feature -> ### 2. Feature...
Patterns can be mixed and matched as needed. Most skills combine patterns (e.g., start with task-based, add workflow for complex operations).
Delete this entire "Structuring This Skill" section when done - it's just guidance.]
## [TODO: Replace with the first main section based on chosen structure]
[TODO: Add content here. See examples in existing skills:
- Code samples for technical skills
- Decision trees for complex workflows
- Concrete examples with realistic user requests
- References to scripts/templates/references as needed]
## Resources (optional)
Create only the resource directories this skill actually needs. Delete this section if no resources are required.
### scripts/
Executable code (Python/Bash/etc.) that can be run directly to perform specific operations.
**Examples from other skills:**
- PDF skill: `fill_fillable_fields.py`, `extract_form_field_info.py` - utilities for PDF manipulation
- DOCX skill: `document.py`, `utilities.py` - Python modules for document processing
**Appropriate for:** Python scripts, shell scripts, or any executable code that performs automation, data processing, or specific operations.
**Note:** Scripts may be executed without loading into context, but can still be read by Codex for patching or environment adjustments.
### references/
Documentation and reference material intended to be loaded into context to inform Codex's process and thinking.
**Examples from other skills:**
- Product management: `communication.md`, `context_building.md` - detailed workflow guides
- BigQuery: API reference documentation and query examples
- Finance: Schema documentation, company policies
**Appropriate for:** In-depth documentation, API references, database schemas, comprehensive guides, or any detailed information that Codex should reference while working.
### assets/
Files not intended to be loaded into context, but rather used within the output Codex produces.
**Examples from other skills:**
- Brand styling: PowerPoint template files (.pptx), logo files
- Frontend builder: HTML/React boilerplate project directories
- Typography: Font files (.ttf, .woff2)
**Appropriate for:** Templates, boilerplate code, document templates, images, icons, fonts, or any files meant to be copied or used in the final output.
---
**Not every skill requires all three types of resources.**
"""
EXAMPLE_SCRIPT = '''#!/usr/bin/env python3
"""
Example helper script for {skill_name}
This is a placeholder script that can be executed directly.
Replace with actual implementation or delete if not needed.
Example real scripts from other skills:
- pdf/scripts/fill_fillable_fields.py - Fills PDF form fields
- pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images
"""
def main():
print("This is an example script for {skill_name}")
# TODO: Add actual script logic here
# This could be data processing, file conversion, API calls, etc.
if __name__ == "__main__":
main()
'''
EXAMPLE_REFERENCE = """# Reference Documentation for {skill_title}
This is a placeholder for detailed reference documentation.
Replace with actual reference content or delete if not needed.
Example real reference docs from other skills:
- product-management/references/communication.md - Comprehensive guide for status updates
- product-management/references/context_building.md - Deep-dive on gathering context
- bigquery/references/ - API references and query examples
## When Reference Docs Are Useful
Reference docs are ideal for:
- Comprehensive API documentation
- Detailed workflow guides
- Complex multi-step processes
- Information too lengthy for main SKILL.md
- Content that's only needed for specific use cases
## Structure Suggestions
### API Reference Example
- Overview
- Authentication
- Endpoints with examples
- Error codes
- Rate limits
### Workflow Guide Example
- Prerequisites
- Step-by-step instructions
- Common patterns
- Troubleshooting
- Best practices
"""
EXAMPLE_ASSET = """# Example Asset File
This placeholder represents where asset files would be stored.
Replace with actual asset files (templates, images, fonts, etc.) or delete if not needed.
Asset files are NOT intended to be loaded into context, but rather used within
the output Codex produces.
Example asset files from other skills:
- Brand guidelines: logo.png, slides_template.pptx
- Frontend builder: hello-world/ directory with HTML/React boilerplate
- Typography: custom-font.ttf, font-family.woff2
- Data: sample_data.csv, test_dataset.json
## Common Asset Types
- Templates: .pptx, .docx, boilerplate directories
- Images: .png, .jpg, .svg, .gif
- Fonts: .ttf, .otf, .woff, .woff2
- Boilerplate code: Project directories, starter files
- Icons: .ico, .svg
- Data files: .csv, .json, .xml, .yaml
Note: This is a text placeholder. Actual assets can be any file type.
"""
def normalize_skill_name(skill_name):
"""Normalize a skill name to lowercase hyphen-case."""
normalized = skill_name.strip().lower()
normalized = re.sub(r"[^a-z0-9]+", "-", normalized)
normalized = normalized.strip("-")
normalized = re.sub(r"-{2,}", "-", normalized)
return normalized
def title_case_skill_name(skill_name):
"""Convert hyphenated skill name to Title Case for display."""
return " ".join(word.capitalize() for word in skill_name.split("-"))
def parse_resources(raw_resources):
if not raw_resources:
return []
resources = [item.strip() for item in raw_resources.split(",") if item.strip()]
invalid = sorted({item for item in resources if item not in ALLOWED_RESOURCES})
if invalid:
allowed = ", ".join(sorted(ALLOWED_RESOURCES))
print(f"[ERROR] Unknown resource type(s): {', '.join(invalid)}")
print(f" Allowed: {allowed}")
sys.exit(1)
deduped = []
seen = set()
for resource in resources:
if resource not in seen:
deduped.append(resource)
seen.add(resource)
return deduped
def create_resource_dirs(skill_dir, skill_name, skill_title, resources, include_examples):
for resource in resources:
resource_dir = skill_dir / resource
resource_dir.mkdir(exist_ok=True)
if resource == "scripts":
if include_examples:
example_script = resource_dir / "example.py"
example_script.write_text(EXAMPLE_SCRIPT.format(skill_name=skill_name))
example_script.chmod(0o755)
print("[OK] Created scripts/example.py")
else:
print("[OK] Created scripts/")
elif resource == "references":
if include_examples:
example_reference = resource_dir / "api_reference.md"
example_reference.write_text(EXAMPLE_REFERENCE.format(skill_title=skill_title))
print("[OK] Created references/api_reference.md")
else:
print("[OK] Created references/")
elif resource == "assets":
if include_examples:
example_asset = resource_dir / "example_asset.txt"
example_asset.write_text(EXAMPLE_ASSET)
print("[OK] Created assets/example_asset.txt")
else:
print("[OK] Created assets/")
def init_skill(skill_name, path, resources, include_examples):
"""
Initialize a new skill directory with template SKILL.md.
Args:
skill_name: Name of the skill
path: Path where the skill directory should be created
resources: Resource directories to create
include_examples: Whether to create example files in resource directories
Returns:
Path to created skill directory, or None if error
"""
# Determine skill directory path
skill_dir = Path(path).resolve() / skill_name
# Check if directory already exists
if skill_dir.exists():
print(f"[ERROR] Skill directory already exists: {skill_dir}")
return None
# Create skill directory
try:
skill_dir.mkdir(parents=True, exist_ok=False)
print(f"[OK] Created skill directory: {skill_dir}")
except Exception as e:
print(f"[ERROR] Error creating directory: {e}")
return None
# Create SKILL.md from template
skill_title = title_case_skill_name(skill_name)
skill_content = SKILL_TEMPLATE.format(skill_name=skill_name, skill_title=skill_title)
skill_md_path = skill_dir / "SKILL.md"
try:
skill_md_path.write_text(skill_content)
print("[OK] Created SKILL.md")
except Exception as e:
print(f"[ERROR] Error creating SKILL.md: {e}")
return None
# Create resource directories if requested
if resources:
try:
create_resource_dirs(skill_dir, skill_name, skill_title, resources, include_examples)
except Exception as e:
print(f"[ERROR] Error creating resource directories: {e}")
return None
# Print next steps
print(f"\n[OK] Skill '{skill_name}' initialized successfully at {skill_dir}")
print("\nNext steps:")
print("1. Edit SKILL.md to complete the TODO items and update the description")
if resources:
if include_examples:
print("2. Customize or delete the example files in scripts/, references/, and assets/")
else:
print("2. Add resources to scripts/, references/, and assets/ as needed")
else:
print("2. Create resource directories only if needed (scripts/, references/, assets/)")
print("3. Run the validator when ready to check the skill structure")
return skill_dir
def main():
parser = argparse.ArgumentParser(
description="Create a new skill directory with a SKILL.md template.",
)
parser.add_argument("skill_name", help="Skill name (normalized to hyphen-case)")
parser.add_argument("--path", required=True, help="Output directory for the skill")
parser.add_argument(
"--resources",
default="",
help="Comma-separated list: scripts,references,assets",
)
parser.add_argument(
"--examples",
action="store_true",
help="Create example files inside the selected resource directories",
)
args = parser.parse_args()
raw_skill_name = args.skill_name
skill_name = normalize_skill_name(raw_skill_name)
if not skill_name:
print("[ERROR] Skill name must include at least one letter or digit.")
sys.exit(1)
if len(skill_name) > MAX_SKILL_NAME_LENGTH:
print(
f"[ERROR] Skill name '{skill_name}' is too long ({len(skill_name)} characters). "
f"Maximum is {MAX_SKILL_NAME_LENGTH} characters."
)
sys.exit(1)
if skill_name != raw_skill_name:
print(f"Note: Normalized skill name from '{raw_skill_name}' to '{skill_name}'.")
resources = parse_resources(args.resources)
if args.examples and not resources:
print("[ERROR] --examples requires --resources to be set.")
sys.exit(1)
path = args.path
print(f"Initializing skill: {skill_name}")
print(f" Location: {path}")
if resources:
print(f" Resources: {', '.join(resources)}")
if args.examples:
print(" Examples: enabled")
else:
print(" Resources: none (create as needed)")
print()
result = init_skill(skill_name, path, resources, args.examples)
if result:
sys.exit(0)
else:
sys.exit(1)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""
Skill Packager - Creates a distributable .skill file of a skill folder
Usage:
python utils/package_skill.py <path/to/skill-folder> [output-directory]
Example:
python utils/package_skill.py skills/public/my-skill
python utils/package_skill.py skills/public/my-skill ./dist
"""
import sys
import zipfile
from pathlib import Path
from quick_validate import validate_skill
def package_skill(skill_path, output_dir=None):
"""
Package a skill folder into a .skill file.
Args:
skill_path: Path to the skill folder
output_dir: Optional output directory for the .skill file (defaults to current directory)
Returns:
Path to the created .skill file, or None if error
"""
skill_path = Path(skill_path).resolve()
# Validate skill folder exists
if not skill_path.exists():
print(f"[ERROR] Skill folder not found: {skill_path}")
return None
if not skill_path.is_dir():
print(f"[ERROR] Path is not a directory: {skill_path}")
return None
# Validate SKILL.md exists
skill_md = skill_path / "SKILL.md"
if not skill_md.exists():
print(f"[ERROR] SKILL.md not found in {skill_path}")
return None
# Run validation before packaging
print("Validating skill...")
valid, message = validate_skill(skill_path)
if not valid:
print(f"[ERROR] Validation failed: {message}")
print(" Please fix the validation errors before packaging.")
return None
print(f"[OK] {message}\n")
# Determine output location
skill_name = skill_path.name
if output_dir:
output_path = Path(output_dir).resolve()
output_path.mkdir(parents=True, exist_ok=True)
else:
output_path = Path.cwd()
skill_filename = output_path / f"{skill_name}.skill"
# Create the .skill file (zip format)
try:
with zipfile.ZipFile(skill_filename, "w", zipfile.ZIP_DEFLATED) as zipf:
# Walk through the skill directory
for file_path in skill_path.rglob("*"):
if file_path.is_file():
# Calculate the relative path within the zip
arcname = file_path.relative_to(skill_path.parent)
zipf.write(file_path, arcname)
print(f" Added: {arcname}")
print(f"\n[OK] Successfully packaged skill to: {skill_filename}")
return skill_filename
except Exception as e:
print(f"[ERROR] Error creating .skill file: {e}")
return None
def main():
if len(sys.argv) < 2:
print("Usage: python utils/package_skill.py <path/to/skill-folder> [output-directory]")
print("\nExample:")
print(" python utils/package_skill.py skills/public/my-skill")
print(" python utils/package_skill.py skills/public/my-skill ./dist")
sys.exit(1)
skill_path = sys.argv[1]
output_dir = sys.argv[2] if len(sys.argv) > 2 else None
print(f"Packaging skill: {skill_path}")
if output_dir:
print(f" Output directory: {output_dir}")
print()
result = package_skill(skill_path, output_dir)
if result:
sys.exit(0)
else:
sys.exit(1)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""
Quick validation script for skills - minimal version
"""
import re
import sys
from pathlib import Path
import yaml
MAX_SKILL_NAME_LENGTH = 64
def validate_skill(skill_path):
"""Basic validation of a skill"""
skill_path = Path(skill_path)
skill_md = skill_path / "SKILL.md"
if not skill_md.exists():
return False, "SKILL.md not found"
content = skill_md.read_text()
if not content.startswith("---"):
return False, "No YAML frontmatter found"
match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)
if not match:
return False, "Invalid frontmatter format"
frontmatter_text = match.group(1)
try:
frontmatter = yaml.safe_load(frontmatter_text)
if not isinstance(frontmatter, dict):
return False, "Frontmatter must be a YAML dictionary"
except yaml.YAMLError as e:
return False, f"Invalid YAML in frontmatter: {e}"
allowed_properties = {"name", "description", "license", "allowed-tools", "metadata"}
unexpected_keys = set(frontmatter.keys()) - allowed_properties
if unexpected_keys:
allowed = ", ".join(sorted(allowed_properties))
unexpected = ", ".join(sorted(unexpected_keys))
return (
False,
f"Unexpected key(s) in SKILL.md frontmatter: {unexpected}. Allowed properties are: {allowed}",
)
if "name" not in frontmatter:
return False, "Missing 'name' in frontmatter"
if "description" not in frontmatter:
return False, "Missing 'description' in frontmatter"
name = frontmatter.get("name", "")
if not isinstance(name, str):
return False, f"Name must be a string, got {type(name).__name__}"
name = name.strip()
if name:
if not re.match(r"^[a-z0-9-]+$", name):
return (
False,
f"Name '{name}' should be hyphen-case (lowercase letters, digits, and hyphens only)",
)
if name.startswith("-") or name.endswith("-") or "--" in name:
return (
False,
f"Name '{name}' cannot start/end with hyphen or contain consecutive hyphens",
)
if len(name) > MAX_SKILL_NAME_LENGTH:
return (
False,
f"Name is too long ({len(name)} characters). "
f"Maximum is {MAX_SKILL_NAME_LENGTH} characters.",
)
description = frontmatter.get("description", "")
if not isinstance(description, str):
return False, f"Description must be a string, got {type(description).__name__}"
description = description.strip()
if description:
if "<" in description or ">" in description:
return False, "Description cannot contain angle brackets (< or >)"
if len(description) > 1024:
return (
False,
f"Description is too long ({len(description)} characters). Maximum is 1024 characters.",
)
return True, "Skill is valid!"
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python quick_validate.py <skill_directory>")
sys.exit(1)
valid, message = validate_skill(sys.argv[1])
print(message)
sys.exit(0 if valid else 1)

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,56 @@
---
name: skill-installer
description: Install Codex skills into $CODEX_HOME/skills from a curated list or a GitHub repo path. Use when a user asks to list installable skills, install a curated skill, or install a skill from another repo (including private repos).
metadata:
short-description: Install curated skills from openai/skills or other repos
---
# Skill Installer
Helps install skills. By default these are from https://github.com/openai/skills/tree/main/skills/.curated, but users can also provide other locations.
Use the helper scripts based on the task:
- List curated skills when the user asks what is available, or if the user uses this skill without specifying what to do.
- Install from the curated list when the user provides a skill name.
- Install from another repo when the user provides a GitHub repo/path (including private repos).
Install skills with the helper scripts.
## Communication
When listing curated skills, output approximately as follows, depending on the context of the user's request:
"""
Skills from {repo}:
1. skill-1
2. skill-2 (already installed)
3. ...
Which ones would you like installed?
"""
After installing a skill, tell the user: "Restart Codex to pick up new skills."
## Scripts
All of these scripts use network, so when running in the sandbox, request escalation when running them.
- `scripts/list-curated-skills.py` (prints curated list with installed annotations)
- `scripts/list-curated-skills.py --format json`
- `scripts/install-skill-from-github.py --repo <owner>/<repo> --path <path/to/skill> [<path/to/skill> ...]`
- `scripts/install-skill-from-github.py --url https://github.com/<owner>/<repo>/tree/<ref>/<path>`
## Behavior and Options
- Defaults to direct download for public GitHub repos.
- If download fails with auth/permission errors, falls back to git sparse checkout.
- Aborts if the destination skill directory already exists.
- Installs into `$CODEX_HOME/skills/<skill-name>` (defaults to `~/.codex/skills`).
- Multiple `--path` values install multiple skills in one run, each named from the path basename unless `--name` is supplied.
- Options: `--ref <ref>` (default `main`), `--dest <path>`, `--method auto|download|git`.
## Notes
- Curated listing is fetched from `https://github.com/openai/skills/tree/main/skills/.curated` via the GitHub API. If it is unavailable, explain the error and exit.
- Private GitHub repos can be accessed via existing git credentials or optional `GITHUB_TOKEN`/`GH_TOKEN` for download.
- Git fallback tries HTTPS first, then SSH.
- The skills at https://github.com/openai/skills/tree/main/skills/.system are preinstalled, so no need to help users install those. If they ask, just explain this. If they insist, you can download and overwrite.
- Installed annotations come from `$CODEX_HOME/skills`.

View File

@@ -0,0 +1,21 @@
#!/usr/bin/env python3
"""Shared GitHub helpers for skill install scripts."""
from __future__ import annotations
import os
import urllib.request
def github_request(url: str, user_agent: str) -> bytes:
headers = {"User-Agent": user_agent}
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
if token:
headers["Authorization"] = f"token {token}"
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req) as resp:
return resp.read()
def github_api_contents_url(repo: str, path: str, ref: str) -> str:
return f"https://api.github.com/repos/{repo}/contents/{path}?ref={ref}"

View File

@@ -0,0 +1,308 @@
#!/usr/bin/env python3
"""Install a skill from a GitHub repo path into $CODEX_HOME/skills."""
from __future__ import annotations
import argparse
from dataclasses import dataclass
import os
import shutil
import subprocess
import sys
import tempfile
import urllib.error
import urllib.parse
import zipfile
from github_utils import github_request
DEFAULT_REF = "main"
@dataclass
class Args:
url: str | None = None
repo: str | None = None
path: list[str] | None = None
ref: str = DEFAULT_REF
dest: str | None = None
name: str | None = None
method: str = "auto"
@dataclass
class Source:
owner: str
repo: str
ref: str
paths: list[str]
repo_url: str | None = None
class InstallError(Exception):
pass
def _codex_home() -> str:
return os.environ.get("CODEX_HOME", os.path.expanduser("~/.codex"))
def _tmp_root() -> str:
base = os.path.join(tempfile.gettempdir(), "codex")
os.makedirs(base, exist_ok=True)
return base
def _request(url: str) -> bytes:
return github_request(url, "codex-skill-install")
def _parse_github_url(url: str, default_ref: str) -> tuple[str, str, str, str | None]:
parsed = urllib.parse.urlparse(url)
if parsed.netloc != "github.com":
raise InstallError("Only GitHub URLs are supported for download mode.")
parts = [p for p in parsed.path.split("/") if p]
if len(parts) < 2:
raise InstallError("Invalid GitHub URL.")
owner, repo = parts[0], parts[1]
ref = default_ref
subpath = ""
if len(parts) > 2:
if parts[2] in ("tree", "blob"):
if len(parts) < 4:
raise InstallError("GitHub URL missing ref or path.")
ref = parts[3]
subpath = "/".join(parts[4:])
else:
subpath = "/".join(parts[2:])
return owner, repo, ref, subpath or None
def _download_repo_zip(owner: str, repo: str, ref: str, dest_dir: str) -> str:
zip_url = f"https://codeload.github.com/{owner}/{repo}/zip/{ref}"
zip_path = os.path.join(dest_dir, "repo.zip")
try:
payload = _request(zip_url)
except urllib.error.HTTPError as exc:
raise InstallError(f"Download failed: HTTP {exc.code}") from exc
with open(zip_path, "wb") as file_handle:
file_handle.write(payload)
with zipfile.ZipFile(zip_path, "r") as zip_file:
_safe_extract_zip(zip_file, dest_dir)
top_levels = {name.split("/")[0] for name in zip_file.namelist() if name}
if not top_levels:
raise InstallError("Downloaded archive was empty.")
if len(top_levels) != 1:
raise InstallError("Unexpected archive layout.")
return os.path.join(dest_dir, next(iter(top_levels)))
def _run_git(args: list[str]) -> None:
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode != 0:
raise InstallError(result.stderr.strip() or "Git command failed.")
def _safe_extract_zip(zip_file: zipfile.ZipFile, dest_dir: str) -> None:
dest_root = os.path.realpath(dest_dir)
for info in zip_file.infolist():
extracted_path = os.path.realpath(os.path.join(dest_dir, info.filename))
if extracted_path == dest_root or extracted_path.startswith(dest_root + os.sep):
continue
raise InstallError("Archive contains files outside the destination.")
zip_file.extractall(dest_dir)
def _validate_relative_path(path: str) -> None:
if os.path.isabs(path) or os.path.normpath(path).startswith(".."):
raise InstallError("Skill path must be a relative path inside the repo.")
def _validate_skill_name(name: str) -> None:
altsep = os.path.altsep
if not name or os.path.sep in name or (altsep and altsep in name):
raise InstallError("Skill name must be a single path segment.")
if name in (".", ".."):
raise InstallError("Invalid skill name.")
def _git_sparse_checkout(repo_url: str, ref: str, paths: list[str], dest_dir: str) -> str:
repo_dir = os.path.join(dest_dir, "repo")
clone_cmd = [
"git",
"clone",
"--filter=blob:none",
"--depth",
"1",
"--sparse",
"--single-branch",
"--branch",
ref,
repo_url,
repo_dir,
]
try:
_run_git(clone_cmd)
except InstallError:
_run_git(
[
"git",
"clone",
"--filter=blob:none",
"--depth",
"1",
"--sparse",
"--single-branch",
repo_url,
repo_dir,
]
)
_run_git(["git", "-C", repo_dir, "sparse-checkout", "set", *paths])
_run_git(["git", "-C", repo_dir, "checkout", ref])
return repo_dir
def _validate_skill(path: str) -> None:
if not os.path.isdir(path):
raise InstallError(f"Skill path not found: {path}")
skill_md = os.path.join(path, "SKILL.md")
if not os.path.isfile(skill_md):
raise InstallError("SKILL.md not found in selected skill directory.")
def _copy_skill(src: str, dest_dir: str) -> None:
os.makedirs(os.path.dirname(dest_dir), exist_ok=True)
if os.path.exists(dest_dir):
raise InstallError(f"Destination already exists: {dest_dir}")
shutil.copytree(src, dest_dir)
def _build_repo_url(owner: str, repo: str) -> str:
return f"https://github.com/{owner}/{repo}.git"
def _build_repo_ssh(owner: str, repo: str) -> str:
return f"git@github.com:{owner}/{repo}.git"
def _prepare_repo(source: Source, method: str, tmp_dir: str) -> str:
if method in ("download", "auto"):
try:
return _download_repo_zip(source.owner, source.repo, source.ref, tmp_dir)
except InstallError as exc:
if method == "download":
raise
err_msg = str(exc)
if "HTTP 401" in err_msg or "HTTP 403" in err_msg or "HTTP 404" in err_msg:
pass
else:
raise
if method in ("git", "auto"):
repo_url = source.repo_url or _build_repo_url(source.owner, source.repo)
try:
return _git_sparse_checkout(repo_url, source.ref, source.paths, tmp_dir)
except InstallError:
repo_url = _build_repo_ssh(source.owner, source.repo)
return _git_sparse_checkout(repo_url, source.ref, source.paths, tmp_dir)
raise InstallError("Unsupported method.")
def _resolve_source(args: Args) -> Source:
if args.url:
owner, repo, ref, url_path = _parse_github_url(args.url, args.ref)
if args.path is not None:
paths = list(args.path)
elif url_path:
paths = [url_path]
else:
paths = []
if not paths:
raise InstallError("Missing --path for GitHub URL.")
return Source(owner=owner, repo=repo, ref=ref, paths=paths)
if not args.repo:
raise InstallError("Provide --repo or --url.")
if "://" in args.repo:
return _resolve_source(
Args(url=args.repo, repo=None, path=args.path, ref=args.ref)
)
repo_parts = [p for p in args.repo.split("/") if p]
if len(repo_parts) != 2:
raise InstallError("--repo must be in owner/repo format.")
if not args.path:
raise InstallError("Missing --path for --repo.")
paths = list(args.path)
return Source(
owner=repo_parts[0],
repo=repo_parts[1],
ref=args.ref,
paths=paths,
)
def _default_dest() -> str:
return os.path.join(_codex_home(), "skills")
def _parse_args(argv: list[str]) -> Args:
parser = argparse.ArgumentParser(description="Install a skill from GitHub.")
parser.add_argument("--repo", help="owner/repo")
parser.add_argument("--url", help="https://github.com/owner/repo[/tree/ref/path]")
parser.add_argument(
"--path",
nargs="+",
help="Path(s) to skill(s) inside repo",
)
parser.add_argument("--ref", default=DEFAULT_REF)
parser.add_argument("--dest", help="Destination skills directory")
parser.add_argument(
"--name", help="Destination skill name (defaults to basename of path)"
)
parser.add_argument(
"--method",
choices=["auto", "download", "git"],
default="auto",
)
return parser.parse_args(argv, namespace=Args())
def main(argv: list[str]) -> int:
args = _parse_args(argv)
try:
source = _resolve_source(args)
source.ref = source.ref or args.ref
if not source.paths:
raise InstallError("No skill paths provided.")
for path in source.paths:
_validate_relative_path(path)
dest_root = args.dest or _default_dest()
tmp_dir = tempfile.mkdtemp(prefix="skill-install-", dir=_tmp_root())
try:
repo_root = _prepare_repo(source, args.method, tmp_dir)
installed = []
for path in source.paths:
skill_name = args.name if len(source.paths) == 1 else None
skill_name = skill_name or os.path.basename(path.rstrip("/"))
_validate_skill_name(skill_name)
if not skill_name:
raise InstallError("Unable to derive skill name.")
dest_dir = os.path.join(dest_root, skill_name)
if os.path.exists(dest_dir):
raise InstallError(f"Destination already exists: {dest_dir}")
skill_src = os.path.join(repo_root, path)
_validate_skill(skill_src)
_copy_skill(skill_src, dest_dir)
installed.append((skill_name, dest_dir))
finally:
if os.path.isdir(tmp_dir):
shutil.rmtree(tmp_dir, ignore_errors=True)
for skill_name, dest_dir in installed:
print(f"Installed {skill_name} to {dest_dir}")
return 0
except InstallError as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))

View File

@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""List curated skills from a GitHub repo path."""
from __future__ import annotations
import argparse
import json
import os
import sys
import urllib.error
from github_utils import github_api_contents_url, github_request
DEFAULT_REPO = "openai/skills"
DEFAULT_PATH = "skills/.curated"
DEFAULT_REF = "main"
class ListError(Exception):
pass
class Args(argparse.Namespace):
repo: str
path: str
ref: str
format: str
def _request(url: str) -> bytes:
return github_request(url, "codex-skill-list")
def _codex_home() -> str:
return os.environ.get("CODEX_HOME", os.path.expanduser("~/.codex"))
def _installed_skills() -> set[str]:
root = os.path.join(_codex_home(), "skills")
if not os.path.isdir(root):
return set()
entries = set()
for name in os.listdir(root):
path = os.path.join(root, name)
if os.path.isdir(path):
entries.add(name)
return entries
def _list_curated(repo: str, path: str, ref: str) -> list[str]:
api_url = github_api_contents_url(repo, path, ref)
try:
payload = _request(api_url)
except urllib.error.HTTPError as exc:
if exc.code == 404:
raise ListError(
"Curated skills path not found: "
f"https://github.com/{repo}/tree/{ref}/{path}"
) from exc
raise ListError(f"Failed to fetch curated skills: HTTP {exc.code}") from exc
data = json.loads(payload.decode("utf-8"))
if not isinstance(data, list):
raise ListError("Unexpected curated listing response.")
skills = [item["name"] for item in data if item.get("type") == "dir"]
return sorted(skills)
def _parse_args(argv: list[str]) -> Args:
parser = argparse.ArgumentParser(description="List curated skills.")
parser.add_argument("--repo", default=DEFAULT_REPO)
parser.add_argument("--path", default=DEFAULT_PATH)
parser.add_argument("--ref", default=DEFAULT_REF)
parser.add_argument(
"--format",
choices=["text", "json"],
default="text",
help="Output format",
)
return parser.parse_args(argv, namespace=Args())
def main(argv: list[str]) -> int:
args = _parse_args(argv)
try:
skills = _list_curated(args.repo, args.path, args.ref)
installed = _installed_skills()
if args.format == "json":
payload = [
{"name": name, "installed": name in installed} for name in skills
]
print(json.dumps(payload))
else:
for idx, name in enumerate(skills, start=1):
suffix = " (already installed)" if name in installed else ""
print(f"{idx}. {name}{suffix}")
return 0
except ListError as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))

View File

@@ -0,0 +1,24 @@
name: MCP Tests
on:
push:
branches: [ main ]
paths:
- 'scripts/**'
- 'docs/**'
- '.gitea/workflows/mcp-tests.yml'
pull_request:
paths:
- 'scripts/**'
- 'docs/**'
- '.gitea/workflows/mcp-tests.yml'
jobs:
mcp-tests:
runs-on: nixos
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Run MCP lint/format/tests via nix-shell
run: ./scripts/mcp-server/run-tests.sh

22
.gitignore vendored
View File

@@ -2,7 +2,29 @@
config.el
*.qcow2
result
.codex/*
!.codex/config.toml
!.codex/requirements.toml
!.codex/rules/
!.codex/rules/**
!.codex/skills/
!.codex/skills/**
!.codex/prompts/
!.codex/prompts/**
# Prevent accidentally committing unencrypted secrets
**/secrets/*.yaml.dec
**/*-decrypted.*
**/temp-secrets.*
# Editor/OS artifacts
.DS_Store
Thumbs.db
.vscode/
.idea/
*.swp
*.tmp
__pycache__/
*.pyc
.venv/
venv/
dist/
*.egg-info/

View File

@@ -2,7 +2,7 @@ keys:
- &devkey age1lufn6t35gs4wgevyr2gud4eec7lvkn7pgnnv4tja64ww3hef7gqq8fas37
- &workstation age17jlsydpgl35qx5ahc3exu44jt8dfa63chymt6xqp9xx0r6dh347qpg55cz
- &server age15hx530yrqmhm80vsjmffyg9deq9gssj7hl5rsqdnsn3dwegj9qusv4sjf5
- &miniserver age13w4elx3x6afrte2d82lak59mwr2k25wfz3hx79tny6sfdk66lqjq989dzl
- &vps age1ml3smrs5mwz4ds84gk0eyss86nwsmp07qh0npxsuae7lfwwpsghssavytw
creation_rules:
- path_regex: secrets/secrets.yaml$
key_groups:
@@ -10,46 +10,46 @@ creation_rules:
- *devkey
- *workstation
- *server
- *miniserver
- *vps
- path_regex: secrets/keys.yaml$
key_groups:
- age:
- *devkey
- *workstation
- *server
- *miniserver
- *vps
- path_regex: secrets/env.yaml$
key_groups:
- age:
- *devkey
- *workstation
- *server
- *miniserver
- *vps
- path_regex: secrets/gallery.yaml$
key_groups:
- age:
- *devkey
- *workstation
- *server
- *miniserver
- *vps
- path_regex: secrets/wireguard.yaml$
key_groups:
- age:
- *devkey
- *workstation
- *server
- *miniserver
- *vps
- path_regex: secrets/homepage.yaml$
key_groups:
- age:
- *devkey
- *workstation
- *server
- *miniserver
- *vps
- path_regex: secrets/certs.yaml$
key_groups:
- age:
- *devkey
- *workstation
- *server
- *miniserver
- *vps

View File

@@ -0,0 +1,50 @@
# [PROJECT_NAME] Constitution
<!-- Example: Spec Constitution, TaskFlow Constitution, etc. -->
## Core Principles
### [PRINCIPLE_1_NAME]
<!-- Example: I. Library-First -->
[PRINCIPLE_1_DESCRIPTION]
<!-- Example: Every feature starts as a standalone library; Libraries must be self-contained, independently testable, documented; Clear purpose required - no organizational-only libraries -->
### [PRINCIPLE_2_NAME]
<!-- Example: II. CLI Interface -->
[PRINCIPLE_2_DESCRIPTION]
<!-- Example: Every library exposes functionality via CLI; Text in/out protocol: stdin/args → stdout, errors → stderr; Support JSON + human-readable formats -->
### [PRINCIPLE_3_NAME]
<!-- Example: III. Test-First (NON-NEGOTIABLE) -->
[PRINCIPLE_3_DESCRIPTION]
<!-- Example: TDD mandatory: Tests written → User approved → Tests fail → Then implement; Red-Green-Refactor cycle strictly enforced -->
### [PRINCIPLE_4_NAME]
<!-- Example: IV. Integration Testing -->
[PRINCIPLE_4_DESCRIPTION]
<!-- Example: Focus areas requiring integration tests: New library contract tests, Contract changes, Inter-service communication, Shared schemas -->
### [PRINCIPLE_5_NAME]
<!-- Example: V. Observability, VI. Versioning & Breaking Changes, VII. Simplicity -->
[PRINCIPLE_5_DESCRIPTION]
<!-- Example: Text I/O ensures debuggability; Structured logging required; Or: MAJOR.MINOR.BUILD format; Or: Start simple, YAGNI principles -->
## [SECTION_2_NAME]
<!-- Example: Additional Constraints, Security Requirements, Performance Standards, etc. -->
[SECTION_2_CONTENT]
<!-- Example: Technology stack requirements, compliance standards, deployment policies, etc. -->
## [SECTION_3_NAME]
<!-- Example: Development Workflow, Review Process, Quality Gates, etc. -->
[SECTION_3_CONTENT]
<!-- Example: Code review requirements, testing gates, deployment approval process, etc. -->
## Governance
<!-- Example: Constitution supersedes all other practices; Amendments require documentation, approval, migration plan -->
[GOVERNANCE_RULES]
<!-- Example: All PRs/reviews must verify compliance; Complexity must be justified; Use [GUIDANCE_FILE] for runtime development guidance -->
**Version**: [CONSTITUTION_VERSION] | **Ratified**: [RATIFICATION_DATE] | **Last Amended**: [LAST_AMENDED_DATE]
<!-- Example: Version: 2.1.1 | Ratified: 2025-06-13 | Last Amended: 2025-07-16 -->

View File

@@ -0,0 +1,166 @@
#!/usr/bin/env bash
# Consolidated prerequisite checking script
#
# This script provides unified prerequisite checking for Spec-Driven Development workflow.
# It replaces the functionality previously spread across multiple scripts.
#
# Usage: ./check-prerequisites.sh [OPTIONS]
#
# OPTIONS:
# --json Output in JSON format
# --require-tasks Require tasks.md to exist (for implementation phase)
# --include-tasks Include tasks.md in AVAILABLE_DOCS list
# --paths-only Only output path variables (no validation)
# --help, -h Show help message
#
# OUTPUTS:
# JSON mode: {"FEATURE_DIR":"...", "AVAILABLE_DOCS":["..."]}
# Text mode: FEATURE_DIR:... \n AVAILABLE_DOCS: \n ✓/✗ file.md
# Paths only: REPO_ROOT: ... \n BRANCH: ... \n FEATURE_DIR: ... etc.
set -e
# Parse command line arguments
JSON_MODE=false
REQUIRE_TASKS=false
INCLUDE_TASKS=false
PATHS_ONLY=false
for arg in "$@"; do
case "$arg" in
--json)
JSON_MODE=true
;;
--require-tasks)
REQUIRE_TASKS=true
;;
--include-tasks)
INCLUDE_TASKS=true
;;
--paths-only)
PATHS_ONLY=true
;;
--help|-h)
cat << 'EOF'
Usage: check-prerequisites.sh [OPTIONS]
Consolidated prerequisite checking for Spec-Driven Development workflow.
OPTIONS:
--json Output in JSON format
--require-tasks Require tasks.md to exist (for implementation phase)
--include-tasks Include tasks.md in AVAILABLE_DOCS list
--paths-only Only output path variables (no prerequisite validation)
--help, -h Show this help message
EXAMPLES:
# Check task prerequisites (plan.md required)
./check-prerequisites.sh --json
# Check implementation prerequisites (plan.md + tasks.md required)
./check-prerequisites.sh --json --require-tasks --include-tasks
# Get feature paths only (no validation)
./check-prerequisites.sh --paths-only
EOF
exit 0
;;
*)
echo "ERROR: Unknown option '$arg'. Use --help for usage information." >&2
exit 1
;;
esac
done
# Source common functions
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Get feature paths and validate branch
eval $(get_feature_paths)
check_feature_branch "$CURRENT_BRANCH" "$HAS_GIT" || exit 1
# If paths-only mode, output paths and exit (support JSON + paths-only combined)
if $PATHS_ONLY; then
if $JSON_MODE; then
# Minimal JSON paths payload (no validation performed)
printf '{"REPO_ROOT":"%s","BRANCH":"%s","FEATURE_DIR":"%s","FEATURE_SPEC":"%s","IMPL_PLAN":"%s","TASKS":"%s"}\n' \
"$REPO_ROOT" "$CURRENT_BRANCH" "$FEATURE_DIR" "$FEATURE_SPEC" "$IMPL_PLAN" "$TASKS"
else
echo "REPO_ROOT: $REPO_ROOT"
echo "BRANCH: $CURRENT_BRANCH"
echo "FEATURE_DIR: $FEATURE_DIR"
echo "FEATURE_SPEC: $FEATURE_SPEC"
echo "IMPL_PLAN: $IMPL_PLAN"
echo "TASKS: $TASKS"
fi
exit 0
fi
# Validate required directories and files
if [[ ! -d "$FEATURE_DIR" ]]; then
echo "ERROR: Feature directory not found: $FEATURE_DIR" >&2
echo "Run /speckit.specify first to create the feature structure." >&2
exit 1
fi
if [[ ! -f "$IMPL_PLAN" ]]; then
echo "ERROR: plan.md not found in $FEATURE_DIR" >&2
echo "Run /speckit.plan first to create the implementation plan." >&2
exit 1
fi
# Check for tasks.md if required
if $REQUIRE_TASKS && [[ ! -f "$TASKS" ]]; then
echo "ERROR: tasks.md not found in $FEATURE_DIR" >&2
echo "Run /speckit.tasks first to create the task list." >&2
exit 1
fi
# Build list of available documents
docs=()
# Always check these optional docs
[[ -f "$RESEARCH" ]] && docs+=("research.md")
[[ -f "$DATA_MODEL" ]] && docs+=("data-model.md")
# Check contracts directory (only if it exists and has files)
if [[ -d "$CONTRACTS_DIR" ]] && [[ -n "$(ls -A "$CONTRACTS_DIR" 2>/dev/null)" ]]; then
docs+=("contracts/")
fi
[[ -f "$QUICKSTART" ]] && docs+=("quickstart.md")
# Include tasks.md if requested and it exists
if $INCLUDE_TASKS && [[ -f "$TASKS" ]]; then
docs+=("tasks.md")
fi
# Output results
if $JSON_MODE; then
# Build JSON array of documents
if [[ ${#docs[@]} -eq 0 ]]; then
json_docs="[]"
else
json_docs=$(printf '"%s",' "${docs[@]}")
json_docs="[${json_docs%,}]"
fi
printf '{"FEATURE_DIR":"%s","AVAILABLE_DOCS":%s}\n' "$FEATURE_DIR" "$json_docs"
else
# Text output
echo "FEATURE_DIR:$FEATURE_DIR"
echo "AVAILABLE_DOCS:"
# Show status of each potential document
check_file "$RESEARCH" "research.md"
check_file "$DATA_MODEL" "data-model.md"
check_dir "$CONTRACTS_DIR" "contracts/"
check_file "$QUICKSTART" "quickstart.md"
if $INCLUDE_TASKS; then
check_file "$TASKS" "tasks.md"
fi
fi

156
.specify/scripts/bash/common.sh Executable file
View File

@@ -0,0 +1,156 @@
#!/usr/bin/env bash
# Common functions and variables for all scripts
# Get repository root, with fallback for non-git repositories
get_repo_root() {
if git rev-parse --show-toplevel >/dev/null 2>&1; then
git rev-parse --show-toplevel
else
# Fall back to script location for non-git repos
local script_dir="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
(cd "$script_dir/../../.." && pwd)
fi
}
# Get current branch, with fallback for non-git repositories
get_current_branch() {
# First check if SPECIFY_FEATURE environment variable is set
if [[ -n "${SPECIFY_FEATURE:-}" ]]; then
echo "$SPECIFY_FEATURE"
return
fi
# Then check git if available
if git rev-parse --abbrev-ref HEAD >/dev/null 2>&1; then
git rev-parse --abbrev-ref HEAD
return
fi
# For non-git repos, try to find the latest feature directory
local repo_root=$(get_repo_root)
local specs_dir="$repo_root/specs"
if [[ -d "$specs_dir" ]]; then
local latest_feature=""
local highest=0
for dir in "$specs_dir"/*; do
if [[ -d "$dir" ]]; then
local dirname=$(basename "$dir")
if [[ "$dirname" =~ ^([0-9]{3})- ]]; then
local number=${BASH_REMATCH[1]}
number=$((10#$number))
if [[ "$number" -gt "$highest" ]]; then
highest=$number
latest_feature=$dirname
fi
fi
fi
done
if [[ -n "$latest_feature" ]]; then
echo "$latest_feature"
return
fi
fi
echo "main" # Final fallback
}
# Check if we have git available
has_git() {
git rev-parse --show-toplevel >/dev/null 2>&1
}
check_feature_branch() {
local branch="$1"
local has_git_repo="$2"
# For non-git repos, we can't enforce branch naming but still provide output
if [[ "$has_git_repo" != "true" ]]; then
echo "[specify] Warning: Git repository not detected; skipped branch validation" >&2
return 0
fi
if [[ ! "$branch" =~ ^[0-9]{3}- ]]; then
echo "ERROR: Not on a feature branch. Current branch: $branch" >&2
echo "Feature branches should be named like: 001-feature-name" >&2
return 1
fi
return 0
}
get_feature_dir() { echo "$1/specs/$2"; }
# Find feature directory by numeric prefix instead of exact branch match
# This allows multiple branches to work on the same spec (e.g., 004-fix-bug, 004-add-feature)
find_feature_dir_by_prefix() {
local repo_root="$1"
local branch_name="$2"
local specs_dir="$repo_root/specs"
# Extract numeric prefix from branch (e.g., "004" from "004-whatever")
if [[ ! "$branch_name" =~ ^([0-9]{3})- ]]; then
# If branch doesn't have numeric prefix, fall back to exact match
echo "$specs_dir/$branch_name"
return
fi
local prefix="${BASH_REMATCH[1]}"
# Search for directories in specs/ that start with this prefix
local matches=()
if [[ -d "$specs_dir" ]]; then
for dir in "$specs_dir"/"$prefix"-*; do
if [[ -d "$dir" ]]; then
matches+=("$(basename "$dir")")
fi
done
fi
# Handle results
if [[ ${#matches[@]} -eq 0 ]]; then
# No match found - return the branch name path (will fail later with clear error)
echo "$specs_dir/$branch_name"
elif [[ ${#matches[@]} -eq 1 ]]; then
# Exactly one match - perfect!
echo "$specs_dir/${matches[0]}"
else
# Multiple matches - this shouldn't happen with proper naming convention
echo "ERROR: Multiple spec directories found with prefix '$prefix': ${matches[*]}" >&2
echo "Please ensure only one spec directory exists per numeric prefix." >&2
echo "$specs_dir/$branch_name" # Return something to avoid breaking the script
fi
}
get_feature_paths() {
local repo_root=$(get_repo_root)
local current_branch=$(get_current_branch)
local has_git_repo="false"
if has_git; then
has_git_repo="true"
fi
# Use prefix-based lookup to support multiple branches per spec
local feature_dir=$(find_feature_dir_by_prefix "$repo_root" "$current_branch")
cat <<EOF
REPO_ROOT='$repo_root'
CURRENT_BRANCH='$current_branch'
HAS_GIT='$has_git_repo'
FEATURE_DIR='$feature_dir'
FEATURE_SPEC='$feature_dir/spec.md'
IMPL_PLAN='$feature_dir/plan.md'
TASKS='$feature_dir/tasks.md'
RESEARCH='$feature_dir/research.md'
DATA_MODEL='$feature_dir/data-model.md'
QUICKSTART='$feature_dir/quickstart.md'
CONTRACTS_DIR='$feature_dir/contracts'
EOF
}
check_file() { [[ -f "$1" ]] && echo "$2" || echo "$2"; }
check_dir() { [[ -d "$1" && -n $(ls -A "$1" 2>/dev/null) ]] && echo "$2" || echo "$2"; }

View File

@@ -0,0 +1,297 @@
#!/usr/bin/env bash
set -e
JSON_MODE=false
SHORT_NAME=""
BRANCH_NUMBER=""
ARGS=()
i=1
while [ $i -le $# ]; do
arg="${!i}"
case "$arg" in
--json)
JSON_MODE=true
;;
--short-name)
if [ $((i + 1)) -gt $# ]; then
echo 'Error: --short-name requires a value' >&2
exit 1
fi
i=$((i + 1))
next_arg="${!i}"
# Check if the next argument is another option (starts with --)
if [[ "$next_arg" == --* ]]; then
echo 'Error: --short-name requires a value' >&2
exit 1
fi
SHORT_NAME="$next_arg"
;;
--number)
if [ $((i + 1)) -gt $# ]; then
echo 'Error: --number requires a value' >&2
exit 1
fi
i=$((i + 1))
next_arg="${!i}"
if [[ "$next_arg" == --* ]]; then
echo 'Error: --number requires a value' >&2
exit 1
fi
BRANCH_NUMBER="$next_arg"
;;
--help|-h)
echo "Usage: $0 [--json] [--short-name <name>] [--number N] <feature_description>"
echo ""
echo "Options:"
echo " --json Output in JSON format"
echo " --short-name <name> Provide a custom short name (2-4 words) for the branch"
echo " --number N Specify branch number manually (overrides auto-detection)"
echo " --help, -h Show this help message"
echo ""
echo "Examples:"
echo " $0 'Add user authentication system' --short-name 'user-auth'"
echo " $0 'Implement OAuth2 integration for API' --number 5"
exit 0
;;
*)
ARGS+=("$arg")
;;
esac
i=$((i + 1))
done
FEATURE_DESCRIPTION="${ARGS[*]}"
if [ -z "$FEATURE_DESCRIPTION" ]; then
echo "Usage: $0 [--json] [--short-name <name>] [--number N] <feature_description>" >&2
exit 1
fi
# Function to find the repository root by searching for existing project markers
find_repo_root() {
local dir="$1"
while [ "$dir" != "/" ]; do
if [ -d "$dir/.git" ] || [ -d "$dir/.specify" ]; then
echo "$dir"
return 0
fi
dir="$(dirname "$dir")"
done
return 1
}
# Function to get highest number from specs directory
get_highest_from_specs() {
local specs_dir="$1"
local highest=0
if [ -d "$specs_dir" ]; then
for dir in "$specs_dir"/*; do
[ -d "$dir" ] || continue
dirname=$(basename "$dir")
number=$(echo "$dirname" | grep -o '^[0-9]\+' || echo "0")
number=$((10#$number))
if [ "$number" -gt "$highest" ]; then
highest=$number
fi
done
fi
echo "$highest"
}
# Function to get highest number from git branches
get_highest_from_branches() {
local highest=0
# Get all branches (local and remote)
branches=$(git branch -a 2>/dev/null || echo "")
if [ -n "$branches" ]; then
while IFS= read -r branch; do
# Clean branch name: remove leading markers and remote prefixes
clean_branch=$(echo "$branch" | sed 's/^[* ]*//; s|^remotes/[^/]*/||')
# Extract feature number if branch matches pattern ###-*
if echo "$clean_branch" | grep -q '^[0-9]\{3\}-'; then
number=$(echo "$clean_branch" | grep -o '^[0-9]\{3\}' || echo "0")
number=$((10#$number))
if [ "$number" -gt "$highest" ]; then
highest=$number
fi
fi
done <<< "$branches"
fi
echo "$highest"
}
# Function to check existing branches (local and remote) and return next available number
check_existing_branches() {
local specs_dir="$1"
# Fetch all remotes to get latest branch info (suppress errors if no remotes)
git fetch --all --prune 2>/dev/null || true
# Get highest number from ALL branches (not just matching short name)
local highest_branch=$(get_highest_from_branches)
# Get highest number from ALL specs (not just matching short name)
local highest_spec=$(get_highest_from_specs "$specs_dir")
# Take the maximum of both
local max_num=$highest_branch
if [ "$highest_spec" -gt "$max_num" ]; then
max_num=$highest_spec
fi
# Return next number
echo $((max_num + 1))
}
# Function to clean and format a branch name
clean_branch_name() {
local name="$1"
echo "$name" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/-\+/-/g' | sed 's/^-//' | sed 's/-$//'
}
# Resolve repository root. Prefer git information when available, but fall back
# to searching for repository markers so the workflow still functions in repositories that
# were initialised with --no-git.
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if git rev-parse --show-toplevel >/dev/null 2>&1; then
REPO_ROOT=$(git rev-parse --show-toplevel)
HAS_GIT=true
else
REPO_ROOT="$(find_repo_root "$SCRIPT_DIR")"
if [ -z "$REPO_ROOT" ]; then
echo "Error: Could not determine repository root. Please run this script from within the repository." >&2
exit 1
fi
HAS_GIT=false
fi
cd "$REPO_ROOT"
SPECS_DIR="$REPO_ROOT/specs"
mkdir -p "$SPECS_DIR"
# Function to generate branch name with stop word filtering and length filtering
generate_branch_name() {
local description="$1"
# Common stop words to filter out
local stop_words="^(i|a|an|the|to|for|of|in|on|at|by|with|from|is|are|was|were|be|been|being|have|has|had|do|does|did|will|would|should|could|can|may|might|must|shall|this|that|these|those|my|your|our|their|want|need|add|get|set)$"
# Convert to lowercase and split into words
local clean_name=$(echo "$description" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/ /g')
# Filter words: remove stop words and words shorter than 3 chars (unless they're uppercase acronyms in original)
local meaningful_words=()
for word in $clean_name; do
# Skip empty words
[ -z "$word" ] && continue
# Keep words that are NOT stop words AND (length >= 3 OR are potential acronyms)
if ! echo "$word" | grep -qiE "$stop_words"; then
if [ ${#word} -ge 3 ]; then
meaningful_words+=("$word")
elif echo "$description" | grep -q "\b${word^^}\b"; then
# Keep short words if they appear as uppercase in original (likely acronyms)
meaningful_words+=("$word")
fi
fi
done
# If we have meaningful words, use first 3-4 of them
if [ ${#meaningful_words[@]} -gt 0 ]; then
local max_words=3
if [ ${#meaningful_words[@]} -eq 4 ]; then max_words=4; fi
local result=""
local count=0
for word in "${meaningful_words[@]}"; do
if [ $count -ge $max_words ]; then break; fi
if [ -n "$result" ]; then result="$result-"; fi
result="$result$word"
count=$((count + 1))
done
echo "$result"
else
# Fallback to original logic if no meaningful words found
local cleaned=$(clean_branch_name "$description")
echo "$cleaned" | tr '-' '\n' | grep -v '^$' | head -3 | tr '\n' '-' | sed 's/-$//'
fi
}
# Generate branch name
if [ -n "$SHORT_NAME" ]; then
# Use provided short name, just clean it up
BRANCH_SUFFIX=$(clean_branch_name "$SHORT_NAME")
else
# Generate from description with smart filtering
BRANCH_SUFFIX=$(generate_branch_name "$FEATURE_DESCRIPTION")
fi
# Determine branch number
if [ -z "$BRANCH_NUMBER" ]; then
if [ "$HAS_GIT" = true ]; then
# Check existing branches on remotes
BRANCH_NUMBER=$(check_existing_branches "$SPECS_DIR")
else
# Fall back to local directory check
HIGHEST=$(get_highest_from_specs "$SPECS_DIR")
BRANCH_NUMBER=$((HIGHEST + 1))
fi
fi
# Force base-10 interpretation to prevent octal conversion (e.g., 010 → 8 in octal, but should be 10 in decimal)
FEATURE_NUM=$(printf "%03d" "$((10#$BRANCH_NUMBER))")
BRANCH_NAME="${FEATURE_NUM}-${BRANCH_SUFFIX}"
# GitHub enforces a 244-byte limit on branch names
# Validate and truncate if necessary
MAX_BRANCH_LENGTH=244
if [ ${#BRANCH_NAME} -gt $MAX_BRANCH_LENGTH ]; then
# Calculate how much we need to trim from suffix
# Account for: feature number (3) + hyphen (1) = 4 chars
MAX_SUFFIX_LENGTH=$((MAX_BRANCH_LENGTH - 4))
# Truncate suffix at word boundary if possible
TRUNCATED_SUFFIX=$(echo "$BRANCH_SUFFIX" | cut -c1-$MAX_SUFFIX_LENGTH)
# Remove trailing hyphen if truncation created one
TRUNCATED_SUFFIX=$(echo "$TRUNCATED_SUFFIX" | sed 's/-$//')
ORIGINAL_BRANCH_NAME="$BRANCH_NAME"
BRANCH_NAME="${FEATURE_NUM}-${TRUNCATED_SUFFIX}"
>&2 echo "[specify] Warning: Branch name exceeded GitHub's 244-byte limit"
>&2 echo "[specify] Original: $ORIGINAL_BRANCH_NAME (${#ORIGINAL_BRANCH_NAME} bytes)"
>&2 echo "[specify] Truncated to: $BRANCH_NAME (${#BRANCH_NAME} bytes)"
fi
if [ "$HAS_GIT" = true ]; then
git checkout -b "$BRANCH_NAME"
else
>&2 echo "[specify] Warning: Git repository not detected; skipped branch creation for $BRANCH_NAME"
fi
FEATURE_DIR="$SPECS_DIR/$BRANCH_NAME"
mkdir -p "$FEATURE_DIR"
TEMPLATE="$REPO_ROOT/.specify/templates/spec-template.md"
SPEC_FILE="$FEATURE_DIR/spec.md"
if [ -f "$TEMPLATE" ]; then cp "$TEMPLATE" "$SPEC_FILE"; else touch "$SPEC_FILE"; fi
# Set the SPECIFY_FEATURE environment variable for the current session
export SPECIFY_FEATURE="$BRANCH_NAME"
if $JSON_MODE; then
printf '{"BRANCH_NAME":"%s","SPEC_FILE":"%s","FEATURE_NUM":"%s"}\n' "$BRANCH_NAME" "$SPEC_FILE" "$FEATURE_NUM"
else
echo "BRANCH_NAME: $BRANCH_NAME"
echo "SPEC_FILE: $SPEC_FILE"
echo "FEATURE_NUM: $FEATURE_NUM"
echo "SPECIFY_FEATURE environment variable set to: $BRANCH_NAME"
fi

View File

@@ -0,0 +1,61 @@
#!/usr/bin/env bash
set -e
# Parse command line arguments
JSON_MODE=false
ARGS=()
for arg in "$@"; do
case "$arg" in
--json)
JSON_MODE=true
;;
--help|-h)
echo "Usage: $0 [--json]"
echo " --json Output results in JSON format"
echo " --help Show this help message"
exit 0
;;
*)
ARGS+=("$arg")
;;
esac
done
# Get script directory and load common functions
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Get all paths and variables from common functions
eval $(get_feature_paths)
# Check if we're on a proper feature branch (only for git repos)
check_feature_branch "$CURRENT_BRANCH" "$HAS_GIT" || exit 1
# Ensure the feature directory exists
mkdir -p "$FEATURE_DIR"
# Copy plan template if it exists
TEMPLATE="$REPO_ROOT/.specify/templates/plan-template.md"
if [[ -f "$TEMPLATE" ]]; then
cp "$TEMPLATE" "$IMPL_PLAN"
echo "Copied plan template to $IMPL_PLAN"
else
echo "Warning: Plan template not found at $TEMPLATE"
# Create a basic plan file if template doesn't exist
touch "$IMPL_PLAN"
fi
# Output results
if $JSON_MODE; then
printf '{"FEATURE_SPEC":"%s","IMPL_PLAN":"%s","SPECS_DIR":"%s","BRANCH":"%s","HAS_GIT":"%s"}\n' \
"$FEATURE_SPEC" "$IMPL_PLAN" "$FEATURE_DIR" "$CURRENT_BRANCH" "$HAS_GIT"
else
echo "FEATURE_SPEC: $FEATURE_SPEC"
echo "IMPL_PLAN: $IMPL_PLAN"
echo "SPECS_DIR: $FEATURE_DIR"
echo "BRANCH: $CURRENT_BRANCH"
echo "HAS_GIT: $HAS_GIT"
fi

View File

@@ -0,0 +1,799 @@
#!/usr/bin/env bash
# Update agent context files with information from plan.md
#
# This script maintains AI agent context files by parsing feature specifications
# and updating agent-specific configuration files with project information.
#
# MAIN FUNCTIONS:
# 1. Environment Validation
# - Verifies git repository structure and branch information
# - Checks for required plan.md files and templates
# - Validates file permissions and accessibility
#
# 2. Plan Data Extraction
# - Parses plan.md files to extract project metadata
# - Identifies language/version, frameworks, databases, and project types
# - Handles missing or incomplete specification data gracefully
#
# 3. Agent File Management
# - Creates new agent context files from templates when needed
# - Updates existing agent files with new project information
# - Preserves manual additions and custom configurations
# - Supports multiple AI agent formats and directory structures
#
# 4. Content Generation
# - Generates language-specific build/test commands
# - Creates appropriate project directory structures
# - Updates technology stacks and recent changes sections
# - Maintains consistent formatting and timestamps
#
# 5. Multi-Agent Support
# - Handles agent-specific file paths and naming conventions
# - Supports: Claude, Gemini, Copilot, Cursor, Qwen, opencode, Codex, Windsurf, Kilo Code, Auggie CLI, Roo Code, CodeBuddy CLI, Qoder CLI, Amp, SHAI, or Amazon Q Developer CLI
# - Can update single agents or all existing agent files
# - Creates default Claude file if no agent files exist
#
# Usage: ./update-agent-context.sh [agent_type]
# Agent types: claude|gemini|copilot|cursor-agent|qwen|opencode|codex|windsurf|kilocode|auggie|shai|q|bob|qoder
# Leave empty to update all existing agent files
set -e
# Enable strict error handling
set -u
set -o pipefail
#==============================================================================
# Configuration and Global Variables
#==============================================================================
# Get script directory and load common functions
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Get all paths and variables from common functions
eval $(get_feature_paths)
NEW_PLAN="$IMPL_PLAN" # Alias for compatibility with existing code
AGENT_TYPE="${1:-}"
# Agent-specific file paths
CLAUDE_FILE="$REPO_ROOT/CLAUDE.md"
GEMINI_FILE="$REPO_ROOT/GEMINI.md"
COPILOT_FILE="$REPO_ROOT/.github/agents/copilot-instructions.md"
CURSOR_FILE="$REPO_ROOT/.cursor/rules/specify-rules.mdc"
QWEN_FILE="$REPO_ROOT/QWEN.md"
AGENTS_FILE="$REPO_ROOT/AGENTS.md"
WINDSURF_FILE="$REPO_ROOT/.windsurf/rules/specify-rules.md"
KILOCODE_FILE="$REPO_ROOT/.kilocode/rules/specify-rules.md"
AUGGIE_FILE="$REPO_ROOT/.augment/rules/specify-rules.md"
ROO_FILE="$REPO_ROOT/.roo/rules/specify-rules.md"
CODEBUDDY_FILE="$REPO_ROOT/CODEBUDDY.md"
QODER_FILE="$REPO_ROOT/QODER.md"
AMP_FILE="$REPO_ROOT/AGENTS.md"
SHAI_FILE="$REPO_ROOT/SHAI.md"
Q_FILE="$REPO_ROOT/AGENTS.md"
BOB_FILE="$REPO_ROOT/AGENTS.md"
# Template file
TEMPLATE_FILE="$REPO_ROOT/.specify/templates/agent-file-template.md"
# Global variables for parsed plan data
NEW_LANG=""
NEW_FRAMEWORK=""
NEW_DB=""
NEW_PROJECT_TYPE=""
#==============================================================================
# Utility Functions
#==============================================================================
log_info() {
echo "INFO: $1"
}
log_success() {
echo "$1"
}
log_error() {
echo "ERROR: $1" >&2
}
log_warning() {
echo "WARNING: $1" >&2
}
# Cleanup function for temporary files
cleanup() {
local exit_code=$?
rm -f /tmp/agent_update_*_$$
rm -f /tmp/manual_additions_$$
exit $exit_code
}
# Set up cleanup trap
trap cleanup EXIT INT TERM
#==============================================================================
# Validation Functions
#==============================================================================
validate_environment() {
# Check if we have a current branch/feature (git or non-git)
if [[ -z "$CURRENT_BRANCH" ]]; then
log_error "Unable to determine current feature"
if [[ "$HAS_GIT" == "true" ]]; then
log_info "Make sure you're on a feature branch"
else
log_info "Set SPECIFY_FEATURE environment variable or create a feature first"
fi
exit 1
fi
# Check if plan.md exists
if [[ ! -f "$NEW_PLAN" ]]; then
log_error "No plan.md found at $NEW_PLAN"
log_info "Make sure you're working on a feature with a corresponding spec directory"
if [[ "$HAS_GIT" != "true" ]]; then
log_info "Use: export SPECIFY_FEATURE=your-feature-name or create a new feature first"
fi
exit 1
fi
# Check if template exists (needed for new files)
if [[ ! -f "$TEMPLATE_FILE" ]]; then
log_warning "Template file not found at $TEMPLATE_FILE"
log_warning "Creating new agent files will fail"
fi
}
#==============================================================================
# Plan Parsing Functions
#==============================================================================
extract_plan_field() {
local field_pattern="$1"
local plan_file="$2"
grep "^\*\*${field_pattern}\*\*: " "$plan_file" 2>/dev/null | \
head -1 | \
sed "s|^\*\*${field_pattern}\*\*: ||" | \
sed 's/^[ \t]*//;s/[ \t]*$//' | \
grep -v "NEEDS CLARIFICATION" | \
grep -v "^N/A$" || echo ""
}
parse_plan_data() {
local plan_file="$1"
if [[ ! -f "$plan_file" ]]; then
log_error "Plan file not found: $plan_file"
return 1
fi
if [[ ! -r "$plan_file" ]]; then
log_error "Plan file is not readable: $plan_file"
return 1
fi
log_info "Parsing plan data from $plan_file"
NEW_LANG=$(extract_plan_field "Language/Version" "$plan_file")
NEW_FRAMEWORK=$(extract_plan_field "Primary Dependencies" "$plan_file")
NEW_DB=$(extract_plan_field "Storage" "$plan_file")
NEW_PROJECT_TYPE=$(extract_plan_field "Project Type" "$plan_file")
# Log what we found
if [[ -n "$NEW_LANG" ]]; then
log_info "Found language: $NEW_LANG"
else
log_warning "No language information found in plan"
fi
if [[ -n "$NEW_FRAMEWORK" ]]; then
log_info "Found framework: $NEW_FRAMEWORK"
fi
if [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]]; then
log_info "Found database: $NEW_DB"
fi
if [[ -n "$NEW_PROJECT_TYPE" ]]; then
log_info "Found project type: $NEW_PROJECT_TYPE"
fi
}
format_technology_stack() {
local lang="$1"
local framework="$2"
local parts=()
# Add non-empty parts
[[ -n "$lang" && "$lang" != "NEEDS CLARIFICATION" ]] && parts+=("$lang")
[[ -n "$framework" && "$framework" != "NEEDS CLARIFICATION" && "$framework" != "N/A" ]] && parts+=("$framework")
# Join with proper formatting
if [[ ${#parts[@]} -eq 0 ]]; then
echo ""
elif [[ ${#parts[@]} -eq 1 ]]; then
echo "${parts[0]}"
else
# Join multiple parts with " + "
local result="${parts[0]}"
for ((i=1; i<${#parts[@]}; i++)); do
result="$result + ${parts[i]}"
done
echo "$result"
fi
}
#==============================================================================
# Template and Content Generation Functions
#==============================================================================
get_project_structure() {
local project_type="$1"
if [[ "$project_type" == *"web"* ]]; then
echo "backend/\\nfrontend/\\ntests/"
else
echo "src/\\ntests/"
fi
}
get_commands_for_language() {
local lang="$1"
case "$lang" in
*"Python"*)
echo "cd src && pytest && ruff check ."
;;
*"Rust"*)
echo "cargo test && cargo clippy"
;;
*"JavaScript"*|*"TypeScript"*)
echo "npm test \\&\\& npm run lint"
;;
*)
echo "# Add commands for $lang"
;;
esac
}
get_language_conventions() {
local lang="$1"
echo "$lang: Follow standard conventions"
}
create_new_agent_file() {
local target_file="$1"
local temp_file="$2"
local project_name="$3"
local current_date="$4"
if [[ ! -f "$TEMPLATE_FILE" ]]; then
log_error "Template not found at $TEMPLATE_FILE"
return 1
fi
if [[ ! -r "$TEMPLATE_FILE" ]]; then
log_error "Template file is not readable: $TEMPLATE_FILE"
return 1
fi
log_info "Creating new agent context file from template..."
if ! cp "$TEMPLATE_FILE" "$temp_file"; then
log_error "Failed to copy template file"
return 1
fi
# Replace template placeholders
local project_structure
project_structure=$(get_project_structure "$NEW_PROJECT_TYPE")
local commands
commands=$(get_commands_for_language "$NEW_LANG")
local language_conventions
language_conventions=$(get_language_conventions "$NEW_LANG")
# Perform substitutions with error checking using safer approach
# Escape special characters for sed by using a different delimiter or escaping
local escaped_lang=$(printf '%s\n' "$NEW_LANG" | sed 's/[\[\.*^$()+{}|]/\\&/g')
local escaped_framework=$(printf '%s\n' "$NEW_FRAMEWORK" | sed 's/[\[\.*^$()+{}|]/\\&/g')
local escaped_branch=$(printf '%s\n' "$CURRENT_BRANCH" | sed 's/[\[\.*^$()+{}|]/\\&/g')
# Build technology stack and recent change strings conditionally
local tech_stack
if [[ -n "$escaped_lang" && -n "$escaped_framework" ]]; then
tech_stack="- $escaped_lang + $escaped_framework ($escaped_branch)"
elif [[ -n "$escaped_lang" ]]; then
tech_stack="- $escaped_lang ($escaped_branch)"
elif [[ -n "$escaped_framework" ]]; then
tech_stack="- $escaped_framework ($escaped_branch)"
else
tech_stack="- ($escaped_branch)"
fi
local recent_change
if [[ -n "$escaped_lang" && -n "$escaped_framework" ]]; then
recent_change="- $escaped_branch: Added $escaped_lang + $escaped_framework"
elif [[ -n "$escaped_lang" ]]; then
recent_change="- $escaped_branch: Added $escaped_lang"
elif [[ -n "$escaped_framework" ]]; then
recent_change="- $escaped_branch: Added $escaped_framework"
else
recent_change="- $escaped_branch: Added"
fi
local substitutions=(
"s|\[PROJECT NAME\]|$project_name|"
"s|\[DATE\]|$current_date|"
"s|\[EXTRACTED FROM ALL PLAN.MD FILES\]|$tech_stack|"
"s|\[ACTUAL STRUCTURE FROM PLANS\]|$project_structure|g"
"s|\[ONLY COMMANDS FOR ACTIVE TECHNOLOGIES\]|$commands|"
"s|\[LANGUAGE-SPECIFIC, ONLY FOR LANGUAGES IN USE\]|$language_conventions|"
"s|\[LAST 3 FEATURES AND WHAT THEY ADDED\]|$recent_change|"
)
for substitution in "${substitutions[@]}"; do
if ! sed -i.bak -e "$substitution" "$temp_file"; then
log_error "Failed to perform substitution: $substitution"
rm -f "$temp_file" "$temp_file.bak"
return 1
fi
done
# Convert \n sequences to actual newlines
newline=$(printf '\n')
sed -i.bak2 "s/\\\\n/${newline}/g" "$temp_file"
# Clean up backup files
rm -f "$temp_file.bak" "$temp_file.bak2"
return 0
}
update_existing_agent_file() {
local target_file="$1"
local current_date="$2"
log_info "Updating existing agent context file..."
# Use a single temporary file for atomic update
local temp_file
temp_file=$(mktemp) || {
log_error "Failed to create temporary file"
return 1
}
# Process the file in one pass
local tech_stack=$(format_technology_stack "$NEW_LANG" "$NEW_FRAMEWORK")
local new_tech_entries=()
local new_change_entry=""
# Prepare new technology entries
if [[ -n "$tech_stack" ]] && ! grep -q "$tech_stack" "$target_file"; then
new_tech_entries+=("- $tech_stack ($CURRENT_BRANCH)")
fi
if [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]] && [[ "$NEW_DB" != "NEEDS CLARIFICATION" ]] && ! grep -q "$NEW_DB" "$target_file"; then
new_tech_entries+=("- $NEW_DB ($CURRENT_BRANCH)")
fi
# Prepare new change entry
if [[ -n "$tech_stack" ]]; then
new_change_entry="- $CURRENT_BRANCH: Added $tech_stack"
elif [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]] && [[ "$NEW_DB" != "NEEDS CLARIFICATION" ]]; then
new_change_entry="- $CURRENT_BRANCH: Added $NEW_DB"
fi
# Check if sections exist in the file
local has_active_technologies=0
local has_recent_changes=0
if grep -q "^## Active Technologies" "$target_file" 2>/dev/null; then
has_active_technologies=1
fi
if grep -q "^## Recent Changes" "$target_file" 2>/dev/null; then
has_recent_changes=1
fi
# Process file line by line
local in_tech_section=false
local in_changes_section=false
local tech_entries_added=false
local changes_entries_added=false
local existing_changes_count=0
local file_ended=false
while IFS= read -r line || [[ -n "$line" ]]; do
# Handle Active Technologies section
if [[ "$line" == "## Active Technologies" ]]; then
echo "$line" >> "$temp_file"
in_tech_section=true
continue
elif [[ $in_tech_section == true ]] && [[ "$line" =~ ^##[[:space:]] ]]; then
# Add new tech entries before closing the section
if [[ $tech_entries_added == false ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then
printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file"
tech_entries_added=true
fi
echo "$line" >> "$temp_file"
in_tech_section=false
continue
elif [[ $in_tech_section == true ]] && [[ -z "$line" ]]; then
# Add new tech entries before empty line in tech section
if [[ $tech_entries_added == false ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then
printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file"
tech_entries_added=true
fi
echo "$line" >> "$temp_file"
continue
fi
# Handle Recent Changes section
if [[ "$line" == "## Recent Changes" ]]; then
echo "$line" >> "$temp_file"
# Add new change entry right after the heading
if [[ -n "$new_change_entry" ]]; then
echo "$new_change_entry" >> "$temp_file"
fi
in_changes_section=true
changes_entries_added=true
continue
elif [[ $in_changes_section == true ]] && [[ "$line" =~ ^##[[:space:]] ]]; then
echo "$line" >> "$temp_file"
in_changes_section=false
continue
elif [[ $in_changes_section == true ]] && [[ "$line" == "- "* ]]; then
# Keep only first 2 existing changes
if [[ $existing_changes_count -lt 2 ]]; then
echo "$line" >> "$temp_file"
((existing_changes_count++))
fi
continue
fi
# Update timestamp
if [[ "$line" =~ \*\*Last\ updated\*\*:.*[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] ]]; then
echo "$line" | sed "s/[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]/$current_date/" >> "$temp_file"
else
echo "$line" >> "$temp_file"
fi
done < "$target_file"
# Post-loop check: if we're still in the Active Technologies section and haven't added new entries
if [[ $in_tech_section == true ]] && [[ $tech_entries_added == false ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then
printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file"
tech_entries_added=true
fi
# If sections don't exist, add them at the end of the file
if [[ $has_active_technologies -eq 0 ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then
echo "" >> "$temp_file"
echo "## Active Technologies" >> "$temp_file"
printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file"
tech_entries_added=true
fi
if [[ $has_recent_changes -eq 0 ]] && [[ -n "$new_change_entry" ]]; then
echo "" >> "$temp_file"
echo "## Recent Changes" >> "$temp_file"
echo "$new_change_entry" >> "$temp_file"
changes_entries_added=true
fi
# Move temp file to target atomically
if ! mv "$temp_file" "$target_file"; then
log_error "Failed to update target file"
rm -f "$temp_file"
return 1
fi
return 0
}
#==============================================================================
# Main Agent File Update Function
#==============================================================================
update_agent_file() {
local target_file="$1"
local agent_name="$2"
if [[ -z "$target_file" ]] || [[ -z "$agent_name" ]]; then
log_error "update_agent_file requires target_file and agent_name parameters"
return 1
fi
log_info "Updating $agent_name context file: $target_file"
local project_name
project_name=$(basename "$REPO_ROOT")
local current_date
current_date=$(date +%Y-%m-%d)
# Create directory if it doesn't exist
local target_dir
target_dir=$(dirname "$target_file")
if [[ ! -d "$target_dir" ]]; then
if ! mkdir -p "$target_dir"; then
log_error "Failed to create directory: $target_dir"
return 1
fi
fi
if [[ ! -f "$target_file" ]]; then
# Create new file from template
local temp_file
temp_file=$(mktemp) || {
log_error "Failed to create temporary file"
return 1
}
if create_new_agent_file "$target_file" "$temp_file" "$project_name" "$current_date"; then
if mv "$temp_file" "$target_file"; then
log_success "Created new $agent_name context file"
else
log_error "Failed to move temporary file to $target_file"
rm -f "$temp_file"
return 1
fi
else
log_error "Failed to create new agent file"
rm -f "$temp_file"
return 1
fi
else
# Update existing file
if [[ ! -r "$target_file" ]]; then
log_error "Cannot read existing file: $target_file"
return 1
fi
if [[ ! -w "$target_file" ]]; then
log_error "Cannot write to existing file: $target_file"
return 1
fi
if update_existing_agent_file "$target_file" "$current_date"; then
log_success "Updated existing $agent_name context file"
else
log_error "Failed to update existing agent file"
return 1
fi
fi
return 0
}
#==============================================================================
# Agent Selection and Processing
#==============================================================================
update_specific_agent() {
local agent_type="$1"
case "$agent_type" in
claude)
update_agent_file "$CLAUDE_FILE" "Claude Code"
;;
gemini)
update_agent_file "$GEMINI_FILE" "Gemini CLI"
;;
copilot)
update_agent_file "$COPILOT_FILE" "GitHub Copilot"
;;
cursor-agent)
update_agent_file "$CURSOR_FILE" "Cursor IDE"
;;
qwen)
update_agent_file "$QWEN_FILE" "Qwen Code"
;;
opencode)
update_agent_file "$AGENTS_FILE" "opencode"
;;
codex)
update_agent_file "$AGENTS_FILE" "Codex CLI"
;;
windsurf)
update_agent_file "$WINDSURF_FILE" "Windsurf"
;;
kilocode)
update_agent_file "$KILOCODE_FILE" "Kilo Code"
;;
auggie)
update_agent_file "$AUGGIE_FILE" "Auggie CLI"
;;
roo)
update_agent_file "$ROO_FILE" "Roo Code"
;;
codebuddy)
update_agent_file "$CODEBUDDY_FILE" "CodeBuddy CLI"
;;
qoder)
update_agent_file "$QODER_FILE" "Qoder CLI"
;;
amp)
update_agent_file "$AMP_FILE" "Amp"
;;
shai)
update_agent_file "$SHAI_FILE" "SHAI"
;;
q)
update_agent_file "$Q_FILE" "Amazon Q Developer CLI"
;;
bob)
update_agent_file "$BOB_FILE" "IBM Bob"
;;
*)
log_error "Unknown agent type '$agent_type'"
log_error "Expected: claude|gemini|copilot|cursor-agent|qwen|opencode|codex|windsurf|kilocode|auggie|roo|amp|shai|q|bob|qoder"
exit 1
;;
esac
}
update_all_existing_agents() {
local found_agent=false
# Check each possible agent file and update if it exists
if [[ -f "$CLAUDE_FILE" ]]; then
update_agent_file "$CLAUDE_FILE" "Claude Code"
found_agent=true
fi
if [[ -f "$GEMINI_FILE" ]]; then
update_agent_file "$GEMINI_FILE" "Gemini CLI"
found_agent=true
fi
if [[ -f "$COPILOT_FILE" ]]; then
update_agent_file "$COPILOT_FILE" "GitHub Copilot"
found_agent=true
fi
if [[ -f "$CURSOR_FILE" ]]; then
update_agent_file "$CURSOR_FILE" "Cursor IDE"
found_agent=true
fi
if [[ -f "$QWEN_FILE" ]]; then
update_agent_file "$QWEN_FILE" "Qwen Code"
found_agent=true
fi
if [[ -f "$AGENTS_FILE" ]]; then
update_agent_file "$AGENTS_FILE" "Codex/opencode"
found_agent=true
fi
if [[ -f "$WINDSURF_FILE" ]]; then
update_agent_file "$WINDSURF_FILE" "Windsurf"
found_agent=true
fi
if [[ -f "$KILOCODE_FILE" ]]; then
update_agent_file "$KILOCODE_FILE" "Kilo Code"
found_agent=true
fi
if [[ -f "$AUGGIE_FILE" ]]; then
update_agent_file "$AUGGIE_FILE" "Auggie CLI"
found_agent=true
fi
if [[ -f "$ROO_FILE" ]]; then
update_agent_file "$ROO_FILE" "Roo Code"
found_agent=true
fi
if [[ -f "$CODEBUDDY_FILE" ]]; then
update_agent_file "$CODEBUDDY_FILE" "CodeBuddy CLI"
found_agent=true
fi
if [[ -f "$SHAI_FILE" ]]; then
update_agent_file "$SHAI_FILE" "SHAI"
found_agent=true
fi
if [[ -f "$QODER_FILE" ]]; then
update_agent_file "$QODER_FILE" "Qoder CLI"
found_agent=true
fi
if [[ -f "$Q_FILE" ]]; then
update_agent_file "$Q_FILE" "Amazon Q Developer CLI"
found_agent=true
fi
if [[ -f "$BOB_FILE" ]]; then
update_agent_file "$BOB_FILE" "IBM Bob"
found_agent=true
fi
# If no agent files exist, create a default Claude file
if [[ "$found_agent" == false ]]; then
log_info "No existing agent files found, creating default Claude file..."
update_agent_file "$CLAUDE_FILE" "Claude Code"
fi
}
print_summary() {
echo
log_info "Summary of changes:"
if [[ -n "$NEW_LANG" ]]; then
echo " - Added language: $NEW_LANG"
fi
if [[ -n "$NEW_FRAMEWORK" ]]; then
echo " - Added framework: $NEW_FRAMEWORK"
fi
if [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]]; then
echo " - Added database: $NEW_DB"
fi
echo
log_info "Usage: $0 [claude|gemini|copilot|cursor-agent|qwen|opencode|codex|windsurf|kilocode|auggie|codebuddy|shai|q|bob|qoder]"
}
#==============================================================================
# Main Execution
#==============================================================================
main() {
# Validate environment before proceeding
validate_environment
log_info "=== Updating agent context files for feature $CURRENT_BRANCH ==="
# Parse the plan file to extract project information
if ! parse_plan_data "$NEW_PLAN"; then
log_error "Failed to parse plan data"
exit 1
fi
# Process based on agent type argument
local success=true
if [[ -z "$AGENT_TYPE" ]]; then
# No specific agent provided - update all existing agent files
log_info "No agent specified, updating all existing agent files..."
if ! update_all_existing_agents; then
success=false
fi
else
# Specific agent provided - update only that agent
log_info "Updating specific agent: $AGENT_TYPE"
if ! update_specific_agent "$AGENT_TYPE"; then
success=false
fi
fi
# Print summary
print_summary
if [[ "$success" == true ]]; then
log_success "Agent context update completed successfully"
exit 0
else
log_error "Agent context update completed with errors"
exit 1
fi
}
# Execute main function if script is run directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi

View File

@@ -0,0 +1,28 @@
# [PROJECT NAME] Development Guidelines
Auto-generated from all feature plans. Last updated: [DATE]
## Active Technologies
[EXTRACTED FROM ALL PLAN.MD FILES]
## Project Structure
```text
[ACTUAL STRUCTURE FROM PLANS]
```
## Commands
[ONLY COMMANDS FOR ACTIVE TECHNOLOGIES]
## Code Style
[LANGUAGE-SPECIFIC, ONLY FOR LANGUAGES IN USE]
## Recent Changes
[LAST 3 FEATURES AND WHAT THEY ADDED]
<!-- MANUAL ADDITIONS START -->
<!-- MANUAL ADDITIONS END -->

View File

@@ -0,0 +1,40 @@
# [CHECKLIST TYPE] Checklist: [FEATURE NAME]
**Purpose**: [Brief description of what this checklist covers]
**Created**: [DATE]
**Feature**: [Link to spec.md or relevant documentation]
**Note**: This checklist is generated by the `/speckit.checklist` command based on feature context and requirements.
<!--
============================================================================
IMPORTANT: The checklist items below are SAMPLE ITEMS for illustration only.
The /speckit.checklist command MUST replace these with actual items based on:
- User's specific checklist request
- Feature requirements from spec.md
- Technical context from plan.md
- Implementation details from tasks.md
DO NOT keep these sample items in the generated checklist file.
============================================================================
-->
## [Category 1]
- [ ] CHK001 First checklist item with clear action
- [ ] CHK002 Second checklist item
- [ ] CHK003 Third checklist item
## [Category 2]
- [ ] CHK004 Another category item
- [ ] CHK005 Item with specific criteria
- [ ] CHK006 Final item in this category
## Notes
- Check items off as completed: `[x]`
- Add comments or findings inline
- Link to relevant resources or documentation
- Items are numbered sequentially for easy reference

View File

@@ -0,0 +1,104 @@
# Implementation Plan: [FEATURE]
**Branch**: `[###-feature-name]` | **Date**: [DATE] | **Spec**: [link]
**Input**: Feature specification from `/specs/[###-feature-name]/spec.md`
**Note**: This template is filled in by the `/speckit.plan` command. See `.specify/templates/commands/plan.md` for the execution workflow.
## Summary
[Extract from feature spec: primary requirement + technical approach from research]
## Technical Context
<!--
ACTION REQUIRED: Replace the content in this section with the technical details
for the project. The structure here is presented in advisory capacity to guide
the iteration process.
-->
**Language/Version**: [e.g., Python 3.11, Swift 5.9, Rust 1.75 or NEEDS CLARIFICATION]
**Primary Dependencies**: [e.g., FastAPI, UIKit, LLVM or NEEDS CLARIFICATION]
**Storage**: [if applicable, e.g., PostgreSQL, CoreData, files or N/A]
**Testing**: [e.g., pytest, XCTest, cargo test or NEEDS CLARIFICATION]
**Target Platform**: [e.g., Linux server, iOS 15+, WASM or NEEDS CLARIFICATION]
**Project Type**: [single/web/mobile - determines source structure]
**Performance Goals**: [domain-specific, e.g., 1000 req/s, 10k lines/sec, 60 fps or NEEDS CLARIFICATION]
**Constraints**: [domain-specific, e.g., <200ms p95, <100MB memory, offline-capable or NEEDS CLARIFICATION]
**Scale/Scope**: [domain-specific, e.g., 10k users, 1M LOC, 50 screens or NEEDS CLARIFICATION]
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
[Gates determined based on constitution file]
## Project Structure
### Documentation (this feature)
```text
specs/[###-feature]/
├── plan.md # This file (/speckit.plan command output)
├── research.md # Phase 0 output (/speckit.plan command)
├── data-model.md # Phase 1 output (/speckit.plan command)
├── quickstart.md # Phase 1 output (/speckit.plan command)
├── contracts/ # Phase 1 output (/speckit.plan command)
└── tasks.md # Phase 2 output (/speckit.tasks command - NOT created by /speckit.plan)
```
### Source Code (repository root)
<!--
ACTION REQUIRED: Replace the placeholder tree below with the concrete layout
for this feature. Delete unused options and expand the chosen structure with
real paths (e.g., apps/admin, packages/something). The delivered plan must
not include Option labels.
-->
```text
# [REMOVE IF UNUSED] Option 1: Single project (DEFAULT)
src/
├── models/
├── services/
├── cli/
└── lib/
tests/
├── contract/
├── integration/
└── unit/
# [REMOVE IF UNUSED] Option 2: Web application (when "frontend" + "backend" detected)
backend/
├── src/
│ ├── models/
│ ├── services/
│ └── api/
└── tests/
frontend/
├── src/
│ ├── components/
│ ├── pages/
│ └── services/
└── tests/
# [REMOVE IF UNUSED] Option 3: Mobile + API (when "iOS/Android" detected)
api/
└── [same as backend above]
ios/ or android/
└── [platform-specific structure: feature modules, UI flows, platform tests]
```
**Structure Decision**: [Document the selected structure and reference the real
directories captured above]
## Complexity Tracking
> **Fill ONLY if Constitution Check has violations that must be justified**
| Violation | Why Needed | Simpler Alternative Rejected Because |
|-----------|------------|-------------------------------------|
| [e.g., 4th project] | [current need] | [why 3 projects insufficient] |
| [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] |

View File

@@ -0,0 +1,115 @@
# Feature Specification: [FEATURE NAME]
**Feature Branch**: `[###-feature-name]`
**Created**: [DATE]
**Status**: Draft
**Input**: User description: "$ARGUMENTS"
## User Scenarios & Testing *(mandatory)*
<!--
IMPORTANT: User stories should be PRIORITIZED as user journeys ordered by importance.
Each user story/journey must be INDEPENDENTLY TESTABLE - meaning if you implement just ONE of them,
you should still have a viable MVP (Minimum Viable Product) that delivers value.
Assign priorities (P1, P2, P3, etc.) to each story, where P1 is the most critical.
Think of each story as a standalone slice of functionality that can be:
- Developed independently
- Tested independently
- Deployed independently
- Demonstrated to users independently
-->
### User Story 1 - [Brief Title] (Priority: P1)
[Describe this user journey in plain language]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [Describe how this can be tested independently - e.g., "Can be fully tested by [specific action] and delivers [specific value]"]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
2. **Given** [initial state], **When** [action], **Then** [expected outcome]
---
### User Story 2 - [Brief Title] (Priority: P2)
[Describe this user journey in plain language]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [Describe how this can be tested independently]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
---
### User Story 3 - [Brief Title] (Priority: P3)
[Describe this user journey in plain language]
**Why this priority**: [Explain the value and why it has this priority level]
**Independent Test**: [Describe how this can be tested independently]
**Acceptance Scenarios**:
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
---
[Add more user stories as needed, each with an assigned priority]
### Edge Cases
<!--
ACTION REQUIRED: The content in this section represents placeholders.
Fill them out with the right edge cases.
-->
- What happens when [boundary condition]?
- How does system handle [error scenario]?
## Requirements *(mandatory)*
<!--
ACTION REQUIRED: The content in this section represents placeholders.
Fill them out with the right functional requirements.
-->
### Functional Requirements
- **FR-001**: System MUST [specific capability, e.g., "allow users to create accounts"]
- **FR-002**: System MUST [specific capability, e.g., "validate email addresses"]
- **FR-003**: Users MUST be able to [key interaction, e.g., "reset their password"]
- **FR-004**: System MUST [data requirement, e.g., "persist user preferences"]
- **FR-005**: System MUST [behavior, e.g., "log all security events"]
*Example of marking unclear requirements:*
- **FR-006**: System MUST authenticate users via [NEEDS CLARIFICATION: auth method not specified - email/password, SSO, OAuth?]
- **FR-007**: System MUST retain user data for [NEEDS CLARIFICATION: retention period not specified]
### Key Entities *(include if feature involves data)*
- **[Entity 1]**: [What it represents, key attributes without implementation]
- **[Entity 2]**: [What it represents, relationships to other entities]
## Success Criteria *(mandatory)*
<!--
ACTION REQUIRED: Define measurable success criteria.
These must be technology-agnostic and measurable.
-->
### Measurable Outcomes
- **SC-001**: [Measurable metric, e.g., "Users can complete account creation in under 2 minutes"]
- **SC-002**: [Measurable metric, e.g., "System handles 1000 concurrent users without degradation"]
- **SC-003**: [User satisfaction metric, e.g., "90% of users successfully complete primary task on first attempt"]
- **SC-004**: [Business metric, e.g., "Reduce support tickets related to [X] by 50%"]

View File

@@ -0,0 +1,251 @@
---
description: "Task list template for feature implementation"
---
# Tasks: [FEATURE NAME]
**Input**: Design documents from `/specs/[###-feature-name]/`
**Prerequisites**: plan.md (required), spec.md (required for user stories), research.md, data-model.md, contracts/
**Tests**: The examples below include test tasks. Tests are OPTIONAL - only include them if explicitly requested in the feature specification.
**Organization**: Tasks are grouped by user story to enable independent implementation and testing of each story.
## Format: `[ID] [P?] [Story] Description`
- **[P]**: Can run in parallel (different files, no dependencies)
- **[Story]**: Which user story this task belongs to (e.g., US1, US2, US3)
- Include exact file paths in descriptions
## Path Conventions
- **Single project**: `src/`, `tests/` at repository root
- **Web app**: `backend/src/`, `frontend/src/`
- **Mobile**: `api/src/`, `ios/src/` or `android/src/`
- Paths shown below assume single project - adjust based on plan.md structure
<!--
============================================================================
IMPORTANT: The tasks below are SAMPLE TASKS for illustration purposes only.
The /speckit.tasks command MUST replace these with actual tasks based on:
- User stories from spec.md (with their priorities P1, P2, P3...)
- Feature requirements from plan.md
- Entities from data-model.md
- Endpoints from contracts/
Tasks MUST be organized by user story so each story can be:
- Implemented independently
- Tested independently
- Delivered as an MVP increment
DO NOT keep these sample tasks in the generated tasks.md file.
============================================================================
-->
## Phase 1: Setup (Shared Infrastructure)
**Purpose**: Project initialization and basic structure
- [ ] T001 Create project structure per implementation plan
- [ ] T002 Initialize [language] project with [framework] dependencies
- [ ] T003 [P] Configure linting and formatting tools
---
## Phase 2: Foundational (Blocking Prerequisites)
**Purpose**: Core infrastructure that MUST be complete before ANY user story can be implemented
**⚠️ CRITICAL**: No user story work can begin until this phase is complete
Examples of foundational tasks (adjust based on your project):
- [ ] T004 Setup database schema and migrations framework
- [ ] T005 [P] Implement authentication/authorization framework
- [ ] T006 [P] Setup API routing and middleware structure
- [ ] T007 Create base models/entities that all stories depend on
- [ ] T008 Configure error handling and logging infrastructure
- [ ] T009 Setup environment configuration management
**Checkpoint**: Foundation ready - user story implementation can now begin in parallel
---
## Phase 3: User Story 1 - [Title] (Priority: P1) 🎯 MVP
**Goal**: [Brief description of what this story delivers]
**Independent Test**: [How to verify this story works on its own]
### Tests for User Story 1 (OPTIONAL - only if tests requested) ⚠️
> **NOTE: Write these tests FIRST, ensure they FAIL before implementation**
- [ ] T010 [P] [US1] Contract test for [endpoint] in tests/contract/test_[name].py
- [ ] T011 [P] [US1] Integration test for [user journey] in tests/integration/test_[name].py
### Implementation for User Story 1
- [ ] T012 [P] [US1] Create [Entity1] model in src/models/[entity1].py
- [ ] T013 [P] [US1] Create [Entity2] model in src/models/[entity2].py
- [ ] T014 [US1] Implement [Service] in src/services/[service].py (depends on T012, T013)
- [ ] T015 [US1] Implement [endpoint/feature] in src/[location]/[file].py
- [ ] T016 [US1] Add validation and error handling
- [ ] T017 [US1] Add logging for user story 1 operations
**Checkpoint**: At this point, User Story 1 should be fully functional and testable independently
---
## Phase 4: User Story 2 - [Title] (Priority: P2)
**Goal**: [Brief description of what this story delivers]
**Independent Test**: [How to verify this story works on its own]
### Tests for User Story 2 (OPTIONAL - only if tests requested) ⚠️
- [ ] T018 [P] [US2] Contract test for [endpoint] in tests/contract/test_[name].py
- [ ] T019 [P] [US2] Integration test for [user journey] in tests/integration/test_[name].py
### Implementation for User Story 2
- [ ] T020 [P] [US2] Create [Entity] model in src/models/[entity].py
- [ ] T021 [US2] Implement [Service] in src/services/[service].py
- [ ] T022 [US2] Implement [endpoint/feature] in src/[location]/[file].py
- [ ] T023 [US2] Integrate with User Story 1 components (if needed)
**Checkpoint**: At this point, User Stories 1 AND 2 should both work independently
---
## Phase 5: User Story 3 - [Title] (Priority: P3)
**Goal**: [Brief description of what this story delivers]
**Independent Test**: [How to verify this story works on its own]
### Tests for User Story 3 (OPTIONAL - only if tests requested) ⚠️
- [ ] T024 [P] [US3] Contract test for [endpoint] in tests/contract/test_[name].py
- [ ] T025 [P] [US3] Integration test for [user journey] in tests/integration/test_[name].py
### Implementation for User Story 3
- [ ] T026 [P] [US3] Create [Entity] model in src/models/[entity].py
- [ ] T027 [US3] Implement [Service] in src/services/[service].py
- [ ] T028 [US3] Implement [endpoint/feature] in src/[location]/[file].py
**Checkpoint**: All user stories should now be independently functional
---
[Add more user story phases as needed, following the same pattern]
---
## Phase N: Polish & Cross-Cutting Concerns
**Purpose**: Improvements that affect multiple user stories
- [ ] TXXX [P] Documentation updates in docs/
- [ ] TXXX Code cleanup and refactoring
- [ ] TXXX Performance optimization across all stories
- [ ] TXXX [P] Additional unit tests (if requested) in tests/unit/
- [ ] TXXX Security hardening
- [ ] TXXX Run quickstart.md validation
---
## Dependencies & Execution Order
### Phase Dependencies
- **Setup (Phase 1)**: No dependencies - can start immediately
- **Foundational (Phase 2)**: Depends on Setup completion - BLOCKS all user stories
- **User Stories (Phase 3+)**: All depend on Foundational phase completion
- User stories can then proceed in parallel (if staffed)
- Or sequentially in priority order (P1 → P2 → P3)
- **Polish (Final Phase)**: Depends on all desired user stories being complete
### User Story Dependencies
- **User Story 1 (P1)**: Can start after Foundational (Phase 2) - No dependencies on other stories
- **User Story 2 (P2)**: Can start after Foundational (Phase 2) - May integrate with US1 but should be independently testable
- **User Story 3 (P3)**: Can start after Foundational (Phase 2) - May integrate with US1/US2 but should be independently testable
### Within Each User Story
- Tests (if included) MUST be written and FAIL before implementation
- Models before services
- Services before endpoints
- Core implementation before integration
- Story complete before moving to next priority
### Parallel Opportunities
- All Setup tasks marked [P] can run in parallel
- All Foundational tasks marked [P] can run in parallel (within Phase 2)
- Once Foundational phase completes, all user stories can start in parallel (if team capacity allows)
- All tests for a user story marked [P] can run in parallel
- Models within a story marked [P] can run in parallel
- Different user stories can be worked on in parallel by different team members
---
## Parallel Example: User Story 1
```bash
# Launch all tests for User Story 1 together (if tests requested):
Task: "Contract test for [endpoint] in tests/contract/test_[name].py"
Task: "Integration test for [user journey] in tests/integration/test_[name].py"
# Launch all models for User Story 1 together:
Task: "Create [Entity1] model in src/models/[entity1].py"
Task: "Create [Entity2] model in src/models/[entity2].py"
```
---
## Implementation Strategy
### MVP First (User Story 1 Only)
1. Complete Phase 1: Setup
2. Complete Phase 2: Foundational (CRITICAL - blocks all stories)
3. Complete Phase 3: User Story 1
4. **STOP and VALIDATE**: Test User Story 1 independently
5. Deploy/demo if ready
### Incremental Delivery
1. Complete Setup + Foundational → Foundation ready
2. Add User Story 1 → Test independently → Deploy/Demo (MVP!)
3. Add User Story 2 → Test independently → Deploy/Demo
4. Add User Story 3 → Test independently → Deploy/Demo
5. Each story adds value without breaking previous stories
### Parallel Team Strategy
With multiple developers:
1. Team completes Setup + Foundational together
2. Once Foundational is done:
- Developer A: User Story 1
- Developer B: User Story 2
- Developer C: User Story 3
3. Stories complete and integrate independently
---
## Notes
- [P] tasks = different files, no dependencies
- [Story] label maps task to specific user story for traceability
- Each user story should be independently completable and testable
- Verify tests fail before implementing
- Commit after each task or logical group
- Stop at any checkpoint to validate story independently
- Avoid: vague tasks, same file conflicts, cross-story dependencies that break independence

39
AGENTS.md Normal file
View File

@@ -0,0 +1,39 @@
# NixOS Development Guidelines (AI Agents)
Auto-generated from feature plans. Last updated: 2026-01-30
## Active Technologies
- Python 3.12 + MCP server library (Python, JSON-RPC/stdin transport), click for CLI entrypoint, pytest + coverage for tests, ruff/black for lint/format (002-mcp-server)
- None (in-memory tool definitions; filesystem access for repo interactions) (002-mcp-server)
- Nix (flakes; nixpkgs 25.11) + nixpkgs, flake-parts, sops-nix (003-vps-image-migration)
- N/A (configuration repo) (003-vps-image-migration)
- Nix (flakes; nixpkgs 25.11) + NixOS modules, sops-nix, nginx, wireguard, openssh, iptables (004-vps-migration)
- Files (configuration and secrets) (004-vps-migration)
- Documentation set (AI-facing constitution and playbooks) in Markdown (001-ai-docs)
## Project Structure
```text
docs/ # Constitution and playbooks for AI guidance
specs/001-ai-docs/ # Planning artifacts (plan, research, tasks, data model, contracts)
```
## Commands
- Primary work is authoring markdown; no build/test commands required beyond manual validation.
## Code Style & Rules
- Follow repo conventions: no blank lines between code blocks; comments only when non-obvious; factor duplication into shared helpers/functions in examples.
- Constitution is authoritative for AI guidance; if human docs conflict, update both with the recorded resolution.
- Keep language business-level and technology-agnostic in AI-facing docs.
## Recent Changes
- 004-vps-migration: Added Nix (flakes; nixpkgs 25.11) + NixOS modules, sops-nix, nginx, wireguard, openssh, iptables
- 003-vps-image-migration: Added Nix (flakes; nixpkgs 25.11) + nixpkgs, flake-parts, sops-nix
- 003-vps-image-migration: Added [if applicable, e.g., PostgreSQL, CoreData, files or N/A]
<!-- MANUAL ADDITIONS START -->
<!-- MANUAL ADDITIONS END -->

View File

@@ -9,12 +9,11 @@
{
imports = [
inputs.home-manager.nixosModules.home-manager
./users.nix
./jawz.nix
../modules/modules.nix
];
system.stateVersion = "23.05";
sops = {
sops = lib.mkIf config.my.secureHost {
defaultSopsFormat = "yaml";
defaultSopsFile = ../secrets/secrets.yaml;
age = {
@@ -66,10 +65,13 @@
groups = {
users.gid = 100;
piracy.gid = 985;
core.gid = 1251;
glue.gid = 6969;
};
};
nixpkgs.config = {
allowUnfree = true;
allowUnfreePredicate = pkg: builtins.elem (lib.getName pkg) [ "corefonts" ];
permittedInsecurePackages = [
"aspnetcore-runtime-wrapped-6.0.36"
"aspnetcore-runtime-6.0.36"
@@ -152,6 +154,10 @@
enable = true;
nssmdns4 = true;
};
clamav = {
daemon.enable = true;
updater.enable = true;
};
openssh = {
enable = true;
openFirewall = true;
@@ -163,6 +169,40 @@
};
};
};
fonts.fontconfig.enable = true;
fonts = {
fontconfig.enable = true;
packages =
let
customFonts = pkgs.stdenvNoCC.mkDerivation {
name = "custom-fonts";
src = inputs.fonts;
installPhase = ''
mkdir -p $out/share/fonts
find $src -type f \( \
-name "*.ttf" -o \
-name "*.otf" -o \
-name "*.woff" -o \
-name "*.woff2" \
\) -exec cp {} $out/share/fonts/ \;
'';
};
in
builtins.attrValues {
inherit customFonts;
inherit (pkgs)
symbola
comic-neue
cascadia-code
corefonts
;
inherit (pkgs.nerd-fonts)
caskaydia-cove
open-dyslexic
comic-shanns-mono
iosevka
agave
;
};
};
powerManagement.cpuFreqGovernor = lib.mkDefault "performance";
}

73
config/derek.nix Normal file
View File

@@ -0,0 +1,73 @@
{
config,
lib,
pkgs,
inputs,
...
}:
let
enableForDerek = {
enable = true;
users = "bearded_dragonn";
};
in
{
my = {
stylix = enableForDerek;
emacs = enableForDerek;
apps = {
art = enableForDerek;
gaming = enableForDerek;
multimedia.videoEditing = enableForDerek;
};
dev = {
nix = enableForDerek;
python = enableForDerek;
sh = enableForDerek;
};
shell = {
exercism = enableForDerek;
tools = enableForDerek;
multimedia = enableForDerek;
};
};
sops.secrets = lib.mkIf config.my.secureHost {
derek-password.neededForUsers = true;
};
services = {
tailscale.enable = true;
open-webui.enable = lib.mkForce false;
ollama.enable = lib.mkForce false;
sunshine = {
enable = true;
autoStart = false;
capSysAdmin = true;
openFirewall = true;
};
};
users.users.bearded_dragonn = {
isNormalUser = true;
createHome = true;
hashedPasswordFile = lib.mkIf config.my.secureHost config.sops.secrets.derek-password.path;
hashedPassword =
lib.mkIf (!config.my.secureHost)
"$6$s4kbia4u7xVwCmyo$LCN7.Ki2n3xQOqPKnTwa5idwOWYeMNTieQYbLkiiKcMFkFmK76BjtNofJk3U7yRmLGnW3oFT433.nTRq1aoN.1";
packages = builtins.attrValues {
inherit (pkgs)
bottles
vscode
nextcloud-client
warp
handbrake
;
inherit (inputs.prem2resolve.packages.x86_64-linux) prem2resolve;
};
extraGroups = [
"audio"
"video"
"input"
"games"
];
};
home-manager.users.bearded_dragonn.home.stateVersion = "23.05";
}

View File

@@ -61,6 +61,8 @@ in
"scanner"
"lp"
"piracy"
"core"
"glue"
"kavita"
"video"
"docker"
@@ -77,7 +79,6 @@ in
"galaxy"
"phone"
"vps"
"windows_vm"
];
};
}

View File

@@ -10,6 +10,9 @@ in
_final: prev: {
handbrake = prev.handbrake.override { useGtk = true; };
ripgrep = prev.ripgrep.override { withPCRE2 = true; };
blender = prev.blender.override { cudaSupport = true; };
sunshine = prev.sunshine.override { cudaSupport = true; };
obs-studio = prev.obs-studio.override { cudaSupport = true; };
nautilus = prev.nautilus.overrideAttrs (old: {
buildInputs =
old.buildInputs

View File

@@ -71,7 +71,7 @@ in
paul = mkScheme {
color = "green";
name = "valua";
polarity = "light";
polarity = "dark";
image = "${wallpapers}/paul1.jpg";
base16Scheme = {
base00 = "#1a1f16"; # dark forest floor (was deep green-black)

View File

@@ -9,12 +9,19 @@ let
schemesFile = import ./schemes.nix {
inherit pkgs inputs;
};
scheme = schemesFile.schemes.jesus;
scheme = schemesFile.schemes.space;
cfg = config.my.stylix;
gnomeEnabled = config.services.desktopManager.gnome.enable;
in
{
options.my.stylix.enable = lib.mkEnableOption "system-wide theming with Stylix";
options.my.stylix = {
enable = lib.mkEnableOption "system-wide theming with Stylix";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.stylix;
description = "Users to apply Stylix theming for";
};
};
config = {
stylix = {
inherit (scheme) image polarity;
@@ -23,7 +30,7 @@ in
targets.qt.platform = lib.mkForce "qtct";
}
// lib.optionalAttrs (scheme ? base16Scheme) { inherit (scheme) base16Scheme; };
home-manager.users.jawz = {
home-manager.users = inputs.self.lib.mkHomeManagerUsers lib config.my.stylix.users (user: {
gtk = lib.mkIf (!cfg.enable && gnomeEnabled) {
enable = true;
iconTheme = {
@@ -37,16 +44,16 @@ in
inherit (cfg) enable;
autoEnable = cfg.enable;
iconTheme = {
inherit (cfg) enable;
enable = true;
package = scheme.iconPackage;
light = "Papirus-Light";
dark = "Papirus-Dark";
};
targets.librewolf = {
firefoxGnomeTheme.enable = true;
profileNames = [ "jawz" ];
profileNames = [ user ];
};
};
};
});
};
}

View File

@@ -1,12 +0,0 @@
_: {
users.users = {
sonarr = {
uid = 274;
group = "piracy";
};
radarr = {
uid = 275;
group = "piracy";
};
};
}

65
docs/constitution.md Normal file
View File

@@ -0,0 +1,65 @@
# AI Constitution for the NixOS Repository
## Scope and Audience
- Audience: AI assistants and contributors needing an authoritative description of repository rules, structure, and workflows.
- Scope: Repo-wide conventions, module categories, host roles, secrets handling, proxy rules, documentation locations, and maintenance triggers.
- Authority: This constitution is the source of truth for AI. If human-facing docs differ, update both with the recorded resolution in `specs/001-ai-docs/research.md`.
## Repository Overview
- Architecture: Flake-based repo using `flake-parts` with inputs for pkgs (stable/unstable), stylix, home-manager, sops-nix, and service overlays. Common modules are composed through `parts/core.nix` and `parts/hosts.nix`.
- Module auto-import: `modules/modules.nix` auto-imports `.nix` files under `modules/apps`, `modules/dev`, `modules/scripts`, `modules/servers`, `modules/services`, `modules/shell`, and `modules/network`, excluding `librewolf.nix`. Factories live in `modules/factories/` (`mkserver`, `mkscript`), and shared options are in `modules/nix` and `modules/users`.
- Hosts and toggles: Host definitions live in `hosts/<name>/configuration.nix` with host-specific toggles in `hosts/<name>/toggles.nix`. The `my` namespace carries toggles for apps/dev/scripts/services/shell, feature flags like `enableProxy` and `enableContainers`, and per-host `interfaces` and `ips` maps.
- Main server and proxies: `my.mainServer` selects the host that should serve traffic by default (default `vps`). Reverse proxies use helpers in `parts/core.nix` (`proxy`, `proxyReverse`, `proxyReverseFix`, `proxyReversePrivate`) and pick IPs from `my.ips` plus the hostName/ip set by `mkserver` options. Nginx defaults to `proxyReverse` for any server with `enableProxy = true` unless `useDefaultProxy = false` or the server is listed in the Fix/Private proxy lists.
- Secure hosts and secrets: `my.secureHost` gates SOPS secrets. Secure hosts load secrets from `secrets/*.yaml` and wireguard definitions; non-secure hosts (e.g., `hosts/emacs`) skip secret-dependent services. Default SOPS file is `secrets/secrets.yaml` via `config/base.nix`. Proxy-only services that need private certificates must still define their cert secrets when `enableProxy = true`.
## Coding Conventions
- No blank lines between code blocks; keep markdown examples tight.
- Minimize comments; prefer clear naming and shared helpers (`modules/factories/mkserver.nix`, `modules/factories/mkscript.nix`) to avoid duplication.
- Use business-level, technology-agnostic language in AI docs; reserve implementation detail for module code.
- Nix structure: flatten single-child attribute sets into their full path; keep multi-child sets nested for readability; merge siblings under a shared parent; flatten the shallowest subtree first to reduce indentation without losing clarity.
```nix
config.services.jellyfin.enable = true; # preferred single-leaf form
config.services = {
nginx.enable = true;
jellyfin = {
enable = true;
port = 1234;
};
};
```
## Terminology and Naming Standards
- Module: A Nix module under `modules/<category>/<name>.nix` auto-imported into the system.
- Factory: Shared option constructors in `modules/factories/` (use `mkserver` for server modules, `mkscript` for script units).
- Options: Settings under the `my` namespace (e.g., `my.services.<service>`, `my.scripts.<script>`).
- Toggles: Enablement maps in `hosts/<name>/toggles.nix` controlling categories (apps/dev/shell/scripts/services/servers/units) and features (`enableProxy`, `enableContainers`).
- Servers: Reverse-proxied services under `modules/servers/`, normally created with `mkserver` options (including `useDefaultProxy` to opt out of default proxyReverse).
- Scripts: Units defined via `mkscript` with `enable`, `install`, `service`, `users`, `timer`, and `package` fields.
- Playbooks: Workflow guides under `docs/playbooks/` for repeatable tasks.
- Reference map: Navigation index under `docs/reference/index.md` for paths and responsibilities.
## Secrets Map and secureHost Behavior
- Secrets files: `secrets/certs.yaml`, `secrets/env.yaml`, `secrets/gallery.yaml`, `secrets/homepage.yaml`, `secrets/keys.yaml`, `secrets/wireguard.yaml`, `secrets/secrets.yaml`, plus `secrets/ssh/` for host keys.
- Placement rules: Keep secrets aligned to their file purpose (certificates → `certs.yaml`; environment/service env vars → `env.yaml`; media/gallery creds → `gallery.yaml`; homepage widgets → `homepage.yaml`; SSH/private keys → `keys.yaml`; WireGuard peers → `wireguard.yaml`; misc defaults → `secrets.yaml`).
- secureHost gating: Only hosts with `my.secureHost = true` load SOPS secrets and WireGuard interfaces. Hosts with `secureHost = false` must avoid secret-dependent services and skip SOPS entries.
- VPS enrollment flow: The vps host generates its own key on first boot, then operators enroll the public key, re-encrypt secrets, and redeploy. Follow `docs/playbooks/enroll-vps.md`.
## Module Categories and Active Hosts
- Module categories: apps, dev, scripts, servers, services, shell, network, users, nix, patches. Factories sit in `modules/factories/` and are imported explicitly.
- Active hosts: `workstation`, `server`, `miniserver`, `galaxy`, `emacs`. Host roles and secure status are defined in `hosts/<name>/configuration.nix` and toggles in `hosts/<name>/toggles.nix`.
## Precedence and Conflict Resolution
- Precedence: This constitution is authoritative for AI. Human docs must be updated to match. If conflicts are found, align human docs to the constitution and log the resolution in `specs/001-ai-docs/research.md`.
- Conflict handling steps: identify the divergent rule, cite the source files, decide the authoritative rule per this constitution, update both the source file and the relevant doc, and record the decision and timestamp.
## Maintenance Triggers and Update Process
- Triggers: New factory/helper, new module category, new host, new toggle set, new proxy rule, new secret category/file, change to `my.mainServer` or `my.ips`, stylix scheme changes, or new auto-import filters.
- Update flow: (1) Amend the relevant module or toggle files; (2) Update `docs/constitution.md` for rules/terminology changes; (3) Update playbooks under `docs/playbooks/` affected by the change; (4) Update `docs/reference/index.md` for navigation paths; (5) Note the decision in `specs/001-ai-docs/research.md` and refresh `quickstart.md` if discoverability shifts.
- Validation: Confirm discoverability within two clicks (constitution → reference map/playbook), secrets map completeness, and alignment with success criteria SC-001SC-004.
## Quick Reference and Navigation
- Constitution: `docs/constitution.md` (this file)
- Reference map: `docs/reference/index.md` (paths, hosts, secrets, proxies, stylix)
- MCP server reference: `docs/reference/mcp-server.md` (tools, invocation, sync checks)
- Playbooks: `docs/playbooks/*.md` (add module/server/script/host toggle/secret, plus template)
- Planning artifacts: `specs/001-ai-docs/` (plan, research, data-model, quickstart, contracts)

View File

@@ -0,0 +1,18 @@
# Playbook: Add a Host Toggle
- Name: Add or adjust host toggles
- Purpose: Enable categories, services, or features per host in `hosts/<name>/toggles.nix`.
- Prerequisites: Identify host role (see Hosts and Roles), secureHost setting, and whether proxies/containers are required.
- Inputs: Toggle category (apps/dev/scripts/services/servers/units), users list, proxy/container flags, mainServer override, network interface names.
- Steps:
1. Open `hosts/<name>/toggles.nix` and adjust category maps using helper patterns (`enableList` with `mkEnabled`, `mkEnabledWithUsers`, or `mkEnabledIp`).
2. Set feature flags such as `enableProxy`, `enableContainers`, and `mainServer` when the host should own proxied services.
3. Add service toggles under `servers` with proxy/ip data as needed; align IPs to `my.ips` (e.g., `mkEnabledIp` for remote hosts).
4. Ensure `interfaces` entries exist for network-facing services and match `my.interfaces` defaults unless intentionally overridden.
5. Reconcile toggle changes with secrets and secureHost: avoid enabling secret-backed services on hosts with `secureHost = false`.
- Validation:
- Toggle sets align with host capabilities and `my.secureHost`.
- Proxy- or container-dependent services have `enableProxy`/`enableContainers` enabled.
- IP/interface values match `docs/reference/index.md` entries.
- Outputs: Updated host toggle file reflecting new enablement and infrastructure flags.
- References: `docs/constitution.md` (Hosts and toggles, Main server and proxies), `docs/reference/index.md` (Hosts and Roles, Proxy rules, Network maps)

View File

@@ -0,0 +1,18 @@
# Playbook: Add a NixOS Module
- Name: Add a module under `modules/<category>/`
- Purpose: Introduce a new module following auto-import and toggle conventions.
- Prerequisites: Identify target host(s) and toggle category; confirm `my.secureHost` if secrets are involved.
- Inputs: Module name, category (apps/dev/scripts/servers/services/shell/network), required options, secret needs, proxy requirements if server-facing.
- Steps:
1. Choose the category path from `docs/reference/index.md` and create `modules/<category>/<name>.nix` (auto-import picks it up; avoid names filtered out such as `librewolf.nix`).
2. Define options under `my.<category>` or reuse factories (`mkserver` for servers, `mkscript` for scripts) instead of hand-rolled patterns.
3. If the module needs secrets, guard references with `lib.mkIf config.my.secureHost` and map them to the correct secrets file (see secrets map).
4. For networked services, align host selection with `my.mainServer` and `my.ips`; enable reverse proxy via `enableProxy` when applicable.
5. Wire toggles for target hosts in `hosts/<host>/toggles.nix`, ensuring users/groups and containers/proxy flags are set.
- Validation:
- Module loads without extra imports (auto-import applies).
- Toggle wiring matches intended hosts; secureHost gating present for secrets.
- Proxy and port choices align with `my.mainServer`, `my.ips`, and firewall rules.
- Outputs: New module file and updated host toggles if required.
- References: `docs/constitution.md` (Module Categories, Secrets Map, Main server and proxies), `docs/reference/index.md` (Module Directories, Proxy rules, Secrets Map)

View File

@@ -0,0 +1,17 @@
# Playbook: Add a Script Unit
- Name: Add a script via `mkscript`
- Purpose: Ship a script package with optional user service and timer.
- Prerequisites: Identify target users (`my.toggleUsers.scripts` defaults), secureHost status if the script needs secrets, and whether a timer/service is required.
- Inputs: Script name, package derivation, description, timer schedule, users list, service needs.
- Steps:
1. Add a definition under `my.scripts.<name>` in `modules/scripts/<name>.nix` using `mkscript` options (`enable`, `install`, `service`, `users`, `timer`, `package`, `description`).
2. Ensure the package exposes the executable name used by the service/timer.
3. For user scoping, set `users` to a single user or list; defaults come from `my.toggleUsers.scripts`.
4. If secrets are required, guard references with `lib.mkIf config.my.secureHost` and map them to the appropriate secrets file.
5. Enable the script toggle in `hosts/<host>/toggles.nix` under `scripts` or `units`, and ensure timers/services are expected on that host.
- Validation:
- Script installs for intended users; systemd user service/timer activates only when `enable` and `service` are true.
- secureHost gating present for any secrets; no orphaned timers.
- Outputs: New script module and updated host toggles if needed.
- References: `docs/constitution.md` (Terminology, Secrets Map), `docs/reference/index.md` (Module Directories, Secrets Map, Hosts and Roles)

View File

@@ -0,0 +1,17 @@
# Playbook: Add a Secret Entry
- Name: Add or update a secret
- Purpose: Place secrets in the correct SOPS file with secureHost gating.
- Prerequisites: Target host(s) must have `my.secureHost = true`; identify secret type and consumer service/module.
- Inputs: Secret name, target file (certs/env/gallery/homepage/keys/wireguard/secrets), owner/group if file material is written, consuming module path.
- Steps:
1. Choose the correct secrets file from the map in `docs/constitution.md` and add the entry there (YAML, encrypted via sops-nix).
2. If a private key or file path is required, specify `owner`, `group`, and target path consistent with the consuming module.
3. In the consuming module, reference the secret under `config.sops.secrets.<name>` and guard with `lib.mkIf config.my.secureHost`.
4. For WireGuard entries, update `secrets/wireguard.yaml` and corresponding interface configuration under the target host.
5. Avoid adding secrets for hosts with `secureHost = false`; instead route the workload to a secure host or skip enablement.
- Validation:
- Secret lives in the correct file and encrypts with SOPS; file ownership matches service user where applicable.
- Module references are gated by `secureHost` and align with host toggles.
- Outputs: Updated secrets file and gated module references.
- References: `docs/constitution.md` (Secrets Map and secureHost), `docs/reference/index.md` (Secrets Map, Hosts and Roles)

View File

@@ -0,0 +1,18 @@
# Playbook: Add a Server Module with mkserver
- Name: Add a reverse-proxied server module
- Purpose: Stand up a server using `modules/factories/mkserver.nix` with correct proxy and host routing.
- Prerequisites: Target host must have `my.enableProxy = true` and container support if needed; confirm `my.secureHost` for secrets.
- Inputs: Service name, desired subdomain, port, proxy type (standard/fix/private), cron needs, secrets/env vars.
- Steps:
1. Create `modules/servers/<name>.nix` and import `mkserver` options to define `enable`, `enableProxy`, `port`, `host`, `hostName`, `url`, `ip`, `enableSocket`, and `certPath` as needed.
2. Default host routing uses `my.mainServer` and `my.ips`; override `hostName`/`ip` only when the service must live elsewhere.
3. For reverse proxy behavior, select helper from `parts/core.nix`: `proxyReverse` (standard), `proxyReverseFix` (preserve host headers/websockets), or `proxyReversePrivate` (mutual TLS).
4. Place secrets/env references in the appropriate file from the secrets map and guard with `lib.mkIf config.my.secureHost`.
5. Enable the service toggle in `hosts/<host>/toggles.nix` under `servers` (and `enableProxy` if not already set); add any firewall/static ports needed.
- Validation:
- Service resolves to the expected URL and IP per `my.ips` and `my.mainServer`.
- Proxy helper matches the protocol needs; SSL settings align with cert sources.
- Secrets load only on secure hosts; firewall assertions pass.
- Outputs: New server module with mkserver options and updated host toggles/firewall settings.
- References: `docs/constitution.md` (Main server and proxies, Secrets Map), `docs/reference/index.md` (Proxy rules, Module Directories, Secrets Map, Hosts and Roles)

View File

@@ -0,0 +1,16 @@
# Playbook: Enroll VPS Secrets
- Name: Enroll VPS secrets after first boot
- Purpose: Enroll the vps host key and re-encrypt secrets so services can start.
- Prerequisites: vps host booted and reachable; secure host; SOPS access on operator machine.
- Inputs: vps host public key; secrets files under `secrets/`; repo checkout.
- Steps:
1. Retrieve the vps host public key from the running instance.
2. Add the vps public key to SOPS recipients for the relevant secrets files.
3. Re-encrypt secrets and commit updates as needed.
4. Rebuild the vps host from an explicitly authorized operator machine.
- Validation:
- Services that require secrets start successfully after the rebuild.
- SOPS decrypt succeeds on the vps host without manual intervention.
- Outputs: Updated secrets files with the vps recipient; vps host with secrets available.
- References: `docs/constitution.md` (Secrets Map and secureHost), `docs/reference/index.md` (Hosts and Roles)

View File

@@ -0,0 +1,15 @@
# Playbook Template
- Name:
- Purpose:
- Prerequisites: (toggles, hosts, secureHost, required secrets)
- Inputs: (paths, options, credentials, ports)
- Steps:
1.
2.
3.
- Validation:
-
-
- Outputs:
- References: `docs/constitution.md` (relevant sections) and `docs/reference/index.md` (paths/hosts/proxies/secrets)

View File

@@ -0,0 +1,15 @@
# Playbook: Rebuild VPS
- Name: Remote rebuild of vps
- Purpose: Apply configuration changes to the vps host from an explicitly authorized operator machine.
- Prerequisites: Operator machine authorized; vps reachable via SSH; repo checkout.
- Inputs: vps hostname or IP; flake path; target profile `vps`.
- Steps:
1. Ensure the operator machine is in the authorized key list for `nixremote`.
2. Run the rebuild helper script with the target host details.
3. Monitor the rebuild for completion and errors.
- Validation:
- vps reports the new configuration after rebuild.
- Remote access remains available after the update.
- Outputs: Updated vps host configuration.
- References: `docs/constitution.md` (Hosts and Roles, secureHost), `docs/reference/index.md` (Hosts and Roles)

67
docs/reference/index.md Normal file
View File

@@ -0,0 +1,67 @@
# Reference Map
## Module Directories
- apps → `modules/apps/` (desktop/workstation apps, auto-imported)
- dev → `modules/dev/` (language toolchains and dev shells, auto-imported)
- scripts → `modules/scripts/` (script units built via `mkscript`, auto-imported)
- servers → `modules/servers/` (reverse-proxied services built via `mkserver`)
- services → `modules/services/` (supporting services like syncthing, wireguard)
- shell → `modules/shell/` (shell customizations and CLI tooling)
- network → `modules/network/` (networking rules, firewall helpers)
- users → `modules/users/` (user-related options)
- nix → `modules/nix/` (Nix configuration and helpers)
- patches → `patches/` (patch artifacts referenced by modules)
- factories → `modules/factories/` (`mkserver.nix`, `mkscript.nix` shared helpers)
## Auto-Import Rules
- Source: `modules/modules.nix` uses `inputs.self.lib.autoImport` to load `.nix` files from module directories.
- Filter: Excludes `librewolf.nix`; all other `.nix` files in target dirs are loaded automatically.
- Implication: Place new modules in the correct category directory with a `.nix` filename; no manual import wiring required unless adding a new factory.
## Hosts and Roles
- Configs: `hosts/<name>/configuration.nix` with toggles in `hosts/<name>/toggles.nix`.
- Active hosts: `workstation`, `server`, `miniserver`, `galaxy`, `emacs`, `vps`.
- Roles:
- workstation: developer desktop; provides build power for distributed builds.
- server: primary services host; runs most services and WireGuard targets.
- miniserver: small-footprint server.
- galaxy: small server variant using nixpkgs-small.
- emacs: VM profile, `my.secureHost = false` for secret-free usage.
- vps: Linode VPS image target, secure host with enrollment-based secrets.
- Network maps: `my.ips` and `my.interfaces` declared in `modules/modules.nix`; host toggles may override.
## Proxy, Firewall, and Networking
- Proxy enablement: `my.enableProxy` toggles Nginx reverse proxy; assertions require at least one `my.servers.*.enableProxy` when enabled.
- Proxy helpers: use `parts/core.nix` helpers (`proxy`, `proxyReverse`, `proxyReverseFix` for header preservation, `proxyReversePrivate` for mutual TLS). `mkserver` supplies `host`, `ip`, `url`, `enableProxy`, and `useDefaultProxy`.
- Default proxying: any server with `enableProxy = true` gets a `proxyReverse` vhost unless `useDefaultProxy = false` or it is listed in `proxyReverseFix` / `proxyReversePrivate`.
- Main server selection: `my.mainServer` chooses where services live by default (default `vps`); `mkserver` sets `isLocal` based on this and picks IPs from `my.ips`.
- Firewall generation: `inputs.self.lib.generateFirewallPorts` combines static ports, additional ports, and service ports from `my.servers` (excluding native firewall services). Use `my.network.firewall` settings and `getServicesWithNativeFirewall` to derive open ports.
## Secrets Map
- Files and purposes:
- `secrets/certs.yaml` → certificates and TLS material.
- `secrets/env.yaml` → environment variables for services (e.g., lidarr-mb-gap).
- `secrets/gallery.yaml` → media/gallery credentials.
- `secrets/homepage.yaml` → homepage widget secrets.
- `secrets/keys.yaml` → SSH/private keys and key ownership.
- `secrets/wireguard.yaml` → WireGuard peers and private keys.
- `secrets/secrets.yaml` → default SOPS file (general secrets, fallback when unspecified).
- `secrets/ssh/` → host SSH keys and related artifacts.
- secureHost: Only hosts with `my.secureHost = true` consume SOPS entries and WireGuard interfaces. Keep secret references behind `lib.mkIf config.my.secureHost`; proxy-only services that use private certs must still declare their cert secrets when `enableProxy = true`.
## Stylix and Theming
- Stylix module: `config/stylix.nix` and stylix inputs in `flake.nix` apply theming. Host toggle `my.stylix.enable` controls activation (see host toggles).
- Schemes and assets: Imported via Stylix inputs; wallpapers/fonts sourced from external flakes (`wallpapers`, `fonts`).
## Playbooks and Templates
- Playbook template: `docs/playbooks/template.md`
- Workflows: `docs/playbooks/add-module.md`, `add-server.md`, `add-script.md`, `add-host-toggle.md`, `add-secret.md`
- Constitution link-back: `docs/constitution.md` sections on terminology, proxies, secrets, and maintenance.
- MCP server reference: `docs/reference/mcp-server.md` (tool catalog, `nixos-mcp` wrapper, invocation, sync-docs)
## Quick Audit Checklist
- Module coverage: All categories (apps, dev, scripts, servers, services, shell, network, users, nix, patches) have corresponding entries and auto-import rules.
- Host coverage: Active hosts listed with roles and secureHost status; `mainServer` noted.
- Proxy rules: `enableProxy` usage, proxy helper selection, and `my.ips` mappings documented.
- Secrets map: Every secrets file and secureHost gating captured; new secret types aligned to file purposes.
- Discoverability: Paths reachable within two clicks from `docs/constitution.md`.

View File

@@ -0,0 +1,50 @@
# MCP Server Reference
## Overview
- Purpose: local-only MCP server that exposes repository maintenance helpers to Codex CLI.
- Transport: MCP protocol over stdio via the official Python SDK; no network listeners; enforced local-only guard.
- Source: `scripts/mcp-server/`; connect via the `nixos-mcp` wrapper package.
## Sources of Truth
- Constitution: `docs/constitution.md` is authoritative for AI rules and workflows.
- Conflict handling: when human docs differ, update both and record the resolution in `specs/001-ai-docs/research.md`.
- Reference map: `docs/reference/index.md` is the navigation index for paths and responsibilities.
- Playbooks: `docs/playbooks/*.md` are the repeatable workflow guides; follow the template structure.
- Planning artifacts: `specs/001-ai-docs/` captures decisions, plans, and change history.
## Tool Catalog
### show-constitution
- Purpose: Display `docs/constitution.md` to confirm authoritative rules.
- Docs anchor: `docs/constitution.md``#ai-constitution-for-the-nixos-repository`.
### list-playbooks
- Purpose: List available playbooks under `docs/playbooks/` for common tasks.
- Docs anchor: `docs/playbooks/template.md``#playbook-template`.
### show-reference
- Purpose: Show `docs/reference/index.md` to navigate repo guidance.
- Docs anchor: `docs/reference/index.md``#reference-map`.
### search-docs
- Purpose: Search the docs set for a query.
- Inputs: `query` (string).
- Docs anchor: `docs/reference/mcp-server.md``#search-docs`.
### list-mcp-tasks
- Purpose: Show MCP feature task list from `specs/002-mcp-server/tasks.md`.
- Docs anchor: `specs/002-mcp-server/tasks.md``#tasks-mcp-server-for-repo-maintenance`.
### sync-docs
- Purpose: Compare tool catalog against documented anchors for drift reporting.
- Docs anchor: `docs/reference/mcp-server.md``#sync-docs`.
## Invocation
- Start server: `nixos-mcp` (stdio mode).
- Dev shell: `nix develop .#mcp` provides `nixos-mcp` and Codex CLI.
- Codex CLI: configure MCP endpoint as local stdio and allowlist `nixos-mcp` in `.codex/requirements.toml`.
- Invoke: call the MCP tool by name with arguments as defined above.
- Drift check: invoke `sync-docs` to report mismatches between tool catalog and documented anchors.
## Local-Only Expectations
- Remote access is blocked by guard clauses; unset `SSH_CONNECTION` applies local-only behavior.
- If `MCP_ALLOW_REMOTE` is set to `true/1/yes`, guard is relaxed (not recommended).
## Maintenance
- Update tool definitions in `scripts/mcp-server/src/mcp_server/tools.py` with doc anchors.
- Keep docs aligned by updating this reference and running `sync-docs`.
- CI: `.gitea/workflows/mcp-tests.yml` runs lint/format/mypy/pytest with a 60s budget on `scripts/**` and `docs/**` changes.

View File

@@ -6,7 +6,7 @@
'(flycheck-flake8-maximum-line-length 88)
'(safe-local-variable-values
'((org-hugo-auto-export-on-save . t)
(org-hugo-base-dir . /home/jawz/Development/Websites/portfolio/)
(org-hugo-base-dir . "~/Development/Websites/portfolio/")
(git-commit-major-mode . git-commit-elisp-text-mode))))
(custom-set-faces
;; custom-set-faces was added by Custom.

View File

@@ -1,38 +1,60 @@
{
config,
inputs,
lib,
pkgs,
...
}:
let
cfg = config.my.environments.gnome;
in
{
qt.enable = true;
services = {
gvfs.enable = true;
displayManager.gdm.enable = true;
desktopManager.gnome.enable = true;
options.my.environments.gnome = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Enable GNOME desktop environment";
};
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = "jawz";
description = "Users to install GNOME extensions for";
};
};
environment.gnome.excludePackages = builtins.attrValues {
inherit (pkgs)
baobab
cheese
epiphany
gnome-characters
gnome-connections
gnome-font-viewer
gnome-photos
# gnome-text-editor
gnome-tour
yelp
gnome-music
totem
;
};
users.users.jawz.packages = builtins.attrValues {
inherit (pkgs.gnomeExtensions)
tactile # window manager
freon # hardware temperature monitor
gamemode-shell-extension # I guess I'm a gamer now?
burn-my-windows # special effects for when closing windows
pano # clipboard manager
pop-shell
;
config = lib.mkIf cfg.enable {
qt.enable = true;
services = {
gvfs.enable = true;
displayManager.gdm.enable = true;
desktopManager.gnome.enable = true;
};
environment.gnome.excludePackages = builtins.attrValues {
inherit (pkgs)
baobab
cheese
epiphany
gnome-characters
gnome-connections
gnome-font-viewer
gnome-photos
# gnome-text-editor
gnome-tour
yelp
gnome-music
totem
;
};
users.users = inputs.self.lib.mkUserPackages lib cfg.users (
builtins.attrValues {
inherit (pkgs.gnomeExtensions)
tactile # window manager
freon # hardware temperature monitor
gamemode-shell-extension # I guess I'm a gamer now?
burn-my-windows # special effects for when closing windows
pano # clipboard manager
pop-shell
;
}
);
};
}

268
flake.lock generated
View File

@@ -20,11 +20,11 @@
]
},
"locked": {
"lastModified": 1765900596,
"narHash": "sha256-+hn8v9jkkLP9m+o0Nm5SiEq10W0iWDSotH2XfjU45fA=",
"lastModified": 1769428758,
"narHash": "sha256-0G/GzF7lkWs/yl82bXuisSqPn6sf8YGTnbEdFOXvOfU=",
"owner": "hyprwm",
"repo": "aquamarine",
"rev": "d83c97f8f5c0aae553c1489c7d9eff3eadcadace",
"rev": "def5e74c97370f15949a67c62e61f1459fcb0e15",
"type": "github"
},
"original": {
@@ -182,11 +182,11 @@
"firefox-gnome-theme": {
"flake": false,
"locked": {
"lastModified": 1764724327,
"narHash": "sha256-OkFLrD3pFR952TrjQi1+Vdj604KLcMnkpa7lkW7XskI=",
"lastModified": 1764873433,
"narHash": "sha256-1XPewtGMi+9wN9Ispoluxunw/RwozuTRVuuQOmxzt+A=",
"owner": "rafaelmardojai",
"repo": "firefox-gnome-theme",
"rev": "66b7c635763d8e6eb86bd766de5a1e1fbfcc1047",
"rev": "f7ffd917ac0d253dbd6a3bf3da06888f57c69f92",
"type": "github"
},
"original": {
@@ -198,15 +198,15 @@
"flake-compat": {
"flake": false,
"locked": {
"lastModified": 1761588595,
"narHash": "sha256-XKUZz9zewJNUj46b4AJdiRZJAvSZ0Dqj2BNfXvFlJC4=",
"owner": "edolstra",
"lastModified": 1767039857,
"narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=",
"owner": "NixOS",
"repo": "flake-compat",
"rev": "f387cd2afec9419c8ee37694406ca490c3f34ee5",
"rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab",
"type": "github"
},
"original": {
"owner": "edolstra",
"owner": "NixOS",
"repo": "flake-compat",
"type": "github"
}
@@ -216,11 +216,11 @@
"nixpkgs-lib": "nixpkgs-lib"
},
"locked": {
"lastModified": 1765835352,
"narHash": "sha256-XswHlK/Qtjasvhd1nOa1e8MgZ8GS//jBoTqWtrS1Giw=",
"lastModified": 1769996383,
"narHash": "sha256-AnYjnFWgS49RlqX7LrC4uA+sCCDBj0Ry/WOJ5XWAsa0=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "a34fae9c08a15ad73f295041fec82323541400a9",
"rev": "57928607ea566b5db3ad13af0e57e921e6b12381",
"type": "github"
},
"original": {
@@ -234,11 +234,11 @@
"nixpkgs-lib": "nixpkgs-lib_2"
},
"locked": {
"lastModified": 1765835352,
"narHash": "sha256-XswHlK/Qtjasvhd1nOa1e8MgZ8GS//jBoTqWtrS1Giw=",
"lastModified": 1768135262,
"narHash": "sha256-PVvu7OqHBGWN16zSi6tEmPwwHQ4rLPU9Plvs8/1TUBY=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "a34fae9c08a15ad73f295041fec82323541400a9",
"rev": "80daad04eddbbf5a4d883996a73f3f542fa437ac",
"type": "github"
},
"original": {
@@ -293,11 +293,11 @@
]
},
"locked": {
"lastModified": 1763759067,
"narHash": "sha256-LlLt2Jo/gMNYAwOgdRQBrsRoOz7BPRkzvNaI/fzXi2Q=",
"lastModified": 1767609335,
"narHash": "sha256-feveD98mQpptwrAEggBQKJTYbvwwglSbOv53uCfH9PY=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "2cccadc7357c0ba201788ae99c4dfa90728ef5e0",
"rev": "250481aafeb741edfe23d29195671c19b36b6dca",
"type": "github"
},
"original": {
@@ -324,6 +324,24 @@
"type": "github"
}
},
"flake-utils_2": {
"inputs": {
"systems": "systems_4"
},
"locked": {
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"fonts": {
"flake": false,
"locked": {
@@ -382,11 +400,11 @@
"flake": false,
"locked": {
"host": "gitlab.gnome.org",
"lastModified": 1764524476,
"narHash": "sha256-bTmNn3Q4tMQ0J/P0O5BfTQwqEnCiQIzOGef9/aqAZvk=",
"lastModified": 1767737596,
"narHash": "sha256-eFujfIUQDgWnSJBablOuG+32hCai192yRdrNHTv0a+s=",
"owner": "GNOME",
"repo": "gnome-shell",
"rev": "c0e1ad9f0f703fd0519033b8f46c3267aab51a22",
"rev": "ef02db02bf0ff342734d525b5767814770d85b49",
"type": "gitlab"
},
"original": {
@@ -404,11 +422,11 @@
]
},
"locked": {
"lastModified": 1766939458,
"narHash": "sha256-VvZeAKyB3vhyHStSO8ACKzWRKNQPmVWktjfuSVdvtUA=",
"lastModified": 1769580047,
"narHash": "sha256-tNqCP/+2+peAXXQ2V8RwsBkenlfWMERb+Uy6xmevyhM=",
"owner": "nix-community",
"repo": "home-manager",
"rev": "e298a148013c980e3c8c0ac075295fab5074d643",
"rev": "366d78c2856de6ab3411c15c1cb4fb4c2bf5c826",
"type": "github"
},
"original": {
@@ -463,11 +481,11 @@
]
},
"locked": {
"lastModified": 1763733840,
"narHash": "sha256-JnET78yl5RvpGuDQy3rCycOCkiKoLr5DN1fPhRNNMco=",
"lastModified": 1769284023,
"narHash": "sha256-xG34vwYJ79rA2wVC8KFuM8r36urJTG6/csXx7LiiSYU=",
"owner": "hyprwm",
"repo": "hyprgraphics",
"rev": "8f1bec691b2d198c60cccabca7a94add2df4ed1a",
"rev": "13c536659d46893596412d180449353a900a1d31",
"type": "github"
},
"original": {
@@ -495,11 +513,11 @@
"xdph": "xdph"
},
"locked": {
"lastModified": 1766929444,
"narHash": "sha256-mGk+mk/miObjivy+6qMqQm+Jyl8R7t6B/1SaiBkUUyY=",
"lastModified": 1769965155,
"narHash": "sha256-KAgGtueNnwLtekIh9tnmLAUDFbRxSff0OZwQwSi05Nk=",
"owner": "hyprwm",
"repo": "Hyprland",
"rev": "6a055fc747a5a899b97f9b4c1d1a52229a805b1e",
"rev": "a0ec2e4daf8e508761f6bc53fc163fbb92ac7aa1",
"type": "github"
},
"original": {
@@ -541,11 +559,11 @@
]
},
"locked": {
"lastModified": 1765643131,
"narHash": "sha256-CCGohW5EBIRy4B7vTyBMqPgsNcaNenVad/wszfddET0=",
"lastModified": 1767023960,
"narHash": "sha256-R2HgtVS1G3KSIKAQ77aOZ+Q0HituOmPgXW9nBNkpp3Q=",
"owner": "hyprwm",
"repo": "hyprland-guiutils",
"rev": "e50ae912813bdfa8372d62daf454f48d6df02297",
"rev": "c2e906261142f5dd1ee0bfc44abba23e2754c660",
"type": "github"
},
"original": {
@@ -595,11 +613,11 @@
]
},
"locked": {
"lastModified": 1764612430,
"narHash": "sha256-54ltTSbI6W+qYGMchAgCR6QnC1kOdKXN6X6pJhOWxFg=",
"lastModified": 1767983607,
"narHash": "sha256-8C2co8NYfR4oMOUEsPROOJ9JHrv9/ktbJJ6X1WsTbXc=",
"owner": "hyprwm",
"repo": "hyprlang",
"rev": "0d00dc118981531aa731150b6ea551ef037acddd",
"rev": "d4037379e6057246b408bbcf796cf3e9838af5b2",
"type": "github"
},
"original": {
@@ -672,11 +690,11 @@
]
},
"locked": {
"lastModified": 1766160771,
"narHash": "sha256-roINUGikWRqqgKrD4iotKbGj3ZKJl3hjMz5l/SyKrHw=",
"lastModified": 1766253372,
"narHash": "sha256-1+p4Kw8HdtMoFSmJtfdwjxM4bPxDK9yg27SlvUMpzWA=",
"owner": "hyprwm",
"repo": "hyprutils",
"rev": "5ac060bfcf2f12b3a6381156ebbc13826a05b09f",
"rev": "51a4f93ce8572e7b12b7284eb9e6e8ebf16b4be9",
"type": "github"
},
"original": {
@@ -726,11 +744,11 @@
]
},
"locked": {
"lastModified": 1766253200,
"narHash": "sha256-26qPwrd3od+xoYVywSB7hC2cz9ivN46VPLlrsXyGxvE=",
"lastModified": 1769202094,
"narHash": "sha256-gdJr/vWWLRW85ucatSjoBULPB2dqBJd/53CZmQ9t91Q=",
"owner": "hyprwm",
"repo": "hyprwire",
"rev": "1079777525b30a947c8d657fac158e00ae85de9d",
"rev": "a45ca05050d22629b3c7969a926d37870d7dd75c",
"type": "github"
},
"original": {
@@ -747,11 +765,11 @@
"sudoku-solver": "sudoku-solver"
},
"locked": {
"lastModified": 1766276320,
"narHash": "sha256-0OjLvaFkXUPy1lCICUH/QUsUpcDpB2rlDner/f8wirQ=",
"lastModified": 1768598739,
"narHash": "sha256-xBX3qJoJowBg80ZPTZ6RvoOkcrIY/RIxBYhq9XtrN8g=",
"ref": "refs/heads/master",
"rev": "64676aca5db212e7a84b154811d69b74c9cd265f",
"revCount": 125,
"rev": "155967f8e9b1018766bbbe85baaedde3156b79ee",
"revCount": 126,
"type": "git",
"url": "https://git.lebubu.org/jawz/scripts.git"
},
@@ -788,11 +806,11 @@
]
},
"locked": {
"lastModified": 1766887720,
"narHash": "sha256-h0rnexpjILYVpOcE76FQ7ieyqevTQhjah6y/bM9A4kE=",
"lastModified": 1769914377,
"narHash": "sha256-8wH3ZYNs36V0A3f/ikraqdoVE++BfnXg9Ql8nAuUkHw=",
"owner": "fufexan",
"repo": "nix-gaming",
"rev": "c308874a31ba27dbf83a66418268079cdb7e320f",
"rev": "f7d17740ed90663b11ae907d33b3fed9fc9e15a9",
"type": "github"
},
"original": {
@@ -801,42 +819,6 @@
"type": "github"
}
},
"nixlib": {
"locked": {
"lastModified": 1736643958,
"narHash": "sha256-tmpqTSWVRJVhpvfSN9KXBvKEXplrwKnSZNAoNPf/S/s=",
"owner": "nix-community",
"repo": "nixpkgs.lib",
"rev": "1418bc28a52126761c02dd3d89b2d8ca0f521181",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "nixpkgs.lib",
"type": "github"
}
},
"nixos-generators": {
"inputs": {
"nixlib": "nixlib",
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1764234087,
"narHash": "sha256-NHF7QWa0ZPT8hsJrvijREW3+nifmF2rTXgS2v0tpcEA=",
"owner": "nix-community",
"repo": "nixos-generators",
"rev": "032a1878682fafe829edfcf5fdfad635a2efe748",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "nixos-generators",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1743576891,
@@ -855,11 +837,11 @@
},
"nixpkgs-lib": {
"locked": {
"lastModified": 1765674936,
"narHash": "sha256-k00uTP4JNfmejrCLJOwdObYC9jHRrr/5M/a/8L2EIdo=",
"lastModified": 1769909678,
"narHash": "sha256-cBEymOf4/o3FD5AZnzC3J9hLbiZ+QDT/KDuyHXVJOpM=",
"owner": "nix-community",
"repo": "nixpkgs.lib",
"rev": "2075416fcb47225d9b68ac469a5c4801a9c4dd85",
"rev": "72716169fe93074c333e8d0173151350670b824c",
"type": "github"
},
"original": {
@@ -903,11 +885,11 @@
},
"nixpkgs-small": {
"locked": {
"lastModified": 1766945671,
"narHash": "sha256-02c5lD9jxmuHK3pa9zvoRaSEtwmR1Dyp3cquGt5i7B4=",
"lastModified": 1769983561,
"narHash": "sha256-Hv7yml1x0gU14H1zxGATCXb+ueeBH7DFBUTIMkLWD4A=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "66ab54eb48d681dd7babe2d0eb9bc36f823ec6d8",
"rev": "8dcf33716a525a7a0b6815cd8d0f4fa9b13abb1b",
"type": "github"
},
"original": {
@@ -919,11 +901,11 @@
},
"nixpkgs-unstable": {
"locked": {
"lastModified": 1766902085,
"narHash": "sha256-coBu0ONtFzlwwVBzmjacUQwj3G+lybcZ1oeNSQkgC0M=",
"lastModified": 1769789167,
"narHash": "sha256-kKB3bqYJU5nzYeIROI82Ef9VtTbu4uA3YydSk/Bioa8=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "c0b0e0fddf73fd517c3471e546c0df87a42d53f4",
"rev": "62c8382960464ceb98ea593cb8321a2cf8f9e3e5",
"type": "github"
},
"original": {
@@ -935,11 +917,11 @@
},
"nixpkgs_2": {
"locked": {
"lastModified": 1766736597,
"narHash": "sha256-BASnpCLodmgiVn0M1MU2Pqyoz0aHwar/0qLkp7CjvSQ=",
"lastModified": 1769900590,
"narHash": "sha256-I7Lmgj3owOTBGuauy9FL6qdpeK2umDoe07lM4V+PnyA=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "f560ccec6b1116b22e6ed15f4c510997d99d5852",
"rev": "41e216c0ca66c83b12ab7a98cc326b5db01db646",
"type": "github"
},
"original": {
@@ -978,11 +960,11 @@
]
},
"locked": {
"lastModified": 1767000376,
"narHash": "sha256-pbK0Nw0Ye/Ftbn0fLHgcNTgdN7k3MNk+ffNNv9IN+i4=",
"lastModified": 1770024533,
"narHash": "sha256-EXQWqlbhkkune23d6xq/0bz3iyJzkVklvDsSlYE3n3Y=",
"owner": "nix-community",
"repo": "nur",
"rev": "3ba02c75254298131216fd7f00871d69879a20be",
"rev": "cdb7c463555d7c6de5ba7251f9b4940249b651e8",
"type": "github"
},
"original": {
@@ -1003,11 +985,11 @@
]
},
"locked": {
"lastModified": 1764773531,
"narHash": "sha256-mCBl7MD1WZ7yCG6bR9MmpPO2VydpNkWFgnslJRIT1YU=",
"lastModified": 1767886815,
"narHash": "sha256-pB2BBv6X9cVGydEV/9Y8+uGCvuYJAlsprs1v1QHjccA=",
"owner": "nix-community",
"repo": "NUR",
"rev": "1d9616689e98beded059ad0384b9951e967a17fa",
"rev": "4ff84374d77ff62e2e13a46c33bfeb73590f9fef",
"type": "github"
},
"original": {
@@ -1026,11 +1008,11 @@
]
},
"locked": {
"lastModified": 1765911976,
"narHash": "sha256-t3T/xm8zstHRLx+pIHxVpQTiySbKqcQbK+r+01XVKc0=",
"lastModified": 1769069492,
"narHash": "sha256-Efs3VUPelRduf3PpfPP2ovEB4CXT7vHf8W+xc49RL/U=",
"owner": "cachix",
"repo": "git-hooks.nix",
"rev": "b68b780b69702a090c8bb1b973bab13756cc7a27",
"rev": "a1ef738813b15cf8ec759bdff5761b027e3e1d23",
"type": "github"
},
"original": {
@@ -1039,6 +1021,27 @@
"type": "github"
}
},
"prem2resolve": {
"inputs": {
"flake-utils": "flake-utils_2",
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1769712701,
"narHash": "sha256-R5IOg12d7lJwaA3qmC7pQBNgUbmCDo5NHSCY/O95VQA=",
"ref": "refs/heads/main",
"rev": "f7b65d0b8f3d010ce6da4afe9dbd16b864260ae0",
"revCount": 5,
"type": "git",
"url": "https://git.lebubu.org/vibe-coded/prem2resolve.git"
},
"original": {
"type": "git",
"url": "https://git.lebubu.org/vibe-coded/prem2resolve.git"
}
},
"qbit_manage": {
"flake": false,
"locked": {
@@ -1065,12 +1068,12 @@
"jawz-scripts": "jawz-scripts",
"lidarr-mb-gap": "lidarr-mb-gap",
"nix-gaming": "nix-gaming",
"nixos-generators": "nixos-generators",
"nixpkgs": "nixpkgs_2",
"nixpkgs-small": "nixpkgs-small",
"nixpkgs-unstable": "nixpkgs-unstable",
"nixtendo-switch": "nixtendo-switch",
"nur": "nur",
"prem2resolve": "prem2resolve",
"qbit_manage": "qbit_manage",
"sops-nix": "sops-nix",
"stylix": "stylix",
@@ -1085,11 +1088,11 @@
]
},
"locked": {
"lastModified": 1766894905,
"narHash": "sha256-pn8AxxfajqyR/Dmr1wnZYdUXHgM3u6z9x0Z1Ijmz2UQ=",
"lastModified": 1769921679,
"narHash": "sha256-twBMKGQvaztZQxFxbZnkg7y/50BW9yjtCBWwdjtOZew=",
"owner": "Mic92",
"repo": "sops-nix",
"rev": "61b39c7b657081c2adc91b75dd3ad8a91d6f07a7",
"rev": "1e89149dcfc229e7e2ae24a8030f124a31e4f24f",
"type": "github"
},
"original": {
@@ -1111,7 +1114,7 @@
"nixpkgs"
],
"nur": "nur_2",
"systems": "systems_4",
"systems": "systems_5",
"tinted-foot": "tinted-foot",
"tinted-kitty": "tinted-kitty",
"tinted-schemes": "tinted-schemes",
@@ -1119,11 +1122,11 @@
"tinted-zed": "tinted-zed"
},
"locked": {
"lastModified": 1766603740,
"narHash": "sha256-F0BovrhzY/siRQYBRUFn2sZH7TJEuwetOJiGgKtITjk=",
"lastModified": 1769885983,
"narHash": "sha256-jLS7410B58f+3WfZ4PQ28aaaTONnmxlfAbDPdNuciLc=",
"owner": "danth",
"repo": "stylix",
"rev": "cfe89cabaae6ea1bbf80709bd53181494566a1b0",
"rev": "fe06391a1e1905fc7e6c13443ea439a89695ca69",
"type": "github"
},
"original": {
@@ -1210,6 +1213,21 @@
"type": "github"
}
},
"systems_5": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"tinted-foot": {
"flake": false,
"locked": {
@@ -1246,11 +1264,11 @@
"tinted-schemes": {
"flake": false,
"locked": {
"lastModified": 1763914658,
"narHash": "sha256-Hju0WtMf3iForxtOwXqGp3Ynipo0EYx1AqMKLPp9BJw=",
"lastModified": 1767817087,
"narHash": "sha256-eGE8OYoK6HzhJt/7bOiNV2cx01IdIrHL7gXgjkHRdNo=",
"owner": "tinted-theming",
"repo": "schemes",
"rev": "0f6be815d258e435c9b137befe5ef4ff24bea32c",
"rev": "bd99656235aab343e3d597bf196df9bc67429507",
"type": "github"
},
"original": {
@@ -1262,11 +1280,11 @@
"tinted-tmux": {
"flake": false,
"locked": {
"lastModified": 1764465359,
"narHash": "sha256-lbSVPqLEk2SqMrnpvWuKYGCaAlfWFMA6MVmcOFJjdjE=",
"lastModified": 1767489635,
"narHash": "sha256-e6nnFnWXKBCJjCv4QG4bbcouJ6y3yeT70V9MofL32lU=",
"owner": "tinted-theming",
"repo": "tinted-tmux",
"rev": "edf89a780e239263cc691a987721f786ddc4f6aa",
"rev": "3c32729ccae99be44fe8a125d20be06f8d7d8184",
"type": "github"
},
"original": {
@@ -1278,11 +1296,11 @@
"tinted-zed": {
"flake": false,
"locked": {
"lastModified": 1764464512,
"narHash": "sha256-rCD/pAhkMdCx6blsFwxIyvBJbPZZ1oL2sVFrH07lmqg=",
"lastModified": 1767488740,
"narHash": "sha256-wVOj0qyil8m+ouSsVZcNjl5ZR+1GdOOAooAatQXHbuU=",
"owner": "tinted-theming",
"repo": "base16-zed",
"rev": "907dbba5fb8cf69ebfd90b00813418a412d0a29a",
"rev": "11abb0b282ad3786a2aae088d3a01c60916f2e40",
"type": "github"
},
"original": {

View File

@@ -22,6 +22,10 @@
url = "git+https://git.lebubu.org/jawz/scripts.git";
inputs.nixpkgs.follows = "nixpkgs";
};
prem2resolve = {
url = "git+https://git.lebubu.org/vibe-coded/prem2resolve.git";
inputs.nixpkgs.follows = "nixpkgs";
};
lidarr-mb-gap = {
url = "git+https://git.lebubu.org/vibe-coded/lidarr-mb-gap.git";
inputs.nixpkgs.follows = "nixpkgs";
@@ -46,10 +50,6 @@
url = "github:nyawox/nixtendo-switch";
inputs.nixpkgs.follows = "nixpkgs";
};
nixos-generators = {
url = "github:nix-community/nixos-generators";
inputs.nixpkgs.follows = "nixpkgs";
};
wallpapers = {
url = "git+https://git.lebubu.org/jawz/wallpapers.git";
flake = false;

View File

@@ -21,7 +21,6 @@
secureHost = false;
stylix.enable = true;
emacs.enable = true;
apps.fonts.enable = true;
shell.tools.enable = true;
services.network.enable = true;
dev = {

View File

@@ -1,22 +1,34 @@
{ inputs }:
let
inherit (inputs.self.lib) mkEnabled mkEnabledWithProxy enableList;
inherit (inputs.self.lib)
mkEnabled
mkEnabledWithUsers
mkEnabledWithProxy
enableList
;
in
{
emacs.enable = true;
emacs = {
enable = true;
users = "jawz";
};
stylix = {
enable = true;
users = "jawz";
};
enableProxy = true;
websites.portfolio.enableProxy = true;
apps = enableList mkEnabled [
apps = enableList mkEnabledWithUsers [
"dictionaries"
];
services = enableList mkEnabled [
"network"
];
shell = enableList mkEnabled [
shell = enableList mkEnabledWithUsers [
"tools"
"multimedia"
];
dev = enableList mkEnabled [
dev = enableList mkEnabledWithUsers [
"nix"
"python"
"sh"

View File

@@ -5,6 +5,9 @@
inputs,
...
}:
let
lidarrMbGapId = 968;
in
{
imports = [
inputs.lidarr-mb-gap.nixosModules.lidarr-mb-gap
@@ -28,6 +31,7 @@
8448 # synapse ssl
8265 # tdarr
5173 # media map
51412 # qbittorrent
];
};
nix.buildMachines = [
@@ -48,13 +52,16 @@
sopsFile = ../../secrets/env.yaml;
};
"private_keys/lidarr-mb-gap" =
lib.mkIf (config.my.secureHost && config.services.lidarr-mb-gap.enable)
{
sopsFile = ../../secrets/keys.yaml;
owner = config.users.users.lidarr-mb-gap.name;
inherit (config.users.users.lidarr-mb-gap) group;
path = "${config.users.users.lidarr-mb-gap.home}/.ssh/ed25519_lidarr-mb-gap";
};
let
cfg = config.services.lidarr-mb-gap;
usr = config.users.users.lidarr-mb-gap;
in
lib.mkIf (config.my.secureHost && cfg.enable) {
sopsFile = ../../secrets/keys.yaml;
owner = usr.name;
inherit (usr) group;
path = "${usr.home}/.ssh/ed25519_lidarr-mb-gap";
};
};
networking = {
hostName = "server";
@@ -72,6 +79,7 @@
allowedIPs = [
"${config.my.ips.wg-vps}/32"
"${config.my.ips.wg-friends}/24" # all friends
"${config.my.ips.wg-gs}/24" # all friends
];
persistentKeepalive = 25;
}
@@ -81,6 +89,13 @@
users.users.jawz.packages = builtins.attrValues {
inherit (pkgs) podman-compose attic-client;
};
users.groups.lidarr-mb-gap.gid = lidarrMbGapId;
users.users.lidarr-mb-gap = {
uid = lidarrMbGapId;
isSystemUser = true;
group = "lidarr-mb-gap";
home = "/var/lib/lidarr-mb-gap";
};
services = {
btrfs.autoScrub = {
enable = true;

View File

@@ -1,45 +1,51 @@
{ config, inputs }:
let
inherit (inputs.self.lib) mkEnabled enableList;
inherit (inputs.self.lib) mkEnabled mkEnabledWithUsers enableList;
mkEnabledIp = inputs.self.lib.mkEnabledIp config.my.ips.wg-server;
in
{
mainServer = "server";
emacs.enable = true;
stylix.enable = true;
emacs = {
enable = true;
users = "jawz";
};
stylix = {
enable = true;
users = "jawz";
};
enableProxy = true;
enableContainers = true;
apps.dictionaries.enable = true;
shell = enableList mkEnabled [
"tools"
apps.dictionaries.users = "jawz";
shell = enableList mkEnabledWithUsers [
"multimedia"
"tools"
];
services = enableList mkEnabled [
"network"
"nvidia"
"syncthing"
];
dev = enableList mkEnabled [
dev = enableList mkEnabledWithUsers [
"nix"
"python"
"sh"
];
units = enableList mkEnabled [
"downloadManga"
"download"
"downloadManga"
"stream-dl"
];
scripts = enableList mkEnabled [
"run"
"download"
"split-dir"
"ffmpreg"
"ffmpeg4discord"
"manage-library"
"library-report"
"stream-dl"
"pika-list"
"ffmpreg"
"find-dup-episodes"
"library-report"
"manage-library"
"pika-list"
"run"
"split-dir"
"stream-dl"
"tuh-activity-logger"
];
servers = {
@@ -50,40 +56,40 @@ in
};
}
// enableList mkEnabled [
"syncplay"
"qbittorrent"
"sabnzbd"
"unpackerr"
"postgres"
"paperless"
"stash"
"atticd"
"bazarr"
"collabora"
"gitea"
"homepage"
"jellyfin"
"kavita"
"lidarr"
"maloja"
"microbin"
"multi-scrobbler"
"plex"
"prowlarr"
"radarr"
"ryot"
"sonarr"
"synapse"
"jellyfin"
"gitea"
"mealie"
"metube"
"atticd"
"microbin"
"multi-scrobbler"
"paperless"
"plausible"
"plex"
"postgres"
"prowlarr"
"qbittorrent"
"radarr"
"sabnzbd"
"sonarr"
"stash"
"synapse"
"syncplay"
"unpackerr"
"yamtrack"
]
// enableList mkEnabledIp [
"audiobookshelf"
"vaultwarden"
"readeck"
"keycloak"
"oauth2-proxy"
"isso"
"plausible"
"keycloak"
"linkwarden"
"oauth2-proxy"
"vaultwarden"
];
}

139
hosts/vps/configuration.nix Normal file
View File

@@ -0,0 +1,139 @@
{
config,
lib,
inputs,
...
}:
let
externalInterface = config.my.interfaces.${config.networking.hostName};
wgInterface = "wg0";
homeServer = config.my.ips.wg-server;
wgFriendsSubnet = "${config.my.ips.wg-friends}/24";
wgGuestsSubnet = "${config.my.ips.wg-gs}/24";
wgServerSubnet = "${config.my.ips.wg-vps}/24";
wgFriend1 = config.my.ips.wg-friend1;
wgGuest1 = config.my.ips.wg-g1;
giteaSshPort = 22;
giteaSshPortStr = toString giteaSshPort;
sshPort = 3456;
webPorts = [
80
443
];
wgPort = 51820;
syncthingPort = toString 22000;
synapseFederationPort = toString 8448;
synapseClientPort = toString config.my.servers.synapse.port;
syncplayPort = toString config.my.servers.syncplay.port;
stashPort = toString config.my.servers.stash.port;
in
{
imports = [
./hardware-configuration.nix
../../config/base.nix
];
my = import ./toggles.nix { inherit config inputs; } // {
secureHost = true;
users.nixremote = {
enable = true;
authorizedKeys = inputs.self.lib.getSshKeys [
"nixworkstation"
"nixserver"
"nixminiserver"
];
};
};
image.modules.linode = { };
services.smartd.enable = lib.mkForce false;
environment.systemPackages = [ ];
networking = {
hostName = "vps";
nat = {
inherit externalInterface;
enable = true;
internalInterfaces = [ "wg0" ];
forwardPorts = [
{
sourcePort = giteaSshPort;
proto = "tcp";
destination = "${homeServer}:${giteaSshPortStr}";
}
];
};
nftables = {
enable = true;
tables.vps-snat = {
family = "ip";
content = ''
chain postrouting {
type nat hook postrouting priority srcnat;
iifname "${externalInterface}" oifname "${wgInterface}" ip daddr ${homeServer}/32 tcp dport ${giteaSshPortStr} masquerade comment "snat ssh forward"
}
'';
};
};
firewall = {
enable = true;
filterForward = true;
checkReversePath = "loose";
allowedTCPPorts = [ sshPort ] ++ webPorts;
allowedUDPPorts = [ wgPort ];
extraForwardRules = ''
iifname "${wgInterface}" ip saddr ${wgFriendsSubnet} ip daddr ${homeServer}/32 tcp dport ${syncthingPort} accept
iifname "${wgInterface}" ip saddr ${homeServer}/32 ip daddr ${wgFriendsSubnet} tcp dport ${syncthingPort} accept
iifname "${wgInterface}" ip saddr ${wgFriendsSubnet} ip daddr ${homeServer}/32 tcp dport { ${synapseClientPort}, ${synapseFederationPort}, ${syncplayPort} } accept
iifname "${wgInterface}" ip saddr ${wgFriendsSubnet} ip daddr ${homeServer}/32 icmp type echo-request accept
iifname "${wgInterface}" ip saddr ${wgFriend1}/32 ip daddr ${homeServer}/32 tcp dport ${stashPort} accept
iifname "${wgInterface}" ip saddr ${wgGuest1}/32 ip daddr ${homeServer}/32 tcp dport ${stashPort} accept
iifname "${wgInterface}" ip saddr ${wgGuestsSubnet} ip daddr ${homeServer}/32 icmp type echo-request accept
iifname "${wgInterface}" ip saddr ${wgFriendsSubnet} oifname "${externalInterface}" accept
iifname "${wgInterface}" ip saddr ${wgGuestsSubnet} oifname "${externalInterface}" accept
ip saddr ${wgFriendsSubnet} ip daddr ${wgServerSubnet} drop
ip saddr ${wgServerSubnet} ip daddr ${wgFriendsSubnet} drop
ip saddr ${wgGuestsSubnet} ip daddr ${wgServerSubnet} drop
ip saddr ${wgServerSubnet} ip daddr ${wgGuestsSubnet} drop
ip saddr ${wgGuestsSubnet} ip daddr ${wgFriendsSubnet} drop
ip saddr ${wgFriendsSubnet} ip daddr ${wgGuestsSubnet} drop
'';
};
};
security.sudo-rs.extraRules = [
{
users = [ "nixremote" ];
commands = [
{
command = "/run/current-system/sw/bin/nixos-rebuild";
options = [ "NOPASSWD" ];
}
];
}
];
services.openssh.ports = [ sshPort ];
sops.age = {
generateKey = true;
keyFile = "/var/lib/sops-nix/key.txt";
sshKeyPaths = [ "/etc/ssh/ssh_host_ed25519_key" ];
};
users = {
groups = {
deploy = { };
lidarr-reports = { };
};
users = {
deploy = {
isSystemUser = true;
group = "deploy";
openssh.authorizedKeys.keyFiles = [ ../../secrets/ssh/ed25519_deploy.pub ];
};
lidarr-reports = {
isSystemUser = true;
group = "lidarr-reports";
openssh.authorizedKeys.keyFiles = [ ../../secrets/ssh/ed25519_lidarr-reports.pub ];
};
};
};
}

View File

@@ -0,0 +1,45 @@
{
lib,
modulesPath,
...
}:
{
imports = [ (modulesPath + "/profiles/qemu-guest.nix") ];
boot = {
kernelModules = [ ];
extraModulePackages = [ ];
kernelParams = [ "console=ttyS0,19200n8" ];
kernel.sysctl = {
"net.ipv4.ip_forward" = 1;
"net.ipv4.conf.wg0.rp_filter" = 0;
};
initrd.availableKernelModules = [
"virtio_pci"
"virtio_scsi"
"ahci"
"sd_mod"
];
loader = {
timeout = 10;
grub = {
device = "nodev";
forceInstall = true;
extraConfig = ''
serial --speed=19200 --unit=0 --word=8 --parity=no --stop=1;
terminal_input serial;
terminal_output serial
'';
};
};
};
fileSystems."/" = {
device = "/dev/disk/by-uuid/f222513b-ded1-49fa-b591-20ce86a2fe7f";
fsType = "ext4";
};
swapDevices = [
{
device = "/dev/disk/by-uuid/f1408ea6-59a0-11ed-bc9d-525400000001";
}
];
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
}

61
hosts/vps/toggles.nix Normal file
View File

@@ -0,0 +1,61 @@
{ config, inputs }:
let
inherit (inputs.self.lib)
enableList
mkEnabled
mkEnabledWithUsers
;
wgServerIp = config.my.ips.wg-server;
mkEnabledProxyIp = inputs.self.lib.mkEnabledProxyIp wgServerIp;
in
{
enableProxy = true;
enableContainers = true;
apps.dictionaries.enable = true;
apps.dictionaries.users = "jawz";
services = enableList mkEnabled [
"network"
"wireguard"
];
shell = enableList mkEnabledWithUsers [
"multimedia"
"tools"
];
dev = enableList mkEnabledWithUsers [
"nix"
"sh"
];
servers = {
nextcloud = {
enableProxy = true;
ip = wgServerIp;
port = 8081;
};
}
// enableList mkEnabledProxyIp [
"audiobookshelf"
"bazarr"
"collabora"
"gitea"
"homepage"
"isso"
"jellyfin"
"kavita"
"keycloak"
"lidarr"
"linkwarden"
"maloja"
"mealie"
"metube"
"microbin"
"multi-scrobbler"
"oauth2-proxy"
"plausible"
"plex"
"prowlarr"
"radarr"
"sonarr"
"vaultwarden"
"yamtrack"
];
}

View File

@@ -22,6 +22,7 @@ in
../../config/base.nix
../../config/stylix.nix
../../environments/gnome.nix
../../config/derek.nix
];
my = import ./toggles.nix { inherit inputs; } // {
nix.cores = 8;
@@ -31,6 +32,10 @@ in
"nixserver"
"nixminiserver"
];
environments.gnome.users = [
"jawz"
"bearded_dragonn"
];
};
home-manager.users.jawz.programs = {
vscode = {
@@ -123,7 +128,6 @@ in
../../secrets/ssh/root-private-ca.pem
];
services = {
minio.enable = true;
flatpak.enable = true;
open-webui.enable = true;
scx = {
@@ -143,48 +147,5 @@ in
acceleration = "cuda";
models = "/srv/ai/ollama";
};
postgresql = {
enable = true;
package = pkgs.postgresql_17;
enableTCPIP = true;
authentication = pkgs.lib.mkOverride 10 ''
local all all trust
host all all ${config.my.localhost}/32 trust
host all all ::1/128 trust
'';
ensureDatabases = [ "webref" ];
ensureUsers = [
{
name = "webref";
ensureDBOwnership = true;
}
];
};
};
programs.virt-manager.enable = true;
users.groups.libvirtd.members = [ "jawz" ];
virtualisation.libvirtd.enable = true;
systemd.services.minio-init = {
description = "Initialize MinIO buckets";
after = [ "minio.service" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
};
script = ''
# Wait for MinIO to be ready
until ${pkgs.curl}/bin/curl -sf http://localhost:9000/minio/health/live > /dev/null 2>&1; do
echo "Waiting for MinIO..."
sleep 1
done
# Configure mc alias and create bucket
${pkgs.minio-client}/bin/mc alias set local http://localhost:9000 minioadmin minioadmin || true
${pkgs.minio-client}/bin/mc mb local/webref || true
${pkgs.minio-client}/bin/mc anonymous set public local/webref || true
echo "MinIO initialized with webref bucket"
'';
};
}

View File

@@ -1,29 +1,37 @@
{ inputs }:
let
inherit (inputs.self.lib) mkEnabled enableList;
inherit (inputs.self.lib) mkEnabled mkEnabledWithUsers enableList;
in
{
stylix.enable = true;
emacs.enable = true;
stylix = {
enable = true;
users = "jawz";
};
emacs = {
enable = true;
users = "jawz";
};
enableContainers = true;
servers.drpp.enable = true;
apps = enableList mkEnabled [
"art"
"dictionaries"
"fonts"
"gaming"
"switch"
"internet"
"multimedia"
"office"
"misc"
];
dev = enableList mkEnabled [
apps =
(enableList mkEnabledWithUsers [
"art"
"dictionaries"
"gaming"
"internet"
"multimedia"
"office"
"misc"
])
// {
switch.enable = true;
};
dev = enableList mkEnabledWithUsers [
"nix"
"python"
"sh"
];
shell = enableList mkEnabled [
shell = enableList mkEnabledWithUsers [
"exercism"
"multimedia"
"tools"

126
iptables Normal file
View File

@@ -0,0 +1,126 @@
# Generated by iptables-save v1.8.11 (nf_tables) on Fri Jan 2 03:44:23 2026
*mangle
:PREROUTING ACCEPT [95853893:179831236298]
:INPUT ACCEPT [94316554:179510512585]
:FORWARD ACCEPT [1536524:320567864]
:OUTPUT ACCEPT [49857522:93072472240]
:POSTROUTING ACCEPT [51393797:93393029789]
COMMIT
# Completed on Fri Jan 2 03:44:23 2026
# Generated by iptables-save v1.8.11 (nf_tables) on Fri Jan 2 03:44:23 2026
*raw
:PREROUTING ACCEPT [95853893:179831236298]
:OUTPUT ACCEPT [49857522:93072472240]
COMMIT
# Completed on Fri Jan 2 03:44:23 2026
# Generated by iptables-save v1.8.11 (nf_tables) on Fri Jan 2 03:44:23 2026
*filter
:INPUT ACCEPT [94315678:179510353216]
:FORWARD ACCEPT [46534:2774394]
:OUTPUT ACCEPT [49857520:93072471971]
# --- Incoming (INPUT) rules for VPS itself ---
# Accept SSH on port 3456 (new SSH port)
# allow SSH to VPS
-A INPUT -p tcp --dport 3456 -m conntrack --ctstate NEW -j ACCEPT
# allow established connections (responses)
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
# (Optionally, add other INPUT rules for any services the VPS itself runs, if any, like HTTP/HTTPS if needed)
# If a default DROP policy is desired on INPUT, or an explicit drop rule:
# -A INPUT -j DROP # (optional: lock down any other input)
# --- Forwarding (FORWARD) rules for VPN traffic ---
# allow return traffic for established sessions
-A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
# Syncthing between 10.8.0.2 and home server
# 10.8.0.2 -> 10.77.0.0 Syncthing
-A FORWARD -s 10.8.0.2/32 -d 10.77.0.2/32 -p tcp --dport 22000 -j ACCEPT
-A FORWARD -s 10.8.0.3/32 -d 10.77.0.2/32 -p tcp --dport 22000 -j ACCEPT
-A FORWARD -s 10.8.0.4/32 -d 10.77.0.2/32 -p tcp --dport 22000 -j ACCEPT
-A FORWARD -s 10.8.0.5/32 -d 10.77.0.2/32 -p tcp --dport 22000 -j ACCEPT
# home -> 10.8.0.0 Syncthing
-A FORWARD -s 10.77.0.2/32 -d 10.8.0.2/32 -p tcp --dport 22000 -j ACCEPT
-A FORWARD -s 10.77.0.2/32 -d 10.8.0.3/32 -p tcp --dport 22000 -j ACCEPT
-A FORWARD -s 10.77.0.2/32 -d 10.8.0.4/32 -p tcp --dport 22000 -j ACCEPT
-A FORWARD -s 10.77.0.2/32 -d 10.8.0.5/32 -p tcp --dport 22000 -j ACCEPT
# Matrix/Synapse access from 10.8 subnet to home server
# allow Matrix client port
-A FORWARD -s 10.8.0.0/24 -d 10.77.0.2/32 -p tcp --dport 8008 -j ACCEPT
# allow Matrix federation port
-A FORWARD -s 10.8.0.0/24 -d 10.77.0.2/32 -p tcp --dport 8448 -j ACCEPT
# allow TURN/other (if used)
-A FORWARD -s 10.8.0.0/24 -d 10.77.0.2/32 -p tcp --dport 8999 -j ACCEPT
# ICMP between 10.8 subnet and home
# ping home from 10.8 clients
-A FORWARD -s 10.8.0.0/24 -d 10.77.0.2/32 -p icmp -j ACCEPT
# ping 10.8 clients from home
-A FORWARD -s 10.77.0.2/32 -d 10.8.0.0/24 -p icmp -j ACCEPT
# New Friend's subnet (10.9) access rule
# allow new subnet to access port 9999 on home
-A FORWARD -s 10.9.0.2/24 -d 10.77.0.2/32 -p tcp --dport 9999 -j ACCEPT
# allow ping to home
-A FORWARD -s 10.9.0.2/24 -d 10.77.0.2/32 -p icmp -j ACCEPT
# allow ping reply from home
-A FORWARD -s 10.77.0.2/32 -d 10.9.0.2/24 -p icmp -j ACCEPT
# Allow VPN subnets to reach Internet (MASQUERADE will SNAT them)
# 10.8 clients to internet
-A FORWARD -s 10.8.0.0/24 -o eth0 -j ACCEPT
# 10.9 clients to internet
-A FORWARD -s 10.9.0.2/24 -o eth0 -j ACCEPT
# Drop all other traffic between these subnets and home or between subnets (isolation)
# drop any 10.8 -> home not allowed
-A FORWARD -s 10.8.0.0/24 -d 10.77.0.0/24 -j DROP
# drop any home -> 10.8 not allowed
-A FORWARD -s 10.77.0.0/24 -d 10.8.0.0/24 -j DROP
# drop any 10.9 -> home not allowed (except 9999/ping above)
-A FORWARD -s 10.9.0.0/24 -d 10.77.0.0/24 -j DROP
# drop any home -> 10.9 not allowed
-A FORWARD -s 10.77.0.0/24 -d 10.9.0.0/24 -j DROP
# drop 10.9 -> 10.8 (no client-to-client)
-A FORWARD -s 10.9.0.0/24 -d 10.8.0.0/24 -j DROP
# drop 10.8 -> 10.9
-A FORWARD -s 10.8.0.0/24 -d 10.9.0.0/24 -j DROP
COMMIT
*nat
:PREROUTING ACCEPT [3368888:178175988]
:INPUT ACCEPT [3348703:174454011]
:OUTPUT ACCEPT [30120:1902454]
:POSTROUTING ACCEPT [32339:2018208]
# Port forwarding (DNAT) rules:
# forward SSH (port 22) to home server
-A PREROUTING -p tcp --dport 22 -j DNAT --to-destination 10.77.0.2:22
# forward port 51412 to home (TCP)
-A PREROUTING -p tcp --dport 51412 -j DNAT --to-destination 10.77.0.2:51412
# forward port 51412 to home (UDP)
-A PREROUTING -p udp --dport 51412 -j DNAT --to-destination 10.77.0.2:51412
# (Remove the above 51412 rules if not used; keep 22 as its for Giteas SSH access)
# Masquerade (SNAT) rules:
# masquerade replies from home for SSH
-A POSTROUTING -d 10.77.0.2/32 -p tcp --dport 22 -j MASQUERADE
# masquerade replies for 51412 (TCP)
-A POSTROUTING -d 10.77.0.2/32 -p tcp --dport 51412 -j MASQUERADE
#masquerade replies for 51412 (UDP)
-A POSTROUTING -d 10.77.0.2/32 -p udp --dport 51412 -j MASQUERADE
# (If 51412 rules removed above, remove their masquerade lines too)
# NAT for 10.8.0.x clients to internet
-A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
# NAT for 10.9.0.x clients to internet
-A POSTROUTING -s 10.9.0.0/24 -o eth0 -j MASQUERADE
COMMIT

View File

@@ -1,5 +1,6 @@
{
config,
inputs,
lib,
pkgs,
...
@@ -36,8 +37,19 @@ let
in
{
options.my = {
apps.art.enable = lib.mkEnableOption "digital art and creative applications";
apps.art = {
enable = lib.mkEnableOption "digital art and creative applications";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.apps;
description = "Users to install art packages for";
};
};
dev.gameDev.enable = lib.mkEnableOption "game development tools and engines";
};
config.users.users.jawz.packages = artPackages ++ gameDevPackages;
config.users.users =
let
packages = artPackages ++ gameDevPackages;
in
inputs.self.lib.mkUserPackages lib config.my.apps.art.users packages;
}

View File

@@ -1,21 +1,32 @@
{
config,
inputs,
lib,
pkgs,
...
}:
let
packages = builtins.attrValues {
inherit (pkgs)
hunspell
;
inherit (pkgs.hunspellDicts)
it_IT
es_MX
en_CA-large
;
};
in
{
options.my.apps.dictionaries.enable = lib.mkEnableOption "dictionaries and language tools";
config = lib.mkIf config.my.apps.dictionaries.enable {
users.users.jawz.packages = builtins.attrValues {
inherit (pkgs)
hunspell
;
inherit (pkgs.hunspellDicts)
it_IT
es_MX
en_CA-large
;
options.my.apps.dictionaries = {
enable = lib.mkEnableOption "dictionaries and language tools";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.apps;
description = "Users to install dictionaries packages for";
};
};
config = lib.mkIf config.my.apps.dictionaries.enable {
users.users = inputs.self.lib.mkUserPackages lib config.my.apps.dictionaries.users packages;
};
}

View File

@@ -1,44 +0,0 @@
{
config,
lib,
pkgs,
inputs,
...
}:
let
customFonts = pkgs.stdenvNoCC.mkDerivation {
name = "custom-fonts";
src = inputs.fonts;
installPhase = ''
mkdir -p $out/share/fonts
find $src -type f \( \
-name "*.ttf" -o \
-name "*.otf" -o \
-name "*.woff" -o \
-name "*.woff2" \
\) -exec cp {} $out/share/fonts/ \;
'';
};
in
{
options.my.apps.fonts.enable = lib.mkEnableOption "additional fonts and typography";
config = lib.mkIf config.my.apps.fonts.enable {
nixpkgs.config.allowUnfreePredicate = pkg: builtins.elem (lib.getName pkg) [ "corefonts" ];
fonts.packages = builtins.attrValues {
inherit customFonts;
inherit (pkgs)
symbola
comic-neue
cascadia-code
corefonts
;
inherit (pkgs.nerd-fonts)
caskaydia-cove
open-dyslexic
comic-shanns-mono
iosevka
agave
;
};
};
}

View File

@@ -1,6 +1,6 @@
{
inputs,
config,
inputs,
lib,
pkgs,
...
@@ -23,7 +23,14 @@ in
{
imports = [ inputs.nix-gaming.nixosModules.platformOptimizations ];
options.my.apps = {
gaming.enable = lib.mkEnableOption "gaming applications and emulators";
gaming = {
enable = lib.mkEnableOption "gaming applications and emulators";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.apps;
description = "Users to install gaming packages for";
};
};
switch.enable = lib.mkEnableOption "Nintendo Switch homebrew tools";
};
config = lib.mkIf config.my.apps.gaming.enable {
@@ -50,23 +57,28 @@ in
# environmentFile = config.sops.secrets.switch-presence.path;
# };
};
users.users.jawz.packages = builtins.attrValues {
inherit retroarchWithCores;
inherit (pkgs)
shipwright # zelda OoT port
mangohud # fps & stats overlay
lutris # games launcher & emulator hub
cartridges # games launcher
gamemode # optimizes linux to have better gaming performance
heroic # install epic games
protonup-qt # update proton-ge
ns-usbloader # load games into my switch
# emulators
rpcs3 # ps3
cemu # wii u
ryubing # switch
prismlauncher # minecraft launcher with jdk overlays
;
};
users.users =
let
packages = builtins.attrValues {
inherit retroarchWithCores;
inherit (pkgs)
mgba # gba emulator
shipwright # zelda OoT port
mangohud # fps & stats overlay
lutris # games launcher & emulator hub
cartridges # games launcher
gamemode # optimizes linux to have better gaming performance
heroic # install epic games
protonup-qt # update proton-ge
ns-usbloader # load games into my switch
# emulators
rpcs3 # ps3
cemu # wii u
ryubing # switch
prismlauncher # minecraft launcher with jdk overlays
;
};
in
inputs.self.lib.mkUserPackages lib config.my.apps.gaming.users packages;
};
}

View File

@@ -1,5 +1,6 @@
{
config,
inputs,
lib,
pkgs,
...
@@ -27,26 +28,39 @@ let
krisp-patcher = pkgs.writers.writePython3Bin "krisp-patcher" krisp-settings krisp-patch;
in
{
options.my.apps.internet.enable = lib.mkEnableOption "internet browsers and communication apps";
config = lib.mkIf config.my.apps.internet.enable {
home-manager.users.jawz.programs.librewolf = import ./librewolf.nix;
programs.geary.enable = true;
users.users.jawz.packages = builtins.attrValues {
# inherit (inputs.zen-browser.packages.x86_64-linux) twilight;
inherit krisp-patcher;
inherit (pkgs)
# thunderbird # email client
warp # transfer files with based ppl
nextcloud-client # self-hosted google-drive alternative
fragments # beautiful torrent client
tor-browser # dark web, so dark!
telegram-desktop # furry chat
nicotine-plus # remember Ares?
discord # :3
vdhcoapp # video download helper assistant
nextcloud-talk-desktop # nextcloud talk client
fractal # matrix client
;
options.my.apps.internet = {
enable = lib.mkEnableOption "internet browsers and communication apps";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.apps;
description = "Users to install internet packages for";
};
};
config = lib.mkIf config.my.apps.internet.enable {
home-manager.users = inputs.self.lib.mkHomeManagerUsers lib config.my.apps.internet.users (_user: {
programs.librewolf = import ./librewolf.nix;
});
programs.geary.enable = true;
users.users =
let
packages = builtins.attrValues {
# inherit (inputs.zen-browser.packages.x86_64-linux) twilight;
inherit krisp-patcher;
inherit (pkgs)
# thunderbird # email client
warp # transfer files with based ppl
nextcloud-client # self-hosted google-drive alternative
fragments # beautiful torrent client
tor-browser # dark web, so dark!
telegram-desktop # furry chat
nicotine-plus # remember Ares?
discord # :3
vdhcoapp # video download helper assistant
nextcloud-talk-desktop # nextcloud talk client
fractal # matrix client
;
};
in
inputs.self.lib.mkUserPackages lib config.my.apps.internet.users packages;
};
}

View File

@@ -1,19 +1,31 @@
{
config,
inputs,
lib,
pkgs,
...
}:
{
options.my.apps.misc.enable = lib.mkEnableOption "miscellaneous desktop applications";
config = lib.mkIf config.my.apps.misc.enable {
users.users.jawz.packages = builtins.attrValues {
inherit (pkgs)
blanket # background noise
metadata-cleaner # remove any metadata and geolocation from files
pika-backup # backups
gnome-obfuscate # censor private information
;
options.my.apps.misc = {
enable = lib.mkEnableOption "miscellaneous desktop applications";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.apps;
description = "Users to install misc packages for";
};
};
config = lib.mkIf config.my.apps.misc.enable {
users.users =
let
packages = builtins.attrValues {
inherit (pkgs)
blanket # background noise
metadata-cleaner # remove any metadata and geolocation from files
pika-backup # backups
gnome-obfuscate # censor private information
;
};
in
inputs.self.lib.mkUserPackages lib config.my.apps.misc.users packages;
};
}

View File

@@ -1,21 +1,55 @@
{
config,
inputs,
lib,
pkgs,
...
}:
let
cfg = config.my.apps.multimedia;
attrValuesIf = cond: attrs: if cond then builtins.attrValues attrs else [ ];
multimediaPackages = attrValuesIf cfg.enable {
inherit (pkgs)
curtail # image compressor
easyeffects # equalizer
identity # compare images or videos
mousai # poor man shazam
shortwave # listen to world radio
tagger # tag music files
;
};
videoEditingPackages = attrValuesIf cfg.videoEditing.enable {
inherit (pkgs)
davinci-resolve
shotcut
pitivi
;
inherit (pkgs.kdePackages)
kdenlive
;
};
in
{
options.my.apps.multimedia.enable = lib.mkEnableOption "multimedia applications and media players";
config = lib.mkIf config.my.apps.multimedia.enable {
users.users.jawz.packages = builtins.attrValues {
inherit (pkgs)
curtail # image compressor
easyeffects # equalizer
identity # compare images or videos
mousai # poor man shazam
shortwave # listen to world radio
tagger # tag music files
;
options.my.apps.multimedia = {
enable = lib.mkEnableOption "multimedia applications and media players";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.apps;
description = "Users to install multimedia packages for";
};
videoEditing = {
enable = lib.mkEnableOption "video editing applications";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.apps;
description = "Users to install video editing packages for";
};
};
};
config = lib.mkIf (cfg.enable || cfg.videoEditing.enable) {
users.users = lib.mkMerge [
(inputs.self.lib.mkUserPackages lib cfg.users multimediaPackages)
(inputs.self.lib.mkUserPackages lib cfg.videoEditing.users videoEditingPackages)
];
};
}

View File

@@ -1,18 +1,30 @@
{
config,
inputs,
lib,
pkgs,
...
}:
{
options.my.apps.piano.enable = lib.mkEnableOption "piano learning and music theory apps";
config = lib.mkIf config.my.apps.piano.enable {
users.users.jawz.packages = builtins.attrValues {
inherit (pkgs)
neothesia
linthesia
timidity
;
options.my.apps.piano = {
enable = lib.mkEnableOption "piano learning and music theory apps";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.apps;
description = "Users to install piano packages for";
};
};
config = lib.mkIf config.my.apps.piano.enable {
users.users =
let
packages = builtins.attrValues {
inherit (pkgs)
neothesia
linthesia
timidity
;
};
in
inputs.self.lib.mkUserPackages lib config.my.apps.piano.users packages;
};
}

View File

@@ -1,22 +1,34 @@
{
config,
inputs,
lib,
pkgs,
...
}:
{
options.my.apps.office.enable = lib.mkEnableOption "office applications and productivity tools";
config = lib.mkIf config.my.apps.office.enable {
environment.variables.CALIBRE_USE_SYSTEM_THEME = "1";
users.users.jawz.packages = builtins.attrValues {
inherit (pkgs)
jre17_minimal # for libreoffice extensions
libreoffice # office, but based & european
calibre # ugly af eBook library manager
newsflash # feed reader, syncs with nextcloud
furtherance # I packaged this one tehee track time utility
# planify # let's pretend I will organize my tasks
;
options.my.apps.office = {
enable = lib.mkEnableOption "office applications and productivity tools";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.apps;
description = "Users to install office packages for";
};
};
config = lib.mkIf config.my.apps.office.enable {
environment.variables.CALIBRE_USE_SYSTEM_THEME = "1";
users.users =
let
packages = builtins.attrValues {
inherit (pkgs)
jre17_minimal # for libreoffice extensions
libreoffice # office, but based & european
calibre # ugly af eBook library manager
newsflash # feed reader, syncs with nextcloud
furtherance # I packaged this one tehee track time utility
# planify # let's pretend I will organize my tasks
;
};
in
inputs.self.lib.mkUserPackages lib config.my.apps.office.users packages;
};
}

View File

@@ -1,5 +1,6 @@
{
config,
inputs,
lib,
pkgs,
...
@@ -17,7 +18,14 @@ let
in
{
options = {
my.dev.cc.enable = lib.mkEnableOption "Install C/C++ tooling globally";
my.dev.cc = {
enable = lib.mkEnableOption "Install C/C++ tooling globally";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.dev;
description = "Users to install C/C++ packages for";
};
};
devShells.cc = lib.mkOption {
type = lib.types.package;
default = pkgs.mkShell {
@@ -31,6 +39,6 @@ in
};
};
config = lib.mkIf config.my.dev.cc.enable {
users.users.jawz = { inherit packages; };
users.users = inputs.self.lib.mkUserAttrs lib config.my.dev.cc.users { inherit packages; };
};
}

View File

@@ -1,5 +1,6 @@
{
config,
inputs,
lib,
pkgs,
...
@@ -14,7 +15,14 @@ let
in
{
options = {
my.dev.docker.enable = lib.mkEnableOption "Install Docker tooling globally";
my.dev.docker = {
enable = lib.mkEnableOption "Install Docker tooling globally";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.dev;
description = "Users to install Docker packages for";
};
};
devShells.docker = lib.mkOption {
type = lib.types.package;
default = pkgs.mkShell {
@@ -29,7 +37,7 @@ in
};
config = lib.mkMerge [
(lib.mkIf config.my.dev.docker.enable {
users.users.jawz = { inherit packages; };
users.users = inputs.self.lib.mkUserAttrs lib config.my.dev.docker.users { inherit packages; };
})
{
environment.variables.DOCKER_CONFIG = "\${XDG_CONFIG_HOME}/docker";

View File

@@ -6,9 +6,16 @@
...
}:
{
options.my.emacs.enable = lib.mkEnableOption "Doom Emacs configuration";
options.my.emacs = {
enable = lib.mkEnableOption "Doom Emacs configuration";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.dev;
description = "Users to install Emacs packages for";
};
};
config = lib.mkIf config.my.emacs.enable {
home-manager.users.jawz = {
home-manager.users = inputs.self.lib.mkHomeManagerUsers lib config.my.emacs.users (_user: {
xdg.dataFile = {
"doom/templates/events.org".source = ../../dotfiles/doom/templates/events.org;
"doom/templates/default.org".source = ../../dotfiles/doom/templates/default.org;
@@ -21,41 +28,46 @@
edit = "emacsclient -t";
e = "edit";
};
};
users.users.jawz.packages = builtins.attrValues {
inherit (pkgs.xorg) xwininfo;
inherit (pkgs)
#emacs everywhere
xdotool
xclip
wl-clipboard-rs
fd # modern find, faster searches
fzf # fuzzy finder! super cool and useful
ripgrep # modern grep
tree-sitter # code parsing based on symbols and shit, I do not get it
graphviz # graphs
tetex # export pdf
languagetool # proofreader for English
# lsps
yaml-language-server
markdownlint-cli
;
inherit (pkgs.nodePackages)
vscode-json-languageserver
prettier # multi-language linter
;
};
});
users.users =
let
packages = builtins.attrValues {
inherit (pkgs.xorg) xwininfo;
inherit (pkgs)
#emacs everywhere
xdotool
xclip
wl-clipboard-rs
fd # modern find, faster searches
fzf # fuzzy finder! super cool and useful
ripgrep # modern grep
tree-sitter # code parsing based on symbols and shit, I do not get it
graphviz # graphs
tetex # export pdf
languagetool # proofreader for English
# lsps
yaml-language-server
markdownlint-cli
;
inherit (pkgs.nodePackages)
vscode-json-languageserver
prettier # multi-language linter
;
};
in
inputs.self.lib.mkUserPackages lib config.my.emacs.users packages;
services.emacs = {
enable = true;
defaultEditor = true;
package = pkgs.emacsWithDoom {
doomDir = ../../dotfiles/doom;
doomLocalDir = "/home/jawz/.local/share/nix-doom";
doomLocalDir = "/home/${inputs.self.lib.getFirstUser config.my.emacs.users}/.local/share/nix-doom";
tangleArgs = "--all config.org";
extraPackages =
epkgs:
let
inherit (config.home-manager.users.jawz.programs.emacs)
inherit
(config.home-manager.users.${inputs.self.lib.getFirstUser config.my.emacs.users}.programs.emacs)
extraPackages
extraConfig
;

View File

@@ -1,5 +1,6 @@
{
config,
inputs,
lib,
pkgs,
...
@@ -20,7 +21,14 @@ let
in
{
options = {
my.dev.go.enable = lib.mkEnableOption "Install Go tooling globally";
my.dev.go = {
enable = lib.mkEnableOption "Install Go tooling globally";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.dev;
description = "Users to install Go packages for";
};
};
devShells.go = lib.mkOption {
type = lib.types.package;
default = pkgs.mkShell {
@@ -38,7 +46,7 @@ in
environment.variables = { inherit GOPATH; };
}
(lib.mkIf config.my.dev.go.enable {
users.users.jawz = { inherit packages; };
users.users = inputs.self.lib.mkUserAttrs lib config.my.dev.go.users { inherit packages; };
})
];
}

View File

@@ -1,5 +1,6 @@
{
config,
inputs,
lib,
pkgs,
...
@@ -18,7 +19,14 @@ let
in
{
options = {
my.dev.haskell.enable = lib.mkEnableOption "Install Haskell tooling globally";
my.dev.haskell = {
enable = lib.mkEnableOption "Install Haskell tooling globally";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.dev;
description = "Users to install Haskell packages for";
};
};
devShells.haskell = lib.mkOption {
type = lib.types.package;
default = pkgs.mkShell {
@@ -33,7 +41,7 @@ in
};
config = lib.mkMerge [
(lib.mkIf config.my.dev.haskell.enable {
users.users.jawz = { inherit packages; };
users.users = inputs.self.lib.mkUserAttrs lib config.my.dev.haskell.users { inherit packages; };
})
{
environment.variables = {

View File

@@ -1,5 +1,6 @@
{
config,
inputs,
lib,
pkgs,
...
@@ -12,7 +13,14 @@ let
in
{
options = {
my.dev.javascript.enable = lib.mkEnableOption "Install JavaScript tooling globally";
my.dev.javascript = {
enable = lib.mkEnableOption "Install JavaScript tooling globally";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.dev;
description = "Users to install JavaScript packages for";
};
};
devShells.javascript = lib.mkOption {
type = lib.types.package;
default = pkgs.mkShell {
@@ -27,16 +35,18 @@ in
};
config = lib.mkMerge [
(lib.mkIf config.my.dev.javascript.enable {
users.users.jawz = { inherit packages; };
users.users = inputs.self.lib.mkUserAttrs lib config.my.dev.javascript.users { inherit packages; };
})
{
home-manager.users.jawz.xdg.configFile = {
"npm/npmrc".source = ../../dotfiles/npmrc;
"configstore/update-notifier-npm-check.json".text = builtins.toJSON {
optOut = false;
lastUpdateCheck = 1646662583446;
home-manager.users = inputs.self.lib.mkHomeManagerUsers lib config.my.dev.javascript.users (_user: {
xdg.configFile = {
"npm/npmrc".source = ../../dotfiles/npmrc;
"configstore/update-notifier-npm-check.json".text = builtins.toJSON {
optOut = false;
lastUpdateCheck = 1646662583446;
};
};
};
});
environment.variables = {
NPM_CONFIG_USERCONFIG = "\${XDG_CONFIG_HOME}/npm/npmrc";
PNPM_HOME = "\${XDG_DATA_HOME}/pnpm";

View File

@@ -1,5 +1,6 @@
{
config,
inputs,
lib,
pkgs,
...
@@ -11,7 +12,14 @@ let
in
{
options = {
my.dev.julia.enable = lib.mkEnableOption "Install Julia globally";
my.dev.julia = {
enable = lib.mkEnableOption "Install Julia globally";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.dev;
description = "Users to install Julia packages for";
};
};
devShells.julia = lib.mkOption {
type = lib.types.package;
default = pkgs.mkShell {
@@ -25,6 +33,6 @@ in
};
};
config = lib.mkIf config.my.dev.julia.enable {
users.users.jawz = { inherit packages; };
users.users = inputs.self.lib.mkUserAttrs lib config.my.dev.julia.users { inherit packages; };
};
}

40
modules/dev/mcp.nix Normal file
View File

@@ -0,0 +1,40 @@
{
config,
inputs,
lib,
pkgs,
...
}:
let
packages = [
pkgs.codex
inputs.self.packages.${pkgs.system}.nixos-mcp
];
in
{
options = {
my.dev.mcp = {
enable = lib.mkEnableOption "Install MCP tooling globally";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.dev;
description = "Users to install MCP packages for";
};
};
devShells.mcp = lib.mkOption {
type = lib.types.package;
description = "MCP dev shell for this repo";
default = pkgs.mkShell {
inherit packages;
name = "mcp-dev-shell";
shellHook = ''
export CODEX_HOME=$PWD/.codex
echo "MCP shell ready: codex + nixos-mcp"
'';
};
};
};
config = lib.mkIf config.my.dev.mcp.enable {
users.users = inputs.self.lib.mkUserAttrs lib config.my.dev.mcp.users { inherit packages; };
};
}

View File

@@ -19,7 +19,14 @@ let
in
{
options = {
my.dev.nix.enable = lib.mkEnableOption "Install Nix tooling globally";
my.dev.nix = {
enable = lib.mkEnableOption "Install Nix tooling globally";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.dev;
description = "Users to install Nix packages for";
};
};
devShells.nix = lib.mkOption {
type = lib.types.package;
default = pkgs.mkShell {
@@ -33,20 +40,20 @@ in
};
};
config = lib.mkIf config.my.dev.nix.enable {
users.users.jawz = { inherit packages; };
home-manager.users.jawz.programs.${shellType}.shellAliases =
inputs.self.lib.mergeAliases inputs.self.lib.commonAliases
{
nixformat = ''
deadnix -e && \
nix run nixpkgs#nixfmt-tree && \
statix fix
'';
nix-push-cache = ''
nix build $NH_FLAKE#nixosConfigurations.${config.networking.hostName}.config.system.build.toplevel \
--print-out-paths --fallback --max-jobs 100 --cores 0 |
nix run nixpkgs#attic-client -- push lan:nixos --stdin
'';
};
users.users = inputs.self.lib.mkUserAttrs lib config.my.dev.nix.users { inherit packages; };
home-manager.users = inputs.self.lib.mkHomeManagerUsers lib config.my.dev.nix.users (_user: {
programs.${shellType}.shellAliases = inputs.self.lib.mergeAliases inputs.self.lib.commonAliases {
nixformat = ''
deadnix -e && \
nix run nixpkgs#nixfmt-tree && \
statix fix
'';
nix-push-cache = ''
nix build $NH_FLAKE#nixosConfigurations.${config.networking.hostName}.config.system.build.toplevel \
--print-out-paths --fallback --max-jobs 100 --cores 0 |
nix run nixpkgs#attic-client -- push lan:nixos --stdin
'';
};
});
};
}

View File

@@ -1,5 +1,6 @@
{
config,
inputs,
lib,
pkgs,
...
@@ -30,7 +31,14 @@ let
in
{
options = {
my.dev.python.enable = lib.mkEnableOption "Install Python tools globally";
my.dev.python = {
enable = lib.mkEnableOption "Install Python tools globally";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.dev;
description = "Users to install Python packages for";
};
};
devShells.python = lib.mkOption {
type = lib.types.package;
default = pkgs.mkShell {
@@ -46,10 +54,12 @@ in
};
config = lib.mkMerge [
(lib.mkIf config.my.dev.python.enable {
users.users.jawz = { inherit packages; };
users.users = inputs.self.lib.mkUserAttrs lib config.my.dev.python.users { inherit packages; };
})
{
home-manager.users.jawz.xdg.configFile."python/pythonrc".source = ../../dotfiles/pythonrc;
home-manager.users = inputs.self.lib.mkHomeManagerUsers lib config.my.dev.python.users (_user: {
xdg.configFile."python/pythonrc".source = ../../dotfiles/pythonrc;
});
environment.variables.PYTHONSTARTUP = "\${XDG_CONFIG_HOME}/python/pythonrc";
}
];

View File

@@ -1,5 +1,6 @@
{
config,
inputs,
lib,
pkgs,
...
@@ -12,7 +13,14 @@ let
in
{
options = {
my.dev.ruby.enable = lib.mkEnableOption "Install Ruby tooling globally";
my.dev.ruby = {
enable = lib.mkEnableOption "Install Ruby tooling globally";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.dev;
description = "Users to install Ruby packages for";
};
};
devShells.ruby = lib.mkOption {
type = lib.types.package;
default = pkgs.mkShell {
@@ -27,7 +35,7 @@ in
};
config = lib.mkMerge [
(lib.mkIf config.my.dev.ruby.enable {
users.users.jawz = { inherit packages; };
users.users = inputs.self.lib.mkUserAttrs lib config.my.dev.ruby.users { inherit packages; };
})
{
environment.variables = {

View File

@@ -1,5 +1,6 @@
{
config,
inputs,
lib,
pkgs,
...
@@ -17,7 +18,14 @@ let
in
{
options = {
my.dev.rust.enable = lib.mkEnableOption "Install Rust tooling globally";
my.dev.rust = {
enable = lib.mkEnableOption "Install Rust tooling globally";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.dev;
description = "Users to install Rust packages for";
};
};
devShells.rust = lib.mkOption {
type = lib.types.package;
default = pkgs.mkShell {
@@ -32,7 +40,7 @@ in
};
config = lib.mkMerge [
(lib.mkIf config.my.dev.rust.enable {
users.users.jawz = { inherit packages; };
users.users = inputs.self.lib.mkUserAttrs lib config.my.dev.rust.users { inherit packages; };
})
{
environment.variables.CARGO_HOME = "\${XDG_DATA_HOME}/cargo";

View File

@@ -1,5 +1,6 @@
{
config,
inputs,
lib,
pkgs,
...
@@ -16,7 +17,14 @@ let
in
{
options = {
my.dev.sh.enable = lib.mkEnableOption "Install shell scripting tools globally";
my.dev.sh = {
enable = lib.mkEnableOption "Install shell scripting tools globally";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.dev;
description = "Users to install shell scripting packages for";
};
};
devShells.sh = lib.mkOption {
type = lib.types.package;
default = pkgs.mkShell {
@@ -30,6 +38,6 @@ in
};
};
config = lib.mkIf config.my.dev.sh.enable {
users.users.jawz = { inherit packages; };
users.users = inputs.self.lib.mkUserAttrs lib config.my.dev.sh.users { inherit packages; };
};
}

View File

@@ -1,5 +1,6 @@
{
config,
inputs,
lib,
pkgs,
...
@@ -14,7 +15,14 @@ let
in
{
options = {
my.dev.zig.enable = lib.mkEnableOption "Install Zig tooling globally";
my.dev.zig = {
enable = lib.mkEnableOption "Install Zig tooling globally";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.dev;
description = "Users to install Zig packages for";
};
};
devShells.zig = lib.mkOption {
type = lib.types.package;
default = pkgs.mkShell {
@@ -28,6 +36,6 @@ in
};
};
config = lib.mkIf config.my.dev.zig.enable {
users.users.jawz = { inherit packages; };
users.users = inputs.self.lib.mkUserAttrs lib config.my.dev.zig.users { inherit packages; };
};
}

View File

@@ -1,5 +1,6 @@
{
config,
inputs,
lib,
pkgs,
...
@@ -12,6 +13,11 @@
enable = lib.mkEnableOption "Whether to enable this script";
install = lib.mkEnableOption "Whether to install the script package";
service = lib.mkEnableOption "Whether to enable the script service";
users = lib.mkOption {
type = inputs.self.lib.usersOptionType lib;
default = config.my.toggleUsers.scripts;
description = "Users to install this script for";
};
name = lib.mkOption {
type = lib.types.str;
description = "Name of the script.";
@@ -36,10 +42,29 @@
description = "Configuration for multiple scripts.";
};
config = lib.mkIf (lib.any (s: s.enable) (lib.attrValues config.my.scripts)) {
users.users.jawz.packages =
config.my.scripts
|> lib.mapAttrsToList (_name: script: lib.optional (script.enable && script.install) script.package)
|> lib.flatten;
users.users =
let
scriptList =
config.my.scripts
|> lib.mapAttrsToList (_name: script: lib.optional (script.enable && script.install) script)
|> lib.flatten;
userMap = lib.foldl' (
acc: script:
let
users = inputs.self.lib.normalizeUsers script.users;
in
lib.foldl' (
acc': user:
acc'
// {
${user} = (acc'.${user} or [ ]) ++ [ script.package ];
}
) acc users
) { } scriptList;
in
lib.mkMerge (
lib.mapAttrsToList (user: packages: inputs.self.lib.mkUserPackages lib user packages) userMap
);
systemd.user.services =
config.my.scripts
|> lib.mapAttrs' (

View File

@@ -48,6 +48,10 @@ let
type = lib.types.bool;
default = false;
};
useDefaultProxy = lib.mkOption {
type = lib.types.bool;
default = true;
};
certPath = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;

View File

@@ -49,11 +49,19 @@ in
server = "192.168.100.15";
miniserver = "192.168.1.100";
workstation = "192.168.100.18";
vps = "45.79.25.87";
vps = "45.33.0.228";
wg-s = "10.77.0.0";
wg-vps = "10.77.0.1";
wg-server = "10.77.0.2";
wg-friend1 = "10.8.0.2";
wg-gs = "10.9.0.0";
wg-g0 = "10.9.0.1";
wg-g1 = "10.9.0.2";
wg-friends = "10.8.0.0";
wg-friend0 = "10.8.0.1";
wg-friend1 = "10.8.0.2";
wg-friend2 = "10.8.0.3";
wg-friend3 = "10.8.0.4";
wg-friend4 = "10.8.0.5";
};
description = "Set of IP's for all my computers.";
};
@@ -63,12 +71,13 @@ in
server = "enp0s31f6";
miniserver = "enp2s0";
workstation = "enp5s0";
vps = "eth0";
};
description = "Set of network interface names for all my computers.";
};
mainServer = lib.mkOption {
type = lib.types.str;
default = "miniserver";
default = "vps";
description = "The hostname of the main server.";
};
postgresSocket = lib.mkOption {
@@ -103,6 +112,31 @@ in
};
enableContainers = lib.mkEnableOption "container services (Docker/Podman)";
enableProxy = lib.mkEnableOption "nginx reverse proxy for services";
toggleUsers = lib.mkOption {
type = lib.types.attrsOf (lib.types.either lib.types.str (lib.types.listOf lib.types.str));
default = {
apps = "jawz";
dev = "jawz";
shell = "jawz";
scripts = "jawz";
services = "jawz";
stylix = "jawz";
};
description = "Map toggle categories to users. Can be a single user (string) or multiple users (list). Determines which user(s) get packages from each toggle category.";
example = {
apps = "jawz";
dev = "bearded_dragonn";
shell = "jawz";
gaming = [
"jawz"
"bearded_dragonn"
];
stylix = [
"jawz"
"bearded_dragonn"
];
};
};
};
config = {
assertions =

View File

@@ -5,44 +5,24 @@
...
}:
let
proxyReverseServices = [
"firefox-syncserver"
"isso"
"plausible"
"readeck"
"microbin"
"ryot"
"bazarr"
"shiori"
"metube"
"maloja"
"vaultwarden"
"mealie"
"kavita"
"multi-scrobbler"
"nix-serve"
"flame"
"flameSecret"
];
proxyReverseFixServices = [
"atticd"
"audiobookshelf"
"lidarr"
"gitea"
"prowlarr"
"lidarr"
"ombi"
"radarr"
"sonarr"
"stash"
"atticd"
];
proxyReversePrivateServices = [
"homepage"
"prowlarr"
"stash"
];
mkServiceConfig =
type: services: lib.listToAttrs (map (name: lib.nameValuePair name { inherit type; }) services);
standardProxyServices =
(mkServiceConfig "proxyReverse" proxyReverseServices)
// (mkServiceConfig "proxyReverseFix" proxyReverseFixServices)
(mkServiceConfig "proxyReverseFix" proxyReverseFixServices)
// (mkServiceConfig "proxyReversePrivate" proxyReversePrivateServices);
generateProxyConfig =
serviceName: serviceConfig:
@@ -59,9 +39,21 @@ let
throw "Unknown proxy type: ${serviceConfig.type}";
in
lib.nameValuePair cfg.host (lib.mkIf cfg.enableProxy (proxyFunc cfg));
standardProxyNames = builtins.attrNames standardProxyServices;
customProxyServices =
config.my.servers
|> lib.filterAttrs (
name: srv:
(srv.enableProxy or false)
&& (srv.useDefaultProxy or true)
&& !(builtins.elem name standardProxyNames)
)
|> lib.mapAttrs (_name: _srv: { type = "proxyReverse"; });
in
{
config = lib.mkIf config.my.enableProxy {
services.nginx.virtualHosts = lib.mapAttrs' generateProxyConfig standardProxyServices;
services.nginx.virtualHosts = lib.mapAttrs' generateProxyConfig (
standardProxyServices // customProxyServices
);
};
}

View File

@@ -6,11 +6,15 @@
}:
let
cfg = config.my.servers.gitea;
id = 969;
gid = id;
uid = id;
in
{
config = lib.mkIf (cfg.enable && config.my.secureHost) {
users.groups.gitea-runner = { };
users.groups.gitea-runner = { inherit gid; };
users.users.gitea-runner = {
inherit uid;
isSystemUser = true;
group = "gitea-runner";
extraGroups = [

View File

@@ -11,8 +11,10 @@
cloudflare-api.sopsFile = ../../secrets/env.yaml;
dns = {
sopsFile = ../../secrets/env.yaml;
owner = config.users.users.jawz.name;
inherit (config.users.users.jawz) group;
owner = config.users.users.${inputs.self.lib.getFirstUser config.my.scripts.update-dns.users}.name;
inherit (config.users.users.${inputs.self.lib.getFirstUser config.my.scripts.update-dns.users})
group
;
};
};
services.cloudflare-dyndns = {

View File

@@ -11,6 +11,11 @@ in
options.my.servers.audiobookshelf = setup.mkOptions "audiobookshelf" "audiobooks" 5687;
config = lib.mkIf (cfg.enable && config.my.secureHost) {
my.servers.audiobookshelf.enableSocket = true;
users.users.audiobookshelf = {
uid = 978;
group = "piracy";
isSystemUser = true;
};
services.audiobookshelf = {
inherit (cfg) enable port;
host = cfg.ip;

View File

@@ -6,11 +6,19 @@
let
setup = import ../factories/mkserver.nix { inherit lib config; };
cfg = config.my.servers.bazarr;
uid = 985;
in
{
options.my.servers.bazarr = setup.mkOptions "bazarr" "subs" config.services.bazarr.listenPort;
config.services.bazarr = lib.mkIf cfg.enable {
inherit (cfg) enable;
group = "piracy";
config = lib.mkIf cfg.enable {
users.users.bazarr = {
inherit uid;
group = "piracy";
isSystemUser = true;
};
services.bazarr = {
inherit (cfg) enable;
group = "piracy";
};
};
}

Some files were not shown because too many files have changed in this diff Show More