Submit

From kbaseincubator/BERIL-research-observatory · View interactive version

Submit is an AI agent skill from the GitHub repository kbaseincubator/BERIL-research-observatory. Approve a project and upload it to the lakehouse. Use when the author is ready to stand behind the report and submit the project for archival.

How to use this skill

Skill file

Project Submission Skill

/submit is the approval + lakehouse upload event. It does NOT run the reviewer — produce reviews via /berdl-review first (you can run as many as you want with whatever model). When the user is ready to stand behind the project, /submit:

  1. Verifies pre-submission checklist passes.
  2. Verifies a current review (matching the latest REPORT.md hash) exists.
  3. Asks the user to explicitly approve completeness.
  4. Uploads to the lakehouse.
  5. Records approval and submission marker files so anyone (the user, future agents) can see at a glance that the project landed in the lakehouse.

The lakehouse archive is the source of truth for "this project was submitted." Local files (beril.yaml, README.md, SUBMITTED.md / SUBMISSION_FAILED.md) tell the user what's happened on their machine; git is convenience.

Usage

/submit <project_id>

If no <project_id> argument is provided, detect from the current working directory (if inside projects/{id}/).

Hash comparison convention

All hash values stored in beril.yaml.approval.* and in REVIEW footer lines are prefixed with sha256: (e.g., "sha256:abcdef..."). Hash values produced by sha256sum (or hashlib.sha256(...).hexdigest()) are raw hex without the prefix. Never compare these forms directly — that's a category error that produces false-positive mismatches.

Use the helpers in tools/notebook_hash.py:

Comparison rule, applied at every hash check site in this skill:

computed_hex == unprefixed(stored_value)

When this skill text says "compare to approval.report_hash" or "verify sha256sum X == approval.foo_hash", read it as the rule above — pass the stored value through unprefixed() first.

Workflow

Step 1: Resolve Project

  1. Accept <project_id> from the argument, or detect from cwd if inside a projects/ subdirectory.
  2. Validate that projects/{project_id}/ exists in the repository root.
  3. If the directory does not exist, print an error and stop.

Phase 0 — exclusion lock

/submit mutates approval state and uploads to a shared remote, so two concurrent invocations on the same project would race. Acquire the lock before any other workflow step (including the read-only checklist) so two agents running concurrently both see the second one's lock check fail rather than both passing the checks and racing into Phase 2.

> Error: another /submit run appears to be in progress for this project (lock at .submit.lock, created {file_mtime}). If no /submit is actually running, delete the file manually and retry.

The lock is advisory and skill-text-enforced, not OS-level. It defends against the common case (the user running /submit twice in quick succession) but a determined parallel run can still bypass it. Document the limitation rather than try to engineer around it.

Step 2: Pre-submission checklist

Run these checks against the project directory and print a checklist summary:

Critical checks (block submission on failure):

Advisory checks (warn but allow submission):

Print the checklist in PASS/FAIL/WARN/INFO format. If any critical check FAILs, print failures, release the lock, and stop — do not enter Phase 1.

Phase 1 — pre-flight gates

This phase performs no state changes except for the explicit reopen confirmation flow on hash mismatch (which has its own user prompt).

1a. Status gate

Read projects/{project_id}/beril.yaml. If it is missing (pre-manifest project), reject submission:

FAIL This project has no beril.yaml manifest. The new submission flow requires a manifest to record approval and submission history. Run /berdl_start on this project to scaffold a manifest (it will detect the existing artifacts), then re-run /submit.

Pre-manifest projects cannot go through approval/upload tracking until upgraded. (Migrating legacy projects to the new manifest format is a separate effort, not handled inline by /submit.)

For projects with beril.yaml:

Status `complete` resolution

1. First validate the approved content against beril.yaml.approval along three axes:

Existence checks (a missing file is a recoverability question, not a hash-mismatch):

Hash checks (only on files that exist; apply the prefix convention — unprefixed(stored) before comparing to sha256sum output):

Any hash mismatch (REPORT, REVIEW, or notebooks) OR the both-review-files-missing case triggers the reopen prompt (phrase the explanation according to which condition fired):

> "{REPORT.md changed | REVIEW.md changed | REVIEW_N.md changed | both REVIEW.md and REVIEW_N.md missing | notebook(s) changed: <list of specific files>} since this project was approved ({approval.at}). The previous approval no longer reflects the current approved content. Demote status to analysis? Previous approval will be archived under previous_approvals; both SUBMITTED.md and SUBMISSION_FAILED.md will be removed (audit lives in beril.yaml)."

Markers are not consulted in this branch — the approved content no longer matches what's on disk. Doing these checks in Phase 1a (rather than only in Phase 3a) avoids an infinite-retry loop where review drift or loss is only detected mid-flight, after Phase 2 has been skipped: without an automated demote path, the user has no way out.

