Skip to content
Open
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
206 changes: 206 additions & 0 deletions bin/fm-artifact-lib.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
#!/usr/bin/env bash
# fm-artifact-lib.sh - the one owner of a worker's artifact lineage.
#
# WHY THIS EXISTS. A secondmate home's parent channel already carried a
# `report=` document pointer and a `pr=` pointer, and both say WHERE an outcome
# lives, not WHICH bytes were verified. A conversational summary is not
# evidence: it cannot be re-checked once the worker's disposable worktree is
# torn down, and forwarding a worker transcript as the result makes the parent
# consume raw worker text instead of a status. This library makes a WorkerResult
# artifact-first: a manifest at data/<task>/artifacts.json names each artifact
# by kind and path and pins it with the full SHA-256 of its bytes.
#
# The contract (docs/artifact-lineage.md):
# - artifact kinds are a closed allowlist (patch, test-log, review-report,
# report, trace, manifest). transcript, chat, session, and conversation
# are NOT artifacts and are refused, so a transcript cannot be forwarded as
# a WorkerResult.
# - every path is the home-relative `data/<task>/...` form and resolves to a
# regular, non-symlinked file under the data directory; the check is a
# resolving one, never a textual prefix test.
# - the manifest is written atomically and verified by recomputing every
# hash, so a changed or missing artifact fails instead of reading intact.
# - the parent channel carries a pointer plus the manifest digest
# (`artifacts=data/<task>/artifacts.json artifacts_sha256=<hex>`), never the
# artifact bodies.
#
# Sourced by bin/fm-artifact-manifest.sh and bin/fm-inactive-reconcile.sh.
# No side effects on source.

