Skip to content

j-mauro-r/SAT-Dengue-V2 / .agents/skills/deepworkplan

deepworkplan

Verified

DeepWorkPlan — turn any repo AI-first and run Deep Work Plans. Routes to create, execute, refine, resume, status, verify, upgrade, and repo-onboarding sub-skills based on intent. Use when the developer wants to plan, execute, manage, or verify structured multi-task work, or make a repository AI-agent-ready.

FileKindSize
SKILL.mdskill md12.0 KB
TRUST.mdmarkdown16.1 KB
addons/README.mdmarkdown11.7 KB
addons/machine-installs.mdmarkdown2.9 KB
examples/CREATE_PLAN.mdmarkdown6.9 KB
examples/ORCHESTRATOR_TASK_TEMPLATE_create_child_dwp.mdmarkdown15.0 KB
examples/ORCHESTRATOR_TASK_TEMPLATE_execute_child_dwp.mdmarkdown16.7 KB
examples/ORCHESTRATOR_TASK_TEMPLATE_integration_checkpoint.mdmarkdown9.0 KB
examples/PROMPTS_TEMPLATE.mdmarkdown4.0 KB
examples/TEAM_AGENTS_TASK_TEMPLATE.mdmarkdown5.1 KB
examples/V6_PLAN_EXAMPLE.mdmarkdown5.5 KB
guide/GUIDE.mdmarkdown8.0 KB
guide/authoring.mdmarkdown28.5 KB
guide/execution.mdmarkdown21.0 KB
guide/large-repo-onboarding.mdmarkdown3.3 KB
guide/orchestration-at-scale.mdmarkdown11.4 KB
guide/orchestrator.mdmarkdown37.9 KB
guide/prompts.mdmarkdown10.1 KB
guide/skills-integration.mdmarkdown6.5 KB
guide/structure.mdmarkdown6.2 KB
guide/swarm.mdmarkdown21.2 KB
guide/team-agents.mdmarkdown12.3 KB
shared/adaptation.mdmarkdown2.7 KB
shared/addon_sync.pyscript17.7 KB
shared/benchmark.pyscript97.6 KB
shared/config.pyscript41.5 KB
shared/context.shscript4.2 KB
shared/context_manifest.pyscript40.8 KB
shared/contract_v6.pyscript82.7 KB
shared/delegators.pyscript3.0 KB
shared/dwp-paths.mdmarkdown5.8 KB
shared/finalize_plan.pyscript7.2 KB
shared/install-verification.mdmarkdown1.8 KB
shared/ledger.pyscript141.5 KB
shared/migrate_v6.pyscript46.5 KB
shared/outcomes.pyscript27.2 KB
shared/plan_paths.pyscript4.8 KB
shared/resources.pyscript49.0 KB
shared/scheduler.pyscript41.6 KB
shared/state_contract.pyscript9.8 KB
shared/swarm.pyscript27.3 KB
shared/troubleshooting.mdmarkdown7.4 KB
shared/update-state.pyscript12.5 KB
shared/views.pyscript21.0 KB
shared/working-principles.mdmarkdown7.1 KB
spec/ADDONS.mdmarkdown27.4 KB
spec/AGENT_PROTOCOL.mdmarkdown28.0 KB
spec/ARCHETYPES.mdmarkdown10.6 KB
spec/BENCHMARK.mdmarkdown20.3 KB
spec/CONFIG.mdmarkdown8.7 KB
spec/DOCUMENTATION_STANDARD.mdmarkdown40.7 KB
spec/DWP_SPECIFICATION.mdmarkdown65.1 KB
spec/LITE_PLANS.mdmarkdown4.0 KB
spec/PLAN_STATE.mdmarkdown34.9 KB
spec/README.mdmarkdown11.5 KB
spec/V6_CONTEXT.mdmarkdown6.4 KB
spec/V6_CONTRACT.mdmarkdown12.3 KB
spec/V6_LIFECYCLE.mdmarkdown13.5 KB
spec/V6_RESOURCES.mdmarkdown4.7 KB
spec/V7_ABILITIES.mdmarkdown4.9 KB
spec/V7_CONTRACT.mdmarkdown6.4 KB
spec/V7_ROADMAP.mdmarkdown4.6 KB
spec/schema/addon-descriptor-v1.schema.jsonconfig5.5 KB
spec/schema/benchmark-record.schema.jsonconfig14.0 KB
spec/schema/context-manifest-v6.schema.jsonconfig12.5 KB
spec/schema/dwp-config-v1.schema.jsonconfig3.5 KB
spec/schema/dwp-handoff-v1.schema.jsonconfig3.0 KB
spec/schema/journal-event-v6.schema.jsonconfig22.3 KB
spec/schema/journal-event-v7.schema.jsonconfig24.9 KB
spec/schema/learnings-record.schema.jsonconfig6.0 KB
spec/schema/plan-contract-v6.schema.jsonconfig16.4 KB
spec/schema/plan-contract-v7.schema.jsonconfig16.6 KB
spec/schema/plan-manifest-v2.schema.jsonconfig1.0 KB
spec/schema/plan-manifest-v5.schema.jsonconfig1.3 KB
spec/schema/plan-manifest-v6.schema.jsonconfig2.0 KB
spec/schema/plan-manifest-v7.schema.jsonconfig1.7 KB
spec/schema/plan-manifest.schema.jsonconfig1.8 KB
spec/schema/plan-snapshot-v6.schema.jsonconfig7.8 KB
spec/schema/plan-state-v2.schema.jsonconfig6.4 KB
spec/schema/plan-state-v5.schema.jsonconfig6.7 KB
spec/schema/plan-state.schema.jsonconfig3.7 KB

shared/config.py

