Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion kits/profile-dev-kit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,8 @@ A complete spec is UTF-8, at most 262144 bytes, has YAML front matter with
`story_key`, non-empty `requirements`, non-empty `repositories`, `dependencies`
and `size_cap_bytes` from 1 through 64000, and has a non-blank body. The
`story_key` and the five front-matter fields are the only contract fields read
by the kit; other fields remain available to the authoring process.
by the kit; `units` is also read by the implement stage. Other fields remain
available to the authoring process.

Stage outcomes use fixed outcomes (`succeeded`, `refused`, `failed`, `stopped`)
and reason codes. Each record is canonical JSON under
Expand All @@ -454,3 +455,16 @@ Run the workflow from the repository root, for example:
```text
beddel run -i ... workflows/plan-story.yaml
```

## Delivery: implement stage

`implement-story` takes `repo_path`, `story_key`, `spec_path`, `branch` and
`base_ref`; its steps prepare, invoke one Coding agent, settle one unit and
record one Stage outcome. It never pushes, approves, verifies, integrates, or
commits the spec. `units` entries have an `id`, relative `paths` and a commit
`subject`; commits carry the identity trailers. One unit runs per invocation.
A baseline-red Gate is advisory; only a green command that becomes red blocks.

```text
beddel run -i ... workflows/implement-story.yaml
```
15 changes: 15 additions & 0 deletions kits/profile-dev-kit/kit.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,14 @@ tools:
target: "beddel_profile_dev.tools.stage_outcome:profile_record_stage_outcome"
description: "Append one create-only Stage outcome record outside the repository"
category: profile
- name: profile_implement_prepare
target: "beddel_profile_dev.tools.implement:profile_implement_prepare"
description: "Prepare one implementation unit on a feature branch"
category: profile
- name: profile_implement_settle
target: "beddel_profile_dev.tools.implement:profile_implement_settle"
description: "Review and commit one implementation unit"
category: profile