# A task id is used as a directory component, so it is accepted only when it is
# path-safe: no empty value, leading dot, slash, or character outside
# [A-Za-z0-9._-].
fm_artifact_task_valid() { # <task>
local task=${1-}
case "$task" in
''|.*|*/*|*[!A-Za-z0-9._-]*) return 1 ;;
esac
}

# The closed allowlist. A transcript/chat/session is deliberately absent: the
# contract prohibits transcript forwarding rather than merely discouraging it.
fm_artifact_kind_valid() { # <kind>
case "${1-}" in
patch|test-log|review-report|report|trace|manifest) return 0 ;;
esac
return 1
}

# Full 64-hex SHA-256 of <file>; non-zero when no hasher is available.
fm_artifact_sha256() { # <file>
local file=$1
if command -v shasum >/dev/null 2>&1; then
shasum -a 256 "$file" 2>/dev/null | awk '{print $1}'
elif command -v sha256sum >/dev/null 2>&1; then
sha256sum "$file" 2>/dev/null | awk '{print $1}'
else
return 1
fi
}

# Validate the home-relative artifact spelling. Only data/<task>/... is
# accepted, with no parent traversal, no empty component, and no character a
# status line or the JSON writer would have to escape.
fm_artifact_rel_valid() { # <task> <rel>
local task=$1 rel=${2-}
case "$rel" in
"data/$task/"*) ;;
*) return 1 ;;
esac
case "/$rel/" in */../*|*/./*) return 1 ;; esac
case "$rel" in *'//'*) return 1 ;; esac
case "$rel" in *[!A-Za-z0-9._/-]*) return 1 ;; esac
}

# Resolve <rel> to a real path under <data-dir>, rejecting a symlink in place
# of the artifact or of any directory it is reached through. Prints the
# resolved path.
fm_artifact_resolve() { # <data-dir> <task> <rel> -> absolute path
local data=$1 task=$2 rel=$3 base real path
fm_artifact_task_valid "$task" || return 1
fm_artifact_rel_valid "$task" "$rel" || return 1
path="$data/${rel#data/}"
[ -f "$path" ] && [ ! -L "$path" ] || return 1
base=$(CDPATH='' cd -- "$data" 2>/dev/null && pwd -P) || return 1
real=$(CDPATH='' cd -- "$(dirname "$path")" 2>/dev/null && pwd -P) || return 1
case "$real" in
"$base"|"$base"/*) ;;
*) return 1 ;;
Comment on lines +84 to +88

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Other tasks' files pass

fm_artifact_resolve checks the resolved directory against the whole data directory, not the task directory. It also allows intermediate directory links. A worker can create data/task/link pointing to ../other and submit data/task/link/report.md; both writing and checking accept the other task's report as its evidence.

Reject linked directory components and require the resolved file to stay under the requested task.

How this was verified: Worker-selected paths pass through the same resolver during writing and checking, and its resolved-path check accepts sibling task directories.

esac
printf '%s\n' "$path"
}

# Write a manifest atomically from <kind>=<rel> pairs. Entries are sorted so the
# same inputs always produce the same bytes. Prints the manifest path.
fm_artifact_manifest_write() { # <data-dir> <task> <kind>=<rel>...
local data=$1 task=$2 entry kind rel path hash bytes dir out tmp sorted
local -a entries=()
fm_artifact_task_valid "$task" || return 2
shift 2
[ "$#" -gt 0 ] || return 2
for entry in "$@"; do
case "$entry" in
*=*) ;;
*) return 3 ;;
esac
kind=${entry%%=*}
rel=${entry#*=}
fm_artifact_kind_valid "$kind" || return 3
path=$(fm_artifact_resolve "$data" "$task" "$rel") || return 3
hash=$(fm_artifact_sha256 "$path") || return 4
Comment on lines +109 to +110

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Manifest overwrites its own evidence

write accepts an existing data/<task>/artifacts.json as a manifest artifact, hashes it, then overwrites that same file with the new manifest. Rerunning with only --artifact manifest=data/task/artifacts.json returns success but immediately fails verification because it records the old file's hash.

Reject the output path as an input before replacing any existing manifest.

[ "${#hash}" -eq 64 ] || return 4
bytes=$(wc -c < "$path" 2>/dev/null | tr -d ' ') || return 4
case "$bytes" in ''|*[!0-9]*) return 4 ;; esac
entries+=("$kind"$'\t'"$rel"$'\t'"$hash"$'\t'"$bytes")
done
sorted=$(printf '%s\n' "${entries[@]}" | LC_ALL=C sort) || return 4
dir="$data/$task"
[ -d "$dir" ] && [ ! -L "$dir" ] || return 5
out="$dir/artifacts.json"
tmp=$(umask 077; mktemp "$dir/.artifacts.XXXXXX") || return 5
{
printf '{\n'
printf ' "schema": "fm-artifact-manifest.v1",\n'
printf ' "task": "%s",\n' "$task"
printf ' "artifacts": [\n'
local first=1 line
while IFS= read -r line; do
[ -n "$line" ] || continue
IFS=$'\t' read -r kind rel hash bytes <<< "$line"
[ "$first" -eq 1 ] || printf ',\n'
first=0
printf ' {"kind": "%s", "path": "%s", "sha256": "%s", "bytes": %s}' \
"$kind" "$rel" "$hash" "$bytes"
done <<< "$sorted"
printf '\n ]\n'
printf '}\n'
} > "$tmp" || { rm -f -- "$tmp"; return 5; }
chmod 0600 "$tmp" || { rm -f -- "$tmp"; return 5; }
mv -f -- "$tmp" "$out" || { rm -f -- "$tmp"; return 5; }
printf '%s\n' "$out"
}

# Read one JSON string field from <line>; the writer's own validated charset
# means no escaping is possible.
_fm_artifact_json_field() { # <line> <key>
printf '%s\n' "$1" | sed -n "s/.*\"$2\": \"\\([^\"]*\\)\".*/\\1/p"
}

# The size field is the manifest's only unquoted JSON value.
_fm_artifact_json_size() { # <line>
printf '%s\n' "$1" | sed -n 's/.*"bytes": \([0-9][0-9]*\).*/\1/p'
}