2. Then recover/reconcile approval-gated memory files before any marker-based early exit. Re-run the same 2c-pre memory extraction logic against the approved REPORT.md and apply the same staged memory actions from 2c-write for projects/{project_id}/memories/{discoveries,performance}.md. This is intentionally idempotent:

Do this even when SUBMITTED.md is present and the run would otherwise exit as already submitted. This closes the retry gap where a previous /submit wrote status: complete and approval but was interrupted before applying memories/{discoveries,performance}.md. If duplicate section validation somehow fails here, abort with the same duplicate-heading error as 2c-pre; the approved report is malformed and must be demoted/re-reviewed rather than guessed.

3. Then branch on markers (SUBMISSION_FAILED.md always wins on conflict):

1b. Review-currency check (status: reviewed)
1c. Author identity check

Run beril user --json. If orcid is empty → FAIL No ORCID configured — run beril setup before submitting. The approval record requires a verified ORCID. (No anonymous approvals.)

1d. Present review summary

Show the latest review's filename, mtime, critical/important issue counts (parsed from the review body), and the one-line abstract (first non-blank paragraph or H1 of the review).

Phase 2 — approval (the human event)

Reached only from status: reviewed with all gates passed.

2a. Approval prompt

Compute last_success = the most recent entry in beril.yaml.submissions[] (if any) with status: success, joined to the corresponding previous_approvals[*] entry via approved_at.

> "Latest review REVIEW_N.md is on the current REPORT.md. Critical: X, important: Y. Reviews are advisory; you can approve with open issues. As the responsible author, do you approve this project complete? (y/n)"

> "Latest review REVIEW_N.md is on the current REPORT.md. Critical: X, important: Y. This project was previously submitted on {last_success.attempted_at} (archive: {last_success.archive_key}). Approving now will replace the existing lakehouse archive. As the responsible author, do you approve this project complete? (y/n)"

2b. TOCTOU re-check

Immediately before writing approval artifacts, recompute sha256sum REPORT.md and sha256sum REVIEW_N.md (the file selected in Phase 1b). Compare against REPORT_HASH_PHASE1 and REVIEW_HASH_PHASE1 captured at the end of Phase 1b. If either has changed, abort with Error: files changed during /submit; please re-run. This guards the brief window between Phase 1 inspection and Phase 2 write.

2c. Write approval artifacts (local filesystem)

Phase 2c is split into a pre-write validation pass (no state mutation) followed by the write pass. All inputs that can fail validation are checked before any file is mutated, so a malformed REPORT.md leaves the project at status: reviewed with zero partial state.

2c-pre. Validate inputs and stage memory extractions (no writes yet)

For each section name in ["Discoveries", "Performance Notes"] (mapping to discoveries.md and performance.md respectively):

1. Detect duplicates first. If the same ## {SectionName} heading appears more than once in REPORT.md (lines matching ^## {SectionName}\s*$, case-sensitive, exact match modulo trailing whitespace), abort with: Error: REPORT.md has duplicate '## {SectionName}' headings; cannot extract memory unambiguously. Fix REPORT.md and re-run /submit. Don't guess which section to use; this indicates a malformed REPORT. Phase 2c stops here; the project remains at status: reviewed with no files modified (this check runs before any write below).

2. Find the section. Locate the single matching ^## {SectionName}\s*$ line. Capture content from the line after the heading until the next ^## heading or EOF.

3. Trim whitespace. Strip leading and trailing whitespace from the captured content. ### subheadings and #### sub-subheadings inside the captured range are preserved verbatim — they're part of the section.

4. Classify the staged action (record this in memory; execute in 2c-write below):

After this pre-pass, you have: notebook hashes, plus a list of staged memory actions (per section: delete-if-exists or write with content). No filesystem changes have occurred. From here on, only filesystem operations remain — they should not fail in normal operation.

2c-write. Apply approval mutations

```yaml

status: complete

last_session_at: "<now ISO 8601>"

approval:

by: "<orcid from beril user --json>"

at: "<now ISO 8601>"

report_hash: "sha256:<REPORT.md hex>"

review: "REVIEW_N.md"

review_hash: "sha256:<REVIEW_N.md hex>"

notebook_hashes: # v5; always write this field for v5 approvals — {} when the project has no notebooks. Field omission is reserved for legacy pre-v5 approvals.

"notebooks/01_setup.ipynb": "sha256:<hex>"

"notebooks/02_analysis.ipynb": "sha256:<hex>"

```

```

## Status

Completed — {one-line summary from REPORT.md ## Key Findings}.

```