View on GitHub
#!/usr/bin/env python3
"""DeepWorkPlan configuration reader and writer (spec/CONFIG.md).

One parser for the two top-level keys of ``.dwp/config.json``:

  * ``benchmark`` — the opt-in field-metrics switch (spec/BENCHMARK.md §1).
    Resolved wholesale: a repository file that carries the object overrides
    the user file; one that omits it defers.
  * ``addons`` — the addon registry (spec/CONFIG.md §3). Resolved **per
    addon key**: the repository entry wins over the user entry for that
    key; a repository file that omits a key defers to the user file.

Locations (highest precedence first): ``<repo>/.dwp/config.json`` — the
repository that owns the plan or the directory given — then
``~/.dwp/config.json``; absent means disabled.

Fail-closed, never raising: a missing file, an unreadable path, invalid
JSON or a wrong-typed value resolves to *disabled* for what it affects,
with exactly one warning naming the file, the key and the reason. An addon
key the pack does not ship (the set of in-pack addon directory names) is
ignored with one warning — forward compatibility. Nothing here imports an
addon or decides anything a plan depends on, and only ``descriptors`` and
``backfill`` (both on explicit request) open addon descriptors: the
registry is informative input to flows that may *offer* or *amplify*,
never to anything that gates conformance.

Usage::

    config.py show [--repo DIR] [--plan DIR]       # resolved view (JSON)
    config.py enabled [--repo DIR] [--plan DIR]    # enabled addon keys, one per line
    config.py enable  KEY [--version vX.Y.Z] [--note TEXT] --repo DIR   # onboarding writer
    config.py backfill --repo DIR [--write]        # upgrade: record present addons
    config.py host CAPABILITY true|false --repo DIR  # host capability record
    config.py benchmark enabled|learnings true|false --repo DIR  # benchmark switches
    config.py disable KEY --repo DIR
    config.py keys                                 # in-pack addon keys
    config.py descriptors                          # audit every addon.json (opens them)
    config.py self-test

Standard library only (Python 3.9+).
"""

import argparse
import json
import os
import re
import sys
import tempfile
from typing import Any, Dict, List, Optional, Tuple

sys.dont_write_bytecode = True

CONFIG_SCHEMA_URL = 'https://deepworkplan.com/schema/dwp-config/v1.json'
VERSION_RE = re.compile(r'^v\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$')
REPO_LABEL = '.dwp/config.json'
USER_LABEL = '~/.dwp/config.json'

_HERE = os.path.dirname(os.path.abspath(__file__))
ADDONS_DIR = os.path.normpath(os.path.join(_HERE, '..', 'addons'))


# ---------------------------------------------------------------------------
# discovery


def addon_keys(addons_dir: str = ADDONS_DIR) -> List[str]:
    """The registry key set: the in-pack addon directory names (contract A1).

    Lists directories only — it never opens a file inside an addon.
    """
    try:
        names = os.listdir(addons_dir)
    except OSError:
        return []
    return sorted(n for n in names
                  if not n.startswith('.')
                  and os.path.isdir(os.path.join(addons_dir, n)))


def find_dwp_root(plan_dir: str) -> Optional[str]:
    """Walk up from a plan directory to its owning ``.dwp`` directory."""
    current = os.path.abspath(plan_dir)
    while True:
        parent = os.path.dirname(current)
        if current == parent:
            return None
        if (os.path.basename(parent) == 'plans'
                and os.path.basename(os.path.dirname(parent)) == '.dwp'):
            return os.path.dirname(parent)
        current = parent


def config_paths(dwp_root: Optional[str],
                 home: Optional[str] = None) -> List[Tuple[str, str]]:
    """(label, path) pairs in precedence order; the repo file only with a root."""
    pairs = []
    if dwp_root is not None:
        pairs.append((REPO_LABEL, os.path.join(dwp_root, 'config.json')))
    home_dir = home if home is not None else os.path.expanduser('~')
    pairs.append((USER_LABEL, os.path.join(home_dir, '.dwp', 'config.json')))
    return pairs


def read_config(path: str) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
    """(parsed object or None, reason or None) for one file; never raises.

    A missing file is the ordinary "omits everything" case: no reason.
    """
    if not os.path.isfile(path):
        return None, None
    try:
        with open(path, 'r', encoding='utf-8') as handle:
            data = json.load(handle)
    except (OSError, ValueError) as exc:
        return None, 'unreadable (%s); treating as absent' % exc
    if not isinstance(data, dict):
        return None, 'is not a JSON object; treating as absent'
    return data, None


def load_files(dwp_root: Optional[str], home: Optional[str] = None
               ) -> List[Tuple[str, str, Optional[Dict[str, Any]], Optional[str]]]:
    """Read both files once: [(label, path, data, reason)] in precedence order."""
    out = []
    for label, path in config_paths(dwp_root, home):
        data, reason = read_config(path)
        out.append((label, path, data, reason))
    return out


# ---------------------------------------------------------------------------
# benchmark key (behaviour pinned by spec/BENCHMARK.md §1)


def benchmark_section(files, warnings: List[str]) -> Optional[Dict[str, Any]]:
    """The winning ``benchmark`` object (repo over user, wholesale), or None."""
    for label, path, data, reason in files:
        if reason:
            warnings.append('benchmark: benchmark config %s %s' % (path, reason))
        if data is None or 'benchmark' not in data:
            continue
        section = data['benchmark']
        if not isinstance(section, dict):
            warnings.append('benchmark: %s "benchmark" is not an object; '
                            'benchmark disabled' % label)
            return None
        return section
    return None