# Verify every entry against the artifact bytes. Returns 0 only when the schema,
# task, every path, and every hash agree; prints a one-line reason on failure.
fm_artifact_manifest_verify() { # <data-dir> <task> <manifest>
local data=$1 task=$2 manifest=$3 line kind rel hash bytes path actual expected
local seen=''
fm_artifact_task_valid "$task" || { printf 'invalid task id\n'; return 1; }
[ -f "$manifest" ] && [ ! -L "$manifest" ] || { printf 'manifest is not a regular file\n'; return 1; }
grep -Fxq ' "schema": "fm-artifact-manifest.v1",' "$manifest" 2>/dev/null \
|| grep -Fxq ' "schema": "fm-artifact-manifest.v1"' "$manifest" 2>/dev/null \
|| { printf 'unknown manifest schema\n'; return 1; }
grep -Fxq " \"task\": \"$task\"," "$manifest" 2>/dev/null \
|| grep -Fxq " \"task\": \"$task\"" "$manifest" 2>/dev/null \
|| { printf 'manifest task does not match\n'; return 1; }
while IFS= read -r line; do
case "$line" in
' {'*'}') ;;
*) continue ;;
Comment on lines +168 to +170

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Most artifacts go unchecked

fm_artifact_manifest_verify skips every non-final entry written by write. The writer adds no newline after each object, so the next separator makes that line end in },. This selector accepts only lines ending in }.

With a patch and a test log, changing or deleting the patch still lets verify and ref succeed while the test log remains intact. Check every entry and add a test that changes a non-final artifact.

How this was verified: The writer produces comma-ended non-final entries, the verifier skips those lines, and the publisher accepts the resulting successful check.

esac
kind=$(_fm_artifact_json_field "$line" kind)
rel=$(_fm_artifact_json_field "$line" path)
hash=$(_fm_artifact_json_field "$line" sha256)
bytes=$(_fm_artifact_json_size "$line")
fm_artifact_kind_valid "$kind" || { printf 'artifact kind is not allowed: %s\n' "$kind"; return 1; }
fm_artifact_rel_valid "$task" "$rel" || { printf 'artifact path is not confined to data/%s/: %s\n' "$task" "$rel"; return 1; }
case "$seen" in
*$'\n'"$rel"$'\n'*) printf 'duplicate artifact path: %s\n' "$rel"; return 1 ;;
esac
seen="$seen"$'\n'"$rel"$'\n'
path=$(fm_artifact_resolve "$data" "$task" "$rel") || { printf 'artifact is missing or unsafe: %s\n' "$rel"; return 1; }
actual=$(fm_artifact_sha256 "$path") || { printf 'artifact hash is unavailable: %s\n' "$rel"; return 1; }
[ "$hash" = "$actual" ] || { printf 'artifact hash mismatch: %s\n' "$rel"; return 1; }
expected=$(wc -c < "$path" 2>/dev/null | tr -d ' ') || { printf 'artifact size is unavailable: %s\n' "$rel"; return 1; }
case "$bytes" in
''|*[!0-9]*) printf 'artifact size is malformed: %s\n' "$rel"; return 1 ;;
esac
[ "$bytes" = "$expected" ] || { printf 'artifact size mismatch: %s\n' "$rel"; return 1; }
done < "$manifest"
[ -n "$seen" ] || { printf 'manifest has no artifacts\n'; return 1; }
return 0
}

# The parent-channel suffix for <task>, or non-zero when no verified manifest
# exists. The digest names the exact manifest bytes the parent will read.
fm_artifact_manifest_ref() { # <data-dir> <task>
local data=$1 task=$2 rel manifest digest
fm_artifact_task_valid "$task" || return 1
rel="data/$task/artifacts.json"
manifest="$data/$task/artifacts.json"
fm_artifact_manifest_verify "$data" "$task" "$manifest" >/dev/null || return 1
digest=$(fm_artifact_sha256 "$manifest") || return 1
[ "${#digest}" -eq 64 ] || return 1
printf 'artifacts=%s artifacts_sha256=%s\n' "$rel" "$digest"
}
107 changes: 107 additions & 0 deletions bin/fm-artifact-manifest.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
#!/usr/bin/env bash
# fm-artifact-manifest.sh - write, verify, or reference a worker's artifact manifest.
#
# A worker's result is its artifacts, not its chat. This entry point writes the
# machine-readable manifest the parent channel points at, verifies it by
# recomputing every hash, or prints the parent-channel reference. Kinds are a
# closed allowlist (patch, test-log, review-report, report, trace, manifest)
# owned by bin/fm-artifact-lib.sh; a transcript, chat log, or session dump is
# refused.
#
# Usage:
# fm-artifact-manifest.sh write --task <id> --artifact <kind>=<path> [--artifact ...]
# fm-artifact-manifest.sh verify --task <id>
# fm-artifact-manifest.sh ref --task <id>
#
# <path> is the home-relative data/<id>/... form. `write` stores the manifest at
# data/<id>/artifacts.json and prints its path; `verify` re-hashes every entry
# and prints the reason on failure; `ref` prints the parent-channel suffix
# `artifacts=data/<id>/artifacts.json artifacts_sha256=<hex>` only when the
# manifest verifies.
#
# Exit codes:
# 0 success
# 2 usage or invalid task id
# 3 an artifact kind is not allowed, or its path is missing, unsafe, or
# outside data/<task>/
# 4 hashing or writing the manifest failed
# 5 the manifest does not verify
#
# Keep artifact output under $DATA/$ID/: ship briefs already allow that, and the
# scout brief allows it alongside the report and status file.
set -u

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FM_ROOT="${FM_ROOT_OVERRIDE:-$(cd "$SCRIPT_DIR/.." && pwd)}"
FM_HOME="${FM_HOME:-${FM_ROOT_OVERRIDE:-$FM_ROOT}}"
DATA="${FM_DATA_OVERRIDE:-$FM_HOME/data}"