If REPORT.md doesn't have a clear one-liner, write a brief summary based on the report's findings.

```markdown

# {SectionName} — {project_id}

<!-- [{project_id}] {approval.at} approved-report extraction (REVIEW: {approval.review}) -->

{trimmed captured content}

```

The HTML-comment provenance line keeps the file readable as plain markdown while making the generation context unambiguous (project tag, approval timestamp, source review). Overwrite the file if it exists from a prior approval.

At this point the project is approved locally regardless of upload outcome. The user can git add and commit if they want git history to reflect the approval.

Phase 3 — lakehouse upload (the system event)

3a. Pre-upload normalization + final hash recheck

Run unconditionally (including retry-only flows that entered Phase 3 directly from Phase 1 on status: complete):

3b. Run upload
python tools/lakehouse_upload.py {project_id}

The script archives all project files to s3a://cdm-lake/tenant-general-warehouse/microbialdiscoveryforge/projects/{project_id}/. If the berdl-minio mc alias isn't configured, set it up first:

mc alias set berdl-minio $S3_ENDPOINT_URL $S3_ACCESS_KEY $S3_SECRET_KEY

On a successful archive, the upload tool also submits the project files to the BERIL-managed context service so the knowledge layer can see the completed project. That step is handled entirely inside lakehouse_upload.py and is best-effort: it runs only when BERIL is reachable and the user is logged in, and if it is skipped or fails the lakehouse archive still succeeds (the tool reports it in its JSON but does not fail the upload). /submit needs no extra handling for it — the exit-code contract below is unchanged.

The mirror goes through BERIL's own HTTP API. knowledge/scripts/ingest_context.py --project <id> --json stages the project (curated files, memories/*.md, plus the generated PROJECT_METADATA.md and CLAIMS_CONTEXT.md), zips that tree, and POSTs it with a manifest to POST /api/context/ingest_files using the personal access token from beril login. The archive is what preserves relative paths — a flat upload would collapse memories/pitfalls.md to pitfalls.md. Ingest is asynchronous, so the script then polls GET /api/context/ingest_status/{batch_id} every few seconds until every file reaches a terminal state (default cap: 10 minutes). A BERIL credential is the only one involved.

The context service skips any file whose exact content it already holds, so re-running /submit on an unchanged project sends nothing and completes immediately. Only a file that actually landed counts as current — one that failed or is still indexing is sent again, so a retry after a failure always does real work.

Re-submission is add-only in the context service. A file that is missing from a later submission is left as it was, not deleted — absence alone can't say whether the author meant "remove it" or "leave it". Withdrawing a file is always explicit, as a !remove <path> line in the ingest manifest. The mirror sends one automatically for each approval-gated memory (memories/discoveries.md, memories/performance.md) that the project no longer has, which is exactly what a delete-if-exists action in 2c-write leaves behind: once the approved REPORT drops that section, the context service drops the memory too, and the project stops suppressing its central docs/discoveries.md entries. Withdrawing a memory the service never held is a harmless no-op, so this is sent on every submission. To withdraw any other file, run knowledge/scripts/ingest_context.py --project <id> --json --remove <relative/path> (repeatable); /submit never infers other removals.

What the context service accepts. POST /api/context/ingest_files checks every submission before it touches anything, and refuses one that fails any check (a 4xx with a detail that names the problem). The mirror already satisfies all of these for a project /submit has just approved; they matter when something is off, or when an archive is built by hand.

Through /submit, a refusal shows up as "failed" with reason context-service submission failed: BERIL returned <code> on …: <detail> — the lakehouse archive has still succeeded. Report the detail to the user, fix the cause (usually a file changed after approval: re-run /berdl-review and /submit), and re-run. Don't work around a refusal by editing beril.yaml by hand; see docs/context-layer.md § "What BERIL accepts" for the full reference.

Verdict mapping in the tool's context_submission JSON:

Scope limitation: this path uploads files only. The knowledge/state/ change manifest is not updated by it — a mirrored project's manifest entry stays whatever the last interactive ingest run (--all / --changed) recorded. Run an interactive ingest mode to reconcile it. This does not affect the lakehouse archive or the submission verdict.

Re-submission overwrite semantics: the upload script pre-clears the remote prefix (mc rm --recursive --force) before mc cp whenever the prefix already has contents. This prevents stale files from a previous submission from contaminating the new archive when files are dropped or renamed between submissions. The brief mid-upload window during which the archive is empty is acceptable: a complete + SUBMISSION_FAILED.md state already signals "incomplete archive" to anyone consuming it. First-time submissions skip the clear because the remote prefix is empty.

The script's final stdout line is a single-line JSON object describing the outcome. Exit-code contract:

In all cases, parse the JSON if exit is 0 or 2; on exit 1 fall back to the stderr text.

3b.5. Post-upload integrity rehash

If lakehouse_upload.py returned exit 0, repeat the Phase 3a verification once more: recompute sha256sum REPORT.md, sha256sum REVIEW.md, sha256sum projects/{project_id}/{approval.review}, AND re-invoke python {repo_root}/tools/notebook_hash.py compute-hashes {project_path}. Compare each against the corresponding stored values in approval (apply unprefixed() to stored values). If any has changed since Phase 3a, the lakehouse archive may now contain content that doesn't match the recorded approval (the user edited a file during the upload window). Treat as a Phase 3 failure: do NOT write SUBMITTED.md; jump to Phase 3c failure handling with error: "files changed during upload (<file list>); archive may be inconsistent. Restore the original files from version control before retrying, or run /synthesize to demote and re-approve with the new content.".

This is best-effort: by the time we detect drift, the archive already exists at archive_key. The failure marker tells the user to re-run, which will overwrite the archive with the (now hopefully stable) approved content. The advisory .submit.lock does not block file edits, only concurrent /submit runs — see Notes for the full limitation.

3c. Record outcome

Markers and beril.yaml.submissions[] are managed exclusively by this step. submissions[i].approved_at is the join key linking each upload attempt to the corresponding approval.at (or previous_approvals[*].at).

Ordering invariant: always write the beril.yaml.submissions[] entry first, then the marker file. beril.yaml is the source of truth for the audit log; the marker is a derived view for at-a-glance user visibility. If the run dies between the YAML write and the marker write, the next /submit invocation rebuilds the marker from submissions[] (Phase 1a's "both markers absent" branch already covers this for success entries; the failure-case reconstruction is documented at the end of this section).

On success
  1. First, append to beril.yaml.submissions: []:

```yaml

submissions:

attempted_at: "<iso>"

archive_key: "{archive_key}"

file_count: {file_count}

byte_total: {byte_total}

duration_seconds: {duration_seconds}

approved_at: "{approval.at}"

```

  1. Then, write projects/{project_id}/SUBMITTED.md:

```markdown

# Project Submitted

This project was successfully archived to the BERDL lakehouse.

## Stats

## Approved content

## History

{M} previous submission(s) archived in beril.yaml.submissions.

```

  1. Then, delete SUBMISSION_FAILED.md if present (defensive — should already be gone after Phase 3a's normalization).
  2. Remind the user about docs/research_ideas.md — move the project entry from "High/Medium Priority Ideas" to "Completed Ideas" with a results summary.
  3. Suggest committing all changes.
On failure
  1. First, append to beril.yaml.submissions: [] with status: failed, error: "...", attempted_at, approved_at, and archive_key: "{archive_key}" when known (include for exit-2 and Phase-3b.5 failures where the upload script emitted JSON containing archive_key; omit for hard exit-1 failures with no archive written).
  2. Then, write projects/{project_id}/SUBMISSION_FAILED.md:

```markdown

# Submission Pending

The lakehouse upload for this project failed.

Status is complete (the approval is recorded in beril.yaml).

Re-run /submit to retry the upload — it will skip the approval step

and only retry the upload.

```

Omit the Archive key (partial) line when the failure is a hard error (exit 1) with no archive written. Include it whenever the upload script emitted JSON containing archive_key (exit 0 but rehash-failed in Phase 3b.5, or exit 2 partial-success).

  1. Status stays complete. Update README.md ## Status to add a parenthetical:

```

## Status

Completed — {summary}. (Submission pending; see SUBMISSION_FAILED.md.)

```

On a subsequent successful retry, the parenthetical is removed by Phase 3a.

  1. Delete SUBMITTED.md if present (a previous successful submission is no longer the latest state).
  2. Print the error and tell the user how to fix the underlying issue (e.g., mc alias config, network) and to re-run /submit.
Marker reconstruction from `submissions[]`

If /submit is invoked and finds an inconsistent state where the audit log has a recent submissions[] entry whose marker is missing (because the run died after step 1 but before step 2 above), reconstruct the marker on the next pass:

Marker invariant

After Phase 3 completes, exactly one of SUBMITTED.md or SUBMISSION_FAILED.md is present, never both. If for any reason both are seen later (manual edits, partial failures outside /submit's control), SUBMISSION_FAILED.md always wins — it represents the more recent attempt's outcome.

Notes

Pitfall Detection

When you encounter errors, unexpected results, retry cycles, performance issues, or data surprises during this task, follow the pitfall-capture protocol. Read .claude/skills/pitfall-capture/SKILL.md and follow its instructions to determine whether the issue should be added to the active project's projects/<id>/memories/pitfalls.md.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.