def resolve_benchmark(files) -> Tuple[bool, bool, List[str]]:
    """(benchmark enabled, learnings enabled, warnings) — fail-closed per key."""
    warnings: List[str] = []
    section = benchmark_section(files, warnings)
    if section is None:
        return False, False, warnings
    enabled = section.get('enabled')
    if not isinstance(enabled, bool):
        warnings.append('benchmark: "benchmark.enabled" is not a boolean; '
                        'benchmark disabled')
        return False, False, warnings
    if not enabled:
        return False, False, warnings
    learnings = section.get('learnings')
    if learnings is None:
        return True, False, warnings
    if not isinstance(learnings, bool):
        warnings.append('benchmark: "benchmark.learnings" is not a boolean; '
                        'learnings disabled (metrics unaffected)')
        return True, False, warnings
    return True, learnings, warnings


# ---------------------------------------------------------------------------
# addons key (spec/CONFIG.md §3)


def _entry_error(value: Any) -> Optional[str]:
    """Why one registry entry is unusable, or None when it is well formed."""
    if not isinstance(value, dict):
        return 'entry is not an object'
    extra = sorted(set(value) - {'enabled', 'version', 'note'})
    if extra:
        return 'carries unknown field(s) %s' % ', '.join(extra)
    if 'enabled' not in value:
        return '"enabled" is missing'
    if not isinstance(value['enabled'], bool):
        return '"enabled" is not a boolean'
    if 'version' in value:
        version = value['version']
        if not isinstance(version, str) or not VERSION_RE.match(version):
            return '"version" is not a tag like v1.2.3 or v1.2.3-beta.1'
    if 'note' in value and not _note_ok(value['note']):
        return '"note" is not a one-line string of 1-200 characters'
    return None


def _note_ok(note: Any) -> bool:
    """F-05: a registry note is one line, 1-200 characters."""
    return isinstance(note, str) and 0 < len(note) <= 200 and \
        '\n' not in note and '\r' not in note


def resolve_addons(files, keys: Optional[List[str]] = None
                   ) -> Tuple[Dict[str, Dict[str, Any]], List[str]]:
    """Resolve every in-pack addon key; return ({key: view}, warnings).

    A view is ``{"enabled": bool, "version": str|None, "source": label|None}``.
    Per-key precedence: the first file (repo, then user) whose ``addons``
    object **names** the key decides it — a malformed entry there resolves
    to not-enabled (fail-closed) and does not fall through.
    """
    known = list(keys) if keys is not None else addon_keys()
    warnings: List[str] = []
    registries = []
    for label, path, data, reason in files:
        if reason:
            warnings.append('addons: %s %s' % (path, reason))
            continue
        if data is None or 'addons' not in data:
            continue
        reg = data['addons']
        if not isinstance(reg, dict):
            warnings.append('addons: %s "addons" is not an object; no addon '
                            'enabled from this file' % label)
            continue
        for name in sorted(reg):
            if name not in known:
                warnings.append('addons: %s key %r is not an addon this pack '
                                'ships; ignored' % (label, name))
        registries.append((label, reg))
    view: Dict[str, Dict[str, Any]] = {}
    for key in known:
        view[key] = {'enabled': False, 'version': None, 'source': None}
        for label, reg in registries:
            if key not in reg:
                continue
            problem = _entry_error(reg[key])
            if problem:
                warnings.append('addons: %s key %r %s; not enabled'
                                % (label, key, problem))
                view[key]['source'] = label
            else:
                view[key] = {'enabled': reg[key]['enabled'],
                             'version': reg[key].get('version'),
                             'source': label}
                if 'note' in reg[key]:
                    view[key]['note'] = reg[key]['note']
            break
    return view, warnings


BENCHMARK_KEYS = ('enabled', 'learnings')
HOST_KEYS = ('stop_agent', 'meter_spend', 'meter_tokens', 'meter_wall_clock',
             'cancel_children', 'model_routing', 'subagents', 'telemetry')


def resolve_host(files) -> Tuple[Dict[str, Dict[str, Any]], List[str]]:
    """F-17: the machine-readable host capability record (``host`` key).

    Per capability, the user file wins over the repository file: the
    record describes the host, and each machine's own file is the better
    witness of it (the tracked repository file is the team baseline). Values
    are booleans; a non-boolean or a capability outside the closed set is
    ignored with one warning (a capability is never invented). Returns
    ({capability: {"value": bool, "source": label}}, warnings) for the
    capabilities a file declares; unstated ones stay at the all-False floor.
    """
    warnings: List[str] = []
    view: Dict[str, Dict[str, Any]] = {}
    for label, _path, data, reason in reversed(list(files)):
        if reason or data is None or 'host' not in data:
            continue
        rec = data['host']
        if not isinstance(rec, dict):
            warnings.append('host: %s "host" is not an object; ignored' % label)
            continue
        for name in sorted(rec):
            if name not in HOST_KEYS:
                warnings.append('host: %s capability %r is not in the closed '
                                'set; ignored' % (label, name))
            elif not isinstance(rec[name], bool):
                warnings.append('host: %s capability %r is not a boolean; '
                                'ignored' % (label, name))
            elif name not in view:
                view[name] = {'value': rec[name], 'source': label}
    return view, warnings


def write_host(dwp_root: str, name: str, value: bool) -> Dict[str, Any]:
    """Set ``host.<name>`` in the repository file (reconciling, atomic)."""
    if name not in HOST_KEYS:
        raise ConfigError('%r is not a host capability (%s)'
                          % (name, ', '.join(HOST_KEYS)))
    path = os.path.join(dwp_root, 'config.json')
    data: Dict[str, Any] = {}
    if os.path.exists(path):
        parsed, reason = read_config(path)
        if parsed is None:
            raise ConfigError('%s %s — the writer never overwrites a file it '
                              'cannot read' % (path, reason or 'unreadable'))
        data = parsed
    rec = data.get('host', {})
    if not isinstance(rec, dict):
        raise ConfigError('%s "host" is not an object — refusing to replace it'
                          % path)
    rec[name] = value
    data['host'] = rec
    _write_config(dwp_root, path, data)
    return rec