# shellcheck source=bin/fm-artifact-lib.sh
. "$SCRIPT_DIR/fm-artifact-lib.sh"

usage() {
sed -n '2,17p' "${BASH_SOURCE[0]}" | sed 's/^# //; s/^#$//'
}

COMMAND=
TASK=
ARTIFACTS=()

while [ "$#" -gt 0 ]; do
case "$1" in
write|verify|ref)
[ -z "$COMMAND" ] || { echo "error: more than one command given" >&2; exit 2; }
COMMAND=$1
shift
;;
--task)
[ "$#" -ge 2 ] || { echo "error: --task needs a value" >&2; exit 2; }
TASK=$2
shift 2
;;
--artifact)
[ "$#" -ge 2 ] || { echo "error: --artifact needs <kind>=<path>" >&2; exit 2; }
ARTIFACTS+=("$2")
shift 2
;;
--help|-h)
usage
exit 0
;;
*)
echo "error: unknown argument: $1" >&2
usage >&2
exit 2
;;
esac
done

[ -n "$COMMAND" ] || { usage >&2; exit 2; }
fm_artifact_task_valid "$TASK" || { echo "error: invalid task id: ${TASK:-<empty>}" >&2; exit 2; }
[ -d "$DATA" ] || { echo "error: data directory is unavailable: $DATA" >&2; exit 2; }

case "$COMMAND" in
write)
[ "${#ARTIFACTS[@]}" -gt 0 ] || { echo "error: write needs at least one --artifact" >&2; exit 2; }
manifest=$(fm_artifact_manifest_write "$DATA" "$TASK" "${ARTIFACTS[@]}")
rc=$?
case "$rc" in
0) printf '%s\n' "$manifest" ;;
2) echo "error: invalid task id" >&2; exit 2 ;;
3) echo "error: artifact kind is not allowed, or its path is missing, unsafe, or outside data/$TASK/" >&2; exit 3 ;;
4) echo "error: hashing an artifact failed" >&2; exit 4 ;;
*) echo "error: cannot write data/$TASK/artifacts.json" >&2; exit 4 ;;
esac
;;
verify)
if reason=$(fm_artifact_manifest_verify "$DATA" "$TASK" "$DATA/$TASK/artifacts.json"); then
printf 'verified: data/%s/artifacts.json\n' "$TASK"
else
printf 'error: %s\n' "${reason:-manifest does not verify}" >&2
exit 5
fi
;;
ref)
fm_artifact_manifest_ref "$DATA" "$TASK"
;;
esac
6 changes: 5 additions & 1 deletion bin/fm-brief.sh
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,7 @@ The report is the only thing that survives, so anything worth keeping must be in