workflows:
- name: verify-change
Expand All @@ -135,6 +143,9 @@ workflows:
- name: read-approval
path: workflows/read-approval.yaml
description: Reads the stored Change Approval without writing records.
- name: implement-story
path: workflows/implement-story.yaml
description: Implements one unit of one spec through a Coding agent and commits only its declared paths; never pushes, verifies or integrates.
- name: plan-story
path: workflows/plan-story.yaml
description: Plans one selected story into one implementation spec through a Coding agent; never implements, verifies or commits.
Expand Down Expand Up @@ -183,6 +194,10 @@ targets:
target: "beddel_profile_dev.tools.plan:profile_plan_settle"
- name: profile_record_stage_outcome
target: "beddel_profile_dev.tools.stage_outcome:profile_record_stage_outcome"
- name: profile_implement_prepare
target: "beddel_profile_dev.tools.implement:profile_implement_prepare"
- name: profile_implement_settle
target: "beddel_profile_dev.tools.implement:profile_implement_settle"
typescript:
status: unavailable
unavailable_reason: >
Expand Down
17 changes: 16 additions & 1 deletion kits/profile-dev-kit/python/beddel_profile_dev/_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"confined",
"diff_text",
"footprint",
"git_run",
"in_head_history",
"in_index",
"is_ancestor",
Expand Down Expand Up @@ -74,13 +75,17 @@ def _repo_error() -> ProfileError:
def _git(
repo: Path,
*args: str,
index_file: Path | None = None,
timeout: float = _GIT_TIMEOUT_SECONDS,
) -> subprocess.CompletedProcess[bytes] | None:
git = shutil.which("git")
if git is None:
return None
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
env["GIT_NO_LAZY_FETCH"] = "1" # no network, even in a partial clone
env["GIT_ATTR_NOSYSTEM"] = "1" # the system attributes file never applies
if index_file is not None:
env["GIT_INDEX_FILE"] = str(index_file)
try:
return subprocess.run(
[
Expand All @@ -94,13 +99,23 @@ def _git(
capture_output=True,
stdin=subprocess.DEVNULL,
env=env,
timeout=_GIT_TIMEOUT_SECONDS,
timeout=timeout,
check=False,
)
except (OSError, ValueError, subprocess.SubprocessError):
return None


def git_run(
repo: Path,
*args: str,
index_file: Path | None = None,
timeout: float = _GIT_TIMEOUT_SECONDS,
) -> subprocess.CompletedProcess[bytes] | None:
"""Run Git with the kit's isolated environment and optional index."""
return _git(repo, *args, index_file=index_file, timeout=timeout)


def _blob_by_oid(repo: Path, oid: str) -> bytes:
"""Return the raw blob bytes for ``oid`` via ``cat-file blob``.

Expand Down
144 changes: 144 additions & 0 deletions kits/profile-dev-kit/python/beddel_profile_dev/implement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
"""Pure contracts for the profile implement stage."""

from __future__ import annotations

import re
from collections.abc import Mapping
from dataclasses import dataclass

from beddel_profile_dev.plan import (
MAX_SPEC_BYTES,
front_matter,
relative_path,
spec_complete,
)

__all__ = [
"MAX_UNITS",
"MAX_UNIT_PATHS",
"PROTECTED_BRANCHES",
"STORY_TRAILER",
"SUBJECT",
"UNIT_ID",
"UNIT_TRAILER",
"Unit",
"branch_reason",
"commit_message",
"covered",
"spec_units",
"trailer_unit",
]

UNIT_ID = re.compile(r"[a-z0-9][a-z0-9-]{0,31}")
MAX_UNITS = 32
MAX_UNIT_PATHS = 64
SUBJECT = re.compile(
r"(?:build|chore|docs|feat|fix|perf|refactor|test)"
r"(?:\([a-z0-9._-]{1,64}\))?: [^\x00-\x1f\x7f]{1,100}"
)
PROTECTED_BRANCHES = ("main", "master", "mainline")
STORY_TRAILER = "Story-Key"
UNIT_TRAILER = "Implementation-Unit"
_BRANCH = re.compile(r"[a-z0-9][a-z0-9._/-]{0,127}")


@dataclass(frozen=True)
class Unit:
"""One ordered implementation unit from a complete plan spec."""

id: str
paths: tuple[str, ...]
subject: str


def _valid_unit(value: object) -> Unit | None:
if not isinstance(value, Mapping) or set(value) != {"id", "paths", "subject"}:
return None
unit_id = value["id"]
paths = value["paths"]
subject = value["subject"]
if not isinstance(unit_id, str) or UNIT_ID.fullmatch(unit_id) is None:
return None
if (
not isinstance(paths, list)
or not 1 <= len(paths) <= MAX_UNIT_PATHS
or len(set(paths)) != len(paths)
or not all(
isinstance(path, str) and len(path) <= 512 and relative_path(path)
for path in paths
)
):
return None
if not isinstance(subject, str) or SUBJECT.fullmatch(subject) is None:
return None
return Unit(unit_id, tuple(paths), subject)


def spec_units(data: bytes, story_key: str) -> tuple[Unit, ...] | None:
"""Return validated implementation units, or ``None`` for an incomplete spec."""
if len(data) > MAX_SPEC_BYTES or not spec_complete(data, story_key):
return None
metadata = front_matter(data)
if metadata is None:
return None
values = metadata.get("units")
if not isinstance(values, list) or not 1 <= len(values) <= MAX_UNITS:
return None
units: list[Unit] = []
seen: set[str] = set()
for value in values:
unit = _valid_unit(value)
if unit is None or unit.id in seen:
return None
seen.add(unit.id)
units.append(unit)
return tuple(units)


def branch_reason(branch: object, base_ref: object) -> str | None:
"""Return the refusal reason for a branch/base pair, if any."""
if not isinstance(branch, str) or _BRANCH.fullmatch(branch) is None:
return "branch.invalid"
parts = branch.split("/")
if (
branch in PROTECTED_BRANCHES
or branch == base_ref
or branch.startswith("-")
or branch.endswith(("/", "."))
or any(p.startswith(".") or p.endswith(".lock") for p in parts)
or ".." in branch
or "//" in branch
or "@{" in branch
):
return (
"branch.protected"
if branch in PROTECTED_BRANCHES or branch == base_ref
else "branch.invalid"
)
return None


def covered(paths: tuple[str, ...] | list[str], path: str) -> bool:
"""Return whether a changed path belongs to a unit's file or directory paths."""
return any(path == item or path.startswith(item + "/") for item in paths)


def commit_message(unit: Unit, story_key: str) -> tuple[str, str]:
"""Return the subject and trailer paragraph for a unit commit."""
return unit.subject, f"{STORY_TRAILER}: {story_key}\n{UNIT_TRAILER}: {unit.id}"


def trailer_unit(message: str, story_key: str) -> str | None:
"""Return a unit id when a commit message has exactly the required trailers."""
if not isinstance(message, str):
return None
story_lines = [
line for line in message.splitlines() if line == f"{STORY_TRAILER}: {story_key}"
]
unit_lines = [
line for line in message.splitlines() if line.startswith(f"{UNIT_TRAILER}: ")
]
if len(story_lines) != 1 or len(unit_lines) != 1:
return None
unit_id = unit_lines[0][len(f"{UNIT_TRAILER}: ") :]
return unit_id if UNIT_ID.fullmatch(unit_id) is not None else None
Loading
Loading