5 Commits

Author SHA1 Message Date
nvaldez 41c8b99bd6 feat: gpgtools ssh-config-summary - per-host table of gpg-enabled logins (v0.11.0)
- read-only: one row per marker-managed block in ~/.ssh/config (or
  --config PATH): alias, hostname, user, key id (first 8 chars of
  the identity's SHA256 fingerprint via ssh-keygen -lf, material
  digest as fallback), and the fallback identity's name
- no managed blocks / missing config: fact + configure_ssh hint,
  exit 0 always (read-only command)
- spec items 2.8 + section 13 first, then tests, then code (SPEC
  6.12); 10 new tests (100 in test_gpgtools.py), registry
  description, README section, CHANGELOG 0.11.0, version pins

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-19 09:49:35 +01:00
nvaldez cdc209536f feat: daedalus init - register argcomplete tab completion (v0.10.0)
- new script python/src/init/init.py: locates the
  register-python-argcomplete that belongs to the running
  interpreter (venv bin, NOT the resolve()d symlink target -
  proven by a live pipx run), appends the managed hook block to
  ~/.bashrc between # BEGIN/END daedalus init markers,
  idempotent; --bashrc, --dry-run; Windows notice; zsh warning
- per-script spec python/src/init/spec.md (SPEC 6.11/6.12),
  tests python/tests/test_init_script.py (13; the plain
  test_init.py name is taken by daedalus/tests)
- registry entry, README row + section, pyproject packaging
  (daedalus.init), CHANGELOG 0.10.0, version pins

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-19 09:31:05 +01:00
nvaldez e9b716b399 feat: gpgtools configure_ssh, store_publickey, --file source, initialize (v0.7.0-v0.9.0)
- configure_ssh (0.7.0): marker-managed per-host ssh client block in
  ~/.ssh/config, idempotent, unmanaged-alias guard (exit 11)
- store_publickey (0.8.0): on-site bootstrap mirror of send_pubkey -
  run on the machine access is granted to, installs the key into the
  local authorized_keys (multi-key preserving, material dedup, 700/600,
  no possession check by design); shared --file PATH source (USB
  stick) for both store subcommands; identity block printed before
  acting (line, source, SHA-256 material digest)
- initialize (0.9.0): gnupg readiness check + install, no card
  expectations; --dry-run; initialize_yubikey step 1 shares the flow
- spec-first per SPEC 6.11/6.12: gpgtools spec.md items 2.6/2.7,
  4.1.5, 4.8, sections 10-12; 91 tests in test_gpgtools.py;
  README/registry/CHANGELOG/version pins through 0.9.0

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-19 08:57:30 +01:00
nvaldez 85e8342a74 docs: per-script local specs + spec-first change order (SPEC 6.11, 6.12)
Every script gets a complete spec.md sectionized like SPEC.md
(python/src/<name>/spec.md, <name>.spec.md for shell scripts).
Change order becomes spec -> tests -> code. Specs added for
gpgtools, hello, hello_bash; CHANGELOG under Unreleased.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-19 00:54:03 +01:00
nvaldez fef68a84c9 feat: gpgtools - YubiKey GPG/SSH helpers (v0.6.0)
initialize_yubikey (guide steps 1-4): gnupg install fallback
(apt-get/dnf/pacman), card check, public-key fetch from the
card's URL field, idempotent gpg-agent SSH config merge,
GNUPGHOME chmod 700; --dry-run, --gnupg-home.

send_pubkey (guide steps 5-6): resolve the SSH public key from
four sources (--yubikey via gpg-agent ssh socket, --url, --fingerprint via store chain local keyring -> keys.openpgp.org
-> keyserver.ubuntu.com with fingerprint checking, --pubkey
literal), prove possession of the private half with a random
challenge signature (ssh-keygen -Y sign -U / verify) before
anything is stored, then append idempotently to the target's
authorized_keys (dedup by key material, comments ignored).
--no-verify opts out explicitly; --dry-run resolves only.

