auto-context-cli 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
auto_context/config.py ADDED
@@ -0,0 +1,65 @@
1
+ """
2
+ config.py — Global path constants and runtime configuration.
3
+
4
+ All path logic is centralised here so every other module can import
5
+ a single named constant rather than re-computing home directories.
6
+ """
7
+ import importlib.resources as _pkg_resources
8
+ from pathlib import Path
9
+
10
+
11
+ def get_templates_dir() -> Path:
12
+ """
13
+ Return the templates directory in a way that works both during development
14
+ (uv run / editable install) and after a wheel install (uv tool install .).
15
+
16
+ importlib.resources.files() is the PEP 451-compliant way to locate data
17
+ files that are bundled inside a Python package, regardless of whether the
18
+ package is installed as a wheel, a zip, or an editable source tree.
19
+ """
20
+ try:
21
+ # Python 3.9+ path — works in wheel and editable installs
22
+ ref = _pkg_resources.files("auto_context").joinpath("templates")
23
+ # Materialise to a real Path so callers can use glob(), iterdir(), etc.
24
+ with _pkg_resources.as_file(ref) as p:
25
+ return p
26
+ except Exception:
27
+ # Hard fallback: source-tree layout (should never be reached in practice)
28
+ return Path(__file__).parent / "templates"
29
+
30
+
31
+ # ── User home-relative roots ───────────────────────────────────────────────────
32
+ HOME = Path.home()
33
+
34
+ # Central memory brain (~/.auto-context/memory)
35
+ MEMORY_DIR: Path = HOME / ".auto-context" / "memory"
36
+
37
+ # Global plugin scope consumed by Antigravity / Gemini CLI
38
+ GLOBAL_PLUGIN_DIR: Path = HOME / ".gemini" / "config" / "plugins" / "auto-context"
39
+ GLOBAL_GEMINI_DIR: Path = HOME / ".gemini" / "config"
40
+
41
+ # Subdirectory conventions (relative to any project or plugin root)
42
+ RULES_SUBDIR = "rules"
43
+ SKILLS_SUBDIR = "skills"
44
+ AGENTS_SUBDIR = ".agents"
45
+ GEMINI_SUBDIR = ".gemini"
46
+
47
+ # ── Stack detection: indicator files → (stack_label, framework_hint_key) ──────
48
+ STACK_INDICATORS: list[tuple[str, str, str]] = [
49
+ # (filename, stack_label, framework_key_for_content_scan)
50
+ ("package.json", "Node.js / JavaScript / TypeScript", "js"),
51
+ ("pyproject.toml", "Python", "py"),
52
+ ("requirements.txt", "Python", "py"),
53
+ ("Pipfile", "Python", "py"),
54
+ ("go.mod", "Go (Golang)", "go"),
55
+ ("Cargo.toml", "Rust", "rust"),
56
+ ("pom.xml", "Java / Kotlin", "jvm"),
57
+ ("build.gradle", "Java / Kotlin", "jvm"),
58
+ ("docker-compose.yml", "Dockerized Container", "docker"),
59
+ ("Dockerfile", "Dockerized Container", "docker"),
60
+ ]
61
+
62
+ # ── Git commit message templates ───────────────────────────────────────────────
63
+ GIT_COMMIT_INIT = "feat(memory): initialize central agent brain knowledge base"
64
+ GIT_COMMIT_SYNC = "chore(memory): sync agent brain knowledge base"
65
+
auto_context/main.py ADDED
@@ -0,0 +1,121 @@
1
+ """
2
+ main.py — Root Typer app and CLI entrypoint.
3
+
4
+ Supports both modern subcommands (rule, skill, mcp, memory, share, import)
5
+ and legacy flag compatibility (-r, -s, --add-mcp, --list-mcp, --remove-mcp).
6
+ """
7
+ from importlib.metadata import version as pkg_version
8
+ from pathlib import Path
9
+ from typing import Annotated, Optional
10
+
11
+ import typer
12
+ from rich.console import Console
13
+
14
+ from auto_context.commands import init_cmd, memory, mcp, share, import_cmd
15
+
16
+ app = typer.Typer(
17
+ name="init-context",
18
+ help="Autonomous context & instruction manager for AI coding assistants.",
19
+ no_args_is_help=False,
20
+ add_completion=False,
21
+ )
22
+ console = Console()
23
+
24
+ # ── Sub-routers ────────────────────────────────────────────────────────────────
25
+ app.add_typer(memory.app, name="memory", help="Central memory brain management.")
26
+ app.add_typer(mcp.app, name="mcp", help="MCP tool registry management.")
27
+
28
+ # ── Inline subcommands ────────────────────────────────────────────────────────
29
+ app.command("init")(init_cmd.init)
30
+ app.command("rule")(init_cmd.new_rule)
31
+ app.command("skill")(init_cmd.new_skill)
32
+ app.command("share")(share.share)
33
+ app.command("import")(import_cmd.import_item)
34
+
35
+
36
+ @app.callback(invoke_without_command=True)
37
+ def root(
38
+ ctx: typer.Context,
39
+ target: Annotated[Optional[Path], typer.Option("--target", "-t", help="Target project directory.")] = None,
40
+ new_rule: Annotated[Optional[str], typer.Option("--new-rule", "-r", help="Scaffold a new agent rule.")] = None,
41
+ new_skill: Annotated[Optional[str], typer.Option("--new-skill", "-s", help="Scaffold a new agent skill.")] = None,
42
+ add_mcp: Annotated[Optional[str], typer.Option("--add-mcp", help="Add or update an MCP server.")] = None,
43
+ remove_mcp: Annotated[Optional[str], typer.Option("--remove-mcp", help="Remove an MCP server.")] = None,
44
+ list_mcp: Annotated[bool, typer.Option("--list-mcp", help="List registered MCP servers.")] = False,
45
+ preset: Annotated[Optional[str], typer.Option("--preset", "-p", help="MCP preset name.")] = None,
46
+ runtime: Annotated[Optional[str], typer.Option("--runtime", "--runner", help="Package runner (uvx vs npx).")] = None,
47
+ command: Annotated[Optional[str], typer.Option("--command", "-c", help="Executable command for MCP server.")] = None,
48
+ args: Annotated[Optional[str], typer.Option("--args", "-a", help="Arguments to pass to MCP command.")] = None,
49
+ url: Annotated[Optional[str], typer.Option("--url", help="HTTP endpoint URL for remote MCP server.")] = None,
50
+ env_var: Annotated[Optional[str], typer.Option("--env-var", help="Secret environment variable name.")] = None,
51
+ env: Annotated[Optional[str], typer.Option("--env", help="Environment variables (KEY=val,KEY2=val2).")] = None,
52
+ global_: Annotated[bool, typer.Option("--global", "-g", help="Target global plugin scope.")] = False,
53
+ force: Annotated[bool, typer.Option("--force", "-f", help="Overwrite existing files.")] = False,
54
+ dry_run: Annotated[bool, typer.Option("--dry-run", "-d", help="Preview without writing.")] = False,
55
+ version: bool = typer.Option(False, "--version", "-v", help="Show version and exit."),
56
+ ) -> None:
57
+ """
58
+ Run without a subcommand to scaffold project context, or use flags for
59
+ rules (-r), skills (-s), MCP (--add-mcp), and options.
60
+ """
61
+ if version:
62
+ try:
63
+ v = pkg_version("auto-context-cli")
64
+ except Exception:
65
+ try:
66
+ v = pkg_version("auto-context")
67
+ except Exception:
68
+ v = "1.0.0"
69
+ console.print(f"init-context v{v}")
70
+ raise typer.Exit()
71
+
72
+ if ctx.invoked_subcommand is not None:
73
+ return
74
+
75
+ # ── Legacy flag routing ────────────────────────────────────────────────────
76
+ if new_rule:
77
+ init_cmd.new_rule(name=new_rule, target=target, global_=global_, force=force, dry_run=dry_run)
78
+ return
79
+
80
+ if new_skill:
81
+ init_cmd.new_skill(name=new_skill, target=target, global_=global_, force=force, dry_run=dry_run)
82
+ return
83
+
84
+ if list_mcp:
85
+ mcp.list_mcp(target=target, global_=global_)
86
+ return
87
+
88
+ if remove_mcp:
89
+ mcp.remove_mcp(name=remove_mcp, target=target, global_=global_)
90
+ return
91
+
92
+ if add_mcp:
93
+ mcp.add_mcp(
94
+ name=add_mcp,
95
+ target=target,
96
+ global_=global_,
97
+ preset=preset,
98
+ runtime=runtime,
99
+ command=command,
100
+ args=args,
101
+ url=url,
102
+ env_var=env_var,
103
+ env=env,
104
+ )
105
+ return
106
+
107
+ # Default action: scaffold workspace
108
+ init_cmd.init(target=target, force=force, dry_run=dry_run)
109
+
110
+
111
+ def main() -> None: # pragma: no cover
112
+ import os, sys
113
+ # Ensure UTF-8 output on all platforms (Windows CP1252 fix)
114
+ if sys.platform == "win32":
115
+ os.environ.setdefault("PYTHONIOENCODING", "utf-8")
116
+ try:
117
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]
118
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]
119
+ except AttributeError:
120
+ pass
121
+ app()
@@ -0,0 +1,162 @@
1
+ """
2
+ security.py — Zero-bypass secret scanner and key auditor.
3
+
4
+ Pure-Python port of the PowerShell Test-SecretSafety function.
5
+ Uses rich for coloured terminal output instead of raw ANSI codes.
6
+
7
+ Public API:
8
+ audit_path(path, single_file=False) -> list[Violation]
9
+ print_report(violations) -> None (prints via rich)
10
+ abort_if_violations(violations) -> None (sys.exit(1) on findings)
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ import sys
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+
19
+ from rich.console import Console
20
+ from rich.text import Text
21
+
22
+ console = Console(stderr=True)
23
+
24
+ # ── Prohibited filenames & extensions ────────────────────────────────────────
25
+ PROHIBITED_FILES: frozenset[str] = frozenset({
26
+ ".env", ".env.local", ".env.production", ".env.development",
27
+ ".env.test", ".env.staging", "id_rsa", "id_rsa.pub",
28
+ "id_ed25519", "id_ed25519.pub", "id_ecdsa", "id_ecdsa.pub",
29
+ "id_dsa", "id_dsa.pub", "authorized_keys", "known_hosts",
30
+ })
31
+
32
+ PROHIBITED_EXTENSIONS: frozenset[str] = frozenset({
33
+ ".pem", ".key", ".pkcs12", ".p12", ".pfx", ".kdbx",
34
+ })
35
+
36
+ # ── Secret patterns (name → compiled regex) ──────────────────────────────────
37
+ _RAW_PATTERNS: list[tuple[str, str]] = [
38
+ ("GitHub Token", r"(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,}"),
39
+ ("GitHub Fine-grained PAT", r"github_pat_[A-Za-z0-9_]{50,}"),
40
+ ("Stripe Live Key", r"sk_live_[0-9a-zA-Z]{24,}"),
41
+ ("OpenAI API Key", r"sk-[a-zA-Z0-9_\-]{32,}"),
42
+ ("Anthropic API Key", r"sk-ant-[a-zA-Z0-9_\-]{32,}"),
43
+ ("OpenAI Project Key", r"sk-proj-[a-zA-Z0-9_\-]{40,}"),
44
+ ("Google API Key", r"AIza[0-9A-Za-z\-_]{35}"),
45
+ ("AWS Access Key ID", r"AKIA[0-9A-Z]{16}"),
46
+ ("Private Key Block", r"-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----"),
47
+ ("Hardcoded Secret/Password",
48
+ r'(?i)(?:password|secret|api[_-]?key|access[_-]?token)\s*[:=]\s*[\'"]'
49
+ r'(?!(?:YOUR_|REPLACE_|MOCK_|TEST_|DUMMY_|\{\{|<))'
50
+ r'[A-Za-z0-9_\-\.\$\!\@\#\%\^\&\*\(\)\+]{8,}[\'"]'),
51
+ ]
52
+
53
+ PATTERNS: list[tuple[str, re.Pattern[str]]] = [
54
+ (name, re.compile(pattern)) for name, pattern in _RAW_PATTERNS
55
+ ]
56
+
57
+
58
+ @dataclass(slots=True)
59
+ class Violation:
60
+ """A single security finding."""
61
+ file: Path
62
+ line: int # 0 = filename-level violation
63
+ pattern: str
64
+ preview: str # masked token preview
65
+
66
+
67
+ # ── Core scanner ─────────────────────────────────────────────────────────────
68
+
69
+ def _mask(token: str) -> str:
70
+ """Return a partially-masked token for safe display."""
71
+ if len(token) <= 8:
72
+ return "****"
73
+ return token[:4] + "*" * (len(token) - 8) + token[-4:]
74
+
75
+
76
+ def _scan_file(path: Path) -> list[Violation]:
77
+ """Return violations found in a single file."""
78
+ violations: list[Violation] = []
79
+ name = path.name
80
+ suffix = path.suffix.lower()
81
+
82
+ # Filename-level checks
83
+ if name in PROHIBITED_FILES or name.startswith(".env."):
84
+ return [Violation(path, 0, "Prohibited Sensitive File", name)]
85
+ if suffix in PROHIBITED_EXTENSIONS:
86
+ return [Violation(path, 0, "Prohibited Key/Certificate Extension", name)]
87
+
88
+ # Content scan (skip binary-looking files gracefully)
89
+ try:
90
+ lines = path.read_text(encoding="utf-8", errors="ignore").splitlines()
91
+ except OSError:
92
+ return violations
93
+
94
+ for lineno, line in enumerate(lines, start=1):
95
+ for pattern_name, regex in PATTERNS:
96
+ m = regex.search(line)
97
+ if m:
98
+ violations.append(Violation(path, lineno, pattern_name, _mask(m.group())))
99
+ break # one finding per line is enough
100
+
101
+ return violations
102
+
103
+
104
+ def audit_path(path: Path, *, single_file: bool = False) -> list[Violation]:
105
+ """
106
+ Scan *path* for secrets and prohibited files.
107
+
108
+ Args:
109
+ path: File or directory to scan.
110
+ single_file: When True, treat *path* as a single file even if it is
111
+ a directory (mirrors the original -Mode "File" flag).
112
+
113
+ Returns:
114
+ List of Violation objects (empty = clean).
115
+ """
116
+ violations: list[Violation] = []
117
+
118
+ if single_file or path.is_file():
119
+ if path.exists():
120
+ violations.extend(_scan_file(path))
121
+ else:
122
+ for child in path.rglob("*"):
123
+ # Skip .git internals
124
+ if ".git" in child.parts:
125
+ continue
126
+ if child.is_file():
127
+ violations.extend(_scan_file(child))
128
+
129
+ return violations
130
+
131
+
132
+ # ── Rich reporter ─────────────────────────────────────────────────────────────
133
+
134
+ def print_report(violations: list[Violation]) -> None:
135
+ """Print a rich-formatted security report to stderr."""
136
+ if not violations:
137
+ console.print("[bold green][✓] Security Audit Passed:[/] 0 sensitive credentials detected.")
138
+ return
139
+
140
+ console.print(
141
+ f"\n[bold red][✗] SECURITY AUDIT VIOLATION — {len(violations)} finding(s):[/]"
142
+ )
143
+ for v in violations:
144
+ loc = f"Line {v.line}" if v.line > 0 else "Filename"
145
+ line = Text()
146
+ line.append(" • ", style="yellow")
147
+ line.append(str(v.file), style="cyan")
148
+ line.append(f" [{loc}]: ", style="white")
149
+ line.append(v.pattern, style="bold red")
150
+ line.append(f" (preview: {v.preview})", style="dim")
151
+ console.print(line)
152
+
153
+
154
+ def abort_if_violations(violations: list[Violation]) -> None:
155
+ """Print the report and exit with code 1 if any violations exist."""
156
+ print_report(violations)
157
+ if violations:
158
+ console.print(
159
+ "\n[bold red][✗] ABORT:[/] Remove credentials before committing or sharing.\n"
160
+ )
161
+ sys.exit(1)
162
+
@@ -0,0 +1,49 @@
1
+ # Standing Agent Rules for {{PROJECT_NAME}}
2
+
3
+ ## Critical Mandate: Autonomous `context.md` Synchronization & Self-Evolution
4
+ As an AI coding assistant working in this repository (`{{PROJECT_DIR}}`), you are **strictly mandated** to keep `{{PROJECT_DIR}}/context.md` continuously up to date and autonomously learn, persist, and crystallize new rules and skills. The user must **never** need to remind or instruct you.
5
+
6
+ ### 1. Mandatory Post-Action Protocol
7
+ Whenever ANY of the following events occur in any session or conversation turn:
8
+ - A configuration file or script is created, edited, moved, or deleted.
9
+ - A problem, bug, or error is encountered and diagnosed.
10
+ - Credentials, tokens, user accounts, or security keys are generated or updated.
11
+ - Architectural decisions or operational steps are modified.
12
+
13
+ **You MUST immediately update `{{PROJECT_DIR}}/context.md` before finalizing your response.**
14
+
15
+ ### 2. Autonomous Learning & Self-Evolution Protocol
16
+ Whenever you learn a new pattern, receive a correction, observe a coding preference, or resolve a complex repeatable problem:
17
+ 1. **Identify the Type:**
18
+ - **Rule:** If it is a constraint, coding standard, safety boundary, or architectural preference -> Create a Rule (`init-context -r <name>`).
19
+ - **Skill:** If it is a multi-step procedure, deployment workflow, diagnosis runbook, or CLI sequence -> Create a Skill (`init-context -s <name>`).
20
+ 2. **Scope Decision:**
21
+ - **Project-Specific:** Save in `.agents/rules/` or `.agents/skills/`.
22
+ - **Machine-Wide / Global:** If it applies to all projects, use `--global` (`-g`) to register in `~/.gemini/config/plugins/auto-context/`.
23
+ 3. **Execution:**
24
+ - Use the `init-context` CLI tool to scaffold the file.
25
+ - Populate it with clear objectives, constraints, or step-by-step instructions.
26
+ - Inform the user of the new rule or skill codified.
27
+
28
+ ### 3. Tool Access: `init-context`
29
+ You have native access to run `init-context` via terminal commands:
30
+ - `init-context`: Scaffolds or repairs project context.
31
+ - `init-context -r <rule-name> [-g]`: Creates a new rule with frontmatter.
32
+ - `init-context -s <skill-name> [-g]`: Creates a new skill with frontmatter.
33
+
34
+ ### 4. Required Content & Structure in `context.md`
35
+ 1. **Master Credentials & Configuration Vault (Section 1):** Keep all ports, IPs, secrets, tokens, and endpoints synchronized.
36
+ 2. **Chronological Problem Log & Technical Solutions (Section 2):** Document symptom, root cause, exact commands/code used, and update Mermaid diagram.
37
+ 3. **Architecture & Component Layout (Section 3):** Keep stack overview and directory maps accurate.
38
+ 4. **Operations Runbook (Section 4):** Ensure 1-step reproduction instructions remain functional.
39
+
40
+ ### 5. Local Sandbox Credentials & Dummy Test Fixtures (`context.local.md`)
41
+ - **Inspection Mandate:** When testing local dev servers, performing browser automation (Playwright/Puppeteer), or authenticating API endpoints, ALWAYS read `context.local.md` first before prompting the user for credentials.
42
+ - **Strict Mock Boundary:** ONLY store dummy test credentials, mock accounts (`admin@test.local`), seed users, and local dev ports in `context.local.md`.
43
+ - **Zero Real Secrets:** Real production secrets, payment keys, or personal tokens MUST NEVER be stored in `context.local.md` or `context.md`; reference them via `.env` or system environment variables.
44
+ - **Git Protection:** Ensure `context.local.md` remains strictly ignored by Git (`.gitignore`) and protected with `chmod 600`.
45
+
46
+ ### 6. Two-Tier Progressive Disclosure Protocol (Token Optimization)
47
+ - **Initial Boot Budget:** NEVER read full `SKILL.md` files into the initial context. Use Section 5 of `context.md` for lightweight routing (< 800 tokens).
48
+ - **Dynamic On-Demand Loading:** Only when a user prompt matches a skill's triggers (e.g. "docker", "rebase", "diagnostics", "browser"), dynamically inspect the file using `read_file`.
49
+ - **Zero Session Bloat:** Once the task concludes, do not keep the full skill body in persistent memory.
@@ -0,0 +1,49 @@
1
+ # Standing Agent Rules for {{PROJECT_NAME}}
2
+
3
+ ## Critical Mandate: Autonomous `context.md` Synchronization & Self-Evolution
4
+ As an AI coding assistant working in this repository (`{{PROJECT_DIR}}`), you are **strictly mandated** to keep `{{PROJECT_DIR}}/context.md` continuously up to date and autonomously learn, persist, and crystallize new rules and skills. The user must **never** need to remind or instruct you.
5
+
6
+ ### 1. Mandatory Post-Action Protocol
7
+ Whenever ANY of the following events occur in any session or conversation turn:
8
+ - A configuration file or script is created, edited, moved, or deleted.
9
+ - A problem, bug, or error is encountered and diagnosed.
10
+ - Credentials, tokens, user accounts, or security keys are generated or updated.
11
+ - Architectural decisions or operational steps are modified.
12
+
13
+ **You MUST immediately update `{{PROJECT_DIR}}/context.md` before finalizing your response.**
14
+
15
+ ### 2. Autonomous Learning & Self-Evolution Protocol
16
+ Whenever you learn a new pattern, receive a correction, observe a coding preference, or resolve a complex repeatable problem:
17
+ 1. **Identify the Type:**
18
+ - **Rule:** If it is a constraint, coding standard, safety boundary, or architectural preference -> Create a Rule (`init-context -r <name>`).
19
+ - **Skill:** If it is a multi-step procedure, deployment workflow, diagnosis runbook, or CLI sequence -> Create a Skill (`init-context -s <name>`).
20
+ 2. **Scope Decision:**
21
+ - **Project-Specific:** Save in `.agents/rules/` or `.agents/skills/`.
22
+ - **Machine-Wide / Global:** If it applies to all projects, use `--global` (`-g`) to register in `~/.gemini/config/plugins/auto-context/`.
23
+ 3. **Execution:**
24
+ - Use the `init-context` CLI tool to scaffold the file.
25
+ - Populate it with clear objectives, constraints, or step-by-step instructions.
26
+ - Inform the user of the new rule or skill codified.
27
+
28
+ ### 3. Tool Access: `init-context`
29
+ You have native access to run `init-context` via terminal commands:
30
+ - `init-context`: Scaffolds or repairs project context.
31
+ - `init-context -r <rule-name> [-g]`: Creates a new rule with frontmatter.
32
+ - `init-context -s <skill-name> [-g]`: Creates a new skill with frontmatter.
33
+
34
+ ### 4. Required Content & Structure in `context.md`
35
+ 1. **Master Credentials & Configuration Vault (Section 1):** Keep all ports, IPs, secrets, tokens, and endpoints synchronized.
36
+ 2. **Chronological Problem Log & Technical Solutions (Section 2):** Document symptom, root cause, exact commands/code used, and update Mermaid diagram.
37
+ 3. **Architecture & Component Layout (Section 3):** Keep stack overview and directory maps accurate.
38
+ 4. **Operations Runbook (Section 4):** Ensure 1-step reproduction instructions remain functional.
39
+
40
+ ### 5. Local Sandbox Credentials & Dummy Test Fixtures (`context.local.md`)
41
+ - **Inspection Mandate:** When testing local dev servers, performing browser automation (Playwright/Puppeteer), or authenticating API endpoints, ALWAYS read `context.local.md` first before prompting the user for credentials.
42
+ - **Strict Mock Boundary:** ONLY store dummy test credentials, mock accounts (`admin@test.local`), seed users, and local dev ports in `context.local.md`.
43
+ - **Zero Real Secrets:** Real production secrets, payment keys, or personal tokens MUST NEVER be stored in `context.local.md` or `context.md`; reference them via `.env` or system environment variables.
44
+ - **Git Protection:** Ensure `context.local.md` remains strictly ignored by Git (`.gitignore`) and protected with `chmod 600`.
45
+
46
+ ### 6. Two-Tier Progressive Disclosure Protocol (Token Optimization)
47
+ - **Initial Boot Budget:** NEVER read full `SKILL.md` files into the initial context. Use Section 5 of `context.md` for lightweight routing (< 800 tokens).
48
+ - **Dynamic On-Demand Loading:** Only when a user prompt matches a skill's triggers (e.g. "docker", "rebase", "diagnostics", "browser"), dynamically inspect the file using `read_file`.
49
+ - **Zero Session Bloat:** Once the task concludes, do not keep the full skill body in persistent memory.
@@ -0,0 +1,52 @@
1
+ # ⚠️ LOCAL SANDBOX & DUMMY TEST FIXTURES ONLY
2
+ # ==============================================================================
3
+ # SECURITY GUARDRAIL:
4
+ # DO NOT STORE REAL PRODUCTION SECRETS, PAYMENT KEYS, OR LIVE PASSWORDS HERE.
5
+ # This file is strictly for mock logins, seed users, localhost ports, and dev test data.
6
+ # Real secrets MUST stay in .env (protected by system environment variables).
7
+ #
8
+ # GIT STATUS: STRICTLY GIT-IGNORED (*.local.md, context.local.md)
9
+ # FILE PERMISSIONS: chmod 600
10
+ # ==============================================================================
11
+
12
+ > **Project:** `{{PROJECT_NAME}}`
13
+ > **Purpose:** Local mock credentials & test logins for AI browser testing and dev automation.
14
+ > **Notice to AI Assistant:** Check this file before asking user for test login credentials. Never commit this file to Git.
15
+
16
+ ---
17
+
18
+ ## 1. Local Dev Endpoints & Test Ports
19
+
20
+ | Service | Local URL / Port | Status / Description |
21
+ | :--- | :--- | :--- |
22
+ | **Frontend Web** | `http://localhost:3000` | Dev server |
23
+ | **Backend API** | `http://localhost:8000` | Local API endpoint |
24
+ | **Local Mock DB** | `localhost:5432` / `database.db` | Non-production dev database |
25
+
26
+ ---
27
+
28
+ ## 2. Seed Accounts & Dummy Test Logins (Browser Automation)
29
+
30
+ Use these mock accounts when performing automated UI testing, Playwright / Puppeteer workflows, or manual verification.
31
+
32
+ | Role | Username / Email | Mock Password | Notes / Permissions |
33
+ | :--- | :--- | :--- | :--- |
34
+ | **Super Admin** | `admin@test.local` | `adminpass123` | Full admin privileges |
35
+ | **Standard User** | `user@test.local` | `userpass123` | Default user permissions |
36
+ | **Guest / Demo** | `guest@test.local` | `guestpass123` | Read-only access |
37
+
38
+ ---
39
+
40
+ ## 3. Local Mock Tokens & Test Headers
41
+
42
+ ```http
43
+ Authorization: Bearer dev-mock-token-12345
44
+ X-Test-Bypass: true
45
+ ```
46
+
47
+ ---
48
+
49
+ ## 4. Local Test Notes & Scratch Data
50
+ <!-- AI and developer can jot temporary test notes, cookie values, or scratch session tokens here -->
51
+ - Test session initialized: {{DATE_NOW}}
52
+
@@ -0,0 +1,94 @@
1
+ # {{PROJECT_NAME}} — Master Architectural Context, Problem Log & Operations Manual
2
+
3
+ > **Last Updated:** {{DATE_NOW}}
4
+ > **Project Directory:** `{{PROJECT_DIR}}`
5
+ > **Repository Name:** `{{PROJECT_NAME}}`
6
+ > **Primary Stack:** {{STACK}} ({{FRAMEWORK}})
7
+
8
+ ---
9
+
10
+ ## 1. Master Credentials & Configuration Vault
11
+
12
+ > 🔒 **Local Sandbox Isolation:** Mock test logins, seed users, and local dev ports are stored in [`context.local.md`](file://{{PROJECT_DIR}}/context.local.md) (strictly protected by `.gitignore` and `chmod 600`). Real secrets reside exclusively in `.env`.
13
+
14
+ | Property | Value / Setting | Description |
15
+ | :--- | :--- | :--- |
16
+ | **Project Name** | `{{PROJECT_NAME}}` | Active project identifier |
17
+ | **Environment** | Development / Production | Current runtime environment |
18
+ | **Base Port** | TBD | Application listening port |
19
+ | **API Endpoints** | TBD | Service URL / Domains |
20
+ | **Secrets / Keys** | Secured in Vault | Credentials, API tokens, passwords |
21
+ | **Test Fixtures** | `context.local.md` | Local dummy test credentials (git-ignored) |
22
+
23
+ ---
24
+
25
+ ## 2. Chronological Problem Log & Technical Solutions
26
+
27
+ ```mermaid
28
+ flowchart TD
29
+ Init["1. Project Initialized"] --> Ready["Ready for development"]
30
+ ```
31
+
32
+ | # | Symptom / Error Message | Root Cause | Exact CLI Solution & Code Patch |
33
+ | :-: | :--- | :--- | :--- |
34
+ | 1 | Initial setup | Clean repository initialization | Generated autonomous context framework |
35
+
36
+ ---
37
+
38
+ ## 3. System Architecture & Tech Stack
39
+
40
+ * **Primary Stack:** {{STACK}}
41
+ * **Framework:** {{FRAMEWORK}}
42
+ * **Database / Cache:** TBD
43
+ * **Deployment Target:** TBD
44
+
45
+ ```
46
+ {{PROJECT_NAME}}/
47
+ ├── .agents/
48
+ │ ├── rules/
49
+ │ │ ├── code-standards.md
50
+ │ │ ├── maintain_context.md
51
+ │ │ └── security-boundaries.md
52
+ │ └── skills/
53
+ │ ├── browser-testing/
54
+ │ ├── docker-ops/
55
+ │ ├── git-workflow/
56
+ │ └── server-diagnostics/
57
+ ├── AGENTS.md
58
+ ├── GEMINI.md
59
+ ├── context.local.md
60
+ └── context.md
61
+ ```
62
+
63
+ ---
64
+
65
+ ## 4. Setup, Reproduction & Operations Runbook
66
+
67
+ ### Prerequisites
68
+ * Operating System: Linux / WSL2 / Windows / macOS
69
+ * Runtime / Package Manager: TBD
70
+
71
+ ### Quick Start
72
+ ```bash
73
+ # Setup instructions will be populated automatically by AI assistant
74
+ ```
75
+
76
+ ---
77
+
78
+ ## 5. Skills & Progressive Disclosure Catalog
79
+
80
+ > 💡 **Progressive Disclosure Protocol:** Agents must NOT read full `SKILL.md` files upfront. When user prompts match any triggers, dynamically inspect the skill file using `read_file`.
81
+
82
+ | Skill | Version | Purpose & Scope | Triggers | Location |
83
+ | :--- | :---: | :--- | :--- | :--- |
84
+ | **`docker-ops`** | 1.0.0 | Production Dockerfile & Compose orchestration | `docker`, `container`, `compose` | [SKILL.md](file://{{PROJECT_DIR}}/.agents/skills/docker-ops/SKILL.md) |
85
+ | **`git-workflow`** | 1.0.0 | Conventional commits & merge conflict resolution | `git`, `commit`, `branch`, `rebase` | [SKILL.md](file://{{PROJECT_DIR}}/.agents/skills/git-workflow/SKILL.md) |
86
+ | **`server-diagnostics`** | 1.0.0 | System health, RAM/swap, CPU, ports & sockets | `health`, `ram`, `cpu`, `swap`, `port` | [SKILL.md](file://{{PROJECT_DIR}}/.agents/skills/server-diagnostics/SKILL.md) |
87
+ | **`browser-testing`** | 1.0.0 | UI testing & mock logins using `context.local.md` | `browser`, `playwright`, `puppeteer`, `ui-test` | [SKILL.md](file://{{PROJECT_DIR}}/.agents/skills/browser-testing/SKILL.md) |
88
+
89
+ ---
90
+
91
+ ## 6. Autonomous Documentation Policy
92
+ * Maintained automatically by AI assistants (Antigravity, Cursor, Claude Code, Copilot, Cline, Windsurf) on every code or configuration change.
93
+ * Governed by [`GEMINI.md`](file://{{PROJECT_DIR}}/GEMINI.md) and [`.agents/rules/maintain_context.md`](file://{{PROJECT_DIR}}/.agents/rules/maintain_context.md).
94
+
@@ -0,0 +1,36 @@
1
+ ---
2
+ name: maintain_context
3
+ description: Mandates autonomous, continuous synchronization of context.md and proactive rule/skill learning on any repository or server configuration change without requiring user prompting.
4
+ trigger: always_on
5
+ ---
6
+
7
+ # Autonomous Context Maintenance & Self-Evolution Rule
8
+
9
+ 1. **Mandatory Synchronization**: Every agent working in this workspace MUST inspect and update `context.md` before finishing their turn whenever any of the following occur:
10
+ - Script or configuration edits (environment variables, docker-compose, configs, network parameters).
11
+ - Problem diagnosis, debugging steps, and technical solutions.
12
+ - User credentials, tokens, secrets, or permissions changes.
13
+ - Architectural decisions or operational runbooks.
14
+
15
+ 2. **Autonomous Learning & Skill Crystallization**:
16
+ - Whenever a new pattern, user preference, architectural guideline, or multi-step procedure is discovered or instructed:
17
+ - Scaffolds a **Rule** (`init-context -r <name> [-g]`) if it is a constraint, coding standard, or guideline.
18
+ - Scaffolds a **Skill** (`init-context -s <name> [-g]`) if it is a multi-step procedure or deployment runbook.
19
+ - Populates the file with clear instructions and notifies the user.
20
+
21
+ 3. **CLI Tool Availability**:
22
+ - The agent has full access to run `init-context` directly via terminal:
23
+ - `init-context`: Initialize/repair context.
24
+ - `init-context -r <name> [-g]`: Create rule.
25
+ - `init-context -s <name> [-g]`: Create skill.
26
+
27
+ 4. **No User Reminder Needed**: The user must never need to ask the agent to update `context.md` or learn rules. This is a strict automated post-condition for all actions.
28
+
29
+ 5. **Local Sandbox Test Credentials (`context.local.md`)**:
30
+ - For local dev logins, automated browser testing, and mock fixtures, inspect and update `context.local.md`.
31
+ - Never store real production secrets or payment tokens in markdown files. Real secrets belong in `.env`.
32
+ - Ensure `context.local.md` is strictly git-ignored and protected with `chmod 600`.
33
+
34
+ 6. **Two-Tier Progressive Disclosure**:
35
+ - Never load full `SKILL.md` bodies into the initial context. Use Section 5 of `context.md` for routing.
36
+ - Dynamically load specific skills via `read_file` only when a user prompt matches their triggers.
@@ -0,0 +1,13 @@
1
+ {
2
+ "mcpServers": {
3
+ "sqlite": {
4
+ "command": "npx",
5
+ "args": ["-y", "@modelcontextprotocol/server-sqlite", "database.db"]
6
+ },
7
+ "filesystem": {
8
+ "command": "npx",
9
+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
10
+ }
11
+ }
12
+ }
13
+