# Rules
1. Never push to any remote and never open a PR.
2. Stay inside this worktree; outside it, write only the report and status file below, except for the task's empty-inventory attestation through \`fm-captain-hold.sh complete --none\`, exactly as specified under Definition of done.
2. Stay inside this worktree; outside it, write only the report, the artifact manifest, and the status file below, except for the task's empty-inventory attestation through \`fm-captain-hold.sh complete --none\`, exactly as specified under Definition of done.
3. Use gh-axi for GitHub operations and chrome-devtools-axi for browser operations.
4. Report status by appending one line:
\`$STATUS_APPEND\`
Expand All @@ -743,6 +743,10 @@ $WAIT_BLOCK$INBOX_SECTION
# Definition of done
Write your findings to \`$DATA/$ID/report.md\`.
The report must stand alone: what you did, what you found, the evidence (commands run, output, file:line references), and what you recommend.
Return artifacts, not a transcript: write the lineage manifest with
\`$FM_ROOT/bin/fm-artifact-manifest.sh write --task $ID --artifact report=$DATA/$ID/report.md\`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Scout command rejects report path

The generated command passes an absolute report path, but fm_artifact_rel_valid accepts only data/<task>/.... DATA is resolved to an absolute directory before this brief is written, so following the command fails with exit code 3 instead of creating the required manifest.

Render report=data/$ID/report.md and keep the chosen home/data directory separate from the artifact's relative path.

and add one \`--artifact <kind>=<path>\` for each other artifact you produced under \`$DATA/$ID/\` (kinds: patch, test-log, review-report, report, trace, manifest).
The manifest pins every artifact with its full SHA-256; a chat log, transcript, or session dump is not an artifact and the contract refuses it.
$LAVISH_LINE
Before reporting done, read and follow \`$FM_ROOT/.agents/skills/captain-hold-lifecycle/SKILL.md\` and pass its shared completion gate for the report and any visual review.
Only when the reviewed inventory is empty, run \`FM_HOME=$(shell_quote "$FM_HOME") bash $(shell_quote "$FM_ROOT/bin/fm-captain-hold.sh") complete $(shell_quote "$ID") --none\`.
Expand Down
15 changes: 15 additions & 0 deletions bin/fm-dod-lib.sh
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,12 @@ EOF
fm_dod_block() { # <mode> <task-id> [branch] [<forge>] [<base>] [<consent>] [<pr>]
local mode=$1 id=$2 forge=${4:-none} base=${5:-} consent=${6:-} pr=${7:-auto}
local branch=${3:-fm/$id} pr_base='' nm_base='' base_q contract_forge='' contract_consent='' forge_cli=gh-axi draft_check adapter
# The lineage block renders a path the worker can invoke. Real callers
# (fm-brief.sh, fm-promote.sh) export FM_ROOT and DATA; a library-only caller
# still gets a usable repo path and a home-relative data path.
local artifact_root=${FM_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}
local artifact_data=${DATA:-${FM_HOME:+$FM_HOME/data}}
artifact_data=${artifact_data:-data}
fm_forge_valid_for_mode "$forge" "$mode" fm_dod_block || return 1
fm_base_branch_valid "$base" "$mode" "$forge" fm_dod_block || return 1
fm_pr_text_valid "$pr" "$mode" "$forge" fm_dod_block || return 1
Expand Down Expand Up @@ -698,6 +704,15 @@ EOF
echo "error: fm_dod_block: unknown delivery mode '$mode'" >&2
return 1 ;;
esac
cat <<EOF

## Artifact lineage
Return artifact references and hashes, not a conversational summary: the parent consumes your manifest, never your transcript.
Before your done line, write the lineage manifest with
\`$artifact_root/bin/fm-artifact-manifest.sh write --task $id --artifact <kind>=<path> ...\`,
Comment on lines +707 to +712

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Manual PRs miss manifest instructions

The new shared block is never printed for no-mistakes tasks with pr=manual. That branch calls fm_dod_manual_pr_block and returns before reaching this block. The helper contains no manifest instructions, so these workers miss the new completion requirement.

Make that branch continue to the shared block too.

listing every artifact you produced under \`$artifact_data/$id/\` (kinds: patch, test-log, review-report, report, trace, manifest; for example \`patch\` for the diff you shipped, \`test-log\` for the run you cite, \`review-report\` for a review).
The manifest pins each file with its full SHA-256; a chat log, transcript, or session dump is not an artifact and the contract refuses it.
EOF
}

# 0 when <sha> is contained in a ref under <namespace> in <repo>.
Expand Down
Loading