51 tests (flow via injected runner: no hardware, network, or
interactive terminal); steps 1-6 of the wiki guide
(yubikey-ssh-guide.md) are now one command each.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-19 00:46:40 +01:00
15 changed files with 3746 additions and 8 deletions
+124
View File
@@ -10,6 +10,130 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
- Nothing yet.
## [0.11.0] - 2026-11-19
### Added in 0.11.0
- `gpgtools ssh-config-summary`: a read-only view of the gpg-enabled ssh
logins. One row per marker-managed block in `~/.ssh/config` (or
`--config FILE`): alias, hostname, user, the key id - first 8 chars of the
identity's SHA256 fingerprint via `ssh-keygen -lf`, with the SHA-256
material digest as fallback when ssh-keygen is unavailable - and the
fallback identity's name. No managed blocks (or a missing config) prints
that fact with the `configure_ssh` hint. Exit code always 0. Spec item 2.8
and section 13 written first, then tests, then code (SPEC 6.12).
## [0.10.0] - 2026-11-19
### Added in 0.10.0
- `daedalus init`: the one-time shell-side setup for tab completion.
Finds the `register-python-argcomplete` that belongs to this exact
daedalus interpreter (the pipx venv, the checkout .venv, or the
system python — argcomplete's script sits beside it), then appends
the completion hook to `~/.bashrc` between managed markers (or
`--bashrc FILE`), idempotently: an already-registered bashrc is left
untouched. `--dry-run` prints the block and the target; on Windows
the script prints a notice and does nothing; a zsh `$SHELL` gets a
logged warning about the `bashcompinit` preamble. Exit 3 when the
register script is nowhere to be found. The full behavior is
`python/src/init/spec.md` (sections 1-7), written first, then tests,
then code (SPEC 6.12).
## [0.9.0] - 2026-11-19
### Added in 0.9.0
- `gpgtools initialize`: checks that gnupg is ready on this machine
(`gpg --version`) and installs what is missing — the gnupg-only
half of `initialize_yubikey`, with no card expectations. Missing gpg
triggers the same manager detection and sudo install; the check
re-runs once after a successful install. `--dry-run` prints
`already ready` or the install command and changes nothing. Intended
as the on-site companion to `store_publickey --fingerprint` on a
bare server. Spec section 12 written first, then tests, then code
(SPEC 6.12); `initialize_yubikey` step 1 now runs the same shared
flow instead of its own inline copy.
## [0.8.0] - 2026-11-19
### Added in 0.8.0
- `gpgtools store_publickey`: the on-site bootstrap mirror of
`send_pubkey`. Run on the machine that access is being granted
**to** (a server with ssh password authentication disabled, no key
there yet, you at its console), it resolves one SSH public key and
appends it to this machine's `authorized_keys` — so the machine
holding the YubiKey can ssh in afterwards. Same five sources as
`send_pubkey`; by design there is no proof-of-possession (the
private half is elsewhere). Existing entries preserved verbatim,
idempotent by key material, `~/.ssh`/file modes forced to 700/600,
`--authorized-keys` override, `--dry-run`. Spec section 11 written
first, then tests, then code (SPEC 6.12).
- New shared source `--file PATH` for both `send_pubkey` and
`store_publickey`: a file holding the SSH public key line,
typically `yubikey_auth.pub` carried on a USB stick — no network,
no gpg needed. Several keys in one file refuse rather than guess.
- Both resolve-and-store subcommands now print an identity block (key
line, source, and the key material's SHA-256 digest) before acting,
so what was resolved can be compared across machines.
## [0.7.0] - 2026-11-19
### Added in 0.7.0
- `gpgtools configure_ssh` (guide step 7): writes a marker-managed
`Host <alias>` block into the ssh client config — YubiKey identity
first, fallback identity only when it exists, `IdentitiesOnly yes`.
Idempotent (re-runs replace the block; everything outside the
markers is preserved), `--dry-run`, and a guard that refuses when an
unmanaged `Host` with the same alias would shadow the block. Spec
items 2.5 and 10 written first, then tests, then code (SPEC 6.12).
- Per-script local specs (SPEC items 6.11, 6.12): every script gets a
spec that completely describes it — `spec.md` in a Python script's
folder, `<name>.spec.md` beside bash/PowerShell/batch scripts — in
the sectionized format of SPEC.md. Script work is spec first, then
tests, then code. First specs added:
`gpgtools`, `hello`, `hello_bash`.
### Fixed in 0.7.0
- Test fixtures no longer carry private values: the real server IP,
host alias, card serial, and public key fingerprint were replaced
with documentation-range placeholders.
## [0.6.0] - 2026-11-18
### Added in 0.6.0
- `gpgtools send_pubkey` (guide steps 5-6): resolves an SSH public key
from one of four sources — `--yubikey` (gpg-agent ssh socket),
`--url` (armored OpenPGP key, converted with `gpg --export-ssh-key`
in a throwaway GNUPGHOME), `--fingerprint` (store chain: local
keyring, keys.openpgp.org VKS, keyserver.ubuntu.com, each
fingerprint-checked), or `--pubkey` (literal line, format-validated).
Before anything is stored, proof of possession: a random challenge is
signed by the private half through the agent (`ssh-keygen -Y sign
-U`; PIN prompts reach the user) and verified against the candidate
line (`ssh-keygen -Y verify`). Only then is the line appended to the
target's `authorized_keys` — idempotent (grep before append), perms
enforced. `--no-verify` skips the check explicitly; `--dry-run`
resolves and prints without side effects. 22 new tests.
## [0.5.0] - 2026-11-18
### Added in 0.5.0
- `gpgtools` (Python, category `gpg`): YubiKey GPG/SSH helpers.
`daedalus gpgtools initialize_yubikey` runs the fresh-machine flow
(steps 1-4 of the wiki guide): installs gnupg when missing (apt-get,
dnf, pacman), checks the card, fetches the public key from the card's
URL field with `gpg --fetch-keys`, and writes the gpg-agent SSH
config (`enable-ssh-support`, cache TTLs) with the GNUPGHOME
directory at mode 700. `--dry-run` prints the plan; steps 5-7
(derive and deploy the SSH key per host) are server-specific and
intentionally out of scope.
## [0.4.0] - 2026-11-18
### Added in 0.4.0
+166 -1
View File
@@ -17,8 +17,10 @@ daedalus --list # list everything
| Script | Type | Categories | What it does |
| --- | --- | --- | --- |
| `gpgtools` | Python | gpg | YubiKey GPG/SSH helpers: initialize (gnupg readiness check + install), initialize_yubikey (fresh machine, steps 1-4), send_pubkey (resolve key, verify possession, append to a server), store_publickey (install the key from the machine being granted access), configure_ssh (marker-managed per-host ssh block) |
| `hello` | Python | test | Prints a hello line and the daedalus version |
| `hello_bash` | Bash | test | Sample bash script through the shared help() interface |
| `init` | Python | setup | Enable tab completion for daedalus: register argcomplete in bash (appends the managed hook block to ~/.bashrc), idempotent |
Run the sample script:
@@ -33,12 +35,175 @@ daedalus test # list the scripts in the 'test' category
`daedalus --list` prints the version, a `script` / `type` / `categories`
table, and each description wrapped under each row.
### gpgtools
`initialize` checks that gnupg is ready on this machine and installs
what is missing — the gnupg-only half of `initialize_yubikey`, with no
card expectations. Its use is on-site: on a bare server where you are
about to run `store_publickey --fingerprint`, this is the command that
makes the gpg-dependent sources work.
```bash
daedalus gpgtools initialize # check gnupg, install when missing
daedalus gpgtools initialize --dry-run # already ready, or the install command
```
| Argument | Default | Meaning |
| --- | --- | --- |
| `--dry-run` | off | Print what would happen (already ready or the install command); change nothing |
Exit codes: `0` gnupg ready (installed or already present), `2` package
install failed or gpg still unusable after it, `3` gpg missing and no
known package manager.
`initialize_yubikey` runs the fresh-machine flow for YubiKey-backed
GPG and SSH (steps 1-4 of the wiki guide): install gnupg when missing,
check the card, fetch the public key from the card's URL field, and
write the gpg-agent SSH config. Steps 5-7 are per-server and covered
by the subcommands below.
```bash
daedalus gpgtools # overview of the subcommands
daedalus gpgtools initialize_yubikey # prepare this machine
daedalus gpgtools initialize_yubikey --dry-run # print the plan only
```
| Argument | Default | Meaning |
| --- | --- | --- |
| `--dry-run` | off | Print the plan, write nothing |
| `--gnupg-home DIR` | `GNUPGHOME` or `~/.gnupg` | Which GnuPG home to configure |
Exit codes: `0` ready, `2` package install failed, `3` gpg missing and
no known package manager, `4` no card found, `5` public-key fetch did
not pair the keyring, `6` keyring unpaired and the card carries no URL.
`send_pubkey` covers guide steps 5-6 for one server: resolve the SSH
public key from one of five sources, prove possession of the private
half with a challenge signature (the YubiKey itself signs; PIN prompts
go to the user), then append the line to the target's
`authorized_keys` — idempotent, fingerprint-checked against stores,
and nothing is sent when verification fails.
```bash
daedalus gpgtools send_pubkey --yubikey you@server
daedalus gpgtools send_pubkey --fingerprint <FP> you@server
daedalus gpgtools send_pubkey --url https://keys.openpgp.org/vks/v1/by-fingerprint/<FP> you@server
daedalus gpgtools send_pubkey --pubkey "ssh-ed25519 AAAA... comment" you@server
daedalus gpgtools send_pubkey --file /media/usb/yubikey_auth.pub you@server
daedalus gpgtools send_pubkey --yubikey --dry-run you@server # resolve only
```
| Argument | Default | Meaning |
| --- | --- | --- |
| `--yubikey` | — | Key from the plugged YubiKey via gpg-agent (must be the only agent key) |
| `--url URL` | — | Armored OpenPGP public key at a URL ([A] subkey is exported) |
| `--fingerprint FP` | — | Searched: local keyring → keys.openpgp.org → keyserver.ubuntu.com |
| `--pubkey LINE` | — | The literal SSH public key line |
| `--file PATH` | — | File holding the key line, e.g. a `.pub` from a USB stick (no network, no gpg) |
| `--no-verify` | verification on | Skip the proof-of-possession signature (explicit risk acceptance) |
| `--dry-run` | off | Resolve and print the key; verify and send nothing |
Additional exit codes: `7` ssh to the target failed, `8` no source
resolved a key, `10` proof-of-possession verification failed (nothing
was sent).
`store_publickey` is the mirror for the on-site bootstrap: run it on
the machine that access is being granted *to* — a server with ssh
password authentication disabled that no key authorizes yet, where
you are logged in at the console. It resolves the same five sources
and appends the key into this machine's `authorized_keys`, so the
machine holding the YubiKey can ssh in afterwards. There is no
proof-of-possession (the private half is, by design, elsewhere);
instead both resolve-and-store subcommands print an identity block —
line, source, and the key material's SHA-256 — to compare across
machines. Existing entries are preserved, nothing is duplicated, and
directory/file modes are forced to 700/600.
```bash
daedalus gpgtools store_publickey --file /media/usb/yubikey_auth.pub
daedalus gpgtools store_publickey --fingerprint <FP>
daedalus gpgtools store_publickey --pubkey "ssh-ed25519 AAAA... comment"
daedalus gpgtools store_publickey --file /media/usb/yubikey_auth.pub --dry-run # print only
```
| Argument | Default | Meaning |
| --- | --- | --- |
| sources | — | Same five sources as `send_pubkey` (exactly one required) |
| `--authorized-keys FILE` | `~/.ssh/authorized_keys` | Where to install the key |
| `--dry-run` | off | Resolve and print the key; write nothing |
Additional exit codes: `8` no source resolved a key.
`configure_ssh` covers guide step 7 for one host: it writes a
marker-managed `Host <alias>` block into the ssh client config.
Outside the markers your config is preserved byte-for-byte; re-runs
replace the block (idempotent), and an unmanaged `Host` with the same
alias is refused rather than shadowed. It never connects anywhere.
```bash
daedalus gpgtools configure_ssh --alias vault1 --hostname 203.0.113.10 --user admin
daedalus gpgtools configure_ssh --alias vault1 --dry-run # print only
daedalus gpgtools configure_ssh --alias vault1 --no-fallback # YubiKey only
```
| Argument | Default | Meaning |
| --- | --- | --- |
| `--alias NAME` | required | The ssh Host alias to configure |
| `--hostname HOST` | the alias | HostName value |
| `--user USER` | ssh's default | User value |
| `--pubkey FILE` | `~/.ssh/yubikey_auth.pub` | Primary IdentityFile (must exist) |
| `--fallback FILE` | `~/.ssh/id_ed25519` | Fallback IdentityFile, included only when it exists |
| `--no-fallback` | off | Never add a fallback IdentityFile |
| `--config PATH` | `~/.ssh/config` | Which ssh client config to edit |
Additional exit code: `11` an unmanaged `Host` with the same alias exists in the
config (move it into the managed markers or rename the alias).
`ssh-config-summary` prints what is enabled where, read-only: one row per
managed block — alias, hostname, user, the key id (first 8 chars of the
identity's SHA256 fingerprint, material-digest fallback), and the fallback
identity. Same id on two rows means the same gpg key guards both hosts.
```bash
daedalus gpgtools ssh-config-summary
daedalus gpgtools ssh-config-summary --config FILE
```
| Argument | Default | Meaning |
| --- | --- | --- |
| `--config FILE` | `~/.ssh/config` | Which ssh client config to read |
## Shell completion
Bash (and other shells argcomplete supports) completes script names and
category labels: `daedalus hel` + TAB completes `hello`, `daedalus test h` +
TAB completes `hello` inside the category, and options complete after `-`.
See [INSTALL](./INSTALL.md#tab-completion).
Run `daedalus init` once to register the hook in `~/.bashrc` (below); see
also [INSTALL](./INSTALL.md#tab-completion).
### init
`init` is the one-time shell-side setup: it finds the
`register-python-argcomplete` that belongs to this exact daedalus
interpreter (so a pipx install wires its own venv, not some other
python), appends the hook to `~/.bashrc` between managed markers, and
tells you how to activate it now. Installing daedalus never touches your
shell — this command does. It is idempotent: re-running on an already
registered `~/.bashrc` writes nothing.
```bash
daedalus init # register completion in ~/.bashrc
daedalus init --dry-run # print the block and the target, change nothing
daedalus init --bashrc FILE # a different bashrc
```
| Argument | Default | Meaning |
| --- | --- | --- |
| `--bashrc FILE` | `~/.bashrc` | Target file for the managed hook block |
| `--dry-run` | off | Print the block and the target, change nothing |
Exit code: `3` when `register-python-argcomplete` is nowhere to be
found (reinstall daedalus — argcomplete is a declared dependency).
## Getting started
+39 -4
View File
@@ -77,13 +77,15 @@ daedalus/
│ ├── daedalus_logging/ # File + console logging (section 11)
│ └── tests/
├── python/
│ ├── src/<name>/ # Python scripts, one folder per script
│ ├── src/<name>/ # Python scripts, one folder per script,
│ │ # holding <name>.py and spec.md (SPEC item 6.11)
│ └── tests/ # pytest tests for python/src, .ps1, .bat
├── bash/ # *.sh scripts (SPEC item 6.10 interface)
├── bash/ # *.sh scripts (SPEC item 6.10 interface),
│ # each with a <name>.spec.md sibling
│ ├── daedalus_common.sh # shared helper: daedalus_bash_dispatch, help() routing
│ └── tests/ # pytest tests that run them
├── powershell/ # *.ps1 scripts
├── batch/ # *.bat scripts (CRLF)
├── powershell/ # *.ps1 scripts, each with <name>.spec.md
├── batch/ # *.bat scripts (CRLF), each with <name>.spec.md
├── ci/ # sanity.py, checks.py, with tests
├── autotest.py # Runs every check (local and CI)
├── pyproject.toml # Package, version, entry point, package data
@@ -496,6 +498,39 @@ SCRIPTS: dict[str, Script] = {
registered `.sh` script (source line, `help()`, `main()`, the
dispatch call) and tests the helper behavior directly.
- **6.11** Every script has a local spec that completely
describes it.
- **6.11.1** A Python script's spec is `spec.md` inside its
own folder: `python/src/<name>/spec.md`.
- **6.11.2** A bash, PowerShell, or batch script's spec is a
sibling file named `<name>.spec.md`:
`bash/<name>.spec.md`, `powershell/<name>.spec.md`,
`batch/<name>.spec.md`.
- **6.11.3** The local spec follows the sectionized format of
this file: every heading and list item has a stable numbered
id (`- **N.M**`), sub-items continue the numbering
(`N.M.K`), and items are cited as
`<name> spec item N.M`.
- **6.11.4** The local spec is complete enough to rebuild the
script from it alone: purpose, commands and arguments,
observable behavior (steps, validation, output), exit
codes, files written, error handling, and testing approach.
- **6.11.5** The local spec does not repeat this file; where it
relies on a repository rule it cites the SPEC item instead.
- **6.12** The change order for script work is spec first, then
tests, then code.
- **6.12.1** Create or modify the script's local spec (SPEC
item 6.11) until it describes the intended behavior - a
change that contradicts an existing spec item updates that
item in the same change.
- **6.12.2** Add or change tests that fail without the
behavior.
- **6.12.3** Make the smallest change that makes the tests
pass, then refactor with them green.
- **6.12.4** Spec, tests, code, README, and CHANGELOG land in
the same change; the version bump follows SPEC item 9.8.
## 7. Quality gates
- **7.1** `python autotest.py [CHECK...]` runs the named checks (default:
+31
View File
@@ -0,0 +1,31 @@
# hello_bash specification
Complete description of `bash/hello_bash.sh`. The sample bash
script of the template: it exercises the SPEC item 6.10 shared
interface end to end. Items are cited as `hello_bash spec item
N.M`.
## 1. Purpose
- **1.1** Print one hello line per name argument, defaulting to
`world` when no argument is given, and exit via the interface:
`hello, <name> (from daedalus bash)`.
## 2. Behavior
- **2.1** The script sources `daedalus_common.sh` once, defines
`help()` (usage text) and `main()` (the printing), and ends
with `daedalus_bash_dispatch "$@"` (SPEC item 6.10).
- **2.2** `daedalus hello_bash me` prints `hello, me (from
daedalus bash)`; `daedalus hello_bash a b` prints one line
per name; no arguments prints the line for `world`.
- **2.3** `help`, `-h`, and `--help` route to `help()` and exit
0; every other invocation routes to `main` unchanged.
- **2.4** Nothing is read or written; the script takes names only.
## 3. Testing approach
- **3.1** `bash/tests/test_hello_bash.py` runs the script through
`runners.find_bash()` (skip when bash is missing) and covers
the default name, multiple names, the help routing, and the
completion words.
+10
View File
@@ -54,6 +54,11 @@ class Script:
SCRIPTS: dict[str, Script] = {
"gpgtools": Script(
path="python/src/gpgtools/gpgtools.py",
description="YubiKey GPG/SSH helpers: initialize (gnupg readiness check + install), initialize_yukikey (fresh machine, steps 1-4), send_pubkey (resolve key, verify possession, append to a server), store_publickey (install the key from the machine being granted access), configure_ssh (marker-managed per-host ssh block), ssh-config-summary (per-host table of gpg-enabled logins)",
categories="gpg",
),
"hello": Script(
path="python/src/hello/hello.py",
description="Print a hello line and the daedalus version",
@@ -64,6 +69,11 @@ SCRIPTS: dict[str, Script] = {
description="Sample bash script through the shared help() interface",
categories="test",
),
"init": Script(
path="python/src/init/init.py",
description="Enable tab completion for daedalus: register argcomplete in bash (appends the managed hook block to ~/.bashrc), idempotent",
categories="setup",
),
}
"""Every script daedalus can run (SPEC.md section 4)."""
+1 -1
View File
@@ -150,7 +150,7 @@ def test_path_with_extra_words_is_a_usage_error(fake_registry, plain, capsys):
assert "usage: daedalus --path <name>" in capsys.readouterr().err
@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.4.0")])
@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.11.0")])
def test_version(monkeypatch, capsys, installed, expected):
"""--version uses metadata or pyproject.toml in a checkout."""
def fake_version(_name):
+5 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "daedalus"
version = "0.4.0"
version = "0.11.0"
description = "Template for daedalus: loose scripts in one repo, run with: daedalus <name> [args...]"
readme = "README.md"
requires-python = ">=3.11"
@@ -19,7 +19,9 @@ daedalus = "daedalus.cli:main"
packages = [
"daedalus",
"daedalus.daedalus_logging",
"daedalus.gpgtools",
"daedalus.hello",
"daedalus.init",
"daedalus._library.python.src",
"daedalus._library.bash",
"daedalus._library.powershell",
@@ -27,7 +29,9 @@ packages = [
]
[tool.setuptools.package-dir]
"daedalus.gpgtools" = "python/src/gpgtools"
"daedalus.hello" = "python/src/hello"
"daedalus.init" = "python/src/init"
"daedalus._library.python.src" = "python/src"
"daedalus._library.bash" = "bash"
"daedalus._library.powershell" = "powershell"
File diff suppressed because it is too large Load Diff
+375
View File
@@ -0,0 +1,375 @@
# gpgtools specification
Complete description of `python/src/gpgtools/gpgtools.py`. Change
this file first, then tests, then code (SPEC items 6.11 and 6.12).
Items are cited as `gpgtools spec item N.M`.
<!-- toc-start: headings 2..6 -->
- [1. Purpose](#1-purpose)
- [2. Commands](#2-commands)
- [3. initialize_yubikey behavior](#3-initialize_yubikey-behavior)
- [4. send_pubkey behavior](#4-send_pubkey-behavior)
- [5. Exit codes](#5-exit-codes)
- [6. Runner contract and injectability](#6-runner-contract-and-injectability)
- [7. Files written](#7-files-written)
- [8. Testing approach](#8-testing-approach)
- [9. References](#9-references)
- [10. configure_ssh behavior](#10-configure_ssh-behavior)
- [11. store_publickey behavior](#11-store_publickey-behavior)
- [12. initialize behavior](#12-initialize-behavior)
- [13. ssh-config-summary behavior](#13-ssh-config-summary-behavior)
<!-- toc-end -->
## 1. Purpose
- **1.1** gpgtools automates the YubiKey SSH flow documented in the
owner's wiki guide
(`~/repositories/vibe-wiki/wiki/queries/yubikey-ssh-guide.md`):
`initialize_yubikey` covers guide steps 1-4 (fresh machine ready
for GPG), `send_pubkey` covers steps 5-6 (key to a server).
`store_publickey` covers the on-site bootstrap case (section 11):
installing the key from the machine that access is being
granted to. Guide step 7 (per-host `~/.ssh/config`) is out of
scope.
- **1.2** Hard constraint: the YubiKey's OpenPGP applet is never
written - no `gpg --card-edit`, no `keytocard`, no applet reset.
Only public card data is read; the card PIN is typed by its
owner into pinentry, never passed through this script.
- **1.3** The user's real GNUPGHOME is written only where section
7 says so; remote public-key imports go to a throwaway home
(item 4.5).
- **1.4** Standard library only; Python 3.11+ (SPEC item 9.6).
## 2. Commands
- **2.1** `daedalus gpgtools` with no subcommand prints the
overview of the subcommands and exits 0.
- **2.2** `daedalus gpgtools initialize_yubikey [--dry-run]
[--gnupg-home DIR]` - prepares this machine (section 3).
- **2.3** `daedalus gpgtools send_pubkey
(--yubikey | --url URL | --fingerprint FP | --pubkey LINE | --file PATH)
[--no-verify] [--dry-run] you@server` - resolves one SSH
public key, proves possession of the private half, appends it
to the target (section 4). The five source flags are mutually
exclusive and exactly one is required; `you@server` is
required.
- **2.4** `--dry-run` on either subcommand prints what would
happen and writes nothing; on `send_pubkey` it resolves and
prints the key but never verifies and never connects.
- **2.5** `daedalus gpgtools configure_ssh --alias NAME
[--hostname HOST] [--user USER] [--pubkey FILE]
[--fallback FILE | --no-fallback] [--config PATH] [--dry-run]`
- writes the per-host ssh client block (guide step 7);
behavior in section 10.
- **2.6** `daedalus gpgtools store_publickey
(--yubikey | --url URL | --fingerprint FP | --pubkey LINE | --file PATH)
[--authorized-keys FILE] [--dry-run]` - resolves one SSH
public key and installs it into *this* machine's
authorized_keys (section 11). The source flags are the
send_pubkey set (items 4.1.1-4.1.5), mutually exclusive,
exactly one required.
- **2.7** `daedalus gpgtools initialize [--dry-run]` - checks
that gnupg is ready on this machine and installs what is
missing; the gnupg-only half of initialize_yubikey
(section 12).
- **2.8** `daedalus gpgtools ssh-config-summary
[--config PATH]` - prints the table of gpg-enabled ssh logins
found in the config (section 13); read-only.
## 3. initialize_yubikey behavior
- **3.1** Step 1 - gnupg: the section 12 flow (item 12.1). When
`gpg --version` fails, the package manager is detected
(`shutil.which` over apt-get, dnf, pacman) and gnupg installed
via `sudo`; no known manager is exit 3. A failed install is
exit 2.
- **3.2** Step 2 - card: `gpg --card-status` parsed for the
`Application type`/`OpenPGP` markers; absent card (including
gpg error text) is exit 4 with the pcscd hint
`systemctl enable --now pcscd`.
- **3.3** Card fields: serial (`Serial number`), authentication
subkey presence (`Authentication key` with a non-`[none]`
value), key URL (`URL of public key`, `[not set]` is None),
keyring pairing (`General key info` non-`[none]`).
- **3.4** Step 3 - public key: when unpaired and a URL exists,
`gpg --fetch-keys <url>`, then re-parse the card; still
unpaired is exit 5. Unpaired without a URL is exit 6 with the
manual-import hint.
- **3.5** A missing `[A]` subkey logs a warning (SSH via
gpg-agent will not work; GPG signing/decryption will) but is
not an error.
- **3.6** Step 4 - agent: the homedir is created at mode 700;
`gpg-agent.conf` gains `enable-ssh-support` and, only when its
key is absent, `default-cache-ttl 600` and `max-cache-ttl
7200`; existing lines, including user TTLs, are kept verbatim
and never duplicated. `gpgconf --kill gpg-agent` restarts the
agent. Exit 0.
## 4. send_pubkey behavior
- **4.1** Sources (exactly one per run):
- **4.1.1** `--yubikey`: the gpg ssh socket from
`gpgconf --list-dirs agent-ssh-socket` (bare path or prefixed
form), `SSH_AUTH_SOCK` set to it, `ssh-add -L`. No socket is
exit 8 with the `initialize_yubikey` hint; no keys is exit 8
with "is the YubiKey plugged in?"; several keys refuses with
the list and the `--pubkey` hint rather than guessing.
- **4.1.2** `--url`: fetch the armored OpenPGP public key,
convert via item 4.5.
- **4.1.3** `--fingerprint`: normalize (strip spaces and `0x`,
case-insensitive, exactly 40 hex chars, else exit 8); resolve
through the store chain, first hit wins: local keyring (`gpg
--export-ssh-key 0x<FP>`), then keys.openpgp.org VKS
(`.../vks/v1/by-fingerprint/<FP>`), then keyserver.ubuntu.com
(`.../pks/lookup?op=get&search=0x<FP>`). Every store result is
fingerprint-checked before use; a mismatch skips the store.
All exhausted is exit 8 naming the stores.
- **4.1.4** `--pubkey`: the literal line, validated by item 4.2;
exit 8 when invalid.
- **4.1.5** `--file PATH`: a file holding the SSH public key
line - typically `yubikey_auth.pub` carried on a USB stick
(zero network, zero gpg). Every line is validated per item
4.2: no valid line is exit 8; several valid lines refuse
listing them with the `--pubkey` hint (item 4.1.1
precedent) rather than guessing; an unreadable or missing
file is exit 8.
- **4.2** Key line validation: `ssh-(ed25519|rsa|dss|ecdsa-sha2-*)
<base64> [comment]`, full line; anything else is rejected.
- **4.3** Key material (type + base64, comment ignored) is the
key's identity for deduplication and reporting.
- **4.4** Proof of possession (default, skipped only with
`--no-verify`): a random hex challenge is signed via
`ssh-keygen -Y sign -U` (the private half - card, PIN prompt
included - must sign) and verified via `ssh-keygen -Y verify`
against the candidate line with an allowed_signers file. Any
failure prints that nothing was sent and exits 10; the ssh
target is never contacted.
- **4.5** Remote conversion: armored keys are imported into a
throwaway `--homedir` via `gpg --import`, fingerprints listed
with `--list-keys --with-colons`, and the ssh line exported with
`gpg --export-ssh-key 0x<FP>`. The real keyring is not touched;
the throwaway home is removed afterwards.
- **4.6** Send: `ssh you@server "cat ~/.ssh/authorized_keys
2>/dev/null"` to read, then - only when the key material is
absent - append the line via stdin with perms forced
(`mkdir -p`, `chmod 700 ~/.ssh`, `chmod 600 authorized_keys`).
Present is reported, not re-appended. Any ssh failure is exit 7;
nothing is appended on failure.
- **4.7** Both ssh calls run without an interactive terminal: the
target must be reachable with existing non-interactive
credentials (agent, passphrase-less key, or ControlMaster
socket). First contact to a brand-new server by password is out
of scope - gain access once manually, then send the key.
- **4.8** Output (identical in section 11): both resolve-and-store
subcommands print the resolved key line, its source, and the
SHA-256 hex digest of the key material (item 4.3) before
acting, so the resolved value can be compared with the machine
the key came from (or read over a phone).
## 5. Exit codes
| Code | Meaning |
| --- | --- |
| 0 | success (initialize ready; send appended or already present) |
| 2 | package install failed (initialize, initialize_yubikey) |
| 3 | gpg missing and no known package manager (initialize, initialize_yubikey) |
| 4 | no OpenPGP card found (initialize) |
| 5 | public-key fetch did not pair the keyring (initialize) |
| 6 | keyring unpaired and the card carries no URL (initialize) |
| 7 | ssh to the target failed; nothing stored (send) |
| 8 | no source resolved a usable key (send, store); pubkey file missing (configure) |
| 10 | proof-of-possession verification failed; nothing sent (send) |
| 11 | an unmanaged `Host <alias>` exists in the config (configure) |
## 6. Runner contract and injectability
- **6.1** Everything external goes through
`run_command(cmd, input_text="", env=None) -> (code,
stdout+stderr)`: env variables are merged over `os.environ`,
`input_text` is piped to stdin, a missing binary returns
`(127, "<cmd>: not found")`.
- **6.2** `initialize_yukikey(home, run_cmd)`,
`verify_possession(line, workdir, run_cmd)`,
`send_key(line, target, run_cmd)`, and the `source_*`
functions accept the runner; `source_url`,
`source_fingerprint`, and `cmd_send_pubkey` also accept a
`fetch(url) -> bytes | None`. Tests inject fakes; defaults are
`run_command` and `fetch_bytes` (urllib, 30 s timeout, None on
any fetch error).
- **6.3** ssh-keygen signature namespaces and identity are the
constants `daedalus-gpgtools` and `daedalus@verify`.
## 7. Files written
- **7.1** initialize: `<gnupg-home>/gpg-agent.conf` (merge per
item 3.6); the homedir permissions set to 700. Nothing else.
- **7.2** send: scratch dirs (throwaway GNUPGHOME, challenge
workspace) are created under the system temp dir and removed in
`finally`. The only persistent write is the target's
`authorized_keys` append via ssh (item 4.6).
- **7.3** store: the local `authorized_keys` (item 11.5) is the
only persistent write; its parent gets mode 700, the file 600.
Scratch rules of item 7.2 apply when remote sources resolve
(item 4.5).
## 8. Testing approach
- **8.1** Tests live in `python/tests/test_gpgtools.py` and never
need hardware, a network, or an interactive terminal (SPEC item
6.6): all flows take an injected runner; fetchers and runners
are fakes scripted per test by command prefix.
- **8.2** Covered groups: card-status parsing (present/absent,
no URL, no auth subkey, unpaired), config merge (empty,
preserving, complete), manager mapping and detection,
GNUPGHOME resolution, the initialize flow's success, failure,
warning, and persistence branches and the standalone
readiness/install/re-check branches (section 12), the five
sources including the store chain and fingerprint mismatch,
challenge sign/verify success and refusal, send idempotence by
material, store: file sources, append, preservation,
idempotence, perms, dry run, summary: block parsing (each
field), key-id resolution and both id fallbacks, the empty
and missing-config paths, and the CLI wiring, guards, and
dry runs.
- **8.3** The change order is spec item 6.12: this spec first,
then failing tests, then the smallest implementation.
## 9. References
- **9.1** The wiki guide behind items 1.1:
`~/repositories/vibe-wiki/wiki/queries/yubikey-ssh-guide.md`
(steps 1-13; automation notes in section 13).
- **9.2** Repository rules: SPEC items 6.6 (tests), 6.9
(argcomplete opt-in after the parser), 9.8 (version bump).
- **9.3** History: `CHANGELOG.md` entries 0.5.0, 0.6.0
(initialize/send), 0.7.0 (configure_ssh), 0.8.0
(--file source, store_publickey), 0.9.0 (initialize), 0.10.0
(init script), 0.11.0 (ssh-config-summary).
## 10. configure_ssh behavior
- **10.1** The block is written into `--config` (default
`~/.ssh/config`) between managed markers, one block per alias:
```text
# BEGIN daedalus gpgtools: <alias>
Host <alias>
HostName <hostname>
User <user> (omitted without --user)
IdentityFile <pubkey>
IdentityFile <fallback> (omitted per item 10.4)
IdentitiesOnly yes
# END daedalus gpgtools: <alias>
```
- **10.2** Defaults: `--hostname` defaults to the alias itself;
`--pubkey` defaults to `~/.ssh/yubikey_auth.pub`;
`--fallback` defaults to `~/.ssh/id_ed25519`.
- **10.3** Idempotence: a run that finds the alias's markers
replaces the whole marked block with the newly built one;
everything outside the markers is preserved byte-for-byte.
Running twice with the same arguments changes nothing.
- **10.4** The fallback `IdentityFile` is included only when its
file exists and `--no-fallback` was not given; a missing
explicit `--fallback FILE` logs a warning.
- **10.5** Guards: a `--pubkey` file that does not exist is exit
8 with the derive hint; a `Host` line naming the same alias
anywhere outside the managed markers is exit 11 (ssh would let
the first match shadow the managed block).
- **10.6** File hygiene: `~/.ssh` is created at mode 700 when
missing; the config file is created at mode 600 when missing.
- **10.7** `--dry-run` prints the block plus
`creating`/`replacing`, and writes nothing.
## 11. store_publickey behavior
- **11.1** Installs one SSH public key into the *current user's*
`~/.ssh/authorized_keys` (`--authorized-keys FILE` overrides)
on this machine - the machine the key will later grant access
to. Use case: a server with ssh password authentication
disabled that no key authorizes yet; you are logged in at its
console and install the key from inside, so the machine
holding the YubiKey can ssh in afterwards. It is the mirror of
section 4: send pushes the key from where it is, store pulls
it from where the access is.
- **11.2** Sources: identical to items 4.1.1-4.1.5, one per run.
On a bare server the realistic ones are `--pubkey` (typed at
the console), `--file` (USB stick; needs no network and no
gpg), and `--fingerprint` (store chain, needs gpg and
network); `--yubikey` works when the card is plugged into
this machine. An unresolvable source is exit 8 (item 5).
- **11.3** There is no proof-of-possession step (item 4.4) and
no `--no-verify` flag: the private half is, by design,
elsewhere - this machine is the one being granted access, so
nothing here could sign the challenge. Hardening instead: line
validation (item 4.2), fingerprint-checked stores (item
4.1.3), and the identity block (item 11.4).
- **11.4** Identity block: the resolved key line, its source,
and the SHA-256 hex digest of the key material (item 4.3) are
printed before writing (shared rule, item 4.8), so the value
can be compared with the machine the key came from.
- **11.5** Storage: the parent directory is created at mode 700
when missing and the authorized_keys file forced to mode 600,
on every write. Existing entries are preserved verbatim -
authorized_keys is a multi-key file; there is no mismatch
guard on the rest, only the new key's absence is checked.
- **11.6** Idempotence follows item 4.3: the line is appended
only when its material is absent (comments ignored); already
present is reported and exits 0. A missing trailing newline
in an existing file is repaired, never glued into a key line.
- **11.7** `--dry-run` prints the identity block plus
`already present`/`creating` and writes nothing.
- **11.8** No ssh is run and the only persistent write is item
11.5; remote sources keep item 4.5's throwaway-home rule
(item 7.3). Exit codes: 0 stored or already present, 8 no
source resolved a usable key.
## 12. initialize behavior
- **12.1** `initialize` covers the gnupg half of item 3.1
only - no card, keyring, or agent expectations. `gpg
--version` decides readiness: present prints the version
line and exits 0. Missing runs manager detection and the
`sudo` install (item 3.1's manager map); no known manager is
exit 3, a failed install is exit 2. After a successful
install the check re-runs once - still unusable is exit 2.
- **12.2** `--dry-run` performs only the read-only
`gpg --version`, prints what would happen (`already ready`
with the version line, the install command it would run, or
the install-manually message), installs nothing, and exits 0
in every dry-run case.
- **12.3** `initialize_yubikey` runs this flow as its step 1
(item 3.1); a `-2`/`-3` return stops it before anything else.
- **12.4** Intended use: the on-site companion to
store_publickey (item 11) - on a machine without the
YubiKey, run `initialize` first when a gpg-dependent source
(`--fingerprint`, `--url`, `--yubikey`) is wanted.
## 13. ssh-config-summary behavior
- **13.1** Scope: every marker-managed block (item 10.1) in
`--config` (default `~/.ssh/config`) is one gpg-enabled
login. The command never writes and never contacts any
host; it reads only the config and the IdentityFiles the
blocks name (`~` expanded).
- **13.2** Output is one row per block with the columns
`alias`, `hostname`, `user`, `key id`, `fallback`:
hostname defaults to the alias when the block omits
HostName; user prints `-` when absent (ssh's own default);
fallback prints `-` when the block has no second
IdentityFile. Columns are padded and separated by two
spaces, like the daedalus script listing.
- **13.3** Key id: taken from the block's *first* IdentityFile.
`ssh-keygen -lf <file>` yields the SHA256 fingerprint; the
row shows its first 8 chars after the `SHA256:` prefix
(shorter values print in full). When ssh-keygen fails or is
missing but the file is readable and holds a valid key line
(item 4.2), the id falls back to the first 8 chars of the
material digest (item 4.8) - both are stable per key. A
missing or unreadable IdentityFile prints `-` for the id.
- **13.4** No managed blocks - a missing config file counts -
prints that fact with the `configure_ssh` hint and exits 0.
- **13.5** Exit code is always 0; the command is read-only and
has no failure modes that would leave anything half-done.
+33
View File
@@ -0,0 +1,33 @@
# hello specification
Complete description of `python/src/hello/hello.py`. The sample
Python script of the template: it exercises the registry, the
`test` category, and the run_python_script entry end to end.
Items are cited as `hello spec item N.M`.
## 1. Purpose
- **1.1** Print one line, `hello from daedalus <version>`, and
exit 0. It takes no arguments of its own.
- **1.2** `<version>` comes from `app_version()`: the installed
daedalus metadata (`importlib.metadata.version("daedalus")`),
else the `version` field of the checkout's `pyproject.toml`
(resolved relative to the script file), else the literal
`unknown`.
## 2. Behavior
- **2.1** `daedalus hello` prints the line and exits 0;
`daedalus test hello` does the same through the category
prefix.
- **2.2** The parser opts in to argcomplete (SPEC item 6.9) with
a guarded import; without argcomplete nothing changes.
- **2.3** No files are read besides `pyproject.toml` in the
fallback; nothing is written.
## 3. Testing approach
- **3.1** `python/tests/test_hello.py` covers both version
resolutions (metadata and pyproject fallback, monkeypatched),
the printed line, `--help`, and end-to-end runs through the
CLI.
+122
View File
@@ -0,0 +1,122 @@
"""Enable tab completion for daedalus in the user's shell (init spec).
Installing daedalus never touches the shell; argcomplete stays
dormant until bash evaluates ``register-python-argcomplete daedalus``
(INSTALL.md "Tab completion"). This script performs the registration:
it finds the register script that belongs to *this* daedalus
interpreter, appends the managed hook block to ``~/.bashrc`` (its
only job for now), and says how to activate it right away.
Run via daedalus: ``daedalus init`` (see daedalus README).
"""
from __future__ import annotations
import argparse
import logging
import os
import pathlib
import shutil
import sys
try: # SPEC item 6.9: complete init's own arguments
from argcomplete import autocomplete
except ImportError: # pragma: no cover - completion off without argcomplete
autocomplete = None
LOGGER = logging.getLogger(__name__)
EXIT_OK = 0
EXIT_NO_REGISTER = 3
MARKER_BEGIN = "# BEGIN daedalus init: argcomplete"
MARKER_END = "# END daedalus init: argcomplete"
def register_script_path() -> pathlib.Path | None:
"""Locate this interpreter's register-python-argcomplete (item 3.1).
The interpreter's folder wins - a pipx venv, a checkout .venv,
and a system install all put argcomplete's scripts beside
python - so the hook matches this exact daedalus install.
Returns:
The script's path, or None when neither location has it.
"""
beside = (pathlib.Path(sys.executable).parent
/ "register-python-argcomplete")
# No resolve(): a venv python is a symlink into the system
# install; resolving it would look beside the wrong python.
if beside.is_file():
return beside
found = shutil.which("register-python-argcomplete")
return pathlib.Path(found) if found else None
def build_block(register_path: pathlib.Path) -> str:
"""Build the managed hook block for one register path (item 3.2)."""
line = f"eval \"$('{register_path}' daedalus)\""
return f"{MARKER_BEGIN}\n{line}\n{MARKER_END}\n"
def main(argv: list[str] | None = None) -> int:
"""Register argcomplete for daedalus; return the exit code.
Args:
argv: argument list; None means sys.argv[1:].
Returns:
EXIT_OK (registered, already enabled, non-POSIX notice, or
dry run) or EXIT_NO_REGISTER (item 3.1).
"""
logging.basicConfig(level=logging.INFO, format="%(levelname)-5s %(message)s")
parser = argparse.ArgumentParser(
prog="init",
description="Enable tab completion for daedalus (register "
"argcomplete in bash)",
)
parser.add_argument("--bashrc", type=pathlib.Path, default=None,
help="target file (default ~/.bashrc)")
parser.add_argument("--dry-run", action="store_true",
help="print the block and the target, "
"change nothing")
if autocomplete is not None: # SPEC item 6.9
autocomplete(parser)
args = parser.parse_args(argv)
if os.name != "posix": # item 3.7
print("nothing to do: tab completion is bash/zsh only")
return EXIT_OK
register = register_script_path()
if register is None: # item 3.1
LOGGER.error("register-python-argcomplete not found next to "
"python (%s) nor on PATH; reinstall daedalus "
"(argcomplete is a declared dependency)",
sys.executable)
return EXIT_NO_REGISTER
target = args.bashrc or pathlib.Path.home() / ".bashrc"
if args.bashrc is None and os.environ.get("SHELL", "").endswith("zsh"):
LOGGER.warning("SHELL is zsh: bash-completion emulation needs "
"these two lines before the hook: "
"'autoload -U bashcompinit' and 'bashcompinit'")
existing = (target.read_text(encoding="utf-8")
if target.exists() else "")
if MARKER_BEGIN in existing: # item 3.4
print(f"already enabled: {MARKER_BEGIN} found in {target}")
return EXIT_OK
block = build_block(register)
if args.dry_run: # item 3.6
print(block, end="")
print(f"dry run: would append the block to {target}")
return EXIT_OK
content = existing
if content and not content.endswith("\n"):
content += "\n" # never glue the marker onto a line
if content.strip():
content += "\n" # blank line before the block (item 3.3)
target.write_text(content + block, encoding="utf-8")
print(f"registered tab completion for daedalus in {target}")
print("activate it now with: exec bash (or open a new shell)")
return EXIT_OK
if __name__ == "__main__":
sys.exit(main())
+92
View File
@@ -0,0 +1,92 @@
# init specification
Complete description of `python/src/init/init.py`. Change this file
first, then tests, then code (SPEC items 6.11 and 6.12). Items are
cited as `init spec item N.M`.
## 1. Purpose
- **1.1** `daedalus init` enables argcomplete tab completion for the
daedalus command in the user's shell. Its only job, for now, is the
shell side: register the completion hook and persist it.
- **1.2** Installing daedalus (pipx, pip, or `bin/daedalus`) never
touches the shell; argcomplete stays dormant until the user's bash
evaluates `register-python-argcomplete daedalus` (INSTALL.md "Tab
completion"). This script performs that registration, so the
one-time setup is one command.
- **1.3** Standard library only; Python 3.11+ (SPEC item 9.6).
## 2. Command
- **2.1** `daedalus init [--bashrc PATH] [--dry-run]` - enables
completion and appends the hook to `--bashrc` (default
`~/.bashrc`), section 3.
## 3. Behavior
- **3.1** Locate `register-python-argcomplete`: first in the
directory of the running interpreter (`sys.executable`'s folder -
pipx venv, checkout .venv, and system installs all put it beside
python), then on `PATH` via `shutil.which`. Neither is exit 3
with a hint to reinstall (argcomplete is a declared dependency).
- **3.2** The hook is one managed block appended to the target
file:
```text
# BEGIN daedalus init: argcomplete
eval "$('<path to register-python-argcomplete>' daedalus)"
# END daedalus init: argcomplete
```
- **3.3** Target: `--bashrc PATH`, default `~/.bashrc`. Existing
content is preserved verbatim; the block is appended at the end
with a blank line before it when the file is non-empty.
- **3.4** Idempotence: when the file already holds the begin
marker, the run reports `already enabled`, writes nothing, and
exits 0. Restoring a `.bashrc` that already registered the hook
and re-running is a no-op.
- **3.5** On registering, the script prints what it appended, the
target, and how to activate it now (`exec bash` or a new shell);
it never re-executes the shell itself.
- **3.6** `--dry-run` prints the block and the target, creating /
appending nothing, and exits 0 (an already-enabled dry run
prints that instead).
- **3.7** On Windows (`os.name` not `posix`), nothing applies:
the script prints a notice (completion is bash/zsh only) and
exits 0 without touching any file.
- **3.8** When `$SHELL` names zsh and `--bashrc` was not passed,
a warning logs the two `bashcompinit` lines bash compat needs;
the script still writes the bash target as asked.
## 4. Exit codes
| Code | Meaning |
| --- | --- |
| 0 | registered, already enabled, nothing to do (non-POSIX), or dry run |
| 3 | `register-python-argcomplete` not found (item 3.1) |
## 5. Files written
- **5.1** Only the target file (item 3.2 block, item 3.3 target).
Nothing else; no package installs, no system files.
## 6. Testing approach
- **6.1** Tests live in `python/tests/test_init_script.py` (the
SPEC 6.6.1 name `test_init.py` is taken by
`daedalus/tests/test_init.py`; pytest needs unique basenames).
No network, no hardware; the register-script path is injectable
and the target is a temp file (daedalus agent rule 5.6).
- **6.2** Covered groups: block building (item 3.2), resolution
order beside python then `PATH` (3.1), idempotence (3.4),
preservation of existing content (3.3), dry run (3.6),
non-POSIX notice (3.7), missing-register exit 3, and the CLI
wiring (`--bashrc`, `--dry-run`, `--help`).
## 7. References
- **7.1** Shell reasons: INSTALL.md "Tab completion"; SPEC items
6.9 and 3.13.5.1 (argcomplete opt-in).
- **7.2** Repository rules: SPEC items 6.6 (tests), 9.8 (version
bump).
- **7.3** History: `CHANGELOG.md` entry 0.10.0.
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -34,7 +34,7 @@ def test_app_version_falls_back_to_pyproject(monkeypatch):
raise hello.importlib.metadata.PackageNotFoundError(_name)
monkeypatch.setattr(hello.importlib.metadata, "version", not_found)
assert hello.app_version() == "0.4.0"
assert hello.app_version() == "0.11.0"
def test_help_exits_zero(capsys):
+167
View File
@@ -0,0 +1,167 @@
"""Tests for the init script: argcomplete registration (init spec).
No network, no hardware: the register-script path is injectable and
the bashrc target a temp file (daedalus agent rule 5.6). File is
named test_init_script.py because daedalus/tests/test_init.py exists
and pytest needs unique basenames (init spec item 6.1).
"""
import pathlib
from daedalus.init import init
REGISTER = pathlib.Path("/venv/bin/register-python-argcomplete")
# --- block building (init spec item 3.2)
def test_build_block_contains_hook():
"""The block holds the markers and the eval line with the path."""
block = init.build_block(REGISTER)
assert block.startswith("# BEGIN daedalus init: argcomplete\n")
assert block.endswith("# END daedalus init: argcomplete\n")
assert f"eval \"$('{REGISTER}' daedalus)\"" in block
# --- register-script resolution (init spec item 3.1)
def test_register_script_path_beside_python(monkeypatch, tmp_path):
"""The interpreter's folder wins (pipx venv, .venv, system)."""
fake = tmp_path / "bin" / "register-python-argcomplete"
fake.parent.mkdir(parents=True)
fake.write_text("#!/bin/sh\n", encoding="utf-8")
monkeypatch.setattr(init.sys, "executable",
str(tmp_path / "bin" / "python"))
assert init.register_script_path() == fake
def test_register_script_path_prefers_venv_symlink(monkeypatch, tmp_path):
"""A venv python is a symlink; its own bin wins, not the target's.
resolve() on sys.executable would dereference the venv symlink
and hand the lookup to the system python's folder (init spec
item 3.1: the *running interpreter's* folder).
"""
real = tmp_path / "real" / "bin"
real.mkdir(parents=True)
(real / "python3").write_text("#!/bin/sh\n", encoding="utf-8")
(real / "register-python-argcomplete").write_text(
"#!/bin/sh\n", encoding="utf-8")
venv = tmp_path / "venv" / "bin"
venv.mkdir(parents=True)
(venv / "python").symlink_to(real / "python3")
(venv / "register-python-argcomplete").write_text(
"#!/bin/sh\n", encoding="utf-8")
monkeypatch.setattr(init.sys, "executable", str(venv / "python"))
assert init.register_script_path() == \
venv / "register-python-argcomplete"
def test_register_script_path_falls_back_to_path(monkeypatch):
"""Without a match beside python, PATH is searched."""
monkeypatch.setattr(init.sys, "executable", "/nowhere/python")
monkeypatch.setattr(init.shutil, "which",
lambda _name: "/usr/local/bin/register-python-argcomplete")
assert init.register_script_path() == \
pathlib.Path("/usr/local/bin/register-python-argcomplete")
def test_register_script_path_missing(monkeypatch):
"""Neither location has it: None (exit 3 upstream)."""
monkeypatch.setattr(init.sys, "executable", "/nowhere/python")
monkeypatch.setattr(init.shutil, "which", lambda _name: None)
assert init.register_script_path() is None
# --- main flow (init spec items 3.3-3.8)
def fake_register(monkeypatch, path):
"""Point register_script_path at a fixed path."""
monkeypatch.setattr(init, "register_script_path",
lambda: pathlib.Path(path))
def test_main_appends_block(tmp_path, monkeypatch, capsys):
"""A fresh bashrc receives the block, exit 0."""
target = tmp_path / "bashrc"
fake_register(monkeypatch, REGISTER)
assert init.main(["--bashrc", str(target)]) == 0
content = target.read_text(encoding="utf-8")
assert "# BEGIN daedalus init: argcomplete" in content
assert f"'{REGISTER}' daedalus" in content
out = capsys.readouterr().out
assert "registered" in out
assert "exec bash" in out
def test_main_preserves_existing_bashrc(tmp_path, monkeypatch):
"""Existing lines stay; the block lands after a blank line."""
target = tmp_path / "bashrc"
target.write_text("alias ll='ls -l'\n", encoding="utf-8")
fake_register(monkeypatch, REGISTER)
assert init.main(["--bashrc", str(target)]) == 0
content = target.read_text(encoding="utf-8")
assert content.startswith("alias ll='ls -l'\n\n")
assert content.endswith("# END daedalus init: argcomplete\n")
def test_main_idempotent(tmp_path, monkeypatch, capsys):
"""A second run reports already enabled and writes nothing."""
target = tmp_path / "bashrc"
fake_register(monkeypatch, REGISTER)
init.main(["--bashrc", str(target)])
before = target.read_text(encoding="utf-8")
assert init.main(["--bashrc", str(target)]) == 0
assert target.read_text(encoding="utf-8") == before
assert "already enabled" in capsys.readouterr().out
def test_main_dry_run(tmp_path, monkeypatch, capsys):
"""Dry run prints the block, creates and appends nothing."""
target = tmp_path / "bashrc"
fake_register(monkeypatch, REGISTER)
assert init.main(["--bashrc", str(target), "--dry-run"]) == 0
out = capsys.readouterr().out
assert "# BEGIN daedalus init: argcomplete" in out
assert "dry run" in out
assert not target.exists()
def test_main_missing_register(tmp_path, monkeypatch):
"""No register script anywhere is exit 3, no file written."""
target = tmp_path / "bashrc"
monkeypatch.setattr(init, "register_script_path", lambda: None)
assert init.main(["--bashrc", str(target)]) == 3
assert not target.exists()
def test_main_non_posix(tmp_path, monkeypatch, capsys):
"""On Windows nothing applies: notice, exit 0, no write."""
target = tmp_path / "bashrc"
fake_register(monkeypatch, REGISTER)
monkeypatch.setattr(init.os, "name", "nt")
assert init.main(["--bashrc", str(target)]) == 0
assert "bash/zsh" in capsys.readouterr().out
assert not target.exists()
def test_main_zsh_shell_gets_a_note(tmp_path, monkeypatch, caplog):
"""A zsh SHELL without --bashrc logs the bashcompinit warning."""
target = tmp_path / "bashrc"
fake_register(monkeypatch, REGISTER)
monkeypatch.setenv("SHELL", "/usr/bin/zsh")
monkeypatch.setattr(init.pathlib.Path, "home",
staticmethod(lambda: tmp_path))
assert init.main([]) == 0
assert "bashcompinit" in caplog.text
assert (tmp_path / ".bashrc").exists()
def test_cli_help():
"""--help prints usage."""
import pytest
with pytest.raises(SystemExit) as exc:
init.main(["--help"])
assert exc.value.code == 0