def write_benchmark(dwp_root: str, name: str, value: bool) -> Dict[str, Any]:
    """Set ``benchmark.<name>`` (``enabled`` or ``learnings``) in the repository file.

    Reconciling and atomic like the other writers: other top-level keys and
    the other benchmark key are preserved, and a file that cannot be read is
    refused, never replaced.
    """
    if name not in BENCHMARK_KEYS:
        raise ConfigError('%r is not a benchmark key (%s)'
                          % (name, ', '.join(BENCHMARK_KEYS)))
    path = os.path.join(dwp_root, 'config.json')
    data: Dict[str, Any] = {}
    if os.path.exists(path):
        parsed, reason = read_config(path)
        if parsed is None:
            raise ConfigError('%s %s — the writer never overwrites a file it '
                              'cannot read' % (path, reason or 'unreadable'))
        data = parsed
    rec = data.get('benchmark', {})
    if not isinstance(rec, dict):
        raise ConfigError('%s "benchmark" is not an object — refusing to '
                          'replace it' % path)
    rec[name] = value
    data['benchmark'] = rec
    _write_config(dwp_root, path, data)
    return rec


def resolve(dwp_root: Optional[str], home: Optional[str] = None,
            keys: Optional[List[str]] = None) -> Dict[str, Any]:
    """Both keys from one read of both files."""
    files = load_files(dwp_root, home)
    bench_on, learn_on, bench_warn = resolve_benchmark(files)
    addons, addon_warn = resolve_addons(files, keys)
    host, host_warn = resolve_host(files)
    return {'benchmark': {'enabled': bench_on, 'learnings': learn_on},
            'addons': addons, 'host': host,
            'warnings': bench_warn + addon_warn + host_warn}


def enabled_addons(dwp_root: Optional[str], home: Optional[str] = None,
                   keys: Optional[List[str]] = None) -> Tuple[List[str], List[str]]:
    """(sorted enabled addon keys, warnings)."""
    files = load_files(dwp_root, home)
    view, warnings = resolve_addons(files, keys)
    return sorted(k for k, v in view.items() if v['enabled']), warnings


# ---------------------------------------------------------------------------
# addon descriptors (spec/ADDONS.md §7) — opened only for an addon a caller
# already decided to consult (an enabled key, or an explicit audit)


DESCRIPTOR_SCHEMA_URL = 'https://deepworkplan.com/schema/addon-descriptor/v1.json'
ABILITIES = ('stop_agent', 'meter_spend', 'meter_tokens', 'meter_wall_clock',
             'cancel_children', 'model_routing', 'subagents', 'telemetry')
GRANTS = ('gate_command_exec', 'fs_write_plan_scope', 'fs_write_repo_scope',
          'git_operations', 'network_access', 'host_adapter_metering',
          'agent_delegation', 'context_export', 'model_routing')
TRANSPORTS = ('headless', 'interactive')
_KEY_RE = re.compile(r'^[a-z][a-z0-9-]{0,63}$')
ID_SAFE_RE = _KEY_RE  # an addon key that is safe to join under addons/
_REPO_RE = re.compile(r'^[A-Za-z0-9-]+/[A-Za-z0-9._-]+$')
_COMMAND_RE = re.compile(r'^[A-Za-z0-9][A-Za-z0-9._/ -]*$')
_PATH_RE = re.compile(r'^(~/)?[A-Za-z0-9._][A-Za-z0-9._/-]*$')
_IFACE_RE = re.compile(r'^(json:[A-Za-z_][A-Za-z0-9_]*|regex:.+|'
                       r'file-json:~/[A-Za-z0-9._/-]+#[A-Za-z_][A-Za-z0-9_]*)$')


