Compare commits
13
Commits
7aeeb6a6c7
..
master
No files matched your search
@@ -1,5 +1,36 @@
|
||||
# Changelog
|
||||
|
||||
## [0.2.0] - 2026-10-31
|
||||
|
||||
Added:
|
||||
|
||||
- Git: *branch-gc* clears merged branches and worktrees with *pkgmgr*
|
||||
- Agents: *subagent-model* uses a cheaper model only at 90 % same result
|
||||
- Agents: *subagent-model* hooks log every spawn and its rated quality
|
||||
|
||||
Changed:
|
||||
|
||||
- Coordination: never cut a running job or agent short, not even at its cap
|
||||
- Resources: *watch.py admit* grants test slots only below CPU and RAM limits
|
||||
- Coordination: a relayer writes an operator rule to shared memory first
|
||||
|
||||
Fixed:
|
||||
|
||||
- Resources: stop-stage cleanup now skips worktrees where *make* still runs
|
||||
- Resources: the block hook ignores heavy commands in quotes and heredocs
|
||||
- Update: *make update* now updates every locked source, not just the first
|
||||
- Update: *make update* installs for Claude Code only
|
||||
- CI: *ci-artifacts* signs lint failures by finding, ignores later steps
|
||||
- Release: *changelog* warns when a workflow on HEAD already failed
|
||||
- CI: ruff pinned in *pyproject.toml*; local and CI lint now agree
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- 0.1.0 was never published (its CI failed); its upgrade notes follow
|
||||
- Install: restart the agent after *make install* to load skills and hooks
|
||||
- Resources: *watch.py* needs *~/.config/agents-council/config.json*
|
||||
- Resources: add *busy_processes* and *load_limits* to that config
|
||||
|
||||
## [0.1.0] - 2026-10-30
|
||||
|
||||
Added:
|
||||
|
||||
@@ -7,9 +7,72 @@ Every skill is pinned in `skills-lock.json` for reproducible installs.
|
||||
First-party skills live under `skills/` and are layered on top of the locked ones at install time.
|
||||
Compatible with Claude Code, Codex, Gemini CLI, Cursor, Copilot, Windsurf, Cline, and other agents.
|
||||
|
||||
## Naming 🏷️
|
||||
|
||||
Every first-party skill is named `kvb-<category>-<name>` with one of these categories: `think`, `create`, `code`, `ci`, `git`, `check`, `org`, `skills`. Only `kvb-cleanup` and `kvb-help` stand without a category. Names use `a-z`, `0-9` and single hyphens, at most 64 characters, and equal their directory name. `tests/test_naming.py` enforces all of it, including that the organigram below lists every skill under its category.
|
||||
|
||||
## Organigram 🏛️
|
||||
|
||||
Every first-party skill under its category.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
kvb((kvb))
|
||||
kvb --> think[think]
|
||||
kvb --> create[create]
|
||||
kvb --> code[code]
|
||||
kvb --> ci[ci]
|
||||
kvb --> git[git]
|
||||
kvb --> check[check]
|
||||
kvb --> org[org]
|
||||
kvb --> skills[skills]
|
||||
kvb --> none[no category]
|
||||
think --> think_listen[kvb-think-listen]
|
||||
think --> think_explain[kvb-think-explain]
|
||||
think --> think_dialectic[kvb-think-dialectic]
|
||||
think --> think_criticize[kvb-think-criticize]
|
||||
create --> create_plan[kvb-create-plan]
|
||||
create --> create_feature[kvb-create-feature]
|
||||
code --> code_scope_guard[kvb-code-scope-guard]
|
||||
code --> code_no_defaults[kvb-code-no-defaults]
|
||||
code --> code_no_comments[kvb-code-no-comments]
|
||||
code --> code_refactor[kvb-code-refactor]
|
||||
code --> code_test[kvb-code-test]
|
||||
code --> code_tune[kvb-code-tune]
|
||||
ci --> ci_triage[kvb-ci-triage]
|
||||
ci --> ci_artifacts[kvb-ci-artifacts]
|
||||
ci --> ci_observe[kvb-ci-observe]
|
||||
git --> git_commit_next[kvb-git-commit-next]
|
||||
git --> git_commit_no_verify[kvb-git-commit-no-verify]
|
||||
git --> git_merge_fix[kvb-git-merge-fix]
|
||||
git --> git_branch_gc[kvb-git-branch-gc]
|
||||
git --> git_changelog[kvb-git-changelog]
|
||||
check --> check_legal[kvb-check-legal]
|
||||
check --> check_security[kvb-check-security]
|
||||
check --> check_principles[kvb-check-principles]
|
||||
check --> check_confidence[kvb-check-confidence]
|
||||
check --> check_break_risk[kvb-check-break-risk]
|
||||
org --> org_organize[kvb-org-organize]
|
||||
org --> org_split[kvb-org-split]
|
||||
org --> org_coordinate[kvb-org-coordinate]
|
||||
org --> org_perform[kvb-org-perform]
|
||||
org --> org_matrix[kvb-org-matrix]
|
||||
org --> org_rasci[kvb-org-rasci]
|
||||
org --> org_artefacts[kvb-org-artefacts]
|
||||
org --> org_wsjf[kvb-org-wsjf]
|
||||
org --> org_robot[kvb-org-robot]
|
||||
skills --> skills_dream[kvb-skills-dream]
|
||||
skills --> skills_tune[kvb-skills-tune]
|
||||
skills --> skills_auto[kvb-skills-auto]
|
||||
skills --> skills_essence[kvb-skills-essence]
|
||||
skills --> skills_shortcuts[kvb-skills-shortcuts]
|
||||
none --> cleanup[kvb-cleanup]
|
||||
none --> help[kvb-help]
|
||||
```
|
||||
|
||||
## Skill map 🗺️
|
||||
|
||||
How the first-party skills work together. A solid arrow means the skill invokes or relies on the other one; a dotted arrow means it fires automatically. Every skill that reports a result closes with the `confidence` block; those arrows are left out. The locked third-party skills (caveman, ponytail, archify) are not drawn.
|
||||
How the first-party skills work together. A solid arrow means the skill invokes or relies on the other one; a dotted arrow means it fires automatically. Every skill that reports a result closes with the `kvb-check-confidence` block; those arrows are left out. The locked third-party skills (caveman, ponytail, archify) are not drawn.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
@@ -19,58 +82,66 @@ flowchart LR
|
||||
edit_hook([edit in a git worktree])
|
||||
reminders([reminder hooks])
|
||||
code_task([code task])
|
||||
spawn([subagent spawn])
|
||||
end
|
||||
subgraph commit [Commit]
|
||||
commit_next[commit-next]
|
||||
commit_no_verify[commit-no-verify]
|
||||
comments_clean[comments-clean]
|
||||
advocate[advocate]
|
||||
confidence[confidence]
|
||||
break_risk[break-risk]
|
||||
explain[explain]
|
||||
subgraph cat_think [think]
|
||||
active_listening[kvb-think-listen]
|
||||
explain[kvb-think-explain]
|
||||
dialectic[kvb-think-dialectic]
|
||||
criticize[kvb-think-criticize]
|
||||
end
|
||||
subgraph coordination [Coordination]
|
||||
democracy[democracy]
|
||||
coordinate[coordinate]
|
||||
funnel[funnel]
|
||||
cleanup[cleanup]
|
||||
subgraph cat_create [create]
|
||||
plan[kvb-create-plan]
|
||||
auto_feature[kvb-create-feature]
|
||||
end
|
||||
subgraph ci [CI]
|
||||
observe[observe]
|
||||
triage[triage]
|
||||
ci_artifacts[ci-artifacts]
|
||||
tune[tune]
|
||||
merge_fix[merge-fix]
|
||||
subgraph cat_code [code]
|
||||
scope_guard[kvb-code-scope-guard]
|
||||
no_defaults[kvb-code-no-defaults]
|
||||
refactor[kvb-code-refactor]
|
||||
test[kvb-code-test]
|
||||
tune[kvb-code-tune]
|
||||
comments_clean[kvb-code-no-comments]
|
||||
end
|
||||
subgraph reasoning [Reasoning]
|
||||
active_listening[active-listening]
|
||||
dialectic[dialectic]
|
||||
criticize[criticize]
|
||||
sceptic[sceptic]
|
||||
auto_feature[auto-feature]
|
||||
subgraph cat_ci [ci]
|
||||
triage[kvb-ci-triage]
|
||||
ci_artifacts[kvb-ci-artifacts]
|
||||
observe[kvb-ci-observe]
|
||||
end
|
||||
subgraph autonomy [Autonomy]
|
||||
plan[plan]
|
||||
robot[robot]
|
||||
subgraph cat_git [git]
|
||||
commit_next[kvb-git-commit-next]
|
||||
commit_no_verify[kvb-git-commit-no-verify]
|
||||
merge_fix[kvb-git-merge-fix]
|
||||
branch_gc[kvb-git-branch-gc]
|
||||
changelog[kvb-git-changelog]
|
||||
end
|
||||
subgraph self_improvement [Self-improvement]
|
||||
dream[dream]
|
||||
autotune[autotune]
|
||||
autoskill[autoskill]
|
||||
essence[essence]
|
||||
shortcuts[shortcuts]
|
||||
subgraph cat_check [check]
|
||||
advocate[kvb-check-legal]
|
||||
medusa[kvb-check-security]
|
||||
sceptic[kvb-check-principles]
|
||||
confidence[kvb-check-confidence]
|
||||
break_risk[kvb-check-break-risk]
|
||||
end
|
||||
subgraph quality [Quality]
|
||||
test[test]
|
||||
refactor[refactor]
|
||||
no_defaults[no-defaults]
|
||||
scope_guard[scope-guard]
|
||||
subgraph cat_org [org]
|
||||
democracy[kvb-org-organize]
|
||||
funnel[kvb-org-split]
|
||||
coordinate[kvb-org-coordinate]
|
||||
subagent_model[kvb-org-perform]
|
||||
status_matrix[kvb-org-matrix]
|
||||
rasci[kvb-org-rasci]
|
||||
artefacts[kvb-org-artefacts]
|
||||
wsjf[kvb-org-wsjf]
|
||||
robot[kvb-org-robot]
|
||||
end
|
||||
subgraph standalone [Standalone]
|
||||
changelog[changelog]
|
||||
help_skills[help-skills]
|
||||
status_matrix[status-matrix]
|
||||
medusa[medusa]
|
||||
subgraph cat_skills [skills]
|
||||
dream[kvb-skills-dream]
|
||||
autotune[kvb-skills-tune]
|
||||
autoskill[kvb-skills-auto]
|
||||
essence[kvb-skills-essence]
|
||||
shortcuts[kvb-skills-shortcuts]
|
||||
end
|
||||
subgraph cat_none [no category]
|
||||
cleanup[kvb-cleanup]
|
||||
help_skills[kvb-help]
|
||||
end
|
||||
|
||||
commit_req -.-> commit_next
|
||||
@@ -81,6 +152,7 @@ flowchart LR
|
||||
reminders -.-> autotune
|
||||
code_task -.-> no_defaults
|
||||
code_task -.-> scope_guard
|
||||
spawn -.-> subagent_model
|
||||
|
||||
commit_next --> merge_fix
|
||||
commit_next --> commit_no_verify
|
||||
@@ -94,9 +166,21 @@ flowchart LR
|
||||
|
||||
coordinate --> democracy
|
||||
cleanup --> democracy
|
||||
cleanup --> branch_gc
|
||||
branch_gc --> democracy
|
||||
funnel --> democracy
|
||||
funnel --> dialectic
|
||||
funnel --> subagent_model
|
||||
dialectic --> subagent_model
|
||||
democracy --> merge_fix
|
||||
democracy -. claim and release .-> rasci
|
||||
funnel --> rasci
|
||||
status_matrix --> rasci
|
||||
cleanup --> artefacts
|
||||
artefacts --> rasci
|
||||
democracy --> wsjf
|
||||
wsjf --> rasci
|
||||
dream --> rasci
|
||||
|
||||
observe --> triage
|
||||
observe --> ci_artifacts
|
||||
@@ -155,7 +239,7 @@ Copy the skills into a specific project (`<repo>/.agents/skills` and `<repo>/.cl
|
||||
make project TARGET=/path/to/repo
|
||||
```
|
||||
|
||||
Both commands also patch the target's `.claude/settings.local.json` — the machine-local, untracked file, so a project's reviewed `.claude/settings.json` is never rewritten by an install: the caveman and ponytail plugins are enabled so their modes auto-activate on session start, and two reminder hooks are registered — `autotune` points you at `/autotune` at most once an hour, `dream` points you at `/dream` at most once every twelve hours per repository (stamped in that repository's git dir). A PreToolUse gate from the `democracy` skill blocks edits to files in a git worktree until the session holds a claim (`skills/democracy/scripts/council.py`), and its resource watch (`skills/democracy/scripts/watch.py`) measures disk, Docker and caches, cleans up low-risk data and blocks new heavy jobs before the disk runs out; it stays inactive until `~/.config/agents-council/config.json` exists. Existing settings are preserved.
|
||||
Both commands also patch the target's `.claude/settings.local.json` — the machine-local, untracked file, so a project's reviewed `.claude/settings.json` is never rewritten by an install: the caveman and ponytail plugins are enabled so their modes auto-activate on session start, and two reminder hooks are registered — `kvb-skills-tune` points you at `/kvb-skills-tune` at most once an hour, `kvb-skills-dream` points you at `/kvb-skills-dream` at most once every twelve hours per repository (stamped in that repository's git dir). A PreToolUse gate from the `kvb-org-organize` skill blocks edits to files in a git worktree until the session holds a claim (`skills/kvb-org-organize/scripts/council.py`), and its resource watch (`skills/kvb-org-organize/scripts/watch.py`) measures disk, Docker and caches, cleans up low-risk data and blocks new heavy jobs before the disk runs out; it stays inactive until `~/.config/agents-council/config.json` exists. Two hooks of the `kvb-org-perform` skill (`skills/kvb-org-perform/scripts/log.py`) log every Agent spawn with its task class, model and effort, and store the quality feedback a sandboxed session prints, in `~/.local/state/agents-council/subagent-model.jsonl`. Existing settings are preserved.
|
||||
|
||||
Restart your agent afterwards so it loads the new skills.
|
||||
|
||||
|
||||
+35
-15
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
// Enable the caveman and ponytail plugins in a Claude Code settings.json so
|
||||
// their SessionStart hooks auto-activate both modes, register the autotune
|
||||
// and dream reminder hooks, the democracy claim gate and the resource watch. Merges non-destructively: existing marketplaces,
|
||||
// plugins and hooks are preserved, unparseable files are left untouched.
|
||||
// their SessionStart hooks auto-activate both modes, register the kvb-skills-tune
|
||||
// and kvb-skills-dream reminder hooks, the kvb-org-organize claim gate, the resource watch and the kvb-org-perform log. Merges non-destructively: existing marketplaces,
|
||||
// plugins and hooks are preserved, hooks of renamed skills are repointed, unparseable files are left untouched.
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
@@ -19,7 +19,14 @@ const MARKETPLACES = {
|
||||
ponytail: { source: { source: "github", repo: "DietrichGebert/ponytail" } },
|
||||
};
|
||||
const PLUGINS = { "caveman@caveman": true, "ponytail@ponytail": true };
|
||||
const REMINDERS = ["autotune", "dream"];
|
||||
const REMINDERS = ["kvb-skills-tune", "kvb-skills-dream"];
|
||||
const RENAMED = {
|
||||
"autotune/hooks/reminder.sh": "kvb-skills-tune/hooks/reminder.sh",
|
||||
"dream/hooks/reminder.sh": "kvb-skills-dream/hooks/reminder.sh",
|
||||
"democracy/scripts/council.py": "kvb-org-organize/scripts/council.py",
|
||||
"democracy/scripts/watch.py": "kvb-org-organize/scripts/watch.py",
|
||||
"subagent-model/scripts/log.py": "kvb-org-perform/scripts/log.py",
|
||||
};
|
||||
|
||||
let data = {};
|
||||
if (fs.existsSync(settingsPath)) {
|
||||
@@ -41,6 +48,17 @@ for (const [name, entry] of Object.entries(MARKETPLACES)) {
|
||||
data.enabledPlugins = Object.assign(data.enabledPlugins || {}, PLUGINS);
|
||||
|
||||
data.hooks = data.hooks || {};
|
||||
for (const entries of Object.values(data.hooks)) {
|
||||
if (!Array.isArray(entries)) continue;
|
||||
for (const entry of entries) {
|
||||
for (const hook of entry.hooks || []) {
|
||||
if (typeof hook.command !== "string") continue;
|
||||
for (const [from, to] of Object.entries(RENAMED)) {
|
||||
hook.command = hook.command.replace(`/skills/${from}`, `/skills/${to}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
data.hooks.UserPromptSubmit = data.hooks.UserPromptSubmit || [];
|
||||
const alreadyRegistered = JSON.stringify(data.hooks.UserPromptSubmit);
|
||||
for (const skill of REMINDERS) {
|
||||
@@ -52,29 +70,31 @@ for (const skill of REMINDERS) {
|
||||
}
|
||||
|
||||
data.hooks.PreToolUse = data.hooks.PreToolUse || [];
|
||||
if (!JSON.stringify(data.hooks.PreToolUse).includes("democracy/scripts/council.py")) {
|
||||
const council = path.join(path.dirname(settingsPath), "skills", "democracy", "scripts", "council.py");
|
||||
if (!JSON.stringify(data.hooks.PreToolUse).includes("kvb-org-organize/scripts/council.py")) {
|
||||
const council = path.join(path.dirname(settingsPath), "skills", "kvb-org-organize", "scripts", "council.py");
|
||||
data.hooks.PreToolUse.push({
|
||||
matcher: "Edit|Write|MultiEdit|NotebookEdit",
|
||||
hooks: [{ type: "command", command: `python3 ${JSON.stringify(council)} gate` }],
|
||||
});
|
||||
}
|
||||
|
||||
const watch = path.join(path.dirname(settingsPath), "skills", "democracy", "scripts", "watch.py");
|
||||
const WATCH_HOOKS = [
|
||||
["UserPromptSubmit", null, "watch"],
|
||||
["PostToolUse", "Bash", "watch"],
|
||||
["PreToolUse", "Bash", "block"],
|
||||
const SCRIPT_HOOKS = [
|
||||
["kvb-org-organize/scripts/watch.py", "UserPromptSubmit", null, "watch"],
|
||||
["kvb-org-organize/scripts/watch.py", "PostToolUse", "Bash", "watch"],
|
||||
["kvb-org-organize/scripts/watch.py", "PreToolUse", "Bash", "block"],
|
||||
["kvb-org-perform/scripts/log.py", "PreToolUse", "Agent|Task", "spawn"],
|
||||
["kvb-org-perform/scripts/log.py", "PostToolUse", "Bash", "persist"],
|
||||
];
|
||||
for (const [event, matcher, sub] of WATCH_HOOKS) {
|
||||
for (const [script, event, matcher, sub] of SCRIPT_HOOKS) {
|
||||
data.hooks[event] = data.hooks[event] || [];
|
||||
const registered = data.hooks[event].some((entry) =>
|
||||
(entry.hooks || []).some((hook) =>
|
||||
String(hook.command).includes("democracy/scripts/watch.py") && String(hook.command).endsWith(` ${sub}`)));
|
||||
String(hook.command).includes(script) && String(hook.command).endsWith(` ${sub}`)));
|
||||
if (registered) continue;
|
||||
const entry = { hooks: [{ type: "command", command: `python3 ${JSON.stringify(watch)} ${sub}` }] };
|
||||
const file = path.join(path.dirname(settingsPath), "skills", ...script.split("/"));
|
||||
const entry = { hooks: [{ type: "command", command: `python3 ${JSON.stringify(file)} ${sub}` }] };
|
||||
data.hooks[event].push(matcher ? { matcher, ...entry } : entry);
|
||||
}
|
||||
|
||||
fs.writeFileSync(settingsPath, JSON.stringify(data, null, 2) + "\n");
|
||||
console.log(`skills: enabled caveman + ponytail plugins, the ${REMINDERS.join(" + ")} reminders, the democracy claim gate and resource watch in ${settingsPath}`);
|
||||
console.log(`skills: enabled caveman + ponytail plugins, the ${REMINDERS.join(" + ")} reminders, the kvb-org-organize claim gate, the resource watch and the kvb-org-perform log in ${settingsPath}`);
|
||||
@@ -1,11 +0,0 @@
|
||||
---
|
||||
name: coordinate
|
||||
description: >
|
||||
Coordinate a failure or fix with the agents on related branches through
|
||||
merges: claim, ask, report. Trigger on /coordinate and when a fix touches
|
||||
code other branches share.
|
||||
---
|
||||
|
||||
Run the `democracy` skill's **Lineage** and **Peer protocol** sections for the
|
||||
failure or fix at hand. They hold the whole procedure; this skill only keeps
|
||||
`/coordinate` working.
|
||||
@@ -1,8 +1,8 @@
|
||||
---
|
||||
name: break-risk
|
||||
name: kvb-check-break-risk
|
||||
description: >
|
||||
Derive the break-risk percentage from measurement, not feel. Called by
|
||||
`confidence` on every report; also when the operator asks "what could this
|
||||
`kvb-check-confidence` on every report; also when the operator asks "what could this
|
||||
break?" or names a break-risk threshold.
|
||||
---
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Break risk: the method in detail
|
||||
|
||||
Each step of the `break-risk` skill, with the trap it defeats.
|
||||
Each step of the `kvb-check-break-risk` skill, with the trap it defeats.
|
||||
|
||||
## The consumer question, first and always
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: confidence
|
||||
name: kvb-check-confidence
|
||||
description: >
|
||||
Report calibrated fix confidence and break risk unprompted whenever you
|
||||
stage changes, declare a fix or bundle ready, or summarize work the operator
|
||||
@@ -9,12 +9,12 @@ description: >
|
||||
Every stage summary, fix report, or ready-to-commit bundle ends with a
|
||||
confidence block.
|
||||
|
||||
Invoke the `break-risk` skill every time, before writing the block; this skill
|
||||
Invoke the `kvb-check-break-risk` skill every time, before writing the block; this skill
|
||||
reports the number it derives and never estimates one itself.
|
||||
|
||||
1. **Fix confidence** (percent): probability the change does what it
|
||||
claims. **Break risk** (percent): probability it breaks anything else,
|
||||
derived via the `break-risk` skill. Two separate numbers, never one
|
||||
derived via the `kvb-check-break-risk` skill. Two separate numbers, never one
|
||||
blended figure.
|
||||
2. **Evidence**: the strongest proof lines only — what was executed,
|
||||
reproduced, enumerated, or read from authoritative source. Distinguish
|
||||
@@ -33,8 +33,8 @@ Calibration rules:
|
||||
(test, reproduction, live probe) justifies more.
|
||||
|
||||
A threshold the operator named ("95% confidence, break risk ≤5%") is a gate on
|
||||
the work, handled as the `break-risk` skill's last section says, for both
|
||||
the work, handled as the `kvb-check-break-risk` skill's last section says, for both
|
||||
numbers.
|
||||
|
||||
Objective: the `autotune` skill's **Objective** section. Two figures with their residuals replace a
|
||||
Objective: the `kvb-skills-tune` skill's **Objective** section. Two figures with their residuals replace a
|
||||
hedging paragraph and save the operator a verification round trip.
|
||||
@@ -1,24 +1,24 @@
|
||||
---
|
||||
name: advocate
|
||||
name: kvb-check-legal
|
||||
description: >
|
||||
Check a commit for legal soundness: licence compatibility of added code and
|
||||
dependencies, attribution, copied snippets, GDPR, trademarks. Run
|
||||
AUTOMATICALLY before every commit the operator requests; also on /advocate
|
||||
AUTOMATICALLY before every commit the operator requests; also on /kvb-check-legal
|
||||
[ref|range], "rechtlich prüfen", "lizenz prüfen".
|
||||
---
|
||||
|
||||
The stance is the project's counsel: find what would make the change unlawful
|
||||
to distribute before it is distributed. This is not legal advice but a reading
|
||||
of the licence texts, with German and EU law where jurisdiction matters; every
|
||||
report says so in one line. Leaked secrets belong to `medusa`, engineering
|
||||
principles to `sceptic`.
|
||||
report says so in one line. Leaked secrets belong to `kvb-check-security`, engineering
|
||||
principles to `kvb-check-principles`.
|
||||
|
||||
## Target
|
||||
|
||||
- Before a commit: the staging index (`git diff --cached`, plus every added or
|
||||
changed file in full where origin or licence is in question).
|
||||
- `/advocate <ref>` or `/advocate <a>..<b>`: that commit or range.
|
||||
- `/advocate` alone: the index if it is non-empty, else `HEAD`.
|
||||
- `/kvb-check-legal <ref>` or `/kvb-check-legal <a>..<b>`: that commit or range.
|
||||
- `/kvb-check-legal` alone: the index if it is non-empty, else `HEAD`.
|
||||
|
||||
## Fast exit
|
||||
|
||||
@@ -56,7 +56,7 @@ attribution, copied snippets, data protection, trademarks).
|
||||
|
||||
## Blockers stop the commit
|
||||
|
||||
Harden every blocker with the `dialectic` skill before reporting it. The
|
||||
Harden every blocker with the `kvb-think-dialectic` skill before reporting it. The
|
||||
antithesis tries: the code is trivial or the operator's own; the dependency is
|
||||
build- or test-only and never distributed; an exception applies (linking or
|
||||
Classpath exception, dual licensing, a licence grant in the issue or commit
|
||||
@@ -75,7 +75,7 @@ the operator's language). Then one table, blockers first:
|
||||
|
||||
`Evidence` is `proven` (licence text, metadata, or file read; cite path:line
|
||||
or the registry URL) or `derived` (inferred). Close with the verdict (commit
|
||||
stops or proceeds) and the `confidence` skill's numbers.
|
||||
stops or proceeds) and the `kvb-check-confidence` skill's numbers.
|
||||
|
||||
## Rules
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Advocate: the checks
|
||||
|
||||
Apply each check to a target the `advocate` skill found in scope.
|
||||
Apply each check to a target the `kvb-check-legal` skill found in scope.
|
||||
|
||||
1. **Inbound code** - every file or block of foreign origin carries a licence
|
||||
that the project licence can absorb in the direction of distribution. GPL
|
||||
@@ -1,15 +1,15 @@
|
||||
---
|
||||
name: sceptic
|
||||
name: kvb-check-principles
|
||||
description: >
|
||||
Analyse a repository, path or diff with a hostile eye for violated
|
||||
principles: SPOT, DRY, KISS, SRP, security at trust boundaries. Trigger on
|
||||
/sceptic, "sei skeptisch", "kritische analyse", "review the architecture",
|
||||
or "what is wrong with the code".
|
||||
Analyse a repository, path or diff for violated principles: SPOT, DRY, KISS,
|
||||
SRP, security at trust boundaries. Trigger on /kvb-check-principles, "sei
|
||||
skeptisch", "kritische analyse", "review the architecture", or "what is
|
||||
wrong with the code".
|
||||
---
|
||||
|
||||
The stance is adversarial: the code is guilty until its structure proves
|
||||
otherwise. This skill hunts violated principles, not bugs (`code-review`),
|
||||
not bloat (`ponytail-audit`), not leaked secrets (`medusa`). Read-only —
|
||||
not bloat (`ponytail-audit`), not leaked secrets (`kvb-check-security`). Read-only —
|
||||
report the findings, change nothing unless the operator asks afterwards.
|
||||
|
||||
## Scope
|
||||
@@ -44,7 +44,7 @@ Apply each independently; a finding belongs to exactly one:
|
||||
findings only.
|
||||
6. **Silent defaults** — a fallback that substitutes a guess for a value the
|
||||
caller failed to supply, turning a misconfiguration into wrong behaviour
|
||||
instead of a loud failure. See the `no-defaults` skill.
|
||||
instead of a loud failure. See the `kvb-code-no-defaults` skill.
|
||||
|
||||
## Method
|
||||
|
||||
@@ -55,7 +55,7 @@ Apply each independently; a finding belongs to exactly one:
|
||||
which value drifts, which caller breaks, which input reaches which sink.
|
||||
A finding whose worst case is "feels wrong" gets deleted, not softened.
|
||||
- **Attack your own finding.** For anything consequential or expensive to
|
||||
fix, run it through the `dialectic` skill before reporting it — the
|
||||
fix, run it through the `kvb-think-dialectic` skill before reporting it — the
|
||||
strongest counter-argument is usually "these two are not the same
|
||||
knowledge" or "this boundary is already checked upstream".
|
||||
- **Respect intent.** A deliberate marker (`ponytail:`, a documented
|
||||
@@ -69,7 +69,7 @@ One ranked table, worst blast radius first:
|
||||
| Severity | Principle | Location | What is wrong | Smallest fix |
|
||||
|
||||
Then three closing lines at most: what the scope excluded, which findings
|
||||
survived `dialectic` versus which are still derived-only, and the single
|
||||
survived `kvb-think-dialectic` versus which are still derived-only, and the single
|
||||
finding to fix first. No per-finding paragraphs — the operator asks when a
|
||||
row needs unpacking.
|
||||
|
||||
@@ -78,7 +78,7 @@ row needs unpacking.
|
||||
- Never report formatting, naming taste, or missing comments; a linter owns
|
||||
those and the operator did not ask.
|
||||
- Distinguish proven (grepped, read, reproduced) from derived (reasoned
|
||||
statically) per finding, and close with the `confidence` skill's numbers
|
||||
statically) per finding, and close with the `kvb-check-confidence` skill's numbers
|
||||
for the audit as a whole.
|
||||
- No silent caps: if you ranked and cut, say how many findings were dropped
|
||||
and by what rule.
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: medusa
|
||||
name: kvb-check-security
|
||||
description: >
|
||||
Run the MEDUSA security scanner (medusa-security, PyPI) on a repository,
|
||||
working tree or secret stores. Use for security scans, vetting a repo before
|
||||
cloning, leaked-secret detection in chat or shell history, or /medusa.
|
||||
cloning, leaked-secret detection in chat or shell history, or /kvb-check-security.
|
||||
Defensive only.
|
||||
---
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: ci-artifacts
|
||||
name: kvb-ci-artifacts
|
||||
description: >
|
||||
Get the evidence out of a CI run: failed job logs (also mid-run) clustered
|
||||
by error line, and the artifacts that hold the cause. Trigger whenever a CI
|
||||
File renamed without changes.
@@ -1,8 +1,8 @@
|
||||
---
|
||||
name: observe
|
||||
name: kvb-ci-observe
|
||||
description: >
|
||||
Watch a named target (CI run, pipeline, build, log) on a cadence and triage
|
||||
new failures as they appear. Trigger on /observe <target> or when the
|
||||
new failures as they appear. Trigger on /kvb-ci-observe <target> or when the
|
||||
operator asks to keep monitoring and fix regressions.
|
||||
---
|
||||
|
||||
@@ -23,18 +23,18 @@ baseline, so a stale baseline re-triages solved failures.
|
||||
|
||||
Drive this with `/loop` in dynamic mode (no fixed interval unless the operator
|
||||
gave one): after each observation, schedule the next wake-up yourself and pass
|
||||
the same `/observe` prompt back so the next firing repeats the watch.
|
||||
the same `/kvb-ci-observe` prompt back so the next firing repeats the watch.
|
||||
|
||||
1. **Poll the target.** Pull its current state (job list, check conclusions, the
|
||||
log's tail); for a GitHub Actions run, the ci-artifacts skill's
|
||||
`ci_failures.py <run>`. Enumerate the failures exactly as the `triage` skill's step 1
|
||||
log's tail); for a GitHub Actions run, the kvb-ci-artifacts skill's
|
||||
`ci_failures.py <run>`. Enumerate the failures exactly as the `kvb-ci-triage` skill's step 1
|
||||
does: failure, cancelled, timed-out; a downstream aggregate that fails only
|
||||
because an upstream did is not its own failure.
|
||||
2. **Diff against the baseline.** A failure is *new* only if it is not in the
|
||||
baseline and was not already triaged this session. If nothing is new, log one
|
||||
short line ("still green" / "N known failures, no change") and reschedule.
|
||||
3. **Triage each new failure.** Invoke the `triage` skill on the new set only —
|
||||
which applies `dialectic` per failing job to a ~99% root cause and a real
|
||||
3. **Triage each new failure.** Invoke the `kvb-ci-triage` skill on the new set only —
|
||||
which applies `kvb-think-dialectic` per failing job to a ~99% root cause and a real
|
||||
fix. Never mask (no retry-until-pass, no disabled check, no soft-skip). Fold
|
||||
each newly fixed failure into the baseline so it is not re-triaged.
|
||||
4. **Reschedule.** Pick the next delay from what you are waiting on: an active
|
||||
@@ -50,7 +50,7 @@ the same `/observe` prompt back so the next firing repeats the watch.
|
||||
notification instead of polling for it; reserve the timed wake-up for external
|
||||
state the harness cannot see (a remote CI run, a deploy queue).
|
||||
- Executed evidence beats reasoning: read the actual failing log line and the
|
||||
artifact, not the job title — triage and dialectic carry this through.
|
||||
artifact, not the job title — kvb-ci-triage and kvb-think-dialectic carry this through.
|
||||
- One baseline, updated in place: dedup every observation against all failures
|
||||
seen so far, or a flaky-then-fixed failure reappears every cycle and the watch
|
||||
never converges.
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: triage
|
||||
name: kvb-ci-triage
|
||||
description: >
|
||||
Triage a failing CI run, pipeline or job set to a verified root cause and a
|
||||
real fix, one cluster per worktree. Trigger when a build, test or deploy
|
||||
@@ -12,7 +12,7 @@ root cause is proven.
|
||||
|
||||
## Procedure
|
||||
|
||||
For a GitHub Actions run, the ci-artifacts skill's `ci_failures.py <run>`
|
||||
For a GitHub Actions run, the kvb-ci-artifacts skill's `ci_failures.py <run>`
|
||||
does the mechanics of steps 0 to 2 in one call: distance to HEAD, the failed
|
||||
jobs' logs, and a first clustering. The judgement in those steps stays yours.
|
||||
|
||||
@@ -37,11 +37,13 @@ jobs' logs, and a first clustering. The judgement in those steps stays yours.
|
||||
actual failing line, not by job name. Jobs whose messages differ in anything
|
||||
but the interpolated identifiers (host, app, port, path) belong in separate
|
||||
clusters.
|
||||
3. **Coordinate every cluster.** Run the `democracy` skill's Lineage and Peer
|
||||
3. **Coordinate every cluster.** Run the `kvb-org-organize` skill's Lineage and Peer
|
||||
protocol for each cluster before fixing it: claim it, ask the lineage
|
||||
whether someone already fixes it, and take their fix or keep yours. Keep
|
||||
investigating while you wait for answers.
|
||||
4. **Download artifacts per cluster.** Use the `ci-artifacts` skill for the
|
||||
investigating while you wait for answers. In the `kvb-org-rasci` register
|
||||
the cluster's objective is the root cause fixed, its key results are the
|
||||
failing jobs passing again, one per job.
|
||||
4. **Download artifacts per cluster.** Use the `kvb-ci-artifacts` skill for the
|
||||
mechanics — it covers per-job logs while a run is still in progress, which
|
||||
bundle to pull, and the grep hygiene that keeps a false positive from
|
||||
becoming a root cause. For each cluster, fetch every artifact of
|
||||
@@ -53,14 +55,15 @@ jobs' logs, and a first clustering. The judgement in those steps stays yours.
|
||||
log looks conclusive, because a log that explains the symptom rarely
|
||||
explains the cause.
|
||||
5. **One funnel per cluster.** Hand every cluster you claimed in step 3 to the
|
||||
`funnel` skill: one agent per cluster, working in its own worktree on its own
|
||||
`kvb-org-split` skill: one agent per cluster, working in its own worktree on its own
|
||||
branch created from the exact current HEAD, with that cluster as its only
|
||||
concern, the artifact paths of step 4 in its brief and a hard time cap.
|
||||
concern, the artifact paths of step 4 in its brief and a time cap for its
|
||||
interim report.
|
||||
Steps 6 to 8 run inside that sidetree, so no cluster's edits land under
|
||||
another cluster's work or under a running gate or deploy. Run clusters in
|
||||
parallel only when their fixes touch different files and the machine has
|
||||
room. A split cluster (step 7) gets a funnel of its own.
|
||||
6. **Dialectic per cluster.** For EACH cluster, invoke the `dialectic` skill:
|
||||
6. **Dialectic per cluster.** For EACH cluster, invoke the `kvb-think-dialectic` skill:
|
||||
form a thesis about the root cause from evidence (the job log, its artifacts,
|
||||
the code at the run's commit, git history), attack it with independent
|
||||
skeptics, and iterate to a ~99% thesis.
|
||||
@@ -70,18 +73,18 @@ jobs' logs, and a first clustering. The judgement in those steps stays yours.
|
||||
is actually green, not just past the first error.
|
||||
8. **Fix at the root, through the funnel.** Apply the real fix for each proven
|
||||
root cause in the cluster's sidetree, with a test and a negative control as
|
||||
the `funnel` skill demands. The fix enters the main line only at the funnel's
|
||||
the `kvb-org-split` skill demands. The fix enters the main line only at the funnel's
|
||||
bar (at least 90 % fix confidence, under 5 % break risk) after its
|
||||
independent review; below the bar the cluster ends as a proposal for the
|
||||
operator, never as a merge. Never mask a failure: no retry-until-pass, no
|
||||
disabling the check, no soft-skip. If a failure is genuinely external
|
||||
(upstream outage, flaky infra), confirm that with evidence and surface it
|
||||
honestly instead of fixing around it. Report every fix, every proposal, and
|
||||
every abandoned attempt to the same agents through the `democracy` Peer protocol,
|
||||
every abandoned attempt to the same agents through the `kvb-org-organize` Peer protocol,
|
||||
then remove the sidetree.
|
||||
9. **Tune what ran out of time.** Only for a cluster whose jobs died on their
|
||||
time budget (timed out, or cancelled by the runner's limit), or when the
|
||||
operator asks: hand the job log that ran furthest to the `tune` skill. Its
|
||||
operator asks: hand the job log that ran furthest to the `kvb-code-tune` skill. Its
|
||||
candidates run through funnels of their own, separate from the cluster's fix
|
||||
sidetree, and never delay or block the fix.
|
||||
10. **Follow the run.** While the run is still in progress, re-check it
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: cleanup
|
||||
name: kvb-cleanup
|
||||
description: >
|
||||
Free disk space agents filled: ask peer sessions what they still need,
|
||||
Free disk space agents filled: ask peers what they still need,
|
||||
inventory /tmp, Docker and agent dirs, and delete only what the operator
|
||||
picks. Trigger on /cleanup, "aufräumen", "bereinigen", "platte voll", "no
|
||||
picks. Trigger on /kvb-cleanup, "aufräumen", "bereinigen", "platte voll", "no
|
||||
space left on device".
|
||||
---
|
||||
|
||||
@@ -12,10 +12,10 @@ its owner, its size, and its risk.
|
||||
|
||||
## Step 0: the resource chair
|
||||
|
||||
Shared resources belong to the resource chair of the `democracy` skill. If
|
||||
Shared resources belong to the resource chair of the `kvb-org-organize` skill. If
|
||||
another session holds the chair, send it the cleanup request and stop, unless
|
||||
the operator ordered the cleanup in this session; then tell the chair before
|
||||
step 1, so its grants and queue stay consistent. The `democracy` resource
|
||||
step 1, so its grants and queue stay consistent. The `kvb-org-organize` resource
|
||||
watch already runs the configured low-risk cleanup at its stop threshold; this
|
||||
skill covers everything that needs the operator's pick.
|
||||
|
||||
@@ -58,7 +58,11 @@ Read-only, in parallel, sizes included:
|
||||
label, anonymous ones included.
|
||||
- **Other agent dirs**: package and tool caches (pip, npm, pre-commit, act,
|
||||
gh, buildx), worktrees with `git status --short` and whether their branch is
|
||||
merged or pushed, Ansible and build temp dirs.
|
||||
merged or pushed, Ansible and build temp dirs. With `pkgmgr` installed,
|
||||
merged branches and worktrees go to the `kvb-git-branch-gc` skill instead.
|
||||
- **Register**: `rasci.py artifacts` of the `kvb-org-artefacts` skill:
|
||||
workdir, branch and artifacts of every task in the `kvb-org-rasci` register,
|
||||
with its status and worker; `--ended` narrows it to the candidates.
|
||||
- **Live use**: open handles (`fuser`, `lsof`) and running processes by name
|
||||
only (`ps -o pid,etime,comm`). Never print full command lines or
|
||||
environments: process arguments carry credentials. A sandboxed agent often
|
||||
@@ -80,10 +84,15 @@ worktree or compose project name, a container label, an open handle, or
|
||||
`unknown`. Then apply, first match wins:
|
||||
|
||||
1. Claimed by a peer: `keep`.
|
||||
2. Attributable to a peer that has not answered: `keep (no answer from
|
||||
2. Listed in the register under a task that is not `done`, `stopped` or `stale`:
|
||||
`keep (task <task>)`. Under an ended task it is a candidate whose owner is
|
||||
the task's worker.
|
||||
3. A job running on it (deploy, gate, test, swarm run, build): `keep
|
||||
(running)`.
|
||||
4. Attributable to a peer that has not answered: `keep (no answer from
|
||||
<peer>)`. Silence is not consent.
|
||||
3. Archive duty: `archive first`.
|
||||
4. Everything else is a candidate with a risk class:
|
||||
5. Archive duty: `archive first`.
|
||||
6. Everything else is a candidate with a risk class:
|
||||
|
||||
| Risk | Meaning | Typical items |
|
||||
| ---- | ------- | ------------- |
|
||||
@@ -145,9 +154,17 @@ ticked items. Revise repeats call 1; nothing is deleted before `Execute`.
|
||||
rest, then put the refused item to the operator again as its own option: an
|
||||
explicit renewed selection may pass; if it is refused again, hand over the
|
||||
exact command with its list file for the operator to run.
|
||||
- Running stacks go down through the project's teardown target, never by
|
||||
- Never stop, take down or kill a running job, and never ask its owner to, to
|
||||
free space: not for a priority slot, not at a disk stop. Free idle items,
|
||||
ask the operator for an exception, or wait; an owner's own disk guard only
|
||||
alerts the chair, and only the operator can order a running job down.
|
||||
A hung job is not freed through cleanup: the `kvb-org-organize` skill's hang rule
|
||||
lets only its owner end it.
|
||||
- Idle running stacks go down through the project's teardown target, never by
|
||||
removing their containers or volumes underneath them.
|
||||
- Archive-first items: copy out, verify the copy, then delete.
|
||||
- Drop every deleted item from its task as the `kvb-org-artefacts` skill
|
||||
says (`set <task> --drop-artifact <kind>:<ref>`), so `artifacts` stays true.
|
||||
- A delete failing on permissions (files owned by a container UID): use the
|
||||
project's container helper. Never sudo, never bypass the sandbox; without a
|
||||
helper, report the path.
|
||||
@@ -1,10 +1,10 @@
|
||||
---
|
||||
name: comments-clean
|
||||
name: kvb-code-no-comments
|
||||
description: >
|
||||
Purge explanatory comments from staged and unstaged changes. Run
|
||||
AUTOMATICALLY before every commit or stage request (commit, commit
|
||||
no-verify, stage next, socon, sobu, socobu, "commite ..."); also on
|
||||
/comments-clean or comment complaints.
|
||||
/kvb-code-no-comments or comment complaints.
|
||||
---
|
||||
|
||||
When the operator asks to commit or stage, run this audit first and only
|
||||
@@ -32,7 +32,7 @@ added lines only) and delete every explanatory comment:
|
||||
both the lint and the language parser can pass over code that no longer
|
||||
executes. Diff against the pre-edit revision (`git show HEAD:<path>`) and
|
||||
confirm that only comment lines left.
|
||||
5. Do not stage in order to run a check (the `commit-next` skill's step 4
|
||||
5. Do not stage in order to run a check (the `kvb-git-commit-next` skill's step 4
|
||||
says why). Re-stage after the audit exactly the files that were staged
|
||||
before it.
|
||||
6. Penalty: if this audit finds anything you wrote yourself, admit it in
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: no-defaults
|
||||
name: kvb-code-no-defaults
|
||||
description: >
|
||||
Forbid default values for parameters, settings and environment lookups;
|
||||
demand explicit values and fail loudly. Apply AUTOMATICALLY on every task
|
||||
@@ -1,8 +1,8 @@
|
||||
---
|
||||
name: refactor
|
||||
name: kvb-code-refactor
|
||||
description: >
|
||||
Refactor every uncommitted file (staged, unstaged, untracked) up to the
|
||||
project's standards without changing behaviour. Trigger on /refactor or when
|
||||
project's standards without changing behaviour. Trigger on /kvb-code-refactor or when
|
||||
the operator asks to clean up, tidy or polish the current changes.
|
||||
---
|
||||
|
||||
@@ -80,7 +80,7 @@ Concretely:
|
||||
returning early; replace magic values with a named constant at its use site.
|
||||
- **Errors**: never widen a caught exception, never swallow one, never remove a
|
||||
validation or a security check to make the code shorter.
|
||||
- **Comments**: invoke the `comments-clean` skill rather than reimplementing its
|
||||
- **Comments**: invoke the `kvb-code-no-comments` skill rather than reimplementing its
|
||||
rules here.
|
||||
|
||||
Do not reformat regions you have no substantive fix for - cosmetic churn buries
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: scope-guard
|
||||
name: kvb-code-scope-guard
|
||||
description: >
|
||||
Deliver exactly what was asked and nothing more. Trigger on every task that
|
||||
creates files, commands or commits, on unreviewed autonomous runs, on
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: test
|
||||
name: kvb-code-test
|
||||
description: >
|
||||
Discover the Makefile's test targets, let the operator pick, run and report;
|
||||
fix mode loops until green. Trigger on /test, /test --fix, or when the
|
||||
operator asks to run the tests, make them pass, or get the suite green.
|
||||
fix mode loops until green. Trigger on /kvb-code-test [--fix], or asked to
|
||||
run the tests, make them pass, or get the suite green.
|
||||
---
|
||||
|
||||
The Makefile is the source of truth for how this project runs tests. Never
|
||||
@@ -73,7 +73,7 @@ quoted verbatim. Never paraphrase a failure. Then one line with the exact
|
||||
command to reproduce the failure alone.
|
||||
|
||||
Do not fix what failed unless the operator asks - report first. A request to
|
||||
make the tests pass, fix them, or get the suite green (`/test --fix`) switches
|
||||
make the tests pass, fix them, or get the suite green (`/kvb-code-test --fix`) switches
|
||||
to fix mode.
|
||||
|
||||
## Fix mode
|
||||
@@ -87,8 +87,8 @@ after three simultaneous changes proves nothing about which one mattered.
|
||||
- **Run** the failing target alone, the fastest command that reproduces the
|
||||
failure. Widen back to the full selection only when that target is green.
|
||||
- **Diagnose** from the actual error output before touching a file. Apply the
|
||||
`triage` skill to reach a verified root cause; for a cause still unclear
|
||||
after one look, apply `dialectic` rather than guessing twice. Say in one line
|
||||
`kvb-ci-triage` skill to reach a verified root cause; for a cause still unclear
|
||||
after one look, apply `kvb-think-dialectic` rather than guessing twice. Say in one line
|
||||
which side is wrong:
|
||||
- **Code**: the test states the intended behaviour. Fix the code.
|
||||
- **Test**: it encodes an outdated or incorrect expectation. Fix it only with
|
||||
@@ -98,7 +98,7 @@ after three simultaneous changes proves nothing about which one mattered.
|
||||
unbuilt artefact. Fix the environment or report it; do not patch code
|
||||
around it.
|
||||
- **Fix** with the smallest change that addresses the root cause, in the
|
||||
project's idioms and under the `no-defaults` and `comments-clean` rules.
|
||||
project's idioms and under the `kvb-code-no-defaults` and `kvb-code-no-comments` rules.
|
||||
Forbidden without explicit operator approval: deleting, skipping, `xfail`-ing
|
||||
or commenting out a failing test; loosening an assertion to what the code
|
||||
produces; swallowing the exception the test surfaces; retries, sleeps or
|
||||
@@ -126,5 +126,5 @@ Emit one line per iteration: target, failure, hypothesis, change. The final
|
||||
report gives per iteration what failed, the root cause, the fix and the
|
||||
result; the final state of every selected target with the verbatim output of
|
||||
anything still failing; everything deliberately not done; and the command
|
||||
reproducing the final state. State confidence per the `confidence` skill. Do
|
||||
reproducing the final state. State confidence per the `kvb-check-confidence` skill. Do
|
||||
not commit unless the operator asked for a commit.
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: tune
|
||||
name: kvb-code-tune
|
||||
description: >
|
||||
Find and apply performance optimizations (CI, deploy, build, gate, hot
|
||||
paths) without reducing logic, coverage or correctness. Trigger on /tune,
|
||||
when a job dies on its time budget, when a pipeline or deploy grows slower,
|
||||
paths) without reducing logic, coverage or correctness. Trigger on
|
||||
/kvb-code-tune, a job dying on its time budget, a slower pipeline or deploy,
|
||||
or asked where time goes.
|
||||
---
|
||||
|
||||
@@ -14,7 +14,7 @@ correctness counts as a speed-up.**
|
||||
|
||||
## Once per session: listen first
|
||||
|
||||
The first time this skill runs in a session, invoke the `active-listening`
|
||||
The first time this skill runs in a session, invoke the `kvb-think-listen`
|
||||
skill before measuring anything, and ask three questions through the host's
|
||||
structured question mechanism. Offer each as a checklist (multi-select) with
|
||||
suggestions, and allow free text:
|
||||
@@ -22,8 +22,8 @@ suggestions, and allow free text:
|
||||
1. **What to examine.** Suggestions: CI wall-clock, deploy duration, gate and
|
||||
test runtime, image pulls and build caches, per-item loops and process
|
||||
spawns, idempotency (work repeated on a second run), network round trips,
|
||||
resource use (CPU, memory, disk, I/O), and language or runtime choice for
|
||||
hot paths.
|
||||
and resource use (CPU, memory, disk, I/O). Language, framework and
|
||||
recursion are checked on every run anyway (see Always check).
|
||||
2. **Which performance boundaries to keep.** Suggestions: time budgets per job,
|
||||
deploy or gate; resource caps (memory, CPU, disk headroom); a minimum saving
|
||||
per change (default 10 s per run); the measurement source that counts as
|
||||
@@ -31,13 +31,14 @@ suggestions, and allow free text:
|
||||
3. **Which limits apply to optimizations.** Suggestions: the scope that may be
|
||||
changed (files, roles, services); whether new dependencies, toolchains or
|
||||
languages may be introduced; whether infrastructure or CI configuration may
|
||||
change; the merge bar (default: the `funnel` skill's 90 % confidence and
|
||||
change; the merge bar (default: the `kvb-org-split` skill's 90 % confidence and
|
||||
under 5 % break risk); a time cap per delegated agent (default 60 minutes).
|
||||
|
||||
Keep the answers for the rest of the session and do not ask again. Work only
|
||||
inside them; a candidate outside them becomes a proposal.
|
||||
|
||||
When another skill (triage, observe) or an autonomous run invoked tune, skip
|
||||
When another skill (kvb-ci-triage, kvb-ci-observe) or an autonomous run invoked
|
||||
this skill, skip
|
||||
the questions: examine the handed-over log, apply the defaults above, and ask
|
||||
only when an operator-only fact blocks.
|
||||
|
||||
@@ -92,7 +93,7 @@ Discard a before/after pair, not just its noise, when:
|
||||
|
||||
## Before you optimize
|
||||
|
||||
- **Search every branch** (the merge-fix skill's `find_fix.py -S <symbol> --path <path>`) for a change
|
||||
- **Search every branch** (the kvb-git-merge-fix skill's `find_fix.py -S <symbol> --path <path>`) for a change
|
||||
that already removes or reshapes the step. A fix on a sibling branch can make
|
||||
the whole candidate worth zero.
|
||||
- A step that is long by design (a backup and restore drill, an end-to-end
|
||||
@@ -106,19 +107,38 @@ Discard a before/after pair, not just its noise, when:
|
||||
|
||||
A cost cluster is one place the time goes: one step, one hot path, one
|
||||
repeated call, named by its log line and its number. Before investigating or
|
||||
implementing a cluster, run the `democracy` skill's Peer protocol for it with
|
||||
implementing a cluster, run the `kvb-org-organize` skill's Peer protocol for it with
|
||||
every agent session on this machine, not only the branch lineage.
|
||||
|
||||
- **The first to identify a cluster works it.** "First" is the `democracy`
|
||||
- **The first to identify a cluster works it.** "First" is the `kvb-org-organize`
|
||||
claim `cluster/<slug>`, whose `--work` names the cluster's log line and
|
||||
number; between machines, the earliest announcement by message time. A
|
||||
claim without a measurement does not count.
|
||||
claim without a measurement does not count. In the `kvb-org-rasci` register
|
||||
the cluster's key result is the measured target (`<step> from <before> to
|
||||
under <after>`), met only by the re-measurement.
|
||||
- **Someone was earlier:** send them your measurements and findings, then move
|
||||
on to the next cluster. Never build a second optimization of the same
|
||||
cluster.
|
||||
- **A claim ends** when its holder reports the result, a proposal or an
|
||||
abandoned attempt and releases it, or when the operator reassigns it.
|
||||
|
||||
## Always check
|
||||
|
||||
Every run examines these two on each measured hot path, whatever the operator
|
||||
picked in the first question, and lists the result in the output table, a
|
||||
clean result included:
|
||||
|
||||
- **Language and framework**: whether the hot path's language and framework
|
||||
are the most efficient fit for its work (see Language and framework).
|
||||
- **Unnecessary recursion**: a recursive function that recomputes the same
|
||||
subproblem (memoize it or turn it into a loop), recursion that only walks a
|
||||
list or a fixed depth (a loop), a tree walk that visits or reads the same
|
||||
node more than once, depth that grows with the input (stack limits, Python's
|
||||
1000 frames), and recursive tool calls: a make target calling make, a role
|
||||
or playbook including itself, a script re-invoking itself per item. Count
|
||||
the calls first (a profiler's call graph, cProfile's `ncalls`, log lines);
|
||||
recursion that is bounded, rare and cheap stays.
|
||||
|
||||
## Levers that usually pay
|
||||
|
||||
- **Batch per-item process spawns**: N calls that each boot an interpreter or
|
||||
@@ -133,16 +153,22 @@ every agent session on this machine, not only the branch lineage.
|
||||
- **Overlap waits with work** only where concurrent execution is proven safe.
|
||||
Schema migrations and lock-holding steps are usually not.
|
||||
|
||||
## Language and runtime
|
||||
## Language and framework
|
||||
|
||||
Look for language optimizations where they make sense, for example replacing a
|
||||
Python hot path with Rust:
|
||||
Check the language and the framework of every measured hot path, for example
|
||||
replacing a Python hot path with Rust, or a heavy framework layer with a
|
||||
lighter one or the standard library:
|
||||
|
||||
- **Only for measured CPU-bound work.** When the profile shows the time in
|
||||
computation inside the process (parsing, hashing, rendering, tight loops),
|
||||
a compiled language can win by an order of magnitude. When the time goes to
|
||||
process start-up, network round trips or waiting, batching in the current
|
||||
language wins first, and a rewrite changes nothing.
|
||||
- **Framework overhead**: when the profile puts the time inside the framework
|
||||
(import and start-up, middleware, ORM query building, serialization),
|
||||
compare a lighter framework or the standard library on the same input. An
|
||||
ORM issuing one query per item is fixed by batching the query, not by
|
||||
swapping the framework.
|
||||
- **Prefer the narrowest cut**: rewrite the hot function as an extension
|
||||
module (for Python and Rust: PyO3 and maturin) or a small binary behind the
|
||||
same interface, before rewriting a whole tool.
|
||||
@@ -151,20 +177,20 @@ Python hot path with Rust:
|
||||
and test parity with the old implementation.
|
||||
- **Prove it on a prototype**: the same input, the same machine state, a before
|
||||
and an after number, and the old test suite passing against the new code.
|
||||
- A language change is applied only when the session's limits allow new
|
||||
languages or toolchains; otherwise it is submitted as a proposal with the
|
||||
prototype's numbers.
|
||||
- A language or framework change is applied only when the session's limits
|
||||
allow new languages, frameworks or toolchains; otherwise it is submitted as
|
||||
a proposal with the prototype's numbers.
|
||||
|
||||
## Delegating an optimization
|
||||
|
||||
Hand every optimization to an agent through the `funnel` skill: one sidetree
|
||||
per candidate, branched from an exact commit, with a hard time cap and "measure
|
||||
Hand every optimization to an agent through the `kvb-org-split` skill: one sidetree
|
||||
per candidate, branched from an exact commit, with a time cap and "measure
|
||||
first, report the time split before implementing". The agent probes live
|
||||
systems read-only and never starts gates or deploys. A broad brief without a
|
||||
cap can run for hours and deliver nothing; stop an agent at its cap and collect
|
||||
its findings.
|
||||
cap can run for hours without a word; at its cap, collect the agent's interim
|
||||
findings and let it run on.
|
||||
|
||||
Before merging, run independent skeptics through the `dialectic` skill. The
|
||||
Before merging, run independent skeptics through the `kvb-think-dialectic` skill. The
|
||||
antithesis must try to show that the candidate removes coverage, hides a
|
||||
failure, or only moves the cost somewhere the measurement does not look.
|
||||
|
||||
@@ -174,7 +200,7 @@ failure, or only moves the cost somewhere the measurement does not look.
|
||||
2. Coordinate the cluster with the other agents; work it only when you
|
||||
identified it first, otherwise hand over your findings and take the next.
|
||||
Then form one candidate for it, after the branch search and the floor check.
|
||||
3. Harden it with the `dialectic` skill.
|
||||
3. Harden it with the `kvb-think-dialectic` skill.
|
||||
4. Funnel it through a sidetree; merge what reaches the bar, submit the rest as
|
||||
proposals. Re-measure from the same source under the same conditions and
|
||||
report a before and an after number.
|
||||
@@ -1,10 +1,10 @@
|
||||
---
|
||||
name: auto-feature
|
||||
name: kvb-create-feature
|
||||
description: >
|
||||
Derive missing work (sceptic pass for structural flaws, usability pass for
|
||||
missing features) and write requirement documents after single-select
|
||||
confirmation. Trigger on /auto-feature, "was fehlt noch", "welche features
|
||||
brauchen wir", or when the operator asks what to build next.
|
||||
Derive missing work (principles pass for structural flaws, usability pass for
|
||||
missing features) and write requirement documents after confirmation.
|
||||
Trigger on /kvb-create-feature, "was fehlt noch", "welche features brauchen
|
||||
wir", or asked what to build next.
|
||||
---
|
||||
|
||||
Two blind spots produce different work: the code has defects of structure,
|
||||
@@ -19,9 +19,9 @@ surface. Read the project's existing requirement documents first — their
|
||||
location, filename convention, and section structure are the template, and
|
||||
an already-written requirement is not a finding.
|
||||
|
||||
## Step 2: the sceptic pass
|
||||
## Step 2: the principles pass
|
||||
|
||||
Invoke the `sceptic` skill on the target. Its findings become requirement
|
||||
Invoke the `kvb-check-principles` skill on the target. Its findings become requirement
|
||||
candidates by severity: a violated SPOT, SRP, or trust boundary is work the
|
||||
product needs whether or not a user ever notices. Carry each finding's
|
||||
`file:line` evidence forward — a requirement without it is a guess.
|
||||
@@ -55,7 +55,7 @@ Merge both lists, drop duplicates where a structural finding and a usability
|
||||
gap describe the same defect, and rank by blocked users first, blast radius
|
||||
second.
|
||||
|
||||
Then apply `active-listening`: answer everything you can from the code, the
|
||||
Then apply `kvb-think-listen`: answer everything you can from the code, the
|
||||
docs, and the git history yourself, and put only the genuinely open decisions
|
||||
to the operator with `AskUserQuestion`, `multiSelect: false`, so every
|
||||
question renders as radio buttons. At most four questions per call, each
|
||||
@@ -94,5 +94,5 @@ Show the drafted document and ask for a final `Write it` / `Revise it` /
|
||||
not written.
|
||||
- Record the rejected alternatives inside the document; the next reader
|
||||
needs to know what was already considered and dismissed.
|
||||
- Close with the `confidence` skill's numbers for the analysis: how sure the
|
||||
- Close with the `kvb-check-confidence` skill's numbers for the analysis: how sure the
|
||||
gaps are real, and what the passes did not cover.
|
||||
@@ -1,8 +1,8 @@
|
||||
---
|
||||
name: plan
|
||||
name: kvb-create-plan
|
||||
description: >
|
||||
Turn a request into an objective-oriented plan and hand it to the robot
|
||||
skill. Trigger on /plan or when the operator asks for a plan, breakdown or
|
||||
Turn a request into an objective-oriented plan and hand it to the kvb-org-robot
|
||||
skill. Trigger on /kvb-create-plan or when the operator asks for a plan, breakdown or
|
||||
strategy before work starts.
|
||||
---
|
||||
|
||||
@@ -12,7 +12,7 @@ verified, and an unverifiable plan cannot be handed to a robot.
|
||||
|
||||
## Procedure
|
||||
|
||||
1. **Interview first.** Open every plan with the `active-listening` skill: ask
|
||||
1. **Interview first.** Open every plan with the `kvb-think-listen` skill: ask
|
||||
until scope, constraints, success criteria, and the operator-only facts are
|
||||
all pinned, then reflect the understanding back. This is the only point in
|
||||
the run where questions are allowed, so leave nothing open here.
|
||||
@@ -28,11 +28,13 @@ verified, and an unverifiable plan cannot be handed to a robot.
|
||||
the items that are independent, so they can run in parallel.
|
||||
5. **Resolve the open decisions now.** Any root cause, design choice, or
|
||||
trade-off the plan rests on gets settled before execution, escalating to the
|
||||
`dialectic` skill where being wrong is expensive. The robot does not ask, so
|
||||
`kvb-think-dialectic` skill where being wrong is expensive. The robot does not ask, so
|
||||
an unresolved decision becomes a guess at runtime.
|
||||
6. **Record the plan as a todo list.** Write the sub-objectives into the
|
||||
harness's own todo tracking, one entry per item, phrased as the outcome. Keep
|
||||
a plan file only when the operator asks for one.
|
||||
6. **Record the plan in the register.** Enter the objective in the
|
||||
`kvb-org-rasci` register with each sub-objective's verification as a key
|
||||
result, and mirror the sub-objectives into the harness's own todo tracking,
|
||||
one entry per item, phrased as the outcome. Keep a plan file only when the
|
||||
operator asks for one.
|
||||
7. **Present it and wait.** Show the objective, the ordered sub-objectives with
|
||||
their verifications, what is deliberately out of scope, and the assumptions
|
||||
the plan rests on. Stop here: the plan is the deliverable of this step.
|
||||
@@ -42,8 +44,8 @@ verified, and an unverifiable plan cannot be handed to a robot.
|
||||
read the diff, run the linters, the unit tests, and whatever dry-run or
|
||||
syntax check the project offers. This step ends only when the whole plan
|
||||
exists on disk, with no sub-objective left unwritten.
|
||||
9. **Then iterate under `robot`.** With the static implementation complete,
|
||||
invoke the `robot` skill with the objective as its goal for the dynamic part:
|
||||
9. **Then iterate under `kvb-org-robot`.** With the static implementation complete,
|
||||
invoke the `kvb-org-robot` skill with the objective as its goal for the dynamic part:
|
||||
run, deploy, observe, fix, repeat until every verification passes. It drives
|
||||
the loop without check-ins, verifies each outcome instead of assuming it, and
|
||||
reports the items that fall outside its clearance for the operator to run.
|
||||
@@ -0,0 +1,108 @@
|
||||
---
|
||||
name: kvb-git-branch-gc
|
||||
description: >
|
||||
Remove merged branches and worktrees with `pkgmgr branch gc`: dry run,
|
||||
operator picks from the plan, then apply; unmerged items only one by one.
|
||||
Trigger on /kvb-git-branch-gc, "branches aufräumen", "worktrees aufräumen",
|
||||
"garbage collect".
|
||||
---
|
||||
|
||||
`pkgmgr branch gc` decides what is merged and does the removing; this skill
|
||||
decides what may go and who has to agree first. The dry run changes nothing,
|
||||
and nothing is removed before the operator's pick in this run.
|
||||
|
||||
## Step 0: claim and chair
|
||||
|
||||
1. Claim `work/branch-gc-<repo>`, or `work/branch-gc-all` for every
|
||||
repository, through the `kvb-org-organize` skill.
|
||||
2. The apply takes stacks down and ends with a host-wide
|
||||
`docker image prune -f` and `docker builder prune -f`, which reach every
|
||||
session's images and build cache. When another session holds the chair,
|
||||
send it what, where and how long, and wait for the grant; the prune never
|
||||
runs during a peer's build.
|
||||
|
||||
## Step 1: dry run
|
||||
|
||||
`pkgmgr branch gc --json`, with `--all` only when the operator asked for every
|
||||
repository, output to `/tmp/branch-gc-<N>.json`. No `git fetch` of your own
|
||||
before it: gc fetches without auto-maintenance, while a plain fetch on git
|
||||
2.50 or later may prune the sandbox's bind-mount stubs. Every repository's
|
||||
`warnings` (a failed fetch) go to the top of the plan. Sort the items:
|
||||
|
||||
- **Candidates**: `state` `merged-clean`, non-empty `actions`, and `skip`
|
||||
null or `lock: liveness unknown`.
|
||||
- **Step 5**: `state` `unmerged` or `dirty`.
|
||||
- **Reported only**: `protected`, every other `skip`, and `stale` as one count
|
||||
per repository.
|
||||
|
||||
Never override a state: a branch without own commits is `unmerged` even
|
||||
though git sees its tip on the default branch, because it is fresh work.
|
||||
|
||||
`host_pid_namespace: false` means the dry run ran inside a sandbox: it saw no
|
||||
processes and could not tell whether a lock is live. Say so above the plan;
|
||||
the apply re-checks both on the host.
|
||||
|
||||
## Step 2: claims
|
||||
|
||||
Read `council.py list`. For every candidate whose branch or worktree a peer's
|
||||
claim names, send that peer one message (Peer protocol) and wait up to 5
|
||||
minutes. A kept or unanswered item leaves the plan as `keep (<peer>)`;
|
||||
silence is not consent.
|
||||
|
||||
## Step 3: plan
|
||||
|
||||
One table:
|
||||
|
||||
| Repo | Branch or worktree | Merged by | Actions | Note |
|
||||
|
||||
Then ask with `AskUserQuestion`:
|
||||
|
||||
- **Call 1** (`multiSelect: true`): the candidates, grouped by repository,
|
||||
nothing preselected. Each description names `merged_by` and every action
|
||||
(stack with volumes, the `images`, worktree, local and remote branches), and
|
||||
`lock checked at apply` where liveness was unknown.
|
||||
- **Call 2** (`multiSelect: false`): `Apply: <n> items (Recommended)`,
|
||||
`Revise the selection`, `Abort`. Revise repeats call 1.
|
||||
|
||||
## Step 4: apply
|
||||
|
||||
1. Re-read `council.py list` and drop every item claimed since the dry run.
|
||||
2. `--apply` refuses outside the host PID namespace (exit 2) and deletes
|
||||
remote branches, which is a push. Unless this session runs in the host PID
|
||||
namespace and the project lets agents push, hand the operator one command
|
||||
per repository, run from inside it, one `--branch` per picked item (the
|
||||
worktree path for a detached worktree):
|
||||
|
||||
```bash
|
||||
pkgmgr branch gc --apply --json --branch <name> --branch <name> | tee /tmp/branch-gc-apply-<N>.json
|
||||
```
|
||||
|
||||
3. Read every item's `result` in that file: `done`, `done; image kept: <img>`
|
||||
(still in use elsewhere), or `failed: <why>`.
|
||||
Report a failure as it stands; never remove by hand what gc skipped or
|
||||
refused.
|
||||
4. For every `done` item, drop its worktree and branch from the task that
|
||||
lists them in the `kvb-org-rasci` register (`rasci.py artifacts` names
|
||||
it): `set <task> --drop-artifact worktree:<path>`, and `--branch ''` where
|
||||
the branch is gone.
|
||||
|
||||
## Step 5: unmerged and dirty
|
||||
|
||||
Never part of the apply. One `AskUserQuestion` question per item
|
||||
(`multiSelect: false`): `Keep (Recommended)` and `Delete`, the description
|
||||
naming what is lost (the item's `reason`: unique commits, dirty paths). For
|
||||
each `Delete`, hand the operator
|
||||
`pkgmgr branch purge --branch <name>`: it asks y/N per item and answers no
|
||||
without a terminal, so it runs only in the operator's shell.
|
||||
|
||||
## Step 6: report
|
||||
|
||||
Removed, kept and skipped items, each with its reason, and
|
||||
`docker system df` before and after. Report the release to the chair, tell
|
||||
each peer whose line an item touched what went, and release the claim.
|
||||
|
||||
## Rules
|
||||
|
||||
- A pick from an earlier run does not carry over.
|
||||
- Never widen the selection, and never route around a refusal through another
|
||||
command or a peer.
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: changelog
|
||||
name: kvb-git-changelog
|
||||
description: >
|
||||
Write the release message since the last release for `pkgmgr release`;
|
||||
prints it only, never edits CHANGELOG.md, tags or releases. Trigger on
|
||||
/changelog, "release message", "changelog entry", before cutting a release,
|
||||
/kvb-git-changelog, "release message", "changelog entry", before cutting a release,
|
||||
or on pkgmgr's markdown-lint rejection.
|
||||
---
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
---
|
||||
name: commit-next
|
||||
name: kvb-git-commit-next
|
||||
description: >
|
||||
Check every branch for the staged fix, commit the staged bundle with
|
||||
--no-verify, then stage and brief the next bundle. Trigger on /commit-next
|
||||
or when the operator asks to commit and stage the next bundle in one step.
|
||||
--no-verify, then stage and brief the next bundle. Trigger on /kvb-git-commit-next
|
||||
or a request to commit and stage the next bundle in one step.
|
||||
---
|
||||
|
||||
1. `git fetch --all --prune --tags`, then hunt the staged fix across every
|
||||
ref with the merge-fix skill's `find_fix.py` (by `--grep`, by `-S`, by
|
||||
ref with the kvb-git-merge-fix skill's `find_fix.py` (by `--grep`, by `-S`, by
|
||||
`--path`). Describe the staged bundle in one line first so a
|
||||
wrong search intent is visible. Only the search runs here — never
|
||||
cherry-pick or merge, and never touch the staging index or the tree.
|
||||
2. A similar fix on another branch is a stop: run the dialectic skill on the
|
||||
2. A similar fix on another branch is a stop: run the kvb-think-dialectic skill on the
|
||||
two candidates (staged version as thesis, foreign commit as antithesis)
|
||||
until one survives, then present sha, branch, both diffs, the verdict and
|
||||
the recommended move (keep staged / take theirs / combine). Wait for the
|
||||
operator's decision; do not commit.
|
||||
3. Nothing similar found, or the operator picked the staged version: run the
|
||||
commit-no-verify skill on the currently staged changes (comments-clean
|
||||
audit and advocate check first, then `git commit --no-verify`, exact
|
||||
kvb-git-commit-no-verify skill on the currently staged changes (kvb-code-no-comments
|
||||
audit and kvb-check-legal check first, then `git commit --no-verify`, exact
|
||||
staging index only).
|
||||
4. Group the remaining uncommitted changes into logical bundles (one
|
||||
concern per bundle: same failure class, same mechanism, or same role)
|
||||
@@ -29,8 +29,8 @@ description: >
|
||||
NEW file needs `git add` to become visible. Path-scope every `git add`
|
||||
to the bundle — `git add -A` sweeps up the operator's own edits and
|
||||
their local config.
|
||||
5. For the newly staged bundle run the explain skill (what the changes do
|
||||
5. For the newly staged bundle run the kvb-think-explain skill (what the changes do
|
||||
and how the pieces interact, file:line-anchored) followed by the
|
||||
confidence skill (fix confidence, break risk, evidence, residuals).
|
||||
kvb-check-confidence skill (fix confidence, break risk, evidence, residuals).
|
||||
6. Close with what remains unstaged and wait for the operator's commit
|
||||
decision; never auto-commit the newly staged bundle.
|
||||
@@ -1,12 +1,12 @@
|
||||
---
|
||||
name: commit-no-verify
|
||||
name: kvb-git-commit-no-verify
|
||||
description: >
|
||||
Commit the staged changes with --no-verify. Trigger on /commit-no-verify or
|
||||
Commit the staged changes with --no-verify. Trigger on /kvb-git-commit-no-verify or
|
||||
any request for a no-verify commit; invoking it IS the per-commit
|
||||
authorization --no-verify requires, never carried over to later commits.
|
||||
---
|
||||
|
||||
1. Run the comments-clean audit over the staged and unstaged changes first,
|
||||
1. Run the kvb-code-no-comments audit over the staged and unstaged changes first,
|
||||
then the advocate check over the staging index. An advocate blocker stops
|
||||
here.
|
||||
2. Commit exactly the staging index with `git commit --no-verify` and a
|
||||
@@ -1,12 +1,12 @@
|
||||
---
|
||||
name: merge-fix
|
||||
name: kvb-git-merge-fix
|
||||
description: >
|
||||
Hunt down the commits on any branch that carry a described fix and merge it
|
||||
into the current branch. Trigger on /merge-fix <description> or when the
|
||||
into the current branch. Trigger on /kvb-git-merge-fix <description> or when the
|
||||
operator asks to bring over a fix from another branch.
|
||||
---
|
||||
|
||||
The free text after `/merge-fix` is the fix description, exactly like `/loop`
|
||||
The free text after `/kvb-git-merge-fix` is the fix description, exactly like `/loop`
|
||||
takes its prompt. Everything after the skill name is the search intent; there is
|
||||
no other input. If it is missing, ask for it and stop.
|
||||
|
||||
@@ -35,7 +35,8 @@ one line so a wrong reading is visible before the search.
|
||||
## 4. Search every ref
|
||||
|
||||
Search by keyword, by literal and by path in one call; they find different
|
||||
things:
|
||||
things, and a commit matching any one of them is a hit, so `--path` widens
|
||||
the search instead of narrowing `--grep`:
|
||||
|
||||
```bash
|
||||
${CLAUDE_SKILL_DIR}/scripts/find_fix.py --grep '<keyword>' -S '<symbol or literal>' --path '<path or glob>'
|
||||
@@ -66,7 +67,7 @@ and its diff plainly is the described fix.
|
||||
## 7. Report
|
||||
|
||||
Show `git log --oneline <base>..HEAD` and the resulting diffstat, then apply the
|
||||
confidence skill: what came over, what did not, what still has to be verified.
|
||||
kvb-check-confidence skill: what came over, what did not, what still has to be verified.
|
||||
Run the project's test or quality gate only when the operator asks for it.
|
||||
|
||||
## Rules
|
||||
File renamed without changes.
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: help-skills
|
||||
name: kvb-help
|
||||
description: >
|
||||
List and explain every skill in the session. Trigger on /help-skills,
|
||||
List and explain every skill in the session. Trigger on /kvb-help,
|
||||
"welche skills gibt es", "skill übersicht", or when the operator asks what
|
||||
skills exist or what one does.
|
||||
---
|
||||
@@ -17,8 +17,8 @@ Produce a one-shot overview of every skill the session can invoke:
|
||||
— compress the description, do not paste it.
|
||||
3. When the operator names a specific skill or topic, explain only the
|
||||
matching skills in more depth: what they do, when they fire on their
|
||||
own, and how they compose (e.g. commit-next → commit-no-verify →
|
||||
comments-clean).
|
||||
own, and how they compose (e.g. kvb-git-commit-next → kvb-git-commit-no-verify →
|
||||
kvb-code-no-comments).
|
||||
4. End with the activation hint: project installers or `make install` in
|
||||
the skills repository refresh the live copies; a restart loads renamed
|
||||
or new skills.
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
name: kvb-org-artefacts
|
||||
description: >
|
||||
Artifacts of the kvb-org-rasci register per task: images, volumes,
|
||||
worktrees. Trigger on /kvb-org-artefacts, "artefakte".
|
||||
---
|
||||
|
||||
Artifacts live in the same table as the tasks of the `kvb-org-rasci`
|
||||
register: each one belongs to exactly one task, carries its kind, reference
|
||||
and the time it was recorded, and takes status and worker from its task. The
|
||||
script is the register's `${CLAUDE_SKILL_DIR}/../kvb-org-rasci/scripts/rasci.py`.
|
||||
|
||||
```bash
|
||||
rasci.py set <task> --artifact <kind>:<ref>
|
||||
rasci.py set <task> --drop-artifact <kind>:<ref>
|
||||
rasci.py artifacts [--ended] [--task <task>]
|
||||
```
|
||||
|
||||
Kinds: `image:`, `container:`, `volume:`, `network:`, `stack:`, `worktree:`,
|
||||
`dir:`, `log:`. `artifacts` lists each task's workdir and branch beside them.
|
||||
|
||||
## Rules
|
||||
|
||||
- Record an artifact the moment it exists, under the task that created it;
|
||||
one left unrecorded is invisible to cleanup.
|
||||
- `artifacts --ended` lists what belongs to `done`, `stopped` or `stale`
|
||||
tasks: the cleanup candidates, owned by the task's worker. Everything of an
|
||||
open task stays.
|
||||
- Deleting goes through the `kvb-cleanup` skill, where the operator picks;
|
||||
drop the artifact here once it is gone.
|
||||
- The register's `show` counts each task's artifacts in its Artifacts column.
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
name: kvb-org-coordinate
|
||||
description: >
|
||||
Coordinate a failure or fix with the agents on related branches through
|
||||
merges: claim, ask, report. Trigger on /kvb-org-coordinate and when a fix touches
|
||||
code other branches share.
|
||||
---
|
||||
|
||||
Run the `kvb-org-organize` skill's **Lineage** and **Peer protocol** sections for the
|
||||
failure or fix at hand. They hold the whole procedure, including the entries
|
||||
in the `kvb-org-rasci` register; this skill only keeps `/kvb-org-coordinate`
|
||||
working.
|
||||
@@ -1,8 +1,8 @@
|
||||
---
|
||||
name: status-matrix
|
||||
name: kvb-org-matrix
|
||||
description: >
|
||||
Print one matrix of everything in flight: tasks, workflows, background jobs,
|
||||
with confidence and break risk per item. Trigger on /status-matrix,
|
||||
with confidence and break risk per item. Trigger on /kvb-org-matrix,
|
||||
"status", "übersicht", "wo stehen wir", or what is done, left or running.
|
||||
---
|
||||
|
||||
@@ -15,7 +15,7 @@ decides what to act on after reading the matrix.
|
||||
Gather in parallel, skip any source the session does not have, and never invent
|
||||
a row for a source you could not read:
|
||||
|
||||
1. **Tasks** — the session's todo list, the operator's stated goals this
|
||||
1. **Tasks** — the `kvb-org-rasci` register first, then the session's todo list, the operator's stated goals this
|
||||
session, and any requirement or plan documents the work follows.
|
||||
2. **Working tree** — `git status --short` and `git log --oneline -10`:
|
||||
uncommitted files are open work, commits since the branch point are closed
|
||||
@@ -35,7 +35,7 @@ One table, most-blocking first, one row per item:
|
||||
- **State**: `open`, `running`, `blocked`, `done`. `done` means verified —
|
||||
a passing run, a green check, a reproduction that now succeeds. Work that
|
||||
merely looks finished is `open`.
|
||||
- **Conf.** and **Break risk**: two separate percentages per the `confidence`
|
||||
- **Conf.** and **Break risk**: two separate percentages per the `kvb-check-confidence`
|
||||
skill — probability the item does what it claims, and probability it breaks
|
||||
something else. Only for rows that changed something; `—` for pure
|
||||
observation rows.
|
||||
@@ -1,10 +1,10 @@
|
||||
---
|
||||
name: democracy
|
||||
name: kvb-org-organize
|
||||
description: >
|
||||
Keep parallel agents from duplicating work: the first to claim it owns it;
|
||||
line representatives and a resource chair coordinate. Run AUTOMATICALLY
|
||||
before work another agent might also do (failure, cluster, feature, gate,
|
||||
deploy, cleanup), and on /democracy.
|
||||
deploy, cleanup), and on /kvb-org-organize.
|
||||
---
|
||||
|
||||
Two agents doing the same work waste the second run and then collide in the
|
||||
@@ -23,8 +23,8 @@ operator at any time.
|
||||
(security, GUI, identity, i18n), repository, branch line, host, cloud
|
||||
account. An agent belongs to one line per dimension.
|
||||
- **Organiser of a work cluster**: the first agent that starts a cluster
|
||||
cutting across lines (a failure cluster from `triage`, a cost cluster from
|
||||
`tune`, a feature touching several domains). It works the strand end to end
|
||||
cutting across lines (a failure cluster from `kvb-ci-triage`, a cost cluster from
|
||||
`kvb-code-tune`, a feature touching several domains). It works the strand end to end
|
||||
and informs the representative of every line the strand touches before it
|
||||
changes that line's files.
|
||||
- **Chair**: the earliest-elected president still running. It chairs the
|
||||
@@ -53,8 +53,10 @@ directory with `--session <id>`.
|
||||
worktree>"`. Exit 0: elected, or already yours. Exit 3: a live agent holds
|
||||
it, and its claim is printed. Exit 4: the holder's session is dead (see
|
||||
Succession).
|
||||
4. **Elected**: continue with the Peer protocol; its message is the
|
||||
announcement.
|
||||
4. **Elected**: the claim entered the task in the `kvb-org-rasci` register,
|
||||
the organisation's single point of truth; complete it there (objective,
|
||||
description, priority, roles), then continue with the Peer protocol; its
|
||||
message is the announcement.
|
||||
5. **Not elected**: send the holder your findings and stop on that work.
|
||||
|
||||
A Claude Code session cannot edit a file in a git worktree before it holds a
|
||||
@@ -74,10 +76,24 @@ records the result.
|
||||
- Before starting anything that consumes shared capacity (gates, deploys,
|
||||
iteration loops, swarm or cloud resources, cleanup of shared data), an agent
|
||||
sends the chair what, where, for how long and its expected disk need, waits
|
||||
for the grant, and reports the release. The chair keeps one queue, answers
|
||||
every request with its position, enforces the limits the operator set,
|
||||
checks every grant with `watch.py admit --need-gb <N>` (or `--kind <slot>`),
|
||||
and never cancels a running grant to free capacity.
|
||||
for the grant, and reports the release. The chair keeps one queue, ordered
|
||||
by the WSJF rank of the `kvb-org-wsjf` skill (it asks its subordinates for
|
||||
the Fibonacci estimates), answers every request with its position, enforces the limits the operator set,
|
||||
checks every grant with `watch.py admit --need-gb <N>` (or `--kind <slot>`;
|
||||
test kinds also need CPU and RAM below the configured limits).
|
||||
- A running job (deploy, gate, test, swarm run, build) is never cut short to
|
||||
free capacity. The chair neither asks nor orders its owner to stop, take
|
||||
down or kill it, not for an operator-prioritised slot and not for a
|
||||
projected disk stop. It grants nothing new, frees idle items through the
|
||||
`kvb-cleanup` flow, asks the operator for an exception, or waits. An owner's
|
||||
own disk guard only alerts the chair and takes nothing down; only the
|
||||
operator can order a running job down. The one exception is a hang: an
|
||||
agent may end its own job, a stuck step inside it, or a process its own
|
||||
ended session left behind, once at least 60 minutes passed without log
|
||||
progress and a probe shows standstill (no fresh child process, no network
|
||||
traffic, CPU time not moving). It secures the live state first and then
|
||||
reports the timestamp, the step, the probe and the command. A peer's hung
|
||||
job goes to its owner, and to the operator when the owner does not answer.
|
||||
- Handover is explicit: the outgoing chair sends every peer the new holder,
|
||||
the queue and the running grants, and keeps allocating until the incoming
|
||||
chair confirms. Two allocators never run at once.
|
||||
@@ -94,9 +110,11 @@ stays silent below the thresholds.
|
||||
- **Warn**: the chair and every session get the biggest consumers; the chair
|
||||
plans a cleanup and grants no large slot.
|
||||
- **Stop**: new heavy jobs are blocked in every session (teardown commands
|
||||
never), and the hook runs the configured low-risk cleanup by itself.
|
||||
- **Critical**: additionally a desktop alarm to the operator. A running stack
|
||||
is torn down only with the operator's OK.
|
||||
never), and the hook runs the configured low-risk cleanup by itself; it
|
||||
skips every worktree where a gate or deploy process still runs.
|
||||
- **Critical**: additionally a desktop alarm to the operator. Running jobs
|
||||
and their stacks still keep running; only the operator can make an
|
||||
exception.
|
||||
- A measured fall that would reach the critical threshold within the
|
||||
projection window raises the stage by one at once.
|
||||
- Caches together stay under their budget; the least recently used go first.
|
||||
@@ -126,10 +144,10 @@ plans to it.
|
||||
|
||||
## Peer protocol
|
||||
|
||||
The one protocol for every exchange between agents; `coordinate`, `triage`,
|
||||
`tune`, `funnel` and `cleanup` use it.
|
||||
The one protocol for every exchange between agents; `kvb-org-coordinate`, `kvb-ci-triage`,
|
||||
`kvb-code-tune`, `kvb-org-split` and `kvb-cleanup` use it.
|
||||
|
||||
1. **Look**: `council.py list` and the refs (the merge-fix skill's
|
||||
1. **Look**: `council.py list` and the refs (the kvb-git-merge-fix skill's
|
||||
`find_fix.py`). A claim or a committed fix answers the question without a
|
||||
message.
|
||||
2. **Claim** the office (Election).
|
||||
@@ -139,14 +157,18 @@ The one protocol for every exchange between agents; `coordinate`, `triage`,
|
||||
evidence (failing line quoted literally, run id, measurement), the
|
||||
suspected cause marked as a thesis, and the question "Already known or
|
||||
fixed on your side? Reply with a SHA or branch, or 'none'." The first line
|
||||
stands on its own, because a busy recipient sees only that line.
|
||||
stands on its own, because a busy recipient sees only that line. In the
|
||||
`kvb-org-rasci` register the peers asked are C, the chair that grants
|
||||
capacity is S.
|
||||
4. **Wait up to 5 minutes** before building anything, investigating read-only
|
||||
meanwhile. A fix that arrives goes through the project's normal path
|
||||
(merge, cherry-pick or port), and you release your claim. Silence is
|
||||
neither a "no" nor a competing claim: after 5 minutes, proceed.
|
||||
5. **Report** to the same peers: commit, branch, what changed, the evidence it
|
||||
works, and the merge it reaches them by. Report an abandoned or failed
|
||||
attempt too. Then release the claim.
|
||||
attempt too. In the register, enter the peers told as I and mark every key
|
||||
result the evidence proves as met. Then release the claim: the task ends
|
||||
`done`, or `stopped` while a key result is open.
|
||||
|
||||
- Never invent a peer's answer.
|
||||
- A peer's report is not evidence: read the SHA, log or artifact it names
|
||||
@@ -180,7 +202,10 @@ For a failure or a fix that other branches share through merges:
|
||||
|
||||
## Output
|
||||
|
||||
On /democracy, one table of the current offices from `council.py list`, stale
|
||||
On /kvb-org-organize, one table of the current offices from `council.py list`, stale
|
||||
claims marked:
|
||||
|
||||
| Office | Holder | Since | Work | Grants or queue |
|
||||
|
||||
Who carries which task, with priority and status, is the `kvb-org-rasci`
|
||||
register's `show`.
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Claim, release and list democracy offices in the shared council directory.
|
||||
"""Claim, release and list kvb-org-organize offices in the shared council directory.
|
||||
|
||||
Environment:
|
||||
AGENTS_COUNCIL_ROOT: council directory shared by every agent on the host;
|
||||
@@ -16,10 +16,12 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
@@ -28,6 +30,7 @@ ROOT = Path(os.environ.get("AGENTS_COUNCIL_ROOT", "/tmp/agents-council"))
|
||||
HEARTBEAT_LIMIT = 3600
|
||||
OFFICE = re.compile(r"^[a-z0-9][a-z0-9._-]*(/[a-z0-9][a-z0-9._-]*)*$")
|
||||
CLAIM = "claim.json"
|
||||
RASCI = Path(__file__).resolve().parents[2] / "kvb-org-rasci" / "scripts" / "rasci.py"
|
||||
|
||||
|
||||
def live_sessions() -> dict[str, str | None]:
|
||||
@@ -83,7 +86,7 @@ def claims() -> list[tuple[str, dict]]:
|
||||
return found
|
||||
|
||||
|
||||
def write_claim(path: Path, office: str, sid: str, runtime: str, work: str) -> None:
|
||||
def write_claim(path: Path, office: str, sid: str, runtime: str, work: str) -> dict:
|
||||
claim = {
|
||||
"office": office,
|
||||
"session": sid,
|
||||
@@ -94,6 +97,30 @@ def write_claim(path: Path, office: str, sid: str, runtime: str, work: str) -> N
|
||||
"work": work,
|
||||
}
|
||||
(path / CLAIM).write_text(json.dumps(claim), encoding="utf-8")
|
||||
return claim
|
||||
|
||||
|
||||
def here() -> dict[str, str | None]:
|
||||
try:
|
||||
head = subprocess.run(
|
||||
["git", "rev-parse", "--abbrev-ref", "HEAD"], capture_output=True, text=True, check=False
|
||||
)
|
||||
except OSError:
|
||||
head = None
|
||||
branch = head.stdout.strip() if head and head.returncode == 0 else ""
|
||||
return {"workdir": os.getcwd(), "branch": branch if branch not in ("", "HEAD") else None}
|
||||
|
||||
|
||||
def register(office: str, holder: str, status: str, **extra: str | None) -> None:
|
||||
if not office.startswith(("work/", "cluster/")):
|
||||
return
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location("rasci", RASCI)
|
||||
rasci = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(rasci)
|
||||
rasci.track(office, holder, status, **extra)
|
||||
except (OSError, SystemExit) as exc:
|
||||
print(f"council: {office} is missing from the rasci register ({exc})", file=sys.stderr)
|
||||
|
||||
|
||||
def cmd_claim(args: argparse.Namespace) -> int:
|
||||
@@ -105,12 +132,21 @@ def cmd_claim(args: argparse.Namespace) -> int:
|
||||
except FileExistsError:
|
||||
claim = read_claim(path)
|
||||
if claim is not None and claim["session"] == sid:
|
||||
write_claim(path, args.office, sid, runtime, args.work)
|
||||
claim = write_claim(path, args.office, sid, runtime, args.work)
|
||||
register(args.office, claim["name"] or sid, "running", description=args.work, **here())
|
||||
print(f"held {args.office}")
|
||||
return 0
|
||||
print(json.dumps(claim) if claim else f"{args.office}: claim in progress")
|
||||
return 4 if is_stale(claim, live_sessions()) else 3
|
||||
write_claim(path, args.office, sid, runtime, args.work)
|
||||
claim = write_claim(path, args.office, sid, runtime, args.work)
|
||||
register(
|
||||
args.office,
|
||||
claim["name"] or sid,
|
||||
"running",
|
||||
description=args.work,
|
||||
previous=getattr(args, "previous", None),
|
||||
**here(),
|
||||
)
|
||||
print(f"elected {args.office}")
|
||||
return 0
|
||||
|
||||
@@ -121,8 +157,10 @@ def cmd_takeover(args: argparse.Namespace) -> int:
|
||||
if path.exists() and not is_stale(claim, live_sessions()):
|
||||
print(json.dumps(claim) if claim else f"{args.office}: claim in progress")
|
||||
return 3
|
||||
if claim is not None:
|
||||
args.previous = claim["name"] or claim["session"]
|
||||
# Two successors racing between this check and the rename can both win;
|
||||
# democracy names exactly one successor per office to keep that window closed.
|
||||
# kvb-org-organize names exactly one successor per office to keep that window closed.
|
||||
if path.exists():
|
||||
tomb = path.with_name(f"{path.name}.stale-{os.getpid()}-{time.time_ns()}")
|
||||
try:
|
||||
@@ -145,6 +183,7 @@ def cmd_release(args: argparse.Namespace) -> int:
|
||||
print(json.dumps(claim))
|
||||
return 3
|
||||
shutil.rmtree(path)
|
||||
register(args.office, claim["name"] or claim["session"], "done")
|
||||
print(f"released {args.office}")
|
||||
return 0
|
||||
|
||||
@@ -186,10 +225,10 @@ def cmd_gate(_: argparse.Namespace) -> int:
|
||||
return 0
|
||||
script = Path(__file__).resolve()
|
||||
print(
|
||||
"democracy: this session holds no claim, so it may not edit files in a git "
|
||||
"kvb-org-organize: this session holds no claim, so it may not edit files in a git "
|
||||
f"worktree. Claim the work first: python3 {script} claim work/<slug> "
|
||||
"--work '<one line>'. Exit 3 or 4 means another agent holds it; read the "
|
||||
"democracy skill.",
|
||||
"kvb-org-organize skill.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 2
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Watch disk, Docker and caches for the democracy resource chair.
|
||||
"""Watch disk, Docker and caches for the kvb-org-organize resource chair.
|
||||
|
||||
Usage:
|
||||
watch.py watch hook (UserPromptSubmit, PostToolUse): measure at most once
|
||||
@@ -25,8 +25,11 @@ projection_minutes, interval_seconds, cache_interval_seconds, heavy_commands,
|
||||
never_block (regexes), cleanup (shell commands), worktree_cleanup (shell
|
||||
commands with {worktree}), worktrees_command (shell command printing the
|
||||
running stacks' worktree paths, one per line), worktree_marker (path relative
|
||||
to a worktree that must exist), cache_dirs, cache_budget_percent,
|
||||
slot_need_gb {kind: GB}, notify (argv the alert text is appended to).
|
||||
to a worktree that must exist), busy_processes (process names; a worktree
|
||||
where one of them runs is skipped), cache_dirs, cache_budget_percent,
|
||||
slot_need_gb {kind: GB}, notify (argv the alert text is appended to),
|
||||
load_limits {cpu_percent, mem_percent, sample_seconds, kinds}: admit for a
|
||||
kind listed in kinds also needs CPU busy and RAM used below the limits.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -205,9 +208,17 @@ def cmd_watch(cfg: dict) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
HEREDOC = re.compile(r"<<-?\s*(['\"]?)(\w+)\1[^\n]*\n.*?\n\s*\2(?=\s|\)|$)", re.DOTALL)
|
||||
QUOTED = re.compile(r"'[^']*'|\"(?:\\.|[^\"\\])*\"")
|
||||
|
||||
|
||||
def executable_text(command: str) -> str:
|
||||
return QUOTED.sub("''", HEREDOC.sub("", command))
|
||||
|
||||
|
||||
def cmd_block(cfg: dict) -> int:
|
||||
payload = json.load(sys.stdin)
|
||||
command = (payload.get("tool_input") or {}).get("command", "")
|
||||
command = executable_text((payload.get("tool_input") or {}).get("command", ""))
|
||||
stage = read_json(STATE).get("stage", "ok")
|
||||
if stage not in ("stop", "critical"):
|
||||
return 0
|
||||
@@ -215,7 +226,7 @@ def cmd_block(cfg: dict) -> int:
|
||||
return 0
|
||||
if any(re.search(p, command) for p in cfg["heavy_commands"]):
|
||||
print(
|
||||
f"democracy: resource stage is {stage}; new heavy jobs are blocked until "
|
||||
f"kvb-org-organize: resource stage is {stage}; new heavy jobs are blocked until "
|
||||
"the disk recovers. Teardown commands still run. Ask the resource chair.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
@@ -223,13 +234,49 @@ def cmd_block(cfg: dict) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def cpu_times() -> tuple[int, int]:
|
||||
fields = [int(v) for v in Path("/proc/stat").read_text(encoding="utf-8").split("\n", 1)[0].split()[1:]]
|
||||
return sum(fields), fields[3] + fields[4]
|
||||
|
||||
|
||||
def cpu_busy_percent(before: tuple[int, int], after: tuple[int, int]) -> float:
|
||||
total = after[0] - before[0]
|
||||
idle = after[1] - before[1]
|
||||
return 100.0 * (total - idle) / total
|
||||
|
||||
|
||||
def mem_used_percent(meminfo: str) -> float:
|
||||
values = {}
|
||||
for line in meminfo.splitlines():
|
||||
key, _, rest = line.partition(":")
|
||||
if rest:
|
||||
values[key] = int(rest.split()[0])
|
||||
return 100.0 * (1 - values["MemAvailable"] / values["MemTotal"])
|
||||
|
||||
|
||||
def load(cfg: dict) -> tuple[float, float]:
|
||||
before = cpu_times()
|
||||
time.sleep(cfg["load_limits"]["sample_seconds"])
|
||||
cpu = cpu_busy_percent(before, cpu_times())
|
||||
return cpu, mem_used_percent(Path("/proc/meminfo").read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def cmd_admit(cfg: dict, args: argparse.Namespace) -> int:
|
||||
need = args.need_gb if args.need_gb is not None else cfg["slot_need_gb"][args.kind]
|
||||
free, _ = disk(cfg)
|
||||
left = free - need
|
||||
floor = cfg["thresholds_gb"]["stop"]
|
||||
verdict = "grant" if left >= floor else "deny"
|
||||
print(f"{verdict}: free {free:.1f} GB, need {need} GB, leaves {left:.1f} GB (floor {floor} GB)")
|
||||
passed = [left >= floor]
|
||||
report = [f"free {free:.1f} GB, need {need} GB, leaves {left:.1f} GB (floor {floor} GB)"]
|
||||
limits = cfg["load_limits"]
|
||||
if args.kind in limits["kinds"]:
|
||||
cpu, mem = load(cfg)
|
||||
passed += [cpu < limits["cpu_percent"], mem < limits["mem_percent"]]
|
||||
report.append(
|
||||
f"cpu {cpu:.0f} % (limit {limits['cpu_percent']}), ram {mem:.0f} % (limit {limits['mem_percent']})"
|
||||
)
|
||||
verdict = "grant" if all(passed) else "deny"
|
||||
print(f"{verdict}: {'; '.join(report)}")
|
||||
return 0 if verdict == "grant" else 3
|
||||
|
||||
|
||||
@@ -275,9 +322,25 @@ def running_worktrees(cfg: dict) -> list[str]:
|
||||
return [t for t in trees if os.path.exists(os.path.join(t, cfg["worktree_marker"]))]
|
||||
|
||||
|
||||
def busy(tree: str, names: list[str]) -> bool:
|
||||
root = os.path.realpath(tree)
|
||||
for pid in filter(str.isdigit, os.listdir("/proc")):
|
||||
try:
|
||||
if Path(f"/proc/{pid}/comm").read_text(encoding="utf-8").strip() not in names:
|
||||
continue
|
||||
cwd = os.readlink(f"/proc/{pid}/cwd")
|
||||
except OSError:
|
||||
continue
|
||||
if cwd == root or cwd.startswith(root + os.sep):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def run_cleanup(cfg: dict) -> list[str]:
|
||||
commands = list(cfg["cleanup"])
|
||||
for tree in running_worktrees(cfg):
|
||||
if busy(tree, cfg["busy_processes"]):
|
||||
continue
|
||||
commands += [t.format(worktree=shlex.quote(tree)) for t in cfg["worktree_cleanup"]]
|
||||
results = []
|
||||
for command in commands:
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
name: kvb-org-perform
|
||||
description: >
|
||||
Pick `model` and `effort` per subagent from a fixed table: cheaper only at
|
||||
90 % confidence that the result equals the default's; log spawns and
|
||||
quality. Apply AUTOMATICALLY before every Agent tool call.
|
||||
---
|
||||
|
||||
A subagent runs on the main model and effort unless the spawn names others.
|
||||
Set `model` and `effort` on an Agent call only when the task clearly matches a
|
||||
row below and you are at least 90 % sure the cheaper setting delivers the same
|
||||
result as the default: no lost findings, no rework. Cost counts per finished
|
||||
task, retries included. Otherwise set neither, and the default stays.
|
||||
|
||||
## Table
|
||||
|
||||
| Task class | Subagent's task | `model` | `effort` | Evidence |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `lookup` | Read-only: find files, symbols or call sites, grep, list, read and quote, pull a log line or field, summarise a given text without judging it | `haiku` | `low` | Haiku 5.5 costs 1/40 of Opus 5.5 per token and is the speed tier; Anthropic names Haiku at low effort for simple, speed-critical and reading-heavy worker tasks; Explore and the cavecrew investigator already run on it |
|
||||
| `mechanical-edit` | An edit the brief fully specifies (exact old and new text, a rename, deleting listed lines) in one or two files | `haiku` | `low` | nothing is left to decide, and the parent checks the diff |
|
||||
| `judgement` | Everything else: root cause, skeptic or dialectic antithesis, review, security or legal checks, design, new or multi-file code, writing tests, performance work | omit | omit | no evidence at 90 % that a cheaper setting gives the same result |
|
||||
|
||||
Prices per million tokens in and out (claude-api reference, cached
|
||||
2026-10-06): Haiku 5.5 $0.10 / $0.50, Sonnet 5.5 $2 / $10, Opus 5.5 $4 / $20,
|
||||
Fable 5.1 $10 / $50.
|
||||
|
||||
## Spawn
|
||||
|
||||
1. Pick the class. A task that mixes classes, or whose class you hesitate
|
||||
over, is `judgement`.
|
||||
2. Start the brief with the line `task-class: <class>`; the spawn hook logs
|
||||
it together with `model`, `effort` and the Agent `description`.
|
||||
3. Set `model` and `effort` from the row; for `judgement` set neither.
|
||||
4. Enter the spawn in the `kvb-org-rasci` register: the subagent as R and as
|
||||
`--worker "subagent <type> (<model>, <effort>)"` of the task it serves.
|
||||
|
||||
- An agent type whose definition sets its own model (Explore, Plan, the
|
||||
cavecrew agents) keeps it; never pass `model` or `effort` for it.
|
||||
- Never pass `fable` or `opus`: neither is cheaper than the default.
|
||||
- A Haiku agent that reports the task needs judgement, or returns an
|
||||
incomplete result, is not retried on Haiku: the default continues it.
|
||||
- Never change the default itself (settings, `CLAUDE_CODE_SUBAGENT_MODEL`,
|
||||
agent definitions); this skill only chooses per call.
|
||||
|
||||
## Feedback
|
||||
|
||||
Once you have judged the subagent's result, rate it under the same Agent
|
||||
`description`:
|
||||
|
||||
```bash
|
||||
${CLAUDE_SKILL_DIR}/scripts/log.py feedback --description "<description>" --completed yes|no --tests pass|fail|none --redo yes|no
|
||||
```
|
||||
|
||||
`--redo yes` when the default had to redo or finish the work. When the
|
||||
operator later asks a follow-up question about that result or corrects it:
|
||||
|
||||
```bash
|
||||
${CLAUDE_SKILL_DIR}/scripts/log.py followup --description "<description>" --text "<question or correction>"
|
||||
```
|
||||
|
||||
All sessions share `~/.local/state/agents-council/subagent-model.jsonl`.
|
||||
Inside a sandbox that cannot write it, the script prints the line as
|
||||
`pending:` and the PostToolUse hook stores it.
|
||||
|
||||
## Evaluation
|
||||
|
||||
`log.py report` shows per task class, model and effort the runs, the rated
|
||||
runs and the share with the same result: completed, not redone, no failing
|
||||
test, no follow-up. A row is added, or a cheaper setting extended to a class,
|
||||
only when the report shows at least 90 % over at least 20 rated runs, and only
|
||||
after the operator confirms it (for example through `/kvb-skills-tune`). A row whose
|
||||
rate falls below 90 % over 20 rated runs goes back to the default. `sonnet`
|
||||
enters the table only this way, and a trial run on a setting the table does
|
||||
not hold needs the operator's order.
|
||||
Executable
+205
@@ -0,0 +1,205 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Log subagent spawns with their quality feedback, and evaluate the table.
|
||||
|
||||
Usage:
|
||||
log.py spawn hook (PreToolUse on Agent): append the spawn line
|
||||
log.py feedback --description D --completed yes|no --tests pass|fail|none --redo yes|no
|
||||
rate the latest spawn with this Agent description
|
||||
log.py followup --description D --text T
|
||||
record an operator follow-up question or correction on it
|
||||
log.py persist hook (PostToolUse on Bash): append the one line a sandboxed
|
||||
feedback or followup printed as `pending: <json>`, only
|
||||
when the command was that bare call and the line is
|
||||
well-formed and from the hook's own session
|
||||
log.py report runs, rated runs and same-result rate per task class,
|
||||
model and effort; a row qualifies at >= 90 % over >= 20
|
||||
|
||||
Environment:
|
||||
SUBAGENT_MODEL_LOG: the log shared by every session;
|
||||
~/.local/state/agents-council/subagent-model.jsonl unless set.
|
||||
CLAUDE_CODE_SESSION_ID: the session that rates its spawns.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
LOG = Path(
|
||||
os.environ.get(
|
||||
"SUBAGENT_MODEL_LOG",
|
||||
str(Path.home() / ".local" / "state" / "agents-council" / "subagent-model.jsonl"),
|
||||
)
|
||||
)
|
||||
TASK_CLASS = re.compile(r"^task-class:\s*(\S+)", re.MULTILINE)
|
||||
PENDING = "pending: "
|
||||
SCRIPT = "kvb-org-perform/scripts/log.py"
|
||||
CONTROL = re.compile(r"^[();<>|&]+$")
|
||||
KEYS = {
|
||||
"feedback": {"kind", "time", "session", "description", "completed", "tests", "redo"},
|
||||
"followup": {"kind", "time", "session", "description", "text"},
|
||||
}
|
||||
QUALIFY_RUNS = 20
|
||||
QUALIFY_RATE = 0.9
|
||||
|
||||
|
||||
def now() -> str:
|
||||
return datetime.datetime.now(datetime.UTC).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def append(line: dict) -> None:
|
||||
LOG.parent.mkdir(parents=True, exist_ok=True)
|
||||
with LOG.open("a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(line, sort_keys=True) + "\n")
|
||||
|
||||
|
||||
def record(line: dict) -> int:
|
||||
try:
|
||||
append(line)
|
||||
except OSError:
|
||||
print(PENDING + json.dumps(line, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_spawn() -> int:
|
||||
payload = json.load(sys.stdin)
|
||||
tool = payload.get("tool_input") or {}
|
||||
match = TASK_CLASS.search(tool.get("prompt", ""))
|
||||
append({
|
||||
"kind": "spawn",
|
||||
"time": now(),
|
||||
"session": payload.get("session_id", ""),
|
||||
"description": tool.get("description", ""),
|
||||
"subagent_type": tool.get("subagent_type") or "general-purpose",
|
||||
"task_class": match.group(1) if match else "unclassified",
|
||||
"model": tool.get("model") or "default",
|
||||
"effort": tool.get("effort") or "default",
|
||||
})
|
||||
return 0
|
||||
|
||||
|
||||
def rated(kind: str, args: argparse.Namespace, **fields: object) -> dict:
|
||||
session = os.environ.get("CLAUDE_CODE_SESSION_ID")
|
||||
if not session:
|
||||
sys.exit("log.py: CLAUDE_CODE_SESSION_ID is not set")
|
||||
return {"kind": kind, "time": now(), "session": session, "description": args.description, **fields}
|
||||
|
||||
|
||||
def invoked_kind(command: str) -> str | None:
|
||||
if "$(" in command or "`" in command:
|
||||
return None
|
||||
lexer = shlex.shlex(command, posix=True, punctuation_chars=True)
|
||||
lexer.whitespace_split = True
|
||||
try:
|
||||
tokens = list(lexer)
|
||||
except ValueError:
|
||||
return None
|
||||
if any(CONTROL.match(token) for token in tokens):
|
||||
return None
|
||||
if tokens[:1] in (["python3"], ["python"]):
|
||||
tokens = tokens[1:]
|
||||
if len(tokens) < 2 or not tokens[0].endswith(SCRIPT) or tokens[1] not in KEYS:
|
||||
return None
|
||||
return tokens[1]
|
||||
|
||||
|
||||
def well_formed(line: object, kind: str, session: str) -> bool:
|
||||
if not isinstance(line, dict) or set(line) != KEYS[kind] or line["kind"] != kind or line["session"] != session:
|
||||
return False
|
||||
if not all(isinstance(line[key], str) for key in ("time", "description")):
|
||||
return False
|
||||
if kind == "feedback":
|
||||
return isinstance(line["completed"], bool) and isinstance(line["redo"], bool) and line["tests"] in ("pass", "fail", "none")
|
||||
return isinstance(line["text"], str)
|
||||
|
||||
|
||||
def cmd_persist() -> int:
|
||||
payload = json.load(sys.stdin)
|
||||
kind = invoked_kind((payload.get("tool_input") or {}).get("command", ""))
|
||||
if not kind:
|
||||
return 0
|
||||
response = payload.get("tool_response")
|
||||
stdout = response.get("stdout", "") if isinstance(response, dict) else str(response or "")
|
||||
pending = [text[len(PENDING):] for text in stdout.splitlines() if text.startswith(PENDING)]
|
||||
if len(pending) != 1:
|
||||
return 0
|
||||
try:
|
||||
line = json.loads(pending[0])
|
||||
except json.JSONDecodeError:
|
||||
return 0
|
||||
if well_formed(line, kind, payload.get("session_id", "")):
|
||||
append(line)
|
||||
return 0
|
||||
|
||||
|
||||
def runs() -> list[dict]:
|
||||
current: dict[tuple[str, str], dict] = {}
|
||||
found: list[dict] = []
|
||||
for text in LOG.read_text(encoding="utf-8").splitlines() if LOG.exists() else []:
|
||||
line = json.loads(text)
|
||||
key = (line["session"], line["description"])
|
||||
if line["kind"] == "spawn":
|
||||
current[key] = {**line, "feedback": None, "followups": 0}
|
||||
found.append(current[key])
|
||||
elif key in current and line["kind"] == "feedback":
|
||||
current[key]["feedback"] = line
|
||||
elif key in current and line["kind"] == "followup":
|
||||
current[key]["followups"] += 1
|
||||
return found
|
||||
|
||||
|
||||
def same_result(run: dict) -> bool:
|
||||
feedback = run["feedback"]
|
||||
return feedback["completed"] and not feedback["redo"] and feedback["tests"] != "fail" and not run["followups"]
|
||||
|
||||
|
||||
def cmd_report() -> int:
|
||||
rows: dict[tuple[str, str, str], list[dict]] = {}
|
||||
for run in runs():
|
||||
rows.setdefault((run["task_class"], run["model"], run["effort"]), []).append(run)
|
||||
print("task_class\tmodel\teffort\truns\trated\tsame\trate\tqualifies")
|
||||
for (task_class, model, effort), group in sorted(rows.items()):
|
||||
rated_runs = [r for r in group if r["feedback"]]
|
||||
same = sum(map(same_result, rated_runs))
|
||||
rate = same / len(rated_runs) if rated_runs else 0.0
|
||||
qualifies = len(rated_runs) >= QUALIFY_RUNS and rate >= QUALIFY_RATE
|
||||
print(f"{task_class}\t{model}\t{effort}\t{len(group)}\t{len(rated_runs)}\t{same}\t{rate:.0%}\t{'yes' if qualifies else 'no'}")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
sub.add_parser("spawn")
|
||||
feedback = sub.add_parser("feedback")
|
||||
feedback.add_argument("--description", required=True)
|
||||
feedback.add_argument("--completed", required=True, choices=("yes", "no"))
|
||||
feedback.add_argument("--tests", required=True, choices=("pass", "fail", "none"))
|
||||
feedback.add_argument("--redo", required=True, choices=("yes", "no"))
|
||||
followup = sub.add_parser("followup")
|
||||
followup.add_argument("--description", required=True)
|
||||
followup.add_argument("--text", required=True)
|
||||
sub.add_parser("persist")
|
||||
sub.add_parser("report")
|
||||
args = parser.parse_args()
|
||||
if args.command == "spawn":
|
||||
return cmd_spawn()
|
||||
if args.command == "feedback":
|
||||
return record(rated(
|
||||
"feedback", args, completed=args.completed == "yes", tests=args.tests, redo=args.redo == "yes"
|
||||
))
|
||||
if args.command == "followup":
|
||||
return record(rated("followup", args, text=args.text))
|
||||
if args.command == "persist":
|
||||
return cmd_persist()
|
||||
return cmd_report()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,63 @@
|
||||
---
|
||||
name: kvb-org-rasci
|
||||
description: >
|
||||
RASCI/OKR register of tasks: roles, key results, worker, status.
|
||||
Trigger on /kvb-org-rasci, "rasci", "raci", "zuständigkeiten".
|
||||
---
|
||||
|
||||
The register is the single point of truth of the organisation: every agent
|
||||
records here what it works on, and claims, queue, handover and reports run
|
||||
over it. `${CLAUDE_SKILL_DIR}/scripts/rasci.py` keeps it in
|
||||
`<council root>/rasci.json`. A `kvb-org-organize` claim enters its task by
|
||||
itself (holder as R and A, `running`, start, workdir, branch); its release
|
||||
sets `done` and the end, or `stopped` while a key result is still open.
|
||||
|
||||
```bash
|
||||
rasci.py set <task> --title <t> --objective <o> --description <d> --prio <n> --status queued|running|blocked|done|stopped --worker "<agent | subagent <type> (<model>)>" --workdir <dir> --branch <b> --artifact <kind>:<ref> --tool <script or command> [--start <iso>] [--end <iso>] [--drop-artifact <a>] [--drop-tool <t>]
|
||||
rasci.py kr <task> add "<measurable result>" | met <n> | open <n> | rm <n>
|
||||
rasci.py role <task> "<party>" <letters>
|
||||
rasci.py get <task>
|
||||
rasci.py rm <task>
|
||||
rasci.py show [--all]
|
||||
rasci.py artifacts [--ended] [--task <task>]
|
||||
rasci.py estimate <task> "<party>" --value <fib> --complexity <fib>
|
||||
rasci.py wsjf [--all]
|
||||
rasci.py tools
|
||||
```
|
||||
|
||||
## Objective and key results
|
||||
|
||||
The objective says what the task is for; its key results are the measurable
|
||||
outcomes that prove it reached (a test green, a run passing, a release
|
||||
published). `done` is refused while one is open; a task ended short of them is
|
||||
`stopped`. `show` puts both in the OKR column as `<objective> (<met>/<all> KR)`.
|
||||
|
||||
## Roles
|
||||
|
||||
- **R Responsible**: does the task: the claim holder, or the subagent it runs.
|
||||
- **A Accountable**: exactly one; takes the final decision and carries the
|
||||
overall responsibility. The claim holder, unless the operator decides.
|
||||
- **S Supportive**: actively helps carry it out: a peer's fix, the chair's
|
||||
grant, a stack or runner.
|
||||
- **C Consulted**: asked for input before acting: line representatives,
|
||||
lineage owners, the operator on a pending decision.
|
||||
- **I Informed**: kept up to date on progress or result, without a say.
|
||||
|
||||
`-` clears a party; the operator is the party `Operator`.
|
||||
|
||||
## Rules
|
||||
|
||||
- On start, `set` title, objective, description, priority and worker, `kr
|
||||
add` every key result, and `role` every party beyond R and A; on each
|
||||
change, update the status. The worker is the one session or subagent
|
||||
executing the task right now.
|
||||
- Artifacts share this table and follow the `kvb-org-artefacts` skill:
|
||||
record each one when it appears, drop it once deleted. Add every script or
|
||||
tool the task ran (`--tool`): `tools` ranks them for `kvb-skills-dream`.
|
||||
- Priority is the rank of the `kvb-org-wsjf` skill: an operator's pin
|
||||
(`--prio`) first, then WSJF from the estimates the chair collects; `show`
|
||||
prints the rank as Prio and the score as WSJF.
|
||||
- Write only your own rows; another session's task belongs to that session.
|
||||
- On /kvb-org-rasci print `show` unchanged; its `gaps:` line names tasks
|
||||
without exactly one A, without R, or open without a key result. `get`
|
||||
prints one task in full, key results numbered.
|
||||
Executable
+497
@@ -0,0 +1,497 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Keep the RASCI register of the organisation's tasks in a local JSON file.
|
||||
|
||||
Environment:
|
||||
AGENTS_COUNCIL_ROOT: council directory shared by every agent on the host;
|
||||
the register is <root>/rasci.json, and `show` also lists every work/
|
||||
and cluster/ claim of the council there. /tmp/agents-council unless set.
|
||||
|
||||
Exit codes:
|
||||
0 done, 2 usage error.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import datetime
|
||||
import fcntl
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import statistics
|
||||
import sys
|
||||
import tempfile
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(os.environ.get("AGENTS_COUNCIL_ROOT", "/tmp/agents-council"))
|
||||
DB = ROOT / "rasci.json"
|
||||
LOCK = ROOT / "rasci.lock"
|
||||
COUNCIL = Path(__file__).resolve().parents[2] / "kvb-org-organize" / "scripts" / "council.py"
|
||||
TASK = re.compile(r"^[a-z0-9][a-z0-9._-]*(/[a-z0-9][a-z0-9._-]*)*$")
|
||||
LETTERS = re.compile(r"^(?!.*(.).*\1)[RASCI]+$")
|
||||
ORDER = "RASCI"
|
||||
STATUSES = ("queued", "running", "blocked", "done", "stopped")
|
||||
ENDED = ("done", "stopped")
|
||||
FIELDS = (
|
||||
"title", "objective", "description", "prio", "status", "worker", "start", "end", "workdir",
|
||||
"branch",
|
||||
)
|
||||
TEXT_FIELDS = ("title", "objective", "description", "worker", "workdir", "branch")
|
||||
LIST_FIELDS = {"tools": "tool"}
|
||||
ARTIFACT = re.compile(r"^[a-z]+:\S")
|
||||
FIBONACCI = (1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
|
||||
OPERATOR = "Operator"
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
print(f"rasci: {message}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
def check_task(task: str) -> None:
|
||||
if not TASK.match(task):
|
||||
fail(f"invalid task {task!r}; use a slug like work/<slug>")
|
||||
|
||||
|
||||
def stamp(value: str = "now") -> str:
|
||||
if value == "now":
|
||||
return datetime.datetime.now(datetime.UTC).isoformat(timespec="seconds")
|
||||
try:
|
||||
parsed = datetime.datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
fail(f"invalid time {value!r}; use ISO 8601 or now")
|
||||
if parsed.tzinfo is None:
|
||||
parsed = parsed.astimezone()
|
||||
return parsed.astimezone(datetime.UTC).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def letters_of(*parts: str) -> str:
|
||||
return "".join(letter for letter in ORDER if any(letter in part for part in parts))
|
||||
|
||||
|
||||
def load() -> dict[str, dict]:
|
||||
try:
|
||||
return json.loads(DB.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except ValueError:
|
||||
fail(f"{DB} is not valid JSON")
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def database() -> Iterator[dict[str, dict]]:
|
||||
ROOT.mkdir(parents=True, exist_ok=True)
|
||||
with LOCK.open("a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
tasks = load()
|
||||
yield tasks
|
||||
with tempfile.NamedTemporaryFile(
|
||||
"w", dir=ROOT, prefix=".rasci-", delete=False, encoding="utf-8"
|
||||
) as tmp:
|
||||
json.dump(tasks, tmp, indent=1, sort_keys=True)
|
||||
os.replace(tmp.name, DB)
|
||||
|
||||
|
||||
def open_results(entry: dict) -> int:
|
||||
return sum(not kr["met"] for kr in entry.get("key_results", []))
|
||||
|
||||
|
||||
def apply_status(entry: dict, status: str) -> None:
|
||||
if status not in ENDED:
|
||||
entry.pop("end", None)
|
||||
entry["status"] = status
|
||||
if status == "running":
|
||||
entry.setdefault("start", stamp())
|
||||
if status in ENDED:
|
||||
entry.setdefault("end", stamp())
|
||||
|
||||
|
||||
def track(task: str, holder: str, status: str, *, description: str | None = None,
|
||||
previous: str | None = None, workdir: str | None = None,
|
||||
branch: str | None = None) -> None:
|
||||
"""Write a council claim (status running) or release (status done) through.
|
||||
|
||||
Args:
|
||||
task: the claimed office, e.g. work/<slug>.
|
||||
holder: the session holding the claim.
|
||||
status: running on claim and takeover, done on release; a release with
|
||||
open key results ends as stopped.
|
||||
description: the claim's --work line, kept unless one is recorded.
|
||||
previous: the stale holder a takeover replaces; loses its R and A.
|
||||
workdir: the claiming process's directory, kept unless one is recorded.
|
||||
branch: the checked-out branch there, kept unless one is recorded.
|
||||
"""
|
||||
with database() as tasks:
|
||||
entry = tasks.setdefault(task, {"roles": {}})
|
||||
roles = entry.setdefault("roles", {})
|
||||
if previous and previous != holder:
|
||||
left = roles.pop(previous, "").replace("R", "").replace("A", "")
|
||||
if left:
|
||||
roles[previous] = left
|
||||
if entry.get("worker") == previous:
|
||||
entry["worker"] = holder
|
||||
entry.setdefault("worker", holder)
|
||||
for field, value in (("description", description), ("workdir", workdir), ("branch", branch)):
|
||||
if value:
|
||||
entry.setdefault(field, value)
|
||||
if status == "done" and open_results(entry):
|
||||
status = "stopped"
|
||||
if status in ENDED or entry.get("status") in (None, "queued", *ENDED):
|
||||
apply_status(entry, status)
|
||||
if status not in ENDED:
|
||||
accountable = any("A" in v for p, v in roles.items() if p != holder)
|
||||
roles[holder] = letters_of(roles.get(holder, ""), "R" if accountable else "RA")
|
||||
|
||||
|
||||
def claimed() -> dict[str, dict]:
|
||||
if not COUNCIL.is_file():
|
||||
return {}
|
||||
spec = importlib.util.spec_from_file_location("council", COUNCIL)
|
||||
council = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(council)
|
||||
live = council.live_sessions()
|
||||
rows = {}
|
||||
for office, claim in council.claims():
|
||||
if not office.startswith(("work/", "cluster/")):
|
||||
continue
|
||||
holder = claim["name"] or claim["session"]
|
||||
rows[office] = {
|
||||
"description": claim["work"],
|
||||
"status": "claimed",
|
||||
"worker": holder,
|
||||
"start": claim["since"],
|
||||
"roles": {holder: "RA"},
|
||||
"stale": council.is_stale(claim, live),
|
||||
}
|
||||
return rows
|
||||
|
||||
|
||||
def merged(include_done: bool) -> dict[str, dict]:
|
||||
rows = claimed()
|
||||
for task, entry in load().items():
|
||||
base = rows.get(task, {"status": "queued", "roles": {}})
|
||||
fields = {k: v for k, v in entry.items() if k != "roles"}
|
||||
rows[task] = {**base, **fields, "roles": {**base["roles"], **entry.get("roles", {})}}
|
||||
for row in rows.values():
|
||||
if row.get("stale"):
|
||||
row["status"] = "stale"
|
||||
return {
|
||||
task: row for task, row in rows.items() if include_done or row["status"] not in ENDED
|
||||
}
|
||||
|
||||
|
||||
def cell(text: object, width: int) -> str:
|
||||
text = " ".join(str(text).split()).replace("|", "\\|")
|
||||
return text if len(text) <= width else text[: width - 1] + "…"
|
||||
|
||||
|
||||
def when(value: str | None) -> str:
|
||||
if not value:
|
||||
return "-"
|
||||
return datetime.datetime.fromisoformat(value).astimezone().strftime("%m-%d %H:%M")
|
||||
|
||||
|
||||
def wsjf(row: dict) -> tuple[float, float, float] | None:
|
||||
estimates = list(row.get("estimates", {}).values())
|
||||
if not estimates:
|
||||
return None
|
||||
value = statistics.median(e["value"] for e in estimates)
|
||||
complexity = statistics.median(e["complexity"] for e in estimates)
|
||||
return value, complexity, round(value / complexity, 2)
|
||||
|
||||
|
||||
def ranked(rows: dict[str, dict]) -> list[str]:
|
||||
def key(task: str) -> tuple:
|
||||
row = rows[task]
|
||||
score = wsjf(row)
|
||||
pinned = row.get("prio")
|
||||
return (pinned is None, pinned or 0, score is None, -(score[2] if score else 0), task)
|
||||
|
||||
return sorted(rows, key=key)
|
||||
|
||||
|
||||
def okr(row: dict) -> str:
|
||||
results = row.get("key_results", [])
|
||||
text = cell(row.get("objective") or "-", 40)
|
||||
if results:
|
||||
text += f" ({sum(kr['met'] for kr in results)}/{len(results)} KR)"
|
||||
return text
|
||||
|
||||
|
||||
def gaps(task: str, row: dict) -> list[str]:
|
||||
found = []
|
||||
roles = row["roles"]
|
||||
accountable = sum("A" in letters for letters in roles.values())
|
||||
if accountable != 1:
|
||||
found.append(f"{task} has {accountable} A")
|
||||
if not any("R" in letters for letters in roles.values()):
|
||||
found.append(f"{task} has no R")
|
||||
if not row.get("key_results") and row["status"] not in ENDED:
|
||||
found.append(f"{task} has no key result")
|
||||
return found
|
||||
|
||||
|
||||
def cmd_set(args: argparse.Namespace) -> int:
|
||||
check_task(args.task)
|
||||
if args.prio is not None and args.prio < 1:
|
||||
fail("--prio must be 1 or higher")
|
||||
times = {f: stamp(getattr(args, f)) for f in ("start", "end") if getattr(args, f)}
|
||||
for ref in args.artifact:
|
||||
if not ARTIFACT.match(ref):
|
||||
fail(f"invalid artifact {ref!r}; use <kind>:<ref>, e.g. image:<name>:<tag>")
|
||||
with database() as tasks:
|
||||
entry = tasks.setdefault(args.task, {"roles": {}})
|
||||
if args.status == "done" and open_results(entry):
|
||||
fail(f"{args.task}: {open_results(entry)} key result(s) open; mark them met or set stopped")
|
||||
for field in (*TEXT_FIELDS, "prio"):
|
||||
value = getattr(args, field)
|
||||
if value is not None:
|
||||
entry[field] = value
|
||||
if args.status:
|
||||
apply_status(entry, args.status)
|
||||
entry.update(times)
|
||||
for field, flag in LIST_FIELDS.items():
|
||||
drop = getattr(args, f"drop_{flag}")
|
||||
items = [i for i in entry.get(field, []) if i not in drop]
|
||||
items += [i for i in dict.fromkeys(getattr(args, flag)) if i not in items]
|
||||
if items:
|
||||
entry[field] = items
|
||||
else:
|
||||
entry.pop(field, None)
|
||||
kept = [a for a in entry.get("artifacts", []) if a["ref"] not in args.drop_artifact]
|
||||
known = {a["ref"] for a in kept}
|
||||
kept += [{"ref": r, "added": stamp()} for r in dict.fromkeys(args.artifact) if r not in known]
|
||||
if kept:
|
||||
entry["artifacts"] = kept
|
||||
else:
|
||||
entry.pop("artifacts", None)
|
||||
print(f"set {args.task}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_role(args: argparse.Namespace) -> int:
|
||||
check_task(args.task)
|
||||
letters = args.letters.upper()
|
||||
if letters != "-" and not LETTERS.match(letters):
|
||||
fail("letters must be distinct ones of R, A, S, C, I, or - to clear")
|
||||
with database() as tasks:
|
||||
roles = tasks.setdefault(args.task, {"roles": {}}).setdefault("roles", {})
|
||||
if letters == "-":
|
||||
roles.pop(args.party, None)
|
||||
else:
|
||||
roles[args.party] = letters_of(letters)
|
||||
print(f"{args.task}: {args.party} {letters}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_kr(args: argparse.Namespace) -> int:
|
||||
check_task(args.task)
|
||||
with database() as tasks:
|
||||
entry = tasks.setdefault(args.task, {"roles": {}})
|
||||
results = entry.setdefault("key_results", [])
|
||||
if args.action == "add":
|
||||
if all(kr["text"] != args.value for kr in results):
|
||||
results.append({"text": args.value, "met": False})
|
||||
else:
|
||||
if not args.value.isdigit() or not 1 <= int(args.value) <= len(results):
|
||||
fail(f"{args.task}: no key result {args.value!r}; `get` lists them by number")
|
||||
index = int(args.value) - 1
|
||||
if args.action == "rm":
|
||||
results.pop(index)
|
||||
else:
|
||||
results[index]["met"] = args.action == "met"
|
||||
if not results:
|
||||
entry.pop("key_results")
|
||||
print(f"{args.task}: key result {args.action} {args.value}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_get(args: argparse.Namespace) -> int:
|
||||
row = merged(True).get(args.task)
|
||||
if row is None:
|
||||
fail(f"{args.task}: not in the register")
|
||||
print(f"task: {args.task}")
|
||||
for field in FIELDS:
|
||||
if row.get(field) not in (None, ""):
|
||||
print(f"{field}: {row[field]}")
|
||||
for number, kr in enumerate(row.get("key_results", []), 1):
|
||||
print(f"key result {number} [{'x' if kr['met'] else ' '}]: {kr['text']}")
|
||||
for artifact in row.get("artifacts", []):
|
||||
print(f"artifact: {artifact['ref']} (since {when(artifact['added'])})")
|
||||
for field, flag in LIST_FIELDS.items():
|
||||
for item in row.get(field, []):
|
||||
print(f"{flag}: {item}")
|
||||
roles = ", ".join(f"{p}={v}" for p, v in sorted(row["roles"].items()))
|
||||
print(f"roles: {roles or '-'}")
|
||||
for party, estimate in sorted(row.get("estimates", {}).items()):
|
||||
print(f"estimate {party}: business value {estimate['value']}, complexity {estimate['complexity']}")
|
||||
score = wsjf(row)
|
||||
if score:
|
||||
print(f"wsjf: {score[2]:g}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_estimate(args: argparse.Namespace) -> int:
|
||||
check_task(args.task)
|
||||
if not args.drop:
|
||||
for name in ("value", "complexity"):
|
||||
if getattr(args, name) not in FIBONACCI:
|
||||
fail(f"--{name} must be one of {', '.join(map(str, FIBONACCI))}")
|
||||
with database() as tasks:
|
||||
entry = tasks.setdefault(args.task, {"roles": {}})
|
||||
estimates = entry.setdefault("estimates", {})
|
||||
if args.drop:
|
||||
estimates.pop(args.party, None)
|
||||
else:
|
||||
estimates[args.party] = {"value": args.value, "complexity": args.complexity, "at": stamp()}
|
||||
if not estimates:
|
||||
entry.pop("estimates")
|
||||
print(f"{args.task}: estimate {'dropped' if args.drop else 'recorded'} for {args.party}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_wsjf(args: argparse.Namespace) -> int:
|
||||
rows = merged(args.all)
|
||||
if not rows:
|
||||
print("no tasks")
|
||||
return 0
|
||||
header = ["Rank", "Task", "OKR", "Business value", "Complexity", "WSJF", "Estimators", "Status"]
|
||||
print("| " + " | ".join(header) + " |")
|
||||
print("|" + "---|" * len(header))
|
||||
unestimated = []
|
||||
for rank, task in enumerate(ranked(rows), 1):
|
||||
row = rows[task]
|
||||
score = wsjf(row)
|
||||
if score is None:
|
||||
unestimated.append(task)
|
||||
figures = [f"{n:g}" for n in score] if score else ["-", "-", "-"]
|
||||
estimators = ", ".join(sorted(row.get("estimates", {}), key=str.lower)) or "-"
|
||||
values = [rank, task, okr(row), *figures, cell(estimators, 40), row["status"]]
|
||||
print("| " + " | ".join(str(v) for v in values) + " |")
|
||||
if unestimated:
|
||||
print("unestimated: " + ", ".join(unestimated))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_artifacts(args: argparse.Namespace) -> int:
|
||||
rows = merged(True)
|
||||
for task in sorted(rows):
|
||||
row = rows[task]
|
||||
if args.task and task != args.task:
|
||||
continue
|
||||
if args.ended and row["status"] not in (*ENDED, "stale"):
|
||||
continue
|
||||
places = [(f"{f}:{row[f]}", None) for f in ("workdir", "branch") if row.get(f)]
|
||||
recorded = [(a["ref"], a["added"]) for a in row.get("artifacts", [])]
|
||||
for ref, added in (*places, *recorded):
|
||||
print(f"{row['status']}\t{task}\t{row.get('worker') or '-'}\t{ref}\t{when(added)}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_tools(_: argparse.Namespace) -> int:
|
||||
used: dict[str, list[str]] = {}
|
||||
for task, row in merged(True).items():
|
||||
for tool in row.get("tools", []):
|
||||
used.setdefault(tool, []).append(task)
|
||||
for tool, tasks in sorted(used.items(), key=lambda item: (-len(item[1]), item[0])):
|
||||
print(f"{len(tasks)}\t{tool}\t{' '.join(sorted(tasks))}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_rm(args: argparse.Namespace) -> int:
|
||||
check_task(args.task)
|
||||
with database() as tasks:
|
||||
removed = tasks.pop(args.task, None)
|
||||
print(f"removed {args.task}" if removed is not None else f"{args.task}: not in the register")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_show(args: argparse.Namespace) -> int:
|
||||
rows = merged(args.all)
|
||||
if not rows:
|
||||
print("no tasks")
|
||||
return 0
|
||||
header = ["Prio", "WSJF", "Task", "OKR", "Status", "Worker", "Artifacts", "Start", "End", *ORDER]
|
||||
print("| " + " | ".join(header) + " |")
|
||||
print("|" + "---|" * len(header))
|
||||
problems = []
|
||||
for rank, task in enumerate(ranked(rows), 1):
|
||||
row = rows[task]
|
||||
title = f"{task}: {row['title']}" if row.get("title") else task
|
||||
score = wsjf(row)
|
||||
values = [
|
||||
rank,
|
||||
f"{score[2]:g}" if score else "-",
|
||||
cell(title, 50),
|
||||
okr(row),
|
||||
row["status"],
|
||||
cell(row.get("worker") or "-", 30),
|
||||
len(row.get("artifacts", [])) or "-",
|
||||
when(row.get("start")),
|
||||
when(row.get("end")),
|
||||
]
|
||||
parties = sorted(row["roles"], key=lambda p: (p != OPERATOR, p.lower()))
|
||||
values += [
|
||||
cell(", ".join(p for p in parties if letter in row["roles"][p]), 30) for letter in ORDER
|
||||
]
|
||||
print("| " + " | ".join(str(v) for v in values) + " |")
|
||||
problems += gaps(task, row)
|
||||
if problems:
|
||||
print("gaps: " + "; ".join(problems))
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
sub = parser.add_subparsers(dest="cmd", required=True)
|
||||
p = sub.add_parser("set")
|
||||
p.add_argument("task")
|
||||
for field in (*TEXT_FIELDS, "start", "end"):
|
||||
p.add_argument(f"--{field}")
|
||||
p.add_argument("--prio", type=int)
|
||||
for flag in (*LIST_FIELDS.values(), "artifact"):
|
||||
p.add_argument(f"--{flag}", action="append", default=[])
|
||||
p.add_argument(f"--drop-{flag}", action="append", default=[])
|
||||
p.add_argument("--status", choices=STATUSES)
|
||||
p.set_defaults(func=cmd_set)
|
||||
p = sub.add_parser("estimate")
|
||||
p.add_argument("task")
|
||||
p.add_argument("party")
|
||||
p.add_argument("--value", type=int)
|
||||
p.add_argument("--complexity", type=int)
|
||||
p.add_argument("--drop", action="store_true")
|
||||
p.set_defaults(func=cmd_estimate)
|
||||
p = sub.add_parser("wsjf")
|
||||
p.add_argument("--all", action="store_true")
|
||||
p.set_defaults(func=cmd_wsjf)
|
||||
p = sub.add_parser("kr")
|
||||
p.add_argument("task")
|
||||
p.add_argument("action", choices=("add", "met", "open", "rm"))
|
||||
p.add_argument("value")
|
||||
p.set_defaults(func=cmd_kr)
|
||||
p = sub.add_parser("role")
|
||||
p.add_argument("task")
|
||||
p.add_argument("party")
|
||||
p.add_argument("letters")
|
||||
p.set_defaults(func=cmd_role)
|
||||
for name, func in (("get", cmd_get), ("rm", cmd_rm)):
|
||||
p = sub.add_parser(name)
|
||||
p.add_argument("task")
|
||||
p.set_defaults(func=func)
|
||||
p = sub.add_parser("show")
|
||||
p.add_argument("--all", action="store_true")
|
||||
p.set_defaults(func=cmd_show)
|
||||
p = sub.add_parser("artifacts")
|
||||
p.add_argument("--ended", action="store_true")
|
||||
p.add_argument("--task")
|
||||
p.set_defaults(func=cmd_artifacts)
|
||||
sub.add_parser("tools").set_defaults(func=cmd_tools)
|
||||
args = parser.parse_args()
|
||||
return args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: robot
|
||||
name: kvb-org-robot
|
||||
description: >
|
||||
Work fully autonomously to a goal: no check-ins, no stopping before the goal,
|
||||
only commands already cleared. Trigger when the operator wants hands-off,
|
||||
@@ -11,7 +11,7 @@ Operate as an autonomous robot: given a goal, reach it without hand-holding.
|
||||
## Contract
|
||||
|
||||
- **No questions once the goal is clear.** Clarify only genuinely-blocking
|
||||
unknowns up front (via the `active-listening` skill), then proceed without
|
||||
unknowns up front (via the `kvb-think-listen` skill), then proceed without
|
||||
further check-ins. Pick the cleanest option and continue; never pause to
|
||||
confirm a choice you can make yourself.
|
||||
- **Never stop before the goal.** Do not end the run, hand back, or declare done
|
||||
@@ -28,10 +28,14 @@ Operate as an autonomous robot: given a goal, reach it without hand-holding.
|
||||
- **Verify, do not assume.** Reaching the goal means proving it: run it, read the
|
||||
output, confirm the end state. Never report success on a step you did not
|
||||
actually verify.
|
||||
- **Run it over the register.** Before the first step, enter the goal in the
|
||||
`kvb-org-rasci` register as the task's objective and every check that proves
|
||||
it as a key result; mark each one met as its proof comes in. The run is
|
||||
finished when the task can be set `done`.
|
||||
|
||||
## Rules
|
||||
|
||||
- Escalate an uncertain root cause or design decision to the `dialectic` skill
|
||||
- Escalate an uncertain root cause or design decision to the `kvb-think-dialectic` skill
|
||||
rather than guessing; uncertainty is never a reason to stop.
|
||||
- Sustain the loop across long, multi-step work — the run is finished only when
|
||||
the whole goal is verifiably met.
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: funnel
|
||||
name: kvb-org-split
|
||||
description: >
|
||||
Keep agent work in its own git worktree until it reaches 90% fix confidence
|
||||
and under 5% break risk; below that bar it becomes a proposal. Trigger when
|
||||
delegating work to agents, when agents work in parallel, or on /funnel.
|
||||
delegating work to agents, when agents work in parallel, or on /kvb-org-split.
|
||||
---
|
||||
|
||||
# Funnel
|
||||
@@ -14,16 +14,19 @@ in a sidetree until it does, or leaves as a proposal.
|
||||
## The bar
|
||||
|
||||
- **Fix confidence of at least 90 %** and **break risk under 5 %**, both
|
||||
reported by the `confidence` skill, the break risk derived through the
|
||||
`break-risk` skill.
|
||||
reported by the `kvb-check-confidence` skill, the break risk derived through the
|
||||
`kvb-check-break-risk` skill.
|
||||
- The operator may set a different bar. Never lower it to make a change fit.
|
||||
|
||||
## The stages
|
||||
|
||||
1. **Brief.** One concern per agent. Name the goal, the exact base commit, the
|
||||
scope that may change, the evidence expected back, a hard time cap (default
|
||||
60 minutes) and what the agent must not do: no pushes, no gates or deploys
|
||||
unless the resource chair of the `democracy` skill granted them, read-only
|
||||
1. **Brief.** One concern per agent, on the model the `kvb-org-perform` skill
|
||||
picks, entered in the `kvb-org-rasci` register as R with `--worker "subagent
|
||||
<type> (<model>)"`. Name the goal, the exact base commit, the
|
||||
scope that may change, the evidence expected back, a time cap (default
|
||||
60 minutes) at which it reports its interim state, and what the agent must
|
||||
not do: no pushes, no gates or deploys
|
||||
unless the resource chair of the `kvb-org-organize` skill granted them, read-only
|
||||
probes on shared live systems.
|
||||
2. **Sidetree.** The agent works in its own worktree on its own branch,
|
||||
created from the exact base commit, so its edits never land under a running
|
||||
@@ -33,8 +36,10 @@ in a sidetree until it does, or leaves as a proposal.
|
||||
behaviour, and makes a negative control: the test fails without the change.
|
||||
Numbers come from the same source before and after.
|
||||
4. **Self-assessment.** The agent reports fix confidence and break risk with
|
||||
their residuals and commits on its branch.
|
||||
5. **Independent review.** Before anything is merged, run the `dialectic` skill
|
||||
their residuals and commits on its branch. Its parent marks the key results
|
||||
that evidence proves as met in the `kvb-org-rasci` register and records
|
||||
the branch and worktree as `--branch` and `--artifact worktree:<path>`.
|
||||
5. **Independent review.** Before anything is merged, run the `kvb-think-dialectic` skill
|
||||
with skeptics who did not write the change. A hole they find returns the
|
||||
change to stage 3.
|
||||
6. **Merge.** At or above the bar, merge the sidetree branch into the main line
|
||||
@@ -64,8 +69,9 @@ and verify each step instead of assuming it:
|
||||
5. **Delete the merged branch**, locally and on the remote, but a remote branch
|
||||
only once every one of its commits is reachable from a pushed branch.
|
||||
6. **Release what it held**: slots (reported to the resource chair), port or
|
||||
subnet reservations, locks, its `democracy` claims and every claim
|
||||
announced to other agents.
|
||||
subnet reservations, locks, its `kvb-org-organize` claims and every claim
|
||||
announced to other agents. Drop each removed item from the register with
|
||||
`--drop-artifact` and set the subagent's task `done` or `stopped`.
|
||||
7. **Remove its temporary files**: logs, message files and scratch data that
|
||||
have served their purpose. Keep only the evidence the report cites, until
|
||||
the report is delivered.
|
||||
@@ -93,8 +99,9 @@ below the bar never enters the main line on its own.
|
||||
|
||||
## Rules
|
||||
|
||||
- Stop an agent at its time cap and ask for its findings; an uncapped brief can
|
||||
run for hours and deliver nothing.
|
||||
- At its time cap, ask an agent for its interim findings and let it run on;
|
||||
never stop a running agent. A brief without a cap can run for hours without
|
||||
a word.
|
||||
- Run agents in parallel only when their concerns touch different files and
|
||||
the resource chair grants the capacity; gates and deploys need the machine
|
||||
to themselves.
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
name: kvb-org-wsjf
|
||||
description: >
|
||||
WSJF priority from Fibonacci estimates. Trigger on /kvb-org-wsjf, "wsjf",
|
||||
"priorisieren".
|
||||
---
|
||||
|
||||
Weighted Shortest Job First ranks the tasks of the `kvb-org-rasci` register
|
||||
by cost of delay over job size: here business value over complexity, each the
|
||||
median of Fibonacci estimates (1, 2, 3, 5, 8, 13, 21, 34, 55, 89). The
|
||||
estimates live in the register's table; `wsjf` is its WSJF view, one row per
|
||||
task with its OKR and the task id the register uses, and the register's Prio
|
||||
column is this rank. The script is
|
||||
`${CLAUDE_SKILL_DIR}/../kvb-org-rasci/scripts/rasci.py`.
|
||||
|
||||
```bash
|
||||
rasci.py estimate <task> "<party>" --value <fib> --complexity <fib>
|
||||
rasci.py estimate <task> "<party>" --drop
|
||||
rasci.py wsjf [--all]
|
||||
```
|
||||
|
||||
## Procedure
|
||||
|
||||
1. **The chair asks.** For every new task, and when its objective or a key
|
||||
result changes, the resource chair of the `kvb-org-organize` skill asks
|
||||
its subordinates (the task's worker and R, the representatives of the
|
||||
lines it touches) for one Fibonacci estimate each of business value and
|
||||
complexity, one message per agent.
|
||||
2. **Record each answer** under the party that gave it; a new estimate
|
||||
replaces the old one. An agent may record its own.
|
||||
3. **Rank**: WSJF = median business value / median complexity, highest
|
||||
first. An operator's pin (`rasci.py set <task> --prio <n>`) outranks every
|
||||
score; unestimated tasks come last and are named under `unestimated:`.
|
||||
4. **Grant in rank order**: the chair hands out capacity by this rank.
|
||||
|
||||
## Rules
|
||||
|
||||
- Estimate relative to the other open tasks, never in hours.
|
||||
- Never invent an estimate for a party that did not answer; a task without
|
||||
one stays unestimated.
|
||||
@@ -1,13 +1,12 @@
|
||||
---
|
||||
name: autoskill
|
||||
name: kvb-skills-auto
|
||||
description: >
|
||||
Turn operator repetition into a skill. Trigger when the operator gives the
|
||||
same instruction, correction or prompt pattern about the third time in a
|
||||
conversation, or says they keep repeating themselves, and the pattern is
|
||||
reusable.
|
||||
Turn operator repetition into a skill. Trigger when the operator repeats an
|
||||
instruction, correction or prompt pattern a third time in a conversation, or
|
||||
says they keep repeating themselves, and the pattern is reusable.
|
||||
---
|
||||
|
||||
Its objective is the `autotune` skill's **Objective** section: a skill is worth
|
||||
Its objective is the `kvb-skills-tune` skill's **Objective** section: a skill is worth
|
||||
creating only when it cuts tokens or time and raises quality; judge every
|
||||
candidate against its three axes and rules.
|
||||
|
||||
@@ -20,9 +19,9 @@ vary), do the following:
|
||||
a skill name suggestion, the trigger phrasing, and what the skill would
|
||||
do. Ask whether to create it.
|
||||
3. On approval, write the skill:
|
||||
- a conversation shortcut or expansion: add it to the `shortcuts` skill
|
||||
- a conversation shortcut or expansion: add it to the `kvb-skills-shortcuts` skill
|
||||
table instead of creating a new skill.
|
||||
- anything else: persist it exactly as the `autotune` skill's
|
||||
- anything else: persist it exactly as the `kvb-skills-tune` skill's
|
||||
**Persistence** section specifies — locate the operator's skills
|
||||
repository, write `skills/<name>/SKILL.md` there (or in the current
|
||||
project for project-specific behavior), then mirror the skill directory
|
||||
@@ -1,10 +1,10 @@
|
||||
---
|
||||
name: dream
|
||||
name: kvb-skills-dream
|
||||
description: >
|
||||
Consolidate the last 24 hours of work in this repository: what held, what
|
||||
broke, which hypotheses follow, into memory and improvement proposals.
|
||||
Trigger on /dream or when the operator asks to reflect on or learn from
|
||||
recent work.
|
||||
Consolidate the last 24 hours of work in this repository (what held, what
|
||||
broke) into memory and improvement proposals.
|
||||
Trigger on /kvb-skills-dream or a request to reflect on or learn from recent
|
||||
work.
|
||||
---
|
||||
|
||||
Sleep on the work: replay what happened in this repository, separate what held
|
||||
@@ -24,13 +24,13 @@ A class of error counts as closed only when something structural prevents it —
|
||||
a test, a lint rule, a CI check, a hook, a written rule in the agent
|
||||
instructions, or a skill. "Be more careful next time" closes nothing. Report the
|
||||
confidence the next run can now hold on each closed class, calibrated as the
|
||||
`confidence` skill requires, and name what is still open.
|
||||
`kvb-check-confidence` skill requires, and name what is still open.
|
||||
|
||||
## Scope
|
||||
|
||||
Everything is read from the repository the skill runs in (`git rev-parse
|
||||
--show-toplevel`); never mix in another project's history or memory. The default
|
||||
window is the last 24 hours — the operator may widen it (`/dream 7d`). State the
|
||||
window is the last 24 hours — the operator may widen it (`/kvb-skills-dream 7d`). State the
|
||||
repository and the window in one line before you start.
|
||||
|
||||
Run only when the operator asks. The 12-hour reminder hook
|
||||
@@ -48,6 +48,9 @@ Gather the window's actual record, not your recollection of it:
|
||||
logs of the red ones — the failing log line, not the job title.
|
||||
- **Reviews**: pull requests and issues touched in the window, and the review
|
||||
comments on them.
|
||||
- **Register**: the `kvb-org-rasci` register: `rasci.py tools` ranks the
|
||||
scripts and tools the window's tasks ran, the refactoring candidates;
|
||||
`get <task>` shows a task's objective, roles, workdir and artifacts.
|
||||
- **Memory**: this project's memory directory and its `MEMORY.md` index — the
|
||||
findings already recorded, so the dream extends them instead of repeating them.
|
||||
- **Instructions**: `CLAUDE.md`, `AGENTS.md`, and the project's own skills, to
|
||||
@@ -77,7 +80,7 @@ that nothing could disprove is not a hypothesis — cut it.
|
||||
|
||||
## Step 4: dialectic
|
||||
|
||||
Put every surviving hypothesis through the `dialectic` skill: thesis,
|
||||
Put every surviving hypothesis through the `kvb-think-dialectic` skill: thesis,
|
||||
independent skeptics, synthesis, iterated to ~99%. What survives becomes a
|
||||
finding. What gets refuted is recorded as discarded **with the refutation**, so
|
||||
the next dream does not re-derive it.
|
||||
@@ -106,10 +109,10 @@ as radio buttons: the improvement, the evidence behind it, and the options
|
||||
`Apply now`, `Record as a task`, `Skip`. Ranked by evidence, one question per
|
||||
improvement. No repository file changes before an answer comes back.
|
||||
|
||||
## Step 7: autotune, then autoskill
|
||||
## Step 7: kvb-skills-tune, then kvb-skills-auto
|
||||
|
||||
With the dialectic done and memory written, run `autotune` — hand it this run's
|
||||
findings as its evidence so it does not re-collect them — and then `autoskill`
|
||||
With the dialectic done and memory written, run `kvb-skills-tune` — hand it this run's
|
||||
findings as its evidence so it does not re-collect them — and then `kvb-skills-auto`
|
||||
for the operator corrections the window revealed. Both keep their own
|
||||
confirmation steps; the dream never writes a skill on their behalf.
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
# UserPromptSubmit hook: emit the dream hint at most once per interval and per
|
||||
# UserPromptSubmit hook: emit the kvb-skills-dream hint at most once per interval and per
|
||||
# repository. The stamp lives in the repository's git dir, so every repository
|
||||
# keeps its own cadence; outside a git repository the hook stays silent.
|
||||
# Stdout lands in the agent's context, which is why the payload tells the agent
|
||||
# to show the hint and keep going instead of running dream by itself.
|
||||
# to show the hint and keep going instead of running kvb-skills-dream by itself.
|
||||
set -euo pipefail
|
||||
|
||||
interval="${DREAM_INTERVAL_SECONDS:-43200}"
|
||||
@@ -31,10 +31,11 @@ printf '%s\n' "${now}" >"${stamp}"
|
||||
cat <<'HINT'
|
||||
DREAM HINT: over twelve hours since the last hint for this repository. Show the
|
||||
operator this notice verbatim as a short block, then continue with their
|
||||
request. Do NOT run dream, do not start replaying the history, do not ask
|
||||
questions about it.
|
||||
request. Do NOT run kvb-skills-dream, do not start replaying the history, do
|
||||
not ask questions about it.
|
||||
|
||||
💤 /dream - consolidate the last 24h in this repository: what held, what
|
||||
broke, which hypotheses follow, into memory and improvement proposals.
|
||||
💤 /kvb-skills-dream - consolidate the last 24h in this repository: what
|
||||
held, what broke, which hypotheses follow, into memory and improvement
|
||||
proposals.
|
||||
Runs only when you trigger it.
|
||||
HINT
|
||||
@@ -1,8 +1,8 @@
|
||||
---
|
||||
name: essence
|
||||
name: kvb-skills-essence
|
||||
description: >
|
||||
Compact skills and memory to their essence after a health pass that finds
|
||||
dead weight. Trigger on /essence or when skills or MEMORY.md grow too long,
|
||||
dead weight. Trigger on /kvb-skills-essence or when skills or MEMORY.md grow too long,
|
||||
duplicate, or eat too much context.
|
||||
---
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: shortcuts
|
||||
name: kvb-skills-shortcuts
|
||||
description: >
|
||||
Operator conversation shortcuts. Trigger when the message is exactly one of
|
||||
these tokens, optionally with arguments: sobu, soco, socobu, socon, sona,
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: autotune
|
||||
name: kvb-skills-tune
|
||||
description: >
|
||||
Generate new skills or optimize existing ones (fewer tokens, fewer errors,
|
||||
persistent learnings), each proposal confirmed by single-select question.
|
||||
Trigger ONLY on an explicit request: /autotune, "autotune", "tune the
|
||||
Trigger ONLY on an explicit request: /kvb-skills-tune, "autotune", "tune the
|
||||
skills"; never on your own initiative.
|
||||
---
|
||||
|
||||
@@ -13,8 +13,8 @@ skill it writes or rewrites lands in the operator's skills repository.
|
||||
|
||||
## Objective
|
||||
|
||||
The shared objective of the self-improving skills (autotune, autoskill,
|
||||
confidence): every skill, rule, or report the agent produces about its own
|
||||
The shared objective of the self-improving skills (kvb-skills-tune,
|
||||
kvb-skills-auto, kvb-check-confidence): every skill, rule, or report the agent produces about its own
|
||||
working is judged on three axes at once. A proposal that cannot name the axis
|
||||
it moves is not an optimization, it is a preference.
|
||||
|
||||
@@ -43,7 +43,7 @@ it moves is not an optimization, it is a preference.
|
||||
|
||||
## Trigger discipline
|
||||
|
||||
- Run **only** when the operator asks: `/autotune`, "autotune", "tune the
|
||||
- Run **only** when the operator asks: `/kvb-skills-tune`, "autotune", "tune the
|
||||
skills", or an equivalent instruction.
|
||||
- The 60-minute reminder hook is a hint for the operator, not a trigger. When it
|
||||
fires, print the hint and continue the operator's actual request.
|
||||
@@ -75,14 +75,14 @@ option, and never write a file before the answers are in.
|
||||
|
||||
Ask in this order, at most four questions per call:
|
||||
|
||||
1. **Scope** - "What should autotune do this run?" Options: `Create a new
|
||||
1. **Scope** - "What should kvb-skills-tune do this run?" Options: `Create a new
|
||||
skill`, `Optimize an existing skill`, `Both`, plus the ranked findings if
|
||||
more than one candidate exists.
|
||||
2. **Target** - which finding becomes a skill, or which existing skill gets
|
||||
optimized. One option per candidate, each with its measured cost in the
|
||||
description.
|
||||
3. **Shape** - for a new skill: `Standalone skill`, `Row in the shortcuts
|
||||
skill`, `Extend an existing skill`, `Memory entry instead of a skill`.
|
||||
3. **Shape** - for a new skill: `Standalone skill`, `Row in the
|
||||
kvb-skills-shortcuts skill`, `Extend an existing skill`, `Memory entry instead of a skill`.
|
||||
For an optimization: `Tighten wording only`, `Change the trigger`, `Add
|
||||
rules`, `Split into two skills`, `Merge into another skill`.
|
||||
4. **Placement** - `Operator skills repository (portable)` or
|
||||
@@ -130,7 +130,7 @@ reverse — remove the mirrors too, or the old name keeps firing.
|
||||
- Optimizing an existing skill means the file gets shorter or sharper, not
|
||||
longer. Delete rules the agent already follows, merge duplicated ones, and
|
||||
cut every sentence that does not change an action. Route that compaction
|
||||
through the `essence` skill instead of trimming by hand: it runs a health
|
||||
through the `kvb-skills-essence` skill instead of trimming by hand: it runs a health
|
||||
pass for dead pointers and rules duplicated across skills before cutting
|
||||
anything, ranks by what loads in every session, and shows the diff before it
|
||||
writes. It asks for its own scope — answer with the skill being optimized.
|
||||
@@ -140,7 +140,7 @@ reverse — remove the mirrors too, or the old name keeps firing.
|
||||
## Rules
|
||||
|
||||
- One skill per run unless the operator picked `Both`; a broad rewrite of the
|
||||
whole collection is not what autotune is for.
|
||||
whole collection is not what kvb-skills-tune is for.
|
||||
- Never write a skill for one-off work, for secrets, or for behaviour an
|
||||
existing skill already covers - propose extending that skill instead.
|
||||
- The **Objective** section decides what counts as an improvement: at least
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# UserPromptSubmit hook: emit the autotune hint at most once per interval.
|
||||
# UserPromptSubmit hook: emit the kvb-skills-tune hint at most once per interval.
|
||||
# Stdout lands in the agent's context, which is why the payload tells the agent
|
||||
# to show the hint and keep going instead of running autotune by itself.
|
||||
# to show the hint and keep going instead of running kvb-skills-tune by itself.
|
||||
set -euo pipefail
|
||||
|
||||
interval="${AUTOTUNE_INTERVAL_SECONDS:-3600}"
|
||||
@@ -24,9 +24,9 @@ printf '%s\n' "${now}" >"${stamp}"
|
||||
cat <<'HINT'
|
||||
AUTOTUNE HINT: over an hour since the last hint. Show the operator this notice
|
||||
verbatim as a short block, then continue with their request. Do NOT run
|
||||
autotune, do not propose skills, do not ask questions about it.
|
||||
kvb-skills-tune, do not propose skills, do not ask questions about it.
|
||||
|
||||
💡 /autotune - generate a new skill or optimize an existing one
|
||||
💡 /kvb-skills-tune - generate a new skill or optimize an existing one
|
||||
(fewer tokens, fewer errors, more focus, learnings that persist).
|
||||
Runs only when you trigger it.
|
||||
HINT
|
||||
@@ -1,21 +1,21 @@
|
||||
---
|
||||
name: criticize
|
||||
name: kvb-think-criticize
|
||||
description: >
|
||||
Give constructive criticism of a problem, plan, design, decision, text or
|
||||
code from diverse aspects, each point hardened by dialectic. Trigger on
|
||||
/criticize, "kritisiere", "kritisch betrachten", "konstruktive Kritik", "was
|
||||
haeltst du davon", or requests for honest feedback.
|
||||
code, each point hardened by dialectic. Trigger on /kvb-think-criticize,
|
||||
"kritisiere", "kritisch betrachten", "konstruktive Kritik", "was haeltst du
|
||||
davon", or requests for honest feedback.
|
||||
---
|
||||
|
||||
The stance is critical but constructive: the goal is a better result, not a
|
||||
verdict on its author. This skill judges any artifact from many angles; it is
|
||||
not limited to code (`sceptic` hunts violated engineering principles in code,
|
||||
not limited to code (`kvb-check-principles` hunts violated engineering principles in code,
|
||||
`code-review` hunts bugs). Read-only: report the critique, change nothing
|
||||
unless the operator asks afterwards.
|
||||
|
||||
## Before you start: listen
|
||||
|
||||
Invoke the `active-listening` skill. Pin down what is being criticized, what it
|
||||
Invoke the `kvb-think-listen` skill. Pin down what is being criticized, what it
|
||||
is meant to achieve, for whom, and under which constraints. Derive what you can
|
||||
from the artifact and its surroundings first; ask only what only the operator
|
||||
knows. A critique against the wrong goal is noise.
|
||||
@@ -53,7 +53,7 @@ Sweep every aspect that applies, and name the ones you skipped and why:
|
||||
|
||||
## Harden every point with dialectic
|
||||
|
||||
Run each candidate critique through the `dialectic` skill before reporting it:
|
||||
Run each candidate critique through the `kvb-think-dialectic` skill before reporting it:
|
||||
|
||||
- **Thesis**: the critique point with its evidence.
|
||||
- **Antithesis**: independent defenders argue that the artifact is right as it
|
||||
@@ -76,7 +76,7 @@ One line of scope, then the steelman. Then:
|
||||
`Evidence` is `proven` (read, run, reproduced, cited) or `derived` (reasoned).
|
||||
|
||||
Close with at most three lines: how many candidate points dialectic dropped and
|
||||
why, the single change that helps most, and the `confidence` skill's numbers for
|
||||
why, the single change that helps most, and the `kvb-check-confidence` skill's numbers for
|
||||
the critique as a whole.
|
||||
|
||||
## Rules
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: dialectic
|
||||
name: kvb-think-dialectic
|
||||
description: >
|
||||
Reach a defensible conclusion by thesis, independent skeptic antithesis and
|
||||
synthesis, iterated to ~99% confidence. Trigger for any consequential root
|
||||
@@ -12,13 +12,13 @@ answer; drive the loop until a thesis survives every attack at ~99% confidence.
|
||||
|
||||
## Before you start: listen
|
||||
|
||||
Invoke the `active-listening` skill first. Do not begin the dialectic until you
|
||||
Invoke the `kvb-think-listen` skill first. Do not begin the dialectic until you
|
||||
have gathered every requirement, constraint, and success criterion the task
|
||||
needs. A dialectic run on the wrong question wastes the whole loop. Return to
|
||||
`active-listening` mid-loop whenever an objection turns on a fact only the
|
||||
`kvb-think-listen` mid-loop whenever an objection turns on a fact only the
|
||||
operator holds.
|
||||
|
||||
When another skill or an autonomous run (robot, observe, a loop) invoked this
|
||||
When another skill or an autonomous run (kvb-org-robot, kvb-ci-observe, a loop) invoked this
|
||||
skill, derive the requirements from the task and the evidence instead of
|
||||
asking; ask only when an operator-only fact blocks the conclusion.
|
||||
|
||||
@@ -30,7 +30,8 @@ asking; ask only when an operator-only fact blocks the conclusion.
|
||||
make or CLI helpers the project exposes); CI logs and artifacts; tests; docs.
|
||||
Cite `file:line` and command output — never a bare assertion.
|
||||
2. **Antithesis.** Spawn MULTIPLE independent skeptics (parallel subagents or a
|
||||
workflow) whose only job is to REFUTE the thesis. Each re-inspects the
|
||||
workflow, on the default model as the `kvb-org-perform` skill requires)
|
||||
whose only job is to REFUTE the thesis. Each re-inspects the
|
||||
sources itself and defaults to "refuted" on any concrete hole. Give diverse
|
||||
skeptics diverse lenses: correctness, an alternate mechanism, does-it-
|
||||
reproduce, does-the-fix-break-something-else.
|
||||
@@ -40,7 +41,7 @@ asking; ask only when an operator-only fact blocks the conclusion.
|
||||
4. **Iterate.** Repeat thesis → antithesis → synthesis until a full skeptic
|
||||
round finds no new hole and the thesis holds at ~99%. If confidence stalls
|
||||
below 99%, name the exact residual and the evidence that would close it, then
|
||||
go get that evidence (more inspection, or `active-listening` for an
|
||||
go get that evidence (more inspection, or `kvb-think-listen` for an
|
||||
operator-only fact) and loop again.
|
||||
|
||||
## Rules
|
||||
@@ -1,8 +1,8 @@
|
||||
---
|
||||
name: explain
|
||||
name: kvb-think-explain
|
||||
description: >
|
||||
Explain code and its interactions. Trigger when the operator asks what code
|
||||
does, how a mechanism works, why components interact, or invokes /explain on
|
||||
does, how a mechanism works, why components interact, or invokes /kvb-think-explain on
|
||||
a file, function, role or module.
|
||||
---
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: active-listening
|
||||
name: kvb-think-listen
|
||||
description: >
|
||||
Ask focused questions until every requirement is pinned down, then reflect
|
||||
the task back. Trigger at the start of any task with unclear scope,
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Validate the autotune reminder hook and its settings registration."""
|
||||
"""Validate the kvb-skills-tune reminder hook and its settings registration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -10,8 +10,8 @@ import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
SKILL = REPO_ROOT / "skills" / "autotune" / "SKILL.md"
|
||||
HOOK = REPO_ROOT / "skills" / "autotune" / "hooks" / "reminder.sh"
|
||||
SKILL = REPO_ROOT / "skills" / "kvb-skills-tune" / "SKILL.md"
|
||||
HOOK = REPO_ROOT / "skills" / "kvb-skills-tune" / "hooks" / "reminder.sh"
|
||||
PATCHER = REPO_ROOT / "scripts" / "enable-plugins.js"
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ def _run_hook(stamp: Path, interval: str = "3600") -> subprocess.CompletedProces
|
||||
class TestAutotuneSkill(unittest.TestCase):
|
||||
def test_skill_is_trigger_only(self):
|
||||
text = SKILL.read_text(encoding="utf-8")
|
||||
self.assertIn("name: autotune", text)
|
||||
self.assertIn("name: kvb-skills-tune", text)
|
||||
self.assertIn("multiSelect: false", text)
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ class TestSkillPersistence(unittest.TestCase):
|
||||
self.assertIn(target, text)
|
||||
|
||||
def test_autoskill_routes_to_the_same_persistence(self):
|
||||
text = (REPO_ROOT / "skills" / "autoskill" / "SKILL.md").read_text(
|
||||
text = (REPO_ROOT / "skills" / "kvb-skills-auto" / "SKILL.md").read_text(
|
||||
encoding="utf-8"
|
||||
)
|
||||
for target in ("Persistence", "~/.claude/skills/", "~/.agents/skills/"):
|
||||
@@ -66,7 +66,7 @@ class TestAutotuneHook(unittest.TestCase):
|
||||
|
||||
def test_first_run_hints_and_stamps(self):
|
||||
result = _run_hook(self.stamp)
|
||||
self.assertIn("/autotune", result.stdout)
|
||||
self.assertIn("/kvb-skills-tune", result.stdout)
|
||||
self.assertTrue(self.stamp.is_file())
|
||||
|
||||
def test_second_run_is_silent_within_interval(self):
|
||||
@@ -75,12 +75,12 @@ class TestAutotuneHook(unittest.TestCase):
|
||||
|
||||
def test_hint_returns_after_the_interval(self):
|
||||
_run_hook(self.stamp)
|
||||
self.assertIn("/autotune", _run_hook(self.stamp, interval="0").stdout)
|
||||
self.assertIn("/kvb-skills-tune", _run_hook(self.stamp, interval="0").stdout)
|
||||
|
||||
def test_corrupt_stamp_does_not_crash(self):
|
||||
self.stamp.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.stamp.write_text("not-a-timestamp\n", encoding="utf-8")
|
||||
self.assertIn("/autotune", _run_hook(self.stamp).stdout)
|
||||
self.assertIn("/kvb-skills-tune", _run_hook(self.stamp).stdout)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("node"), "node not installed")
|
||||
@@ -100,7 +100,7 @@ class TestSettingsRegistration(unittest.TestCase):
|
||||
self._patch()
|
||||
data = self._patch()
|
||||
entries = json.dumps(data["hooks"]["UserPromptSubmit"])
|
||||
self.assertEqual(entries.count("autotune/hooks/reminder.sh"), 1)
|
||||
self.assertEqual(entries.count("kvb-skills-tune/hooks/reminder.sh"), 1)
|
||||
|
||||
def test_existing_hooks_preserved(self):
|
||||
self.settings.write_text(
|
||||
|
||||
@@ -11,8 +11,8 @@ import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
CI_FAILURES = REPO_ROOT / "skills" / "ci-artifacts" / "scripts" / "ci_failures.py"
|
||||
FIND_FIX = REPO_ROOT / "skills" / "merge-fix" / "scripts" / "find_fix.py"
|
||||
CI_FAILURES = REPO_ROOT / "skills" / "kvb-ci-artifacts" / "scripts" / "ci_failures.py"
|
||||
FIND_FIX = REPO_ROOT / "skills" / "kvb-git-merge-fix" / "scripts" / "find_fix.py"
|
||||
|
||||
|
||||
def _load(path: Path):
|
||||
@@ -55,7 +55,7 @@ class TestCiFailures(unittest.TestCase):
|
||||
"Ran 41 tests in 1.0s\n"
|
||||
"OK\n"
|
||||
"UP017 [*] Use `datetime.UTC` alias\n"
|
||||
" --> skills/democracy/scripts/council.py:92:40\n"
|
||||
" --> skills/kvb-org-organize/scripts/council.py:92:40\n"
|
||||
"Found 1 error.\n"
|
||||
"make: *** [Makefile:15: test] Error 1\n"
|
||||
"##[error]Process completed with exit code 2.\n"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Exercise the democracy council script: election, staleness, release, gate."""
|
||||
"""Exercise the kvb-org-organize council script: election, staleness, release, gate."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -10,7 +10,7 @@ import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
COUNCIL = REPO_ROOT / "skills" / "democracy" / "scripts" / "council.py"
|
||||
COUNCIL = REPO_ROOT / "skills" / "kvb-org-organize" / "scripts" / "council.py"
|
||||
|
||||
|
||||
class TestCouncil(unittest.TestCase):
|
||||
|
||||
+59
-14
@@ -10,8 +10,8 @@ import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
SKILL = REPO_ROOT / "skills" / "dream" / "SKILL.md"
|
||||
HOOK = REPO_ROOT / "skills" / "dream" / "hooks" / "reminder.sh"
|
||||
SKILL = REPO_ROOT / "skills" / "kvb-skills-dream" / "SKILL.md"
|
||||
HOOK = REPO_ROOT / "skills" / "kvb-skills-dream" / "hooks" / "reminder.sh"
|
||||
PATCHER = REPO_ROOT / "scripts" / "enable-plugins.js"
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ def _run_hook(
|
||||
class TestDreamSkill(unittest.TestCase):
|
||||
def test_skill_is_trigger_only(self):
|
||||
text = SKILL.read_text(encoding="utf-8")
|
||||
self.assertIn("name: dream", text)
|
||||
self.assertIn("name: kvb-skills-dream", text)
|
||||
self.assertIn("multiSelect: false", text)
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ class TestDreamHook(unittest.TestCase):
|
||||
|
||||
def test_first_run_hints_and_stamps(self):
|
||||
result = _run_hook(self.cwd, self.stamp)
|
||||
self.assertIn("/dream", result.stdout)
|
||||
self.assertIn("/kvb-skills-dream", result.stdout)
|
||||
self.assertTrue(self.stamp.is_file())
|
||||
|
||||
def test_second_run_is_silent_within_interval(self):
|
||||
@@ -60,12 +60,12 @@ class TestDreamHook(unittest.TestCase):
|
||||
|
||||
def test_hint_returns_after_the_interval(self):
|
||||
_run_hook(self.cwd, self.stamp)
|
||||
self.assertIn("/dream", _run_hook(self.cwd, self.stamp, interval="0").stdout)
|
||||
self.assertIn("/kvb-skills-dream", _run_hook(self.cwd, self.stamp, interval="0").stdout)
|
||||
|
||||
def test_corrupt_stamp_does_not_crash(self):
|
||||
self.stamp.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.stamp.write_text("not-a-timestamp\n", encoding="utf-8")
|
||||
self.assertIn("/dream", _run_hook(self.cwd, self.stamp).stdout)
|
||||
self.assertIn("/kvb-skills-dream", _run_hook(self.cwd, self.stamp).stdout)
|
||||
|
||||
def test_outside_a_repository_it_stays_silent(self):
|
||||
self.assertEqual(_run_hook(self.cwd).stdout, "")
|
||||
@@ -78,7 +78,7 @@ class TestDreamHook(unittest.TestCase):
|
||||
subprocess.run(
|
||||
["git", "init", "-q", str(repo)], check=True, capture_output=True
|
||||
)
|
||||
self.assertIn("/dream", _run_hook(repo).stdout)
|
||||
self.assertIn("/kvb-skills-dream", _run_hook(repo).stdout)
|
||||
self.assertTrue((repo / ".git" / ".dream-stamp").is_file())
|
||||
self.assertEqual(_run_hook(repo).stdout, "")
|
||||
|
||||
@@ -103,7 +103,7 @@ class TestDreamHook(unittest.TestCase):
|
||||
subprocess.run(
|
||||
["git", *args], check=True, capture_output=True, env=env, cwd=str(repo)
|
||||
)
|
||||
self.assertIn("/dream", _run_hook(repo).stdout)
|
||||
self.assertIn("/kvb-skills-dream", _run_hook(repo).stdout)
|
||||
self.assertEqual(_run_hook(tree).stdout, "")
|
||||
|
||||
|
||||
@@ -124,14 +124,59 @@ class TestSettingsRegistration(unittest.TestCase):
|
||||
self._patch()
|
||||
data = self._patch()
|
||||
entries = json.dumps(data["hooks"]["UserPromptSubmit"])
|
||||
self.assertEqual(entries.count("dream/hooks/reminder.sh"), 1)
|
||||
self.assertEqual(entries.count("autotune/hooks/reminder.sh"), 1)
|
||||
self.assertEqual(entries.count("kvb-skills-dream/hooks/reminder.sh"), 1)
|
||||
self.assertEqual(entries.count("kvb-skills-tune/hooks/reminder.sh"), 1)
|
||||
gate = json.dumps(data["hooks"]["PreToolUse"])
|
||||
self.assertEqual(gate.count("democracy/scripts/council.py"), 1)
|
||||
self.assertEqual(gate.count("democracy/scripts/watch.py"), 1)
|
||||
self.assertEqual(entries.count("democracy/scripts/watch.py"), 1)
|
||||
self.assertEqual(gate.count("kvb-org-organize/scripts/council.py"), 1)
|
||||
self.assertEqual(gate.count("kvb-org-organize/scripts/watch.py"), 1)
|
||||
self.assertEqual(entries.count("kvb-org-organize/scripts/watch.py"), 1)
|
||||
post = json.dumps(data["hooks"]["PostToolUse"])
|
||||
self.assertEqual(post.count("democracy/scripts/watch.py"), 1)
|
||||
self.assertEqual(post.count("kvb-org-organize/scripts/watch.py"), 1)
|
||||
self.assertEqual(gate.count("kvb-org-perform/scripts/log.py"), 1)
|
||||
self.assertEqual(post.count("kvb-org-perform/scripts/log.py"), 1)
|
||||
|
||||
def test_hooks_of_renamed_skills_are_repointed(self):
|
||||
base = Path(self.tmp.name) / "skills"
|
||||
|
||||
def hook(command):
|
||||
return {"hooks": [{"type": "command", "command": command}]}
|
||||
|
||||
self.settings.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"hooks": {
|
||||
"UserPromptSubmit": [
|
||||
hook(f'bash "{base}/autotune/hooks/reminder.sh"'),
|
||||
hook(f'bash "{base}/dream/hooks/reminder.sh"'),
|
||||
hook(f'python3 "{base}/democracy/scripts/watch.py" watch'),
|
||||
hook("echo keep"),
|
||||
],
|
||||
"PreToolUse": [
|
||||
hook(f'python3 "{base}/democracy/scripts/council.py" gate'),
|
||||
hook(f'python3 "{base}/democracy/scripts/watch.py" block'),
|
||||
hook(f'python3 "{base}/subagent-model/scripts/log.py" spawn'),
|
||||
],
|
||||
"PostToolUse": [
|
||||
hook(f'python3 "{base}/democracy/scripts/watch.py" watch'),
|
||||
hook(f'python3 "{base}/subagent-model/scripts/log.py" persist'),
|
||||
],
|
||||
}
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
data = self._patch()
|
||||
text = json.dumps(data["hooks"])
|
||||
for old in ("/autotune/", "/dream/", "/democracy/", "/subagent-model/"):
|
||||
self.assertNotIn(f"skills{old}", text)
|
||||
self.assertIn("echo keep", text)
|
||||
entries = json.dumps(data["hooks"]["UserPromptSubmit"])
|
||||
self.assertEqual(entries.count("kvb-skills-dream/hooks/reminder.sh"), 1)
|
||||
self.assertEqual(entries.count("kvb-skills-tune/hooks/reminder.sh"), 1)
|
||||
self.assertEqual(entries.count("kvb-org-organize/scripts/watch.py"), 1)
|
||||
gate = json.dumps(data["hooks"]["PreToolUse"])
|
||||
self.assertEqual(gate.count("kvb-org-organize/scripts/council.py"), 1)
|
||||
self.assertEqual(gate.count("kvb-org-perform/scripts/log.py"), 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Pin every first-party skill name to kvb-<category>-<name> and the Agent Skills name rules."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
SKILLS = REPO_ROOT / "skills"
|
||||
README = REPO_ROOT / "README.md"
|
||||
CATEGORIES = ("think", "create", "code", "ci", "git", "check", "org", "skills")
|
||||
UNCATEGORIZED = frozenset({"kvb-cleanup", "kvb-help"})
|
||||
SPEC = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")
|
||||
SCHEMA = re.compile(rf"^kvb-(?:{'|'.join(CATEGORIES)})-[a-z0-9]+(?:-[a-z0-9]+)*$")
|
||||
NAME_LINE = re.compile(r"^name:\s*(\S+)\s*$", re.MULTILINE)
|
||||
ORGANIGRAM_EDGE = re.compile(r"^\s*(\w+) --> \w+\[(kvb-[a-z0-9-]+)\]\s*$", re.MULTILINE)
|
||||
|
||||
|
||||
class TestSkillNames(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.names = sorted(p.name for p in SKILLS.iterdir() if p.is_dir())
|
||||
|
||||
def test_name_field_matches_the_directory(self):
|
||||
for name in self.names:
|
||||
with self.subTest(skill=name):
|
||||
text = (SKILLS / name / "SKILL.md").read_text(encoding="utf-8")
|
||||
match = NAME_LINE.search(text)
|
||||
self.assertIsNotNone(match, "SKILL.md has no name: line")
|
||||
self.assertEqual(match.group(1), name)
|
||||
|
||||
def test_names_follow_the_agent_skills_rules(self):
|
||||
for name in self.names:
|
||||
with self.subTest(skill=name):
|
||||
self.assertRegex(name, SPEC)
|
||||
self.assertLessEqual(len(name), 64)
|
||||
self.assertNotRegex(name, "anthropic|claude")
|
||||
|
||||
def test_names_use_a_listed_category(self):
|
||||
for name in self.names:
|
||||
if name in UNCATEGORIZED:
|
||||
continue
|
||||
with self.subTest(skill=name):
|
||||
self.assertRegex(name, SCHEMA)
|
||||
|
||||
def test_every_category_and_exception_is_in_use(self):
|
||||
for category in CATEGORIES:
|
||||
with self.subTest(category=category):
|
||||
self.assertTrue(
|
||||
any(n.startswith(f"kvb-{category}-") for n in self.names),
|
||||
f"category {category} has no skill",
|
||||
)
|
||||
self.assertLessEqual(UNCATEGORIZED, set(self.names))
|
||||
|
||||
def test_readme_organigram_places_every_skill_under_its_category(self):
|
||||
text = README.read_text(encoding="utf-8")
|
||||
section = text.split("## Organigram", 1)[1].split("\n## ", 1)[0]
|
||||
edges = ORGANIGRAM_EDGE.findall(section)
|
||||
self.assertEqual(sorted(name for _, name in edges), self.names)
|
||||
for parent, name in edges:
|
||||
with self.subTest(skill=name):
|
||||
expected = "none" if name in UNCATEGORIZED else name.split("-")[1]
|
||||
self.assertEqual(parent, expected)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The self-improving skills must share the objective held by autotune."""
|
||||
"""The self-improving skills must share the objective held by kvb-skills-tune."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,12 +7,12 @@ from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
SKILLS = REPO_ROOT / "skills"
|
||||
ROUTERS = ("autoskill", "confidence")
|
||||
ROUTERS = ("kvb-skills-auto", "kvb-check-confidence")
|
||||
|
||||
|
||||
class TestOptimizeObjective(unittest.TestCase):
|
||||
def test_autotune_names_the_three_axes(self):
|
||||
text = (SKILLS / "autotune" / "SKILL.md").read_text(encoding="utf-8")
|
||||
text = (SKILLS / "kvb-skills-tune" / "SKILL.md").read_text(encoding="utf-8")
|
||||
self.assertIn("## Objective", text)
|
||||
for axis in ("**Tokens**", "**Time**", "**Quality**"):
|
||||
self.assertIn(axis, text)
|
||||
@@ -21,9 +21,9 @@ class TestOptimizeObjective(unittest.TestCase):
|
||||
for skill in ROUTERS:
|
||||
text = (SKILLS / skill / "SKILL.md").read_text(encoding="utf-8")
|
||||
self.assertIn(
|
||||
"`autotune` skill's **Objective**",
|
||||
"`kvb-skills-tune` skill's **Objective**",
|
||||
text,
|
||||
f"{skill} does not route to the autotune objective",
|
||||
f"{skill} does not route to the kvb-skills-tune objective",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
"""Exercise the kvb-org-rasci register: fields, roles, priority order, claims, artifacts, tools."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
RASCI = REPO_ROOT / "skills" / "kvb-org-rasci" / "scripts" / "rasci.py"
|
||||
COUNCIL = REPO_ROOT / "skills" / "kvb-org-organize" / "scripts" / "council.py"
|
||||
HEADER = "| Prio | WSJF | Task | OKR | Status | Worker | Artifacts | Start | End | R | A | S | C | I |"
|
||||
|
||||
|
||||
def local(iso: str) -> str:
|
||||
return datetime.datetime.fromisoformat(iso).astimezone().strftime("%m-%d %H:%M")
|
||||
|
||||
|
||||
class TestRasci(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.home = Path(self.tmp.name) / "home"
|
||||
self.root = Path(self.tmp.name) / "council"
|
||||
self.sessions = self.home / ".claude" / "sessions"
|
||||
self.sessions.mkdir(parents=True)
|
||||
for sid, name in (("s1", "One"), ("s2", "Two")):
|
||||
(self.sessions / f"{sid}.json").write_text(
|
||||
json.dumps({"sessionId": sid, "name": name}), encoding="utf-8"
|
||||
)
|
||||
|
||||
def _run(self, *args: str, script: Path = RASCI, sid: str = "s1") -> subprocess.CompletedProcess:
|
||||
env = {
|
||||
"PATH": "/usr/bin:/bin",
|
||||
"HOME": str(self.home),
|
||||
"AGENTS_COUNCIL_ROOT": str(self.root),
|
||||
"CLAUDE_CODE_SESSION_ID": sid,
|
||||
}
|
||||
return subprocess.run(
|
||||
[sys.executable, str(script), *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env=env,
|
||||
cwd=self.tmp.name,
|
||||
check=False,
|
||||
)
|
||||
|
||||
def _out(self, *args: str) -> list[str]:
|
||||
result = self._run(*args)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
return result.stdout.splitlines()
|
||||
|
||||
def _claim(self, office: str, session: str, name: str, work: str) -> None:
|
||||
path = self.root / office
|
||||
path.mkdir(parents=True)
|
||||
claim = {
|
||||
"office": office,
|
||||
"session": session,
|
||||
"runtime": "claude-code",
|
||||
"name": name,
|
||||
"since": "2026-11-01T00:00:00+00:00",
|
||||
"beat": time.time(),
|
||||
"work": work,
|
||||
}
|
||||
(path / "claim.json").write_text(json.dumps(claim), encoding="utf-8")
|
||||
|
||||
def test_matrix_orders_by_priority_and_lists_roles(self):
|
||||
start = "2026-11-01T10:00:00+00:00"
|
||||
self._run("set", "work/a", "--title", "Alpha", "--objective", "Ship A", "--prio", "2",
|
||||
"--status", "running", "--worker", "Skills", "--start", start)
|
||||
self._run("role", "work/a", "Skills", "ar")
|
||||
self._run("role", "work/a", "Operator", "ic")
|
||||
self._run("role", "work/a", "Pkgmgr", "C")
|
||||
self._run("set", "work/b", "--title", "Beta", "--prio", "1", "--worker", "subagent Explore (haiku)")
|
||||
self._run("role", "work/b", "Pkgmgr", "R")
|
||||
lines = self._out("show")
|
||||
self.assertEqual(lines[0], HEADER)
|
||||
self.assertEqual(
|
||||
lines[2], "| 1 | - | work/b: Beta | - | queued | subagent Explore (haiku) | - | - | - | Pkgmgr | | | | |"
|
||||
)
|
||||
self.assertEqual(
|
||||
lines[3],
|
||||
f"| 2 | - | work/a: Alpha | Ship A | running | Skills | - | {local(start)} | - "
|
||||
"| Skills | Skills | | Operator, Pkgmgr | Operator |",
|
||||
)
|
||||
self.assertEqual(
|
||||
lines[4], "gaps: work/b has 0 A; work/b has no key result; work/a has no key result"
|
||||
)
|
||||
|
||||
def test_key_results_gate_done_and_fill_the_okr_column(self):
|
||||
self._run("set", "work/a", "--objective", "Ship A", "--status", "running")
|
||||
self._run("role", "work/a", "Skills", "RA")
|
||||
self._run("kr", "work/a", "add", "tests green")
|
||||
self._run("kr", "work/a", "add", "released")
|
||||
self._run("kr", "work/a", "met", "1")
|
||||
lines = self._out("show")
|
||||
self.assertIn("| Ship A (1/2 KR) | running |", lines[2])
|
||||
self.assertEqual(len(lines), 3)
|
||||
self.assertEqual(self._run("set", "work/a", "--status", "done").returncode, 2)
|
||||
self.assertIn("key result 2 [ ]: released", self._out("get", "work/a"))
|
||||
self._run("kr", "work/a", "met", "2")
|
||||
self.assertEqual(self._run("set", "work/a", "--status", "done").returncode, 0)
|
||||
self.assertEqual(self._out("show"), ["no tasks"])
|
||||
|
||||
def test_status_sets_start_and_end(self):
|
||||
self._run("set", "work/a", "--status", "running")
|
||||
self._run("set", "work/a", "--status", "done", "--description", "long text")
|
||||
lines = self._out("get", "work/a")
|
||||
self.assertIn("status: done", lines)
|
||||
self.assertIn("description: long text", lines)
|
||||
self.assertTrue(any(line.startswith("start: 20") for line in lines))
|
||||
self.assertTrue(any(line.startswith("end: 20") for line in lines))
|
||||
self._run("set", "work/a", "--status", "running")
|
||||
self.assertFalse(any(line.startswith("end:") for line in self._out("get", "work/a")))
|
||||
|
||||
def test_done_tasks_show_only_with_all(self):
|
||||
self._run("set", "work/a", "--status", "done", "--end", "2026-11-01T12:00:00+00:00")
|
||||
self._run("role", "work/a", "Skills", "RA")
|
||||
self.assertEqual(self._out("show"), ["no tasks"])
|
||||
self.assertIn("| done | - |", self._out("show", "--all")[2])
|
||||
|
||||
def test_artifacts_and_tools(self):
|
||||
self._run("set", "work/a", "--workdir", "/w/a", "--branch", "feat/a", "--status", "done",
|
||||
"--artifact", "image:core:dev", "--artifact", "volume:db",
|
||||
"--tool", "council.py", "--tool", "make test")
|
||||
self._run("set", "work/b", "--worker", "Two", "--tool", "make test", "--artifact", "dir:/tmp/b")
|
||||
self._run("set", "work/a", "--drop-artifact", "volume:db")
|
||||
self._run("set", "work/b", "--branch", "")
|
||||
rows = [line.split("\t") for line in self._out("artifacts")]
|
||||
self.assertEqual(
|
||||
[row[:4] for row in rows],
|
||||
[
|
||||
["done", "work/a", "-", "workdir:/w/a"],
|
||||
["done", "work/a", "-", "branch:feat/a"],
|
||||
["done", "work/a", "-", "image:core:dev"],
|
||||
["queued", "work/b", "Two", "dir:/tmp/b"],
|
||||
],
|
||||
)
|
||||
self.assertEqual(rows[0][4], "-")
|
||||
self.assertRegex(rows[2][4], r"^\d\d-\d\d \d\d:\d\d$")
|
||||
self.assertEqual([r.split("\t")[1] for r in self._out("artifacts", "--ended")], ["work/a"] * 3)
|
||||
self.assertEqual(len(self._out("artifacts", "--task", "work/b")), 1)
|
||||
self.assertIn("| queued | Two | 1 |", self._out("show")[2])
|
||||
self.assertTrue(any(line.startswith("artifact: image:core:dev (since ") for line in self._out("get", "work/a")))
|
||||
self.assertEqual(
|
||||
self._out("tools"), ["2\tmake test\twork/a work/b", "1\tcouncil.py\twork/a"]
|
||||
)
|
||||
self.assertIn("tool: council.py", self._out("get", "work/a"))
|
||||
|
||||
def test_claims_join_the_matrix_with_holder_as_ra(self):
|
||||
self._claim("work/live", "s1", "One", "Gamma")
|
||||
self._claim("cluster/dead", "s9", "Gone", "Delta")
|
||||
self._claim("chair", "s1", "One", "allocator")
|
||||
self._run("set", "work/live", "--prio", "1", "--status", "running")
|
||||
self._run("role", "work/live", "Two", "S")
|
||||
lines = self._out("show")
|
||||
self.assertTrue(lines[2].startswith("| 1 | - | work/live | - | running | One |"))
|
||||
self.assertTrue(lines[2].endswith("| One | One | Two | | |"))
|
||||
self.assertTrue(lines[3].startswith("| 2 | - | cluster/dead | - | stale | Gone |"))
|
||||
self.assertFalse(any("chair" in line for line in lines))
|
||||
|
||||
def test_council_claim_takeover_and_release_write_through(self):
|
||||
self.assertEqual(self._run("claim", "work/x", "--work", "Do X", script=COUNCIL).returncode, 0)
|
||||
lines = self._out("get", "work/x")
|
||||
self.assertIn("status: running", lines)
|
||||
self.assertIn("worker: One", lines)
|
||||
self.assertIn("description: Do X", lines)
|
||||
self.assertIn(f"workdir: {self.tmp.name}", lines)
|
||||
self.assertIn("roles: One=RA", lines)
|
||||
(self.sessions / "s1.json").unlink()
|
||||
self.assertEqual(self._run("takeover", "work/x", "--work", "Do X", script=COUNCIL, sid="s2").returncode, 0)
|
||||
lines = self._out("get", "work/x")
|
||||
self.assertIn("worker: Two", lines)
|
||||
self.assertIn("roles: Two=RA", lines)
|
||||
self._run("kr", "work/x", "add", "X shipped")
|
||||
self.assertEqual(self._run("release", "work/x", script=COUNCIL, sid="s2").returncode, 0)
|
||||
lines = self._out("get", "work/x")
|
||||
self.assertIn("status: stopped", lines)
|
||||
self.assertTrue(any(line.startswith("end: 20") for line in lines))
|
||||
|
||||
def test_rm_and_clear_a_party(self):
|
||||
self._run("set", "work/a", "--title", "Alpha")
|
||||
self._run("role", "work/a", "Skills", "RA")
|
||||
self._run("role", "work/a", "Pkgmgr", "C")
|
||||
self._run("role", "work/a", "Pkgmgr", "-")
|
||||
self.assertTrue(self._out("show")[2].endswith("| Skills | Skills | | | |"))
|
||||
self.assertEqual(self._out("rm", "work/a"), ["removed work/a"])
|
||||
self.assertEqual(self._out("show"), ["no tasks"])
|
||||
|
||||
def test_invalid_input_exits_2(self):
|
||||
for args in (
|
||||
("role", "work/a", "Skills", "RR"),
|
||||
("role", "work/a", "Skills", "Q"),
|
||||
("set", "Bad Task"),
|
||||
("set", "work/a", "--prio", "0"),
|
||||
("set", "work/a", "--status", "finished"),
|
||||
("set", "work/a", "--start", "yesterday"),
|
||||
("get", "work/none"),
|
||||
("kr", "work/a", "met", "1"),
|
||||
("set", "work/a", "--artifact", "no-kind"),
|
||||
("estimate", "work/a", "One", "--value", "4", "--complexity", "2"),
|
||||
("estimate", "work/a", "One", "--value", "8"),
|
||||
):
|
||||
with self.subTest(args=args):
|
||||
self.assertEqual(self._run(*args).returncode, 2)
|
||||
self.assertFalse((self.root / "rasci.json").exists())
|
||||
|
||||
def test_pipe_in_a_title_does_not_break_the_table(self):
|
||||
self._run("set", "work/a", "--title", "a | b")
|
||||
self._run("role", "work/a", "Skills", "RA")
|
||||
self.assertTrue(self._out("show")[2].startswith("| 1 | - | work/a: a \\| b | - | queued |"))
|
||||
|
||||
def test_wsjf_ranks_by_median_estimates(self):
|
||||
self._run("set", "work/a", "--objective", "Ship A")
|
||||
self._run("kr", "work/a", "add", "released")
|
||||
self._run("estimate", "work/a", "One", "--value", "8", "--complexity", "2")
|
||||
self._run("estimate", "work/a", "Two", "--value", "13", "--complexity", "3")
|
||||
self._run("estimate", "work/b", "One", "--value", "5", "--complexity", "5")
|
||||
self._run("set", "work/c", "--title", "Gamma")
|
||||
lines = self._out("wsjf")
|
||||
self.assertEqual(
|
||||
lines[0], "| Rank | Task | OKR | Business value | Complexity | WSJF | Estimators | Status |"
|
||||
)
|
||||
self.assertEqual(lines[2], "| 1 | work/a | Ship A (0/1 KR) | 10.5 | 2.5 | 4.2 | One, Two | queued |")
|
||||
self.assertEqual(lines[3], "| 2 | work/b | - | 5 | 5 | 1 | One | queued |")
|
||||
self.assertEqual(lines[4], "| 3 | work/c | - | - | - | - | - | queued |")
|
||||
self.assertEqual(lines[5], "unestimated: work/c")
|
||||
self.assertTrue(self._out("show")[2].startswith("| 1 | 4.2 | work/a |"))
|
||||
self.assertIn("wsjf: 4.2", self._out("get", "work/a"))
|
||||
self._run("set", "work/c", "--prio", "1")
|
||||
self.assertTrue(self._out("show")[2].startswith("| 1 | - | work/c: Gamma |"))
|
||||
self._run("estimate", "work/b", "One", "--drop")
|
||||
self.assertFalse(any(line.startswith("estimate ") for line in self._out("get", "work/b")))
|
||||
|
||||
|
||||
class TestOrgSkillsUseTheRegister(unittest.TestCase):
|
||||
def test_every_org_skill_names_the_register(self):
|
||||
for skill in sorted((REPO_ROOT / "skills").glob("kvb-org-*/SKILL.md")):
|
||||
if skill.parent.name == "kvb-org-rasci":
|
||||
continue
|
||||
with self.subTest(skill=skill.parent.name):
|
||||
self.assertIn("`kvb-org-rasci`", skill.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Validate the shortcuts skill table: rows present, sorted, ``soc``-prefixed,
|
||||
"""Validate the kvb-skills-shortcuts skill table: rows present, sorted, ``soc``-prefixed,
|
||||
no two adjacent consonants."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -8,7 +8,7 @@ import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
SKILL = REPO_ROOT / "skills" / "shortcuts" / "SKILL.md"
|
||||
SKILL = REPO_ROOT / "skills" / "kvb-skills-shortcuts" / "SKILL.md"
|
||||
|
||||
ROW_RE = re.compile(r"^\|\s*`(?P<shortcut>[^`]+)`\s*\|")
|
||||
VOWELS = frozenset("aeiou")
|
||||
@@ -37,7 +37,7 @@ class TestShortcuts(unittest.TestCase):
|
||||
]
|
||||
|
||||
def test_shortcuts_present(self):
|
||||
self.assertTrue(self.shortcuts, "no shortcut rows found in shortcuts skill")
|
||||
self.assertTrue(self.shortcuts, "no shortcut rows found in kvb-skills-shortcuts skill")
|
||||
|
||||
def test_shortcuts_sorted_ascending(self):
|
||||
self.assertEqual(
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Exercise the kvb-org-perform log: spawn hook, feedback, sandbox persist, report."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
LOG_PY = REPO_ROOT / "skills" / "kvb-org-perform" / "scripts" / "log.py"
|
||||
|
||||
|
||||
class TestSubagentModelLog(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.base = Path(self.tmp.name)
|
||||
self.log = self.base / "state" / "subagent-model.jsonl"
|
||||
|
||||
def _run(self, *args: str, stdin: str = "", log: Path | None = None) -> subprocess.CompletedProcess:
|
||||
env = {"SUBAGENT_MODEL_LOG": str(log or self.log), "CLAUDE_CODE_SESSION_ID": "s1"}
|
||||
return subprocess.run(
|
||||
[sys.executable, str(LOG_PY), *args], capture_output=True, text=True, env=env, input=stdin, check=False
|
||||
)
|
||||
|
||||
def _spawn(self, description: str, prompt: str, **tool: str) -> None:
|
||||
payload = {"session_id": "s1", "tool_input": {"description": description, "prompt": prompt, **tool}}
|
||||
self.assertEqual(self._run("spawn", stdin=json.dumps(payload)).returncode, 0)
|
||||
|
||||
def _feedback(self, description: str, completed: str = "yes", redo: str = "no", tests: str = "none") -> None:
|
||||
result = self._run(
|
||||
"feedback", "--description", description, "--completed", completed, "--tests", tests, "--redo", redo
|
||||
)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def _lines(self) -> list[dict]:
|
||||
return [json.loads(text) for text in self.log.read_text(encoding="utf-8").splitlines()]
|
||||
|
||||
def _report(self) -> dict[str, list[str]]:
|
||||
rows = self._run("report").stdout.splitlines()[1:]
|
||||
return {row.split("\t")[0]: row.split("\t") for row in rows}
|
||||
|
||||
def test_spawn_logs_class_model_and_effort_or_the_defaults(self):
|
||||
self._spawn("find callers", "task-class: lookup\nFind every caller.", model="haiku", effort="low")
|
||||
self._spawn("fix it", "Find the root cause.")
|
||||
first, second = self._lines()
|
||||
self.assertEqual((first["task_class"], first["model"], first["effort"]), ("lookup", "haiku", "low"))
|
||||
self.assertEqual((second["task_class"], second["model"], second["effort"]), ("unclassified", "default", "default"))
|
||||
|
||||
def _pending_feedback(self) -> str:
|
||||
blocked = self.base / "file"
|
||||
blocked.write_text("", encoding="utf-8")
|
||||
result = self._run(
|
||||
"feedback", "--description", "d", "--completed", "yes", "--tests", "none", "--redo", "no",
|
||||
log=blocked / "log.jsonl",
|
||||
)
|
||||
self.assertTrue(result.stdout.startswith("pending: "), result.stdout)
|
||||
return result.stdout
|
||||
|
||||
def _persist(self, command: str, stdout: str, session: str = "s1") -> None:
|
||||
payload = {"session_id": session, "tool_input": {"command": command}, "tool_response": {"stdout": stdout}}
|
||||
self.assertEqual(self._run("persist", stdin=json.dumps(payload)).returncode, 0)
|
||||
|
||||
def test_sandboxed_feedback_is_printed_and_stored_by_the_persist_hook(self):
|
||||
stdout = self._pending_feedback()
|
||||
self._persist("python3 /x/skills/kvb-org-perform/scripts/log.py feedback --description 'd'", stdout)
|
||||
self.assertEqual(self._lines()[0]["kind"], "feedback")
|
||||
|
||||
def test_persist_rejects_pending_lines_it_did_not_get_from_a_bare_log_call(self):
|
||||
stdout = self._pending_feedback()
|
||||
line = json.loads(stdout[len("pending: "):])
|
||||
call = "/x/skills/kvb-org-perform/scripts/log.py feedback --description d"
|
||||
for command, output, session in (
|
||||
("cat ci.log", stdout, "s1"),
|
||||
(f"{call}; cat ci.log", stdout, "s1"),
|
||||
(f"{call} | tee /tmp/x", stdout, "s1"),
|
||||
(f"echo $({call})", stdout, "s1"),
|
||||
(call, stdout, "other-session"),
|
||||
(call, stdout + stdout, "s1"),
|
||||
(call, "pending: " + json.dumps({**line, "extra": 1}), "s1"),
|
||||
(call, "pending: " + json.dumps({**line, "completed": "yes"}), "s1"),
|
||||
("/x/skills/kvb-org-perform/scripts/log.py followup --description d", stdout, "s1"),
|
||||
):
|
||||
self._persist(command, output, session)
|
||||
self.assertFalse(self.log.exists())
|
||||
|
||||
def test_report_qualifies_a_row_only_at_ninety_percent_over_twenty_rated_runs(self):
|
||||
for i in range(20):
|
||||
self._spawn(f"q{i}", "task-class: lookup", model="haiku", effort="low")
|
||||
self._feedback(f"q{i}", redo="yes" if i < 2 else "no")
|
||||
for i in range(19):
|
||||
self._spawn(f"r{i}", "task-class: mechanical-edit", model="haiku", effort="low")
|
||||
self._feedback(f"r{i}")
|
||||
self._run("followup", "--description", "q5", "--text", "that list missed a caller")
|
||||
report = self._report()
|
||||
self.assertEqual(report["lookup"][3:], ["20", "20", "17", "85%", "no"])
|
||||
self.assertEqual(report["mechanical-edit"][3:], ["19", "19", "19", "100%", "no"])
|
||||
self._spawn("r19", "task-class: mechanical-edit", model="haiku", effort="low")
|
||||
self._feedback("r19")
|
||||
self.assertEqual(self._report()["mechanical-edit"][-1], "yes")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+54
-3
@@ -1,4 +1,4 @@
|
||||
"""Exercise the democracy resource watch: stages, projection, block, admit, alerts, caches."""
|
||||
"""Exercise the kvb-org-organize resource watch: stages, projection, block, admit, alerts, caches."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -13,7 +13,7 @@ import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
WATCH = REPO_ROOT / "skills" / "democracy" / "scripts" / "watch.py"
|
||||
WATCH = REPO_ROOT / "skills" / "kvb-org-organize" / "scripts" / "watch.py"
|
||||
LIMITS = {"warn": 40, "stop": 15, "critical": 12}
|
||||
|
||||
|
||||
@@ -34,6 +34,11 @@ class TestStage(unittest.TestCase):
|
||||
for free, stage in ((50, "ok"), (30, "warn"), (14, "stop"), (5, "critical")):
|
||||
self.assertEqual(self.watch.stage_for(free, [], self.cfg, now), stage)
|
||||
|
||||
def test_cpu_and_ram_percentages(self):
|
||||
self.assertEqual(self.watch.cpu_busy_percent((100, 40), (200, 60)), 80.0)
|
||||
meminfo = "MemTotal: 1000 kB\nMemFree: 100 kB\nMemAvailable: 250 kB\n"
|
||||
self.assertEqual(self.watch.mem_used_percent(meminfo), 75.0)
|
||||
|
||||
def test_fast_fall_escalates_one_stage(self):
|
||||
now = time.time()
|
||||
self.assertEqual(self.watch.stage_for(32, [[now - 600, 48]], self.cfg, now), "stop")
|
||||
@@ -61,10 +66,12 @@ class TestWatchCommands(unittest.TestCase):
|
||||
"worktree_cleanup": [],
|
||||
"worktrees_command": "true",
|
||||
"worktree_marker": "Makefile",
|
||||
"busy_processes": ["sleep"],
|
||||
"cache_dirs": [str(self.cache)],
|
||||
"cache_budget_percent": 3,
|
||||
"slot_need_gb": {"swarm": 30},
|
||||
"slot_need_gb": {"swarm": 30, "test": 0.001},
|
||||
"notify": ["true"],
|
||||
"load_limits": {"cpu_percent": 101, "mem_percent": 101, "sample_seconds": 0.1, "kinds": ["test"]},
|
||||
}
|
||||
self._write_config()
|
||||
|
||||
@@ -98,12 +105,41 @@ class TestWatchCommands(unittest.TestCase):
|
||||
self._stage("warn")
|
||||
self.assertEqual(self._run("block", stdin=self._bash("make compose-deploy")).returncode, 0)
|
||||
|
||||
def test_block_ignores_heavy_words_inside_quotes_and_heredocs(self):
|
||||
self.cfg["heavy_commands"] = [r"\bmake\s+(-C\s+\S+\s+)?(compose-deploy|test|swarm-\S+)(\s|$)"]
|
||||
self._write_config()
|
||||
self._stage("stop")
|
||||
message = "$(cat <<'EOF'\nfix: run \"make test\" and make swarm-zombie\nEOF\n)"
|
||||
for command in (
|
||||
'git commit --no-verify -m "fix: passes the vars to make swarm-zombie app=x"',
|
||||
"grep -n 'make test' Makefile",
|
||||
f'git commit --no-verify -m "{message}"',
|
||||
):
|
||||
self.assertEqual(self._run("block", stdin=self._bash(command)).returncode, 0, command)
|
||||
for command in (
|
||||
"make -C x swarm-zombie app=y",
|
||||
"env FOO=1 make swarm-zombie",
|
||||
'make compose-deploy apps="web-app-x"',
|
||||
):
|
||||
self.assertEqual(self._run("block", stdin=self._bash(command)).returncode, 2, command)
|
||||
|
||||
def test_admit_keeps_the_stop_floor(self):
|
||||
self.cfg["thresholds_gb"] = {"warn": 0, "stop": 0, "critical": 0}
|
||||
self._write_config()
|
||||
self.assertEqual(self._run("admit", "--need-gb", "0.001").returncode, 0)
|
||||
self.assertEqual(self._run("admit", "--need-gb", "1e9").returncode, 3)
|
||||
|
||||
def test_admit_for_a_load_kind_also_needs_cpu_and_ram_below_the_limits(self):
|
||||
self.cfg["thresholds_gb"] = {"warn": 0, "stop": 0, "critical": 0}
|
||||
self._write_config()
|
||||
self.assertEqual(self._run("admit", "--kind", "test").returncode, 0)
|
||||
self.cfg["load_limits"]["cpu_percent"] = 0
|
||||
self._write_config()
|
||||
denied = self._run("admit", "--kind", "test")
|
||||
self.assertEqual(denied.returncode, 3)
|
||||
self.assertIn("cpu", denied.stdout)
|
||||
self.assertEqual(self._run("admit", "--need-gb", "0.001").returncode, 0)
|
||||
|
||||
def test_warn_alert_reaches_each_session_once(self):
|
||||
self.cfg["thresholds_gb"] = {"warn": 1e9, "stop": -1, "critical": -2}
|
||||
self._write_config()
|
||||
@@ -141,6 +177,21 @@ class TestWatchCommands(unittest.TestCase):
|
||||
self.assertEqual((marked / "cleaned").read_text(encoding="utf-8"), "x\n")
|
||||
self.assertFalse((foreign / "cleaned").exists())
|
||||
|
||||
def test_full_cleanup_skips_a_worktree_where_a_busy_process_runs(self):
|
||||
idle, gated = self.base / "idle", self.base / "gated"
|
||||
for tree in (idle, gated):
|
||||
(tree / "sub").mkdir(parents=True)
|
||||
(tree / "Makefile").write_text("", encoding="utf-8")
|
||||
gate = subprocess.Popen(["sleep", "60"], cwd=gated / "sub")
|
||||
self.addCleanup(gate.wait)
|
||||
self.addCleanup(gate.kill)
|
||||
self.cfg["worktrees_command"] = f"echo {idle}; echo {gated}"
|
||||
self.cfg["worktree_cleanup"] = ["echo x >> {worktree}/cleaned"]
|
||||
self._write_config()
|
||||
self.assertEqual(self._run("cleanup", "--full").returncode, 0)
|
||||
self.assertTrue((idle / "cleaned").exists())
|
||||
self.assertFalse((gated / "cleaned").exists())
|
||||
|
||||
def test_without_config_every_command_is_a_no_op(self):
|
||||
self.config.unlink()
|
||||
result = self._run("status")
|
||||
|
||||
Reference in new issue
Block a user