def descriptor_errors(doc: Any, dirname: Optional[str] = None) -> List[str]:
    """Runtime half of schema/addon-descriptor-v1 (closed object)."""
    errs: List[str] = []
    if not isinstance(doc, dict):
        return ['descriptor is not an object']
    allowed = {'schema', 'key', 'product', 'detect', 'provides_abilities',
               'requires_grants', 'transport'}
    for extra in sorted(set(doc) - allowed):
        errs.append('unknown field %r' % extra)
    for req in ('schema', 'key', 'detect', 'provides_abilities', 'requires_grants'):
        if req not in doc:
            errs.append('missing %r' % req)
    if doc.get('schema', DESCRIPTOR_SCHEMA_URL) != DESCRIPTOR_SCHEMA_URL:
        errs.append('schema is not %s' % DESCRIPTOR_SCHEMA_URL)
    key = doc.get('key')
    if 'key' in doc and (not isinstance(key, str) or not _KEY_RE.match(key)):
        errs.append('key is not a kebab-case name')
    if dirname is not None and key != dirname:
        errs.append('key %r does not equal its directory %r' % (key, dirname))
    if 'product' in doc:
        prod = doc['product']
        if not isinstance(prod, dict):
            errs.append('product is not an object')
        else:
            for extra in sorted(set(prod) - {'repo', 'tag', 'interface'}):
                errs.append('product: unknown field %r' % extra)
            if not isinstance(prod.get('repo'), str) or not _REPO_RE.match(prod['repo']):
                errs.append('product.repo is not owner/name')
            if not isinstance(prod.get('tag'), str) or not VERSION_RE.match(prod['tag']):
                errs.append('product.tag is not an exact tag')
            if 'interface' in prod and (type(prod['interface']) is not int
                                        or prod['interface'] < 1):
                errs.append('product.interface is not an integer >= 1')
    if 'detect' in doc:
        det = doc['detect']
        if not isinstance(det, dict):
            errs.append('detect is not an object')
        else:
            for extra in sorted(set(det) - {'command', 'paths', 'interface_from',
                                            'legacy_paths'}):
                errs.append('detect: unknown field %r' % extra)
            if ('command' in det) == ('paths' in det):
                errs.append('detect needs exactly one of command or paths')
            if 'command' in det and (not isinstance(det['command'], str)
                                     or len(det['command']) > 200
                                     or not _COMMAND_RE.match(det['command'])):
                errs.append('detect.command is not a plain argv line')
            if 'paths' in det:
                paths = det['paths']
                if (not isinstance(paths, list) or not paths
                        or len(set(map(str, paths))) != len(paths)
                        or not all(isinstance(x, str) and _PATH_RE.match(x)
                                   and '..' not in x.split('/')
                                   for x in paths)):
                    errs.append('detect.paths is not a non-empty list of plain paths')
            if 'legacy_paths' in det:
                legacy = det['legacy_paths']
                if ('paths' not in det or not isinstance(legacy, list) or not legacy
                        or len(set(map(str, legacy))) != len(legacy)
                        or not all(isinstance(x, str) and _PATH_RE.match(x)
                                   and '..' not in x.split('/') for x in legacy)):
                    errs.append('detect.legacy_paths is not a non-empty list of '
                                'plain paths beside detect.paths')
            if 'interface_from' in det and (not isinstance(det['interface_from'], str)
                                            or not _IFACE_RE.match(det['interface_from'])):
                errs.append('detect.interface_from has an unknown form')
    for field, vocab in (('provides_abilities', ABILITIES), ('requires_grants', GRANTS)):
        if field in doc:
            vals = doc[field]
            if (not isinstance(vals, list) or len(set(map(str, vals))) != len(vals)
                    or not all(v in vocab for v in vals)):
                errs.append('%s holds an unknown or repeated value' % field)
    if 'transport' in doc:
        if doc['transport'] not in TRANSPORTS:
            errs.append('transport is not headless|interactive')
        else:
            if 'subagents' not in (doc.get('provides_abilities') or []):
                errs.append('a transport addon must provide subagents')
            if 'agent_delegation' not in (doc.get('requires_grants') or []):
                errs.append('a transport addon must require agent_delegation')
    return errs


def load_descriptor(key: str, addons_dir: str = ADDONS_DIR
                    ) -> Tuple[Optional[Dict[str, Any]], List[str]]:
    """(descriptor or None, errors) for one addon key. Never raises."""
    path = os.path.join(addons_dir, key, 'addon.json')
    try:
        with open(path, 'r', encoding='utf-8') as handle:
            doc = json.load(handle)
    except (OSError, ValueError) as exc:
        return None, ['%s unreadable (%s)' % (path, exc)]
    errs = descriptor_errors(doc, key)
    return (doc if not errs else None), errs


# ---------------------------------------------------------------------------
# writer (onboarding consent; spec/CONFIG.md §4)


class ConfigError(Exception):
    """A write that would clobber or invent — refused, never applied."""


def write_addon(dwp_root: str, key: str, enabled: bool,
                version: Optional[str] = None,
                keys: Optional[List[str]] = None,
                note: Optional[str] = None) -> Dict[str, Any]:
    """Set ``addons.<key>`` in the repository file, reconciling, atomically.

    Every other byte of meaning is preserved: other top-level keys, other
    addon entries. An existing file that is not a JSON object is refused —
    a writer never clobbers what it cannot read.
    """
    known = list(keys) if keys is not None else addon_keys()
    if key not in known:
        hint = (' — benchmark keys are set with: config.py benchmark '
                'enabled|learnings true|false --repo <repo>'
                if key.startswith('benchmark') else '')
        raise ConfigError('%r is not an addon this pack ships (%s)%s'
                          % (key, ', '.join(known), hint))
    if version is not None and not VERSION_RE.match(version):
        raise ConfigError('version %r is not a tag like v1.2.3' % version)
    if note is not None and not _note_ok(note):
        raise ConfigError('note must be one line of 1-200 characters')
    path = os.path.join(dwp_root, 'config.json')
    if os.path.islink(dwp_root) or os.path.islink(path):
        raise ConfigError('%s or its .dwp directory is a symbolic link — the '
                          'writer refuses to write through a link' % path)
    data: Dict[str, Any] = {}
    if os.path.exists(path):
        parsed, reason = read_config(path)
        if parsed is None:
            raise ConfigError('%s %s — fix or remove it by hand; the writer '
                              'never overwrites a file it cannot read'
                              % (path, reason or 'unreadable'))
        data = parsed
    reg = data.get('addons')
    if reg is None:
        reg = {}
    if not isinstance(reg, dict):
        raise ConfigError('%s "addons" is not an object — refusing to replace '
                          'it' % path)
    entry: Dict[str, Any] = {'enabled': enabled}
    if version is not None:
        entry['version'] = version
    if note is not None:
        entry['note'] = note
    reg[key] = entry
    data['addons'] = reg
    _write_config(dwp_root, path, data)
    return entry


def _write_config(dwp_root: str, path: str, data: Dict[str, Any]) -> None:
    """Atomic, mode-preserving write that refuses symbolic links."""
    if os.path.islink(dwp_root) or os.path.islink(path):
        raise ConfigError('%s or its .dwp directory is a symbolic link — the '
                          'writer refuses to write through a link' % path)
    os.makedirs(dwp_root, exist_ok=True)
    mode = (os.stat(path).st_mode & 0o777) if os.path.exists(path) else 0o644
    handle, temp = tempfile.mkstemp(dir=dwp_root, prefix='.config-')
    try:
        os.chmod(temp, mode)  # mkstemp creates 0600; keep the file's mode
        with os.fdopen(handle, 'w', encoding='utf-8') as out:
            json.dump(data, out, indent=2, sort_keys=True)
            out.write('\n')
        os.replace(temp, path)
    except BaseException:
        if os.path.exists(temp):
            os.unlink(temp)
        raise


def backfill(dwp_root: str, write: bool = False,
             keys: Optional[List[str]] = None, addons_dir: Optional[str] = None
             ) -> List[Dict[str, Any]]:
    """F-15: record addons that are already present but not in the registry.

    For every in-pack key the repository file does not name (a recorded
    decision - enabled or disabled - is never touched), run the addon's
    read-only detection. Only a repository-level install (a repo-relative
    detect path, e.g. a vendored skill) is back-filled - a machine-level
    install (a detect command or a ~/ path) is reported, never recorded in
    the tracked registry. A detected repository-level addon is proposed as
    ``{"enabled": true, "version": <observed tag>, "note": "back-filled
    ..."}``. Dry run by default; ``write`` applies the proposals through the
    reconciling writer. An addon installed before the registry existed was
    accepted when it was installed; the back-fill records that decision,
    it never makes a new one.
    """
    import resources  # sibling; imported late (resources imports config)
    known = list(keys) if keys is not None else addon_keys(
        addons_dir or ADDONS_DIR)
    path = os.path.join(dwp_root, 'config.json')
    named: List[str] = []
    if os.path.exists(path):
        parsed, reason = read_config(path)
        if parsed is None:
            raise ConfigError('%s %s - fix it before back-filling'
                              % (path, reason or 'unreadable'))
        reg = parsed.get('addons')
        named = sorted(reg) if isinstance(reg, dict) else []
    repo_root = os.path.dirname(os.path.abspath(dwp_root))
    proposals = []
    for key in known:
        if key in named:
            continue
        doc, errs = load_descriptor(key, addons_dir or ADDONS_DIR)
        det = (doc or {}).get('detect') or {}
        machine = 'command' in det or not any(
            not p.startswith('~/') for p in det.get('paths', []))
        verdict = resources.addon_status(key, repo_root, addons_dir)
        if not verdict['detected']:
            continue
        if errs or machine:
            # W3: a machine-level install describes this machine, not the
            # repository - the tracked registry records it only on the
            # developer's acceptance (onboarding offers it)
            proposals.append({'key': key, 'version': verdict.get('version'),
                              'machine': True})
            continue
        version = verdict.get('version')
        note = 'back-filled on upgrade: already installed (detected %s)' % (
            version or 'present')
        proposals.append({'key': key, 'version': version, 'note': note,
                          'machine': False})
        if write:
            write_addon(dwp_root, key, True, version, known, note)
    return proposals


# ---------------------------------------------------------------------------
# CLI


def _root_from_args(args) -> Optional[str]:
    if getattr(args, 'plan', None):
        return find_dwp_root(args.plan)
    if getattr(args, 'repo', None):
        return os.path.join(os.path.abspath(args.repo), '.dwp')
    return os.path.join(os.getcwd(), '.dwp')


def _emit_warnings(warnings: List[str]) -> None:
    for line in warnings:
        print('WARNING: ' + line, file=sys.stderr)


def main(argv: Optional[List[str]] = None) -> int:
    parser = argparse.ArgumentParser(prog='config.py', description=__doc__.split('\n')[0])
    sub = parser.add_subparsers(dest='command')
    for name in ('show', 'enabled'):
        p = sub.add_parser(name)
        p.add_argument('--repo')
        p.add_argument('--plan')
    for name in ('enable', 'disable'):
        p = sub.add_parser(name)
        p.add_argument('key')
        p.add_argument('--repo', required=True)
        if name == 'enable':
            p.add_argument('--version')
            p.add_argument('--note')
    p = sub.add_parser('host')
    p.add_argument('capability')
    p.add_argument('value', choices=['true', 'false'])
    p.add_argument('--repo', required=True)
    p = sub.add_parser('benchmark')
    p.add_argument('key', choices=['enabled', 'learnings'])
    p.add_argument('value', choices=['true', 'false'])
    p.add_argument('--repo', required=True)
    p = sub.add_parser('backfill')
    p.add_argument('--repo', required=True)
    p.add_argument('--write', action='store_true')
    sub.add_parser('keys')
    sub.add_parser('descriptors')
    sub.add_parser('self-test')
    args = parser.parse_args(argv)
    if args.command == 'show':
        result = resolve(_root_from_args(args))
        _emit_warnings(result.pop('warnings'))
        print(json.dumps(result, indent=2, sort_keys=True))
        return 0
    if args.command == 'enabled':
        keys, warnings = enabled_addons(_root_from_args(args))
        _emit_warnings(warnings)
        for key in keys:
            print(key)
        return 0
    if args.command in ('enable', 'disable'):
        try:
            entry = write_addon(_root_from_args(args), args.key,
                                args.command == 'enable',
                                getattr(args, 'version', None),
                                note=getattr(args, 'note', None))
        except ConfigError as exc:
            print('ERROR: %s' % exc, file=sys.stderr)
            return 2
        print('OK: addons.%s = %s' % (args.key, json.dumps(entry, sort_keys=True)))
        return 0
    if args.command == 'host':
        try:
            rec = write_host(_root_from_args(args), args.capability,
                             args.value == 'true')
        except ConfigError as exc:
            print('ERROR: %s' % exc, file=sys.stderr)
            return 2
        print('OK: host = %s' % json.dumps(rec, sort_keys=True))
        return 0
    if args.command == 'benchmark':
        try:
            rec = write_benchmark(_root_from_args(args), args.key,
                                  args.value == 'true')
        except ConfigError as exc:
            print('ERROR: %s' % exc, file=sys.stderr)
            return 2
        print('OK: benchmark = %s' % json.dumps(rec, sort_keys=True))
        return 0
    if args.command == 'backfill':
        try:
            found = backfill(_root_from_args(args), write=args.write)
        except ConfigError as exc:
            print('ERROR: %s' % exc, file=sys.stderr)
            return 2
        for item in found:
            if item['machine']:
                print('SKIP  addons.%s: present on this machine only - a '
                      'machine-level install is offered, never back-filled '
                      'into the tracked registry' % item['key'])
                continue
            print('%s addons.%s = enabled%s' % (
                'WROTE' if args.write else 'WOULD', item['key'],
                ' ' + item['version'] if item['version'] else ''))
        if not [i for i in found if not i['machine']]:
            print('OK: nothing to back-fill (every present addon is already '
                  'recorded)')
        elif not args.write:
            print('dry run - re-run with --write to record these')
        return 0
    if args.command == 'descriptors':
        bad = 0
        for key in addon_keys():
            _doc, errs = load_descriptor(key)
            print('%s %s' % ('OK  ' if not errs else 'FAIL', key)
                  + ('' if not errs else ': ' + '; '.join(errs)))
            bad += bool(errs)
        return 1 if bad else 0
    if args.command == 'keys':
        for key in addon_keys():
            print(key)
        return 0
    if args.command == 'self-test':
        return self_test()
    parser.print_help()
    return 2


# ---------------------------------------------------------------------------
# self-test


SELF_TEST_PROBES = 36


def self_test() -> int:
    import shutil
    failures: List[str] = []
    probes = 0

    def check(name: str, ok: bool, detail: str = '') -> None:
        nonlocal probes
        probes += 1
        if not ok:
            failures.append('%s %s' % (name, detail))

    keys = ['agentkit', 'herdr', 'vim']
    tmp = tempfile.mkdtemp(prefix='dwp-config-selftest-')
    try:
        repo = os.path.join(tmp, 'repo', '.dwp')
        home = os.path.join(tmp, 'home')
        os.makedirs(repo)
        os.makedirs(os.path.join(home, '.dwp'))
        user = os.path.join(home, '.dwp', 'config.json')
        repo_cfg = os.path.join(repo, 'config.json')

        def put(path, text):
            with open(path, 'w', encoding='utf-8') as fh:
                fh.write(text)

        def run():
            files = load_files(repo, home)
            return resolve_addons(files, keys)

        # 1. nothing anywhere: everything disabled, no warning
        view, warn = run()
        check('absent', not any(v['enabled'] for v in view.values()) and not warn,
              repr((view, warn)))
        # 2. user file enables herdr
        put(user, '{"addons": {"herdr": {"enabled": true, "version": "v0.1.0"}}}')
        view, warn = run()
        check('user enables', view['herdr'] == {'enabled': True, 'version': 'v0.1.0',
                                                'source': USER_LABEL}, repr(view))
        # 3. repo file omitting the key defers to the user file
        put(repo_cfg, '{"addons": {"vim": {"enabled": true}}}')
        view, warn = run()
        check('repo omits defers', view['herdr']['enabled'] and view['vim']['enabled'],
              repr(view))
        check('repo source', view['vim']['source'] == REPO_LABEL, repr(view))
        # 4. repo entry wins per key
        put(repo_cfg, '{"addons": {"herdr": {"enabled": false}}}')
        view, warn = run()
        check('repo wins', view['herdr'] == {'enabled': False, 'version': None,
                                             'source': REPO_LABEL}, repr(view))
        # 5. wrong-typed enabled fails closed, one warning, no fall-through
        put(repo_cfg, '{"addons": {"herdr": {"enabled": "yes"}}}')
        view, warn = run()
        check('wrong type closed', not view['herdr']['enabled'], repr(view))
        check('wrong type one warning', len(warn) == 1 and 'herdr' in warn[0]
              and REPO_LABEL in warn[0], repr(warn))
        # 6. bad version string fails closed
        put(repo_cfg, '{"addons": {"vim": {"enabled": true, "version": "latest"}}}')
        view, warn = run()
        check('bad version closed', not view['vim']['enabled'] and len(warn) == 1,
              repr((view, warn)))
        # 7. pre-release version accepted
        put(repo_cfg, '{"addons": {"vim": {"enabled": true, "version": "v7.0.0-beta.1"}}}')
        view, warn = run()
        check('prerelease version', view['vim']['enabled'] and not warn, repr((view, warn)))
        # 8. missing "enabled" is not enabled
        put(repo_cfg, '{"addons": {"vim": {"version": "v0.4.0"}}}')
        view, warn = run()
        check('missing enabled', not view['vim']['enabled'] and len(warn) == 1,
              repr(warn))
        # 8b. an unknown field inside an entry fails closed (closed entry)
        put(repo_cfg, '{"addons": {"vim": {"enabled": true, "pin": "main"}}}')
        view, warn = run()
        check('closed entry', not view['vim']['enabled'] and len(warn) == 1
              and 'pin' in warn[0], repr(warn))
        # 9. unknown key ignored with exactly one warning
        put(repo_cfg, '{"addons": {"teleport": {"enabled": true}}}')
        view, warn = run()
        check('unknown ignored', 'teleport' not in view and len(warn) == 1
              and 'teleport' in warn[0], repr(warn))
        # 10. invalid JSON in repo: one warning, user file still applies
        put(repo_cfg, '{"addons": {"vim": {"enabled": tru')
        view, warn = run()
        check('invalid json warns once', len(warn) == 1 and 'unreadable' in warn[0],
              repr(warn))
        check('invalid json defers', view['herdr']['enabled'], repr(view))
        # 11. "addons" not an object
        put(repo_cfg, '{"addons": ["vim"]}')
        view, warn = run()
        check('addons not object', len(warn) == 1 and not view['vim']['enabled'],
              repr(warn))
        # 12. a non-object top level
        put(repo_cfg, '[1, 2]')
        view, warn = run()
        check('top not object', len(warn) == 1, repr(warn))
        # 13. benchmark resolution unchanged and independent of addons
        put(repo_cfg, '{"benchmark": {"enabled": true}, "addons": {"vim": {"enabled": true}}}')
        files = load_files(repo, home)
        check('benchmark on', resolve_benchmark(files)[:2] == (True, False),
              repr(resolve_benchmark(files)))
        put(repo_cfg, '{"benchmark": {"enabled": "yes"}}')
        b = resolve_benchmark(load_files(repo, home))
        check('benchmark wrong type', b[0] is False and len(b[2]) == 1, repr(b))
        # 14. writer reconciles: preserves other keys and entries
        put(repo_cfg, '{"benchmark": {"enabled": true}, "addons": {"herdr": {"enabled": false}}}')
        write_addon(repo, 'vim', True, 'v0.4.0', keys)
        with open(repo_cfg, encoding='utf-8') as fh:
            data = json.load(fh)
        check('writer preserves', data['benchmark'] == {'enabled': True}
              and data['addons']['herdr'] == {'enabled': False}
              and data['addons']['vim'] == {'enabled': True, 'version': 'v0.4.0'},
              repr(data))
        # 15. writer refuses an unknown key, a bad version, an unreadable file
        for label, call in (
                ('writer unknown', lambda: write_addon(repo, 'teleport', True, None, keys)),
                ('writer version', lambda: write_addon(repo, 'vim', True, 'latest', keys))):
            try:
                call()
                check(label, False, 'accepted')
            except ConfigError:
                check(label, True)
        put(repo_cfg, '{oops')
        try:
            write_addon(repo, 'vim', True, None, keys)
            check('writer unreadable', False, 'clobbered')
        except ConfigError:
            with open(repo_cfg, encoding='utf-8') as fh:
                check('writer unreadable', fh.read() == '{oops', 'file changed')
        # 16. writer creates a fresh file
        os.unlink(repo_cfg)
        write_addon(repo, 'agentkit', False, None, keys)
        with open(repo_cfg, encoding='utf-8') as fh:
            check('writer fresh', json.load(fh) == {'addons': {'agentkit': {'enabled': False}}})
        # 17. key set is directory names only, and the shipped set is non-empty
        check('addon keys', 'vim' in addon_keys() and all(
            os.path.isdir(os.path.join(ADDONS_DIR, k)) for k in addon_keys()),
            repr(addon_keys()))
        # 17b. descriptor validator: the shipped set is valid; mutants refused
        good = {'schema': DESCRIPTOR_SCHEMA_URL, 'key': 'herdr',
                'product': {'repo': 'DailybotHQ/herdr-peers', 'tag': 'v0.1.0',
                            'interface': 1},
                'detect': {'command': 'herdr-peers --version'},
                'provides_abilities': ['subagents'],
                'requires_grants': ['agent_delegation'],
                'transport': 'interactive'}
        check('descriptor ok', descriptor_errors(good, 'herdr') == [],
              repr(descriptor_errors(good, 'herdr')))
        for label, mutate in (
                ('key mismatch', lambda d: d.update(key='vim')),
                ('shell command', lambda d: d['detect'].update(command='ak doctor | sh')),
                ('both detect', lambda d: d['detect'].update(paths=['x'])),
                ('unknown ability', lambda d: d.update(provides_abilities=['root'])),
                ('transport without grant', lambda d: d.update(requires_grants=[])),
                ('floating tag', lambda d: d['product'].update(tag='main'))):
            bad = json.loads(json.dumps(good))
            mutate(bad)
            check('descriptor ' + label, bool(descriptor_errors(bad, 'herdr')))
        # 18. find_dwp_root
        plan = os.path.join(repo, 'plans', 'PLAN_x')
        os.makedirs(plan)
        check('find root', find_dwp_root(plan) == os.path.abspath(repo),
              repr(find_dwp_root(plan)))
        check('no root', find_dwp_root(tmp) is None)
    finally:
        shutil.rmtree(tmp, ignore_errors=True)
    # benchmark writer (X-2): sets one key, keeps the others, refuses junk
    tmp_b = tempfile.mkdtemp(prefix='dwp-config-bench-')
    try:
        bdir = os.path.join(tmp_b, '.dwp')
        os.makedirs(bdir)
        with open(os.path.join(bdir, 'config.json'), 'w', encoding='utf-8') as fh:
            fh.write('{"addons": {"vim": {"enabled": true}}}')
        write_benchmark(bdir, 'enabled', True)
        rec = write_benchmark(bdir, 'learnings', True)
        check('benchmark writer sets both keys', rec == {'enabled': True, 'learnings': True})
        with open(os.path.join(bdir, 'config.json'), encoding='utf-8') as fh:
            kept = json.load(fh)
        check('benchmark writer keeps other keys', kept.get('addons') == {'vim': {'enabled': True}})
        refused = False
        try:
            write_benchmark(bdir, 'verbose', True)
        except ConfigError:
            refused = True
        check('benchmark writer refuses unknown key', refused)
    finally:
        shutil.rmtree(tmp_b, ignore_errors=True)
    if probes != SELF_TEST_PROBES:
        failures.append('probe count %d != pinned %d' % (probes, SELF_TEST_PROBES))
    for line in failures:
        print('FAIL: ' + line)
    if failures:
        return 1
    print('OK: config self-test (%d probes)' % probes)
    return 0


if __name__ == '__main__':
    sys.exit(main())
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall