Skip to content

fix(apps): run setup.onInstall on local-dir installs and gate enable on it - #10599

Open
atomsbaza wants to merge 1 commit into
kirodotdev:mainfrom
atomsbaza:feat/app-oninstall-local
Open

atomsbaza wants to merge 1 commit into
kirodotdev:mainfrom
atomsbaza:feat/app-oninstall-local

Conversation

@atomsbaza

@atomsbaza atomsbaza commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: An app installed from a local directory runs its setup.onInstall and setup.onEnable hooks in the order its backend needs, so it starts on the first enable instead of after an install → enable → disable → enable loop.

Installing an app from a local directory never executes the manifest's setup.onInstall. The hook runs on exactly one path — install_from_registry() in src/kiro_crew/apps/registry.py — so an app installed via kirocrew app install <path> or POST /api/apps/install ships without the artifacts the script is supposed to produce. The concrete symptom from issue #10583: a Node.js backend app installed from a local folder has no node_modules, its backend dies with ERR_MODULE_NOT_FOUND on every start, and the only recovery is install → enable → disable → enable.

Two adjacent gaps in the same lifecycle surfaced while fixing that:

  • The dashboard enable route (handle_enable_app) started the backend before running onEnable, so an onEnable that installs backend dependencies (npm install) raced the backend's first boot and lost — the reporter's second finding, with stat-verified timeline evidence.
  • The CLI (kirocrew app enable) skipped onEnable entirely, so even after the route behaved correctly the CLI's own "Run: kirocrew app enable " hint still led to an un-startable app.

Why it matters

Every third-party app whose manifest uses setup.onInstall for dependency installation is broken on the local-directory install path — the path every app developer uses first. The enable race then turns the missing node_modules into a confusing loop (enable fails, re-enable "fixes" it) that looks like flaky infrastructure rather than an ordering bug. The CLI gap means the documented recovery command itself does not do what the dashboard does.

Not a goal

  • Running a hook from update_app: it still runs none and is deferred to its own change.
  • Defending against a script that detaches into a new session (setsid) and rewrites the manifest later; the docs state the limit.
  • Changing the registry install path, the sandbox scope, or the execution-policy rules.

What changed (motivation → approach → change)

Observed symptom → root cause: install_app() in src/kiro_crew/apps/manager.py only managed files — it never read setup.onInstall; the registry path gates script execution on app_execution_denied before cloning because a manifest's shell script is third-party code. Running that script inside the app directory also means third-party code now executes between the gateway's own writes, so the change treats everything the script can touch as untrusted afterwards.

  • manager.py — install_app() runs setup.onInstall after the copy, gated by the same app_execution_denied(action="install") check the registry uses (fail-closed before anything registers), through the shared lifecycle_scripts.run_lifecycle_script runner (sandboxed, cwd set to the copied app dir, never the developer's source tree, whole process group reaped on exit). Failure, timeout, cancellation or interruption fails the install closed: installed.json is never written and the copied tree is removed. After the script the gateway re-reads and re-admits the manifest (name, version, admission policy), re-sweeps the gateway-owned root entries (.app_secret, data), and write_app_secret unlinks first and opens O_EXCL|O_NOFOLLOW, so a planted link cannot redirect the secret write.
  • Preserved user data survives every exit. Before the script, data/ is copied to a temporary .partial-* name and renamed to .{name}-data-script-backup only when complete; a half-written copy is never authoritative. Restores and deletions are renames (swap, then trash) rather than in-place deletes, read-only directories are made writable before removal, a link at the app directory or at data is never followed, and an interrupted install is recovered at the next install entry from the authoritative backup. Leftover non-authoritative backup/trash names are swept at install entry and by a purge uninstall.
  • routes.py — onEnable gates backend start. Dependency resolution and the onEnable script run before register_app()/start_app_backend(). The route re-reads the manifest under the lifecycle lock, reads it off the event loop, and re-admits it after the script. A failed activation — including a failed re-enable — rolls back to disabled and stops the backend of a gateway app, on both the route and the CLI.
  • cli_commands.py — CLI enable mirrors the route. kirocrew app enable runs onEnable via the shared runner, reproduces both platform carve-outs (unsupported-OS skip; installMode: "client" scripts are advisory), re-reads and re-admits the manifest after the script, and rolls back with the same teardown as kirocrew app disable (scheduled crons, disable, deregister), also when interrupted. kirocrew app install re-admits after onInstall before registering.
  • Process-group reaping is scoped. A local onInstall and a gateway-managed onEnable reap leftover members of the script's process group; onEnable of self-managed and client-install apps does not, so those hooks may still start detached work. A script that detaches into a new session (setsid) escapes the reaper; the docs state that post-script re-admission does not defend against it.
  • Docs (docs/app-kit/publishing-guide.md, manifest-reference.md, docs/system-specs/modules/app-kit-platform.md) describe the new onInstall behaviour on local installs, the onEnable order (before registration and backend start), the rollback-to-disabled rule, the reaping scope, what re-admission compares, and that update_app runs no hook (deferred).

Tests

  • test/test_app_manager.py — TestLocalInstallScript: onInstall runs in the copied dir; the script cannot mutate the source tree; execution-policy denial refuses before the script runs and leaves no metadata; script failure keeps data/ while removing the rest of the copied tree; timeout produces the timed-out failure shape.
  • test/test_app_oninstall_r1.py — each case runs a real script against real filesystem state: a script that re-plants .app_secret as a link cannot redirect the secret write; a script that replaces data with a link cannot capture the restore; a TERM-ignoring straggler is killed on timeout and on cancellation during the grace wait; an interrupted install restores the pristine data on retry; a half-written backup is never authoritative; read-only data survives the swap and leaves no leftover copy; purge uninstall sweeps leftover backup names; a failed backup rename returns an error result with data untouched; a link at the app directory is never followed; self-managed onEnable background work survives while gateway-managed work is reaped; a failed CLI re-enable runs the full disable teardown; a post-onEnable manifest rewrite is re-admitted.
  • test/test_app_routes.py — ordering (onEnable before start_app_backend), failing onEnable leaves no backend and a disabled app, failed re-enable rolls back to disabled, manifest re-read under the lifecycle lock, post-onEnable denial stops a freshly started backend, reaping scope per resource mode.
  • test/test_app_cli.py, test/test_lifecycle_scripts_cov80.py, test/test_spawn_audit.py, test/test_security_posture.py, test/test_enable_deps_resolution.py — CLI enable/rollback, runner timeout and cancellation behaviour, spawn allowlist entry, security-posture log-site census, and the shared fake runner signature.

Validation: 662 tests pass across test_app_routes, test_apps_routes_coverage, test_lifecycle_hooks, test_app_manager, test_app_cli, test_security_posture, test_lifecycle_scripts_cov80, test_app_oninstall_r1, test_spawn_audit and test_enable_deps_resolution; mypy --platform linux src/kiro_crew, flake8, the black ratchet gate (four files graduated out of the baseline), the comment-history gate and scripts/docs-lint.sh pass.

Manual verification

N/A — unit coverage sufficient for the ordering and gating logic; the end-to-end npm-install flow requires a real Node toolchain on the host, and the sandbox/policy matrix exercised here is the same one the existing registry-path tests already cover end to end.

Related Issues

Fixes #10583

Pattern harvest

Rule candidate: review-prompt
Pattern: a sync API that returns a result-typed value calling a sandbox helper documented to RAISE (wrap_argv) — the raise escapes the result contract and skips the caller's rollback; convert at the seam and audit new call sites of raising sandbox helpers for the same shape.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable) — docs/app-kit/publishing-guide.md, docs/app-kit/manifest-reference.md, docs/system-specs/modules/app-kit-platform.md
  • No secrets, credentials, or internal references in the diff

Contribution License Agreement

@atomsbaza
atomsbaza requested review from a team and cixuuz September 13, 2026 18:20
@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: action required A blocking check or review needs attention labels Sep 13, 2026
@atomsbaza
atomsbaza force-pushed the feat/app-oninstall-local branch from 5d14498 to f523b70 Compare September 14, 2026 03:39
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 14, 2026
@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5, fork) — 🔴 BLOCK

Premise-level review of bd9cbb477232cc72d49a6f2713e157e090443ee6 via the fork AI-review pipeline — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

First-Principles-Verdict: BLOCK

kill_pgid/posix_getpgid and sanitize_script_output are second spellings of existing platform_compat and terminal_safe helpers. The data-backup machinery covers a hazard a staging run avoids.

Not justified as shipped

  • Item 7 — duplicate of platform_compat.kill_process_group/pgroup_of_leader: kill_pgid repeats the same captured-pgid kill, with the same guards.
    Subtraction: delete kill_pgid and posix_getpgid, and call kill_process_group/pgroup_of_leader instead.
    Clears when: both new helpers are removed.
  • Item 8 — duplicate of terminal_safe._TERMINAL_CTRL_RE: the new _TERMINAL_CONTROL_RE is a fresh copy of the same CSI/OSC/C0 policy.
    Subtraction: delete sanitize_script_output and the __all__ re-export, and use _TERMINAL_CTRL_RE.sub("", …).
    Clears when: the new regex is gone.
  • Item 4 — oversized: the .data-script-backup/.partial-*/trash/recovery-at-install-entry/purge-sweep machinery exists only because onInstall runs in dest after the preserved data/ is restored.
    Subtraction: run onInstall in a staging copy before the preserve transaction, as the registry path already does. Delete the backup, trash and recovery code.
    Clears when: the script no longer runs against live preserved data, or a human amends the Goal.
  • Item 6 — inherited: _post_install_registration_denial repeats install_app's own re-admission "or a future runner seam can widen that window".
    Subtraction: delete it.
    Clears when: a concrete writer in that window is named.
  • Item 10 — undeclared, rides along: black reformats unrelated hunks across manager.py.

What this change ships

Inventory (10 items) — 4 justified

Intent: let an app installed from a local folder start on its first enable, without an enable/disable loop (FIX, #10583).

  1. Local app install now runs setup.onInstall in the copied directory — justified
  2. Dashboard enable runs onEnable before registration and backend start — justified
  3. CLI app enable now runs onEnable and rolls back on failure — justified
  4. Preserved data/ is backed up, trashed and recovered around the script — oversized
  5. The manifest is re-admitted after onInstall/onEnable (route and CLI) — justified
  6. CLI install re-admits again before registration — rides along, inherited
  7. New pgid-capture kill helpers in platform_compat — duplicate of kill_process_group/pgroup_of_leader
  8. New terminal-control sanitizer in manager — duplicate of terminal_safe._TERMINAL_CTRL_RE
  9. .app_secret is written unlink-first with O_EXCL|O_NOFOLLOW — justified
  10. Black reformatting and baseline removal for four files — undeclared, rides along

Blockers

  • kill_pgid duplicates kill_process_group. The grep kill_process_group\( finds 7 existing call sites (process_identity.py:580, platform_compat.py:6881/7047/7054/7098/7107). It already takes a captured pgid and refuses ≤1 and our own group. The new helper does the same.
    Subtraction: delete kill_pgid and posix_getpgid and call the existing pair.
    Clears when: both helpers are removed from the diff.
  • sanitize_script_output duplicates _TERMINAL_CTRL_RE. The grep _TERMINAL_CTRL_RE finds 19 existing uses, 17 of them in cli_commands.py, the file this PR edits.
    Subtraction: delete the new regex and function and use the existing pattern.
    Clears when: _TERMINAL_CONTROL_RE and sanitize_script_output are removed.

[FIRST-PRINCIPLES-REVIEWED] bd9cbb4

Description read

[DESCRIPTION-READ] b80cd22310041e94e53a2fadb3bae9704b68440ce94a51b3df42cf03fad39e4a

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5, fork) — 🟡 CONCERNS

Design-level review of bd9cbb477232cc72d49a6f2713e157e090443ee6 via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: CONCERNS

Running onInstall inside the live install directory, instead of in a staging copy first, opened a tamper window that ~500 lines of backup, trash and re-admission code now patch.

Watch

  • The script runs in the wrong place. install_app runs the script "in the copied directory" after data/ has been preserved there. That puts third-party shell with write access next to live user data and the gateway-owned names. That is why the patch needs .{name}-data-script-backup, .partial-* and -trash- swaps, crash recovery when the next install starts, .app_secret and data re-sweeps, and an O_EXCL change to write_app_secret. The docs still admit a setsid gap. The registry already avoids all of this: it runs the hook in its checkout before install_app copies it, inside registry_source_repository. Copying the local source to a temp dir, running the hook there, then sending the result through the existing copy and admission path would give the script no access to data/. It would also match the registry's semantics and drop most of the new recovery code.
    Clears when: the hook runs in a staging tree before the existing copy, or the description says why the script must see the installed tree, including data/.
  • Third-party apps get a new contract. The publishing guide said onEnable runs "After resources are registered, the backend is started". It now runs before both, and a failed re-enable now disables an app that was enabled. A third-party onEnable that calls its own backend or reads registered resources will now fail and be left disabled. No app in this repo declares onEnable, so only external apps hit this. I can't confirm it is listed: the description is truncated before ## Backwards compatibility.
    Clears when: the Backwards compatibility section lists the onEnable reordering and the re-enable-disables rule as Breaking, with a migration note for app authors.

Suggestions

  • If staging is adopted, reap_surviving_group for install and the post-script app.json re-read can be removed: the existing copy-time admission already judges the tree the script produced.

[DESIGN-REVIEWED] bd9cbb4

Description read

[DESCRIPTION-READ] c668b04eb5eb3aafc31fea0e44455988bca57914d5616e5c2c2a99ccc0801b57

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review (fork) — 🔴 changes requested (blocking)

Reviewed bd9cbb477232cc72d49a6f2713e157e090443ee6 via the fork AI-review pipeline; updated in place on each push.

5 of 5 blocking finding(s) are security-class and were withheld from adjudication, so the blocking verdict stands.

BLOCKING -- src/kiro_crew/apps/manager.py:1310 -- Preserved-data backup exposes sandbox-hidden credentials

shutil.copytree(str(dest / "data"), str(partial_backup))
Preserved data/loot links to the gateway signing key -> local reinstall dereferences it outside the sandbox -> the hook reads a regular-file copy of the credential.
Anchor: backend-security-controls
Fix: Preserve symlinks in the backup and prevent copying through directory junctions.

BLOCKING -- src/kiro_crew/apps/manager.py:1453 -- Post-hook sweep deletes a sibling app’s authentication secret

_remove_any_shape(dest / ".app_secret")
Successful onInstall renames its directory and links dest to a sibling app -> this sweep follows the parent link before identity rejection -> the sibling loses its secret and authentication fails.
Anchor: residual/crash-data-loss-corruption
Fix: Reject a symlink/junction at dest before any post-hook child-path operation, retaining the preserved-data backup.

BLOCKING -- src/kiro_crew/apps/lifecycle_scripts.py:136 -- Fast-exiting hook leaders escape process-group cleanup

pgid = platform_compat.posix_getpgid(proc.pid)
A redirected background manifest writer outlives a leader reaped before spawn returns -> group lookup fails and PID-based cleanup signals nothing -> the writer replaces the admitted manifest before registration.
Anchor: residual/security
Fix: Retain proc.pid as the process-group identity established by start_new_session=True, including when the leader has already exited.

BLOCKING -- src/kiro_crew/apps/manager.py:1482 -- Malformed post-hook manifests bypass failure restoration

except (OSError, ValueError) as exc:
Successful onInstall writes "crons": null -> the new manifest read raises TypeError in AppManifest.from_dict() -> install crashes without running the restoration branch.
Anchor: residual/crash-data-loss-corruption
Fix: Route malformed-field parsing exceptions, including TypeError, through the existing cleanup and failure-result branch.

BLOCKING -- test/test_app_oninstall_r1.py:346 -- Cancellation regression leaves child cleanup on the happy path

task = asyncio.create_task(run_lifecycle_script("cancel-app", script, timeout=30))
Readiness assertion fails before task.cancel() -> the test exits without independent teardown -> the shell and its infinite-loop child outlive the test.
Anchor: no-test-side-effects
Fix: Put task cancellation and independently addressed process-group termination in finally blocks around the real-process regressions.

FINDING -- src/kiro_crew/apps/manager.py:812 -- f".{path.name}..." adds a second leading dot to backup names, so generated crash copies evade retry and purge sweeps -> Fix: avoid prepending another dot when path.name already starts with one.

[BLOCK-MERGE] bd9cbb4
[GPT-REVIEWED] bd9cbb4

Adjudication (Opus 5.5) — is blocking on each finding proportionate?

F1: unbounded. manager.py:1310 (patch 766) shutil.copytree runs with its default symlinks=False, so it follows any symlink the app planted under data/. Fixing it means passing symlinks=True and rejecting junctions.
F2: unbounded. manager.py:1453 (patch 909) runs _remove_any_shape(dest / ".app_secret") with no check that dest itself is still a real directory after the hook ran. Fixing it means one is_symlink/junction check at dest before that sweep.
F3: unbounded. If the leader has already exited, lifecycle_scripts.py:136 (patch 308–315) swallows the OSError and leaves leader_pgid=None. On POSIX it then falls through to kill_process_tree_async(proc.pid) (patch 331) or does nothing (patch 338). Fixing it means defaulting to leader_pgid = proc.pid.
F4: unbounded. Confirmed: with "crons": null, the loop over crons_raw at manifest.py:2889-2890 raises TypeError. from_json_file (manifest.py:2979-2984) doesn't wrap it, and manager.py:1482 (patch 938) catches only (OSError, ValueError). Fixing it means adding TypeError to that tuple.
F5: The test leak needs only the readiness assert at test_app_oninstall_r1.py:346 (patch 3178) to fail. That assert has a 2s budget, which a loaded CI worker can plausibly miss. Fixing it means a try/finally around the test.

[ADJUDICATION] bd9cbb477232cc72d49a6f2713e157e090443ee6 total=0 uphold=0 downgrade=0
[GPT-ADJUDICATED] bd9cbb477232cc72d49a6f2713e157e090443ee6

[ADJUDICATION-FENCED] bd9cbb477232cc72d49a6f2713e157e090443ee6 fenced=5 flagged=0
UPHOLD-FENCED F1 src/kiro_crew/apps/manager.py:1310 -- copytree defaults to following symlinks and the app controls what is in data/, so pointing a link at a sandbox-hidden credential is a plausible attacker move, not an extreme one.
UPHOLD-FENCED F2 src/kiro_crew/apps/manager.py:1453 -- the hook can write to dest's parent, and nothing checks dest's shape before the .app_secret sweep, so swapping dest for a link to a sibling app is in reach of an ordinary malicious hook.
UPHOLD-FENCED F3 src/kiro_crew/apps/lifecycle_scripts.py:136 -- a hook that backgrounds a writer and exits at once is a common shell pattern, and the swallowed getpgid failure leaves POSIX cleanup without the group id.
UPHOLD-FENCED F4 src/kiro_crew/apps/manager.py:1482 -- confirmed: "crons": null raises TypeError at manifest.py:2890, which the (OSError, ValueError) catch misses, so the restore branch is skipped on an input the hook can easily write.
UPHOLD-FENCED F5 test/test_app_oninstall_r1.py:346 -- missing a 2s readiness budget on a loaded CI worker is plausible, and the process leak that follows is the side effect the no-test-side-effects rule exists to stop.
[GPT-ADJUDICATED-FENCED] bd9cbb477232cc72d49a6f2713e157e090443ee6

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Sep 14, 2026
@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review (fork) — ✅ no blocking findings

Reviewed bd9cbb477232cc72d49a6f2713e157e090443ee6 via the fork AI-review pipeline; updated in place on each push.

Review details

No findings.

[OPUS-REVIEWED] bd9cbb4

@atomsbaza
atomsbaza force-pushed the feat/app-oninstall-local branch from f523b70 to d6a15a3 Compare September 14, 2026 11:00
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 14, 2026
@atomsbaza
atomsbaza force-pushed the feat/app-oninstall-local branch from d6a15a3 to aa5ab82 Compare September 14, 2026 14:37
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 14, 2026
@atomsbaza
atomsbaza force-pushed the feat/app-oninstall-local branch from aa5ab82 to 19c659f Compare September 14, 2026 17:13
@atomsbaza

Copy link
Copy Markdown
Contributor Author
  • Local-install script execution — product-shape change without accepted RFC

Disposition: rebutted — the behavior change IS the request being fulfilled.

docs/app-kit/publishing-guide.md records the old shape, but the opposite behavior is not an internal design whim: #10583 is the tracked, open maintainer issue asking for exactly this (an app installed from a local folder arrives unable to start because its install hook never runs). Closing a tracked issue is the accepted-change record for a fix PR; the doc line is stale copy this PR supersedes, and the PR body states the behavior change explicitly so the doc update lands with review rather than as a rider.

The execution path reuses the registry's existing sandboxed hook machinery (wrap_argv sandbox + cgroup ceiling + the execution-policy gate + post-script identity/admission re-check) — not a new trust surface and no capability the registry path does not already run.

This PR deliberately does not rewrite the publishing guide in the same commit; if the maintainer wants the doc/RFC record updated first, that is a one-line ask and the PR will carry it.

@atomsbaza

Copy link
Copy Markdown
Contributor Author
  • Terminal-control stripping — second spelling of _ANSI_CSI_RE

Disposition: rebutted — the two matchers cover different classes and share no code path.

_ANSI_CSI_RE (instances/ssh_tunnel_manager.py) matches only CSI sequences, to sanitize a single tunnel-status line this repo itself renders. The new _TERMINAL_CONTROL_RE (apps/manager.py) matches CSI plus OSC plus bare ESC plus C0/DEL, because its input is captured stdout of THIRD-PARTY scripts, where OSC clipboard/title injection and raw C0 bytes are realistic payloads.

Collapsing them would either widen ssh_tunnel_manager's matcher beyond its need or narrow the app-output sanitizer below its threat model — the overlap is one regex family, not one mechanism. Both are pure string functions with no shared state, so the duplication cost is one pattern literal. Registered here as a class ruling: lifecycle-script-output sanitizers are a distinct mechanism from internal-tunnel-line sanitizers.

@atomsbaza

atomsbaza commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor Author
  • Failed re-enable / rollback state / install-failure findings on apps (symlink cleanup, descendant reap, exfil-URL redaction, stale snapshot, CLI re-enable)

Disposition: fixed

All five blocking findings on this head are fixed in head 19c659f: cleanup unlinks a symlink/junction dest before iterating (_remove_installed_tree_except_data); the script process group is tree-killed after wait on both success and failure so a descendant cannot rewrite app.json behind the re-admission check; both enable-response paths chain redact_exfiltration_urls after sanitize+redact_credentials; was_enabled/resources are re-derived from a get_app() re-fetch inside the lifecycle lock; and the CLI snapshots app_enabled_state before enable_app so a failed re-enable no longer disables an already-enabled app. Regression tests added for the symlink cleanup and the failed-re-enable path.

self-added: yes
mechanism: bounded-tail install-script capture + post-script re-admission + scoped enable rollback

@atomsbaza
atomsbaza force-pushed the feat/app-oninstall-local branch from 19c659f to 2ca714a Compare September 15, 2026 18:27
@atomsbaza

Copy link
Copy Markdown
Contributor Author
  • Reaped-leader straggler kill and post-onEnable manifest re-admission (F1 manager.py, F2 routes.py)

Disposition: fixed

Both blocking findings on head 19c659f are fixed in head 2ca714a. (F1) _run_install_script now captures the kill authority BEFORE any wait — the POSIX process-group id is pinned while the bash wrapper is alive (with the fork race handled: a pre-setsid capture falls back to the child's pid, which start_new_session guarantees is its own group leader) and the straggler kill goes through the new platform_compat.kill_pgid, which carries the same reserved/self-group broadcast guards as kill_process_tree; on Windows the leader's creation time is captured and killed via kill_process_tree_pinned. A regression test proves a backgrounded descendant no longer survives its reaped leader (and fails on the pre-fix code). (F2) The enable route now re-reads the app manifest after a successful onEnable, re-verifies name/version identity, and re-runs app_admission_denied(action="enable") BEFORE registration reads the rewritten manifest — a tampered, corrupted, or removed manifest rolls the enable back (backend stop, disable, deregister) and returns 400 on_enable_admission_denied, mirroring the install path's post-script re-admission. Tests cover identity swap, manifest destruction, policy denial, and the benign pass-through. The two non-blocking findings are also fixed: the security redaction imports are hoisted to top level, and the rollback comment now states the unconditional-disable behavior.

self-added: yes
mechanism: pre-wait kill-authority capture (pgid / pinned start time) + post-onEnable manifest re-read and re-admission

@github-actions github-actions Bot removed the readiness: action required A blocking check or review needs attention label Sep 15, 2026
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 24, 2026

@bolichen97 bolichen97 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Requesting changes: the new onEnable order and the Windows local-install failure are not documented

The First Principles review already covers the local-install onInstall reversal against manifest-reference.md:830,841-842 and publishing-guide.md:143,170-172. No comment yet raises the two effects below.

1. onEnable now runs before registration and backend start, but the docs still say it runs after.
In handle_enable_app the script now runs at src/kiro_crew/apps/routes.py:1632 (script_output = await _run_lifecycle_script(...)). Registration and start moved below it, to routes.py:1742-1744 (reg = await _register_app_off_loop(name) and then start_app_backend). On main the order is register, start, deps, then onEnable. At this head these docs are unchanged:

  • docs/app-kit/publishing-guide.md:145: onEnable runs "After resources are registered, the backend is started, and dependencies are resolved"
  • docs/system-specs/modules/app-kit-platform.md:177, the owning spec: Enable = "register resources, start backend, resolve dependencies, run onEnable"

Who is affected: execution-trusted third-party gateway apps whose onEnable was written for the documented order. These apps now run their script with no backend whenever none is already running: re-enabling after a disable, enabling after a CLI install, or enabling after a gateway restart that happened while the app was disabled. If the script fails, the enable is rolled back. The first dashboard enable right after an install still finds the backend the install started. No builtin app declares onEnable.
Fix: the reason for the change is already written in the comment at routes.py:1734-1740 (the npm install race). Update both docs in this commit, as AGENTS.md requires for the owning spec, and state the order change in the PR description.

2. On native Windows, a local install of an app that declares onInstall now always fails.
manager.py:1092 runs the hook for every non-registry install, through base_cmd = ["/bin/bash", "-c", safe_script] (manager.py:680). Without /bin/bash, either wrap_argv or the spawn fails. The copied tree is then removed (manager.py:1127) and the install returns on_install_failed, even when trust is granted. On main, install_app "only manages files", so the documented "build first, then install" workflow works on Windows. The new scripted-install tests in TestLocalInstallScript skip on Windows. Registry installs already fail this way, and publishing-guide.md:153-155 documents that for hooks, so this may be acceptable. But it should be a stated decision, not a side effect.
Fix: either skip the local-install hook on hosts where lifecycle scripts cannot run, or document the Windows failure in the corrected local-install docs.

From a full open-PR audit against origin/main c66f95b (2026-09-25); findings were checked by independent reviewers reading the code. Reply here if this is wrong.

@github-actions github-actions Bot added the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Sep 25, 2026
@atomsbaza
atomsbaza force-pushed the feat/app-oninstall-local branch from 5af977e to 367dc0b Compare September 26, 2026 18:50
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention merge conflict Branch has merge conflicts with its base — author must resolve before merge and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running merge conflict Branch has merge conflicts with its base — author must resolve before merge labels Sep 26, 2026
@atomsbaza
atomsbaza force-pushed the feat/app-oninstall-local branch from 367dc0b to b4c897e Compare September 27, 2026 09:16
@atomsbaza
atomsbaza requested a review from a team as a code owner September 27, 2026 09:16
@atomsbaza
atomsbaza requested review from cruisercohen and removed request for cixuuz September 27, 2026 09:16
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed merge conflict Branch has merge conflicts with its base — author must resolve before merge readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 27, 2026

Copy link
Copy Markdown
Contributor

Triage against origin/main a97659dfc3: this PR is still needed. On main, install_app still only copies files and never runs setup.onInstall. handle_enable_app still registers and starts the backend before onEnable, and the CLI enable does not run onEnable at all. Nothing merged covers it, so this should stay open.

Rebase needed. The branch is 1229 commits behind and conflicts in testing-conventions.md, security_posture.py, test_app_manager.py and test_security_posture.py. Since your last push, merged PRs have changed the same code:

The open blockers still apply at b4c897ef, and this comment does not replace them: the data/ backup at manager.py:1123 is swallowed and then restored anyway (Opus/GPT), and the doc order plus the Windows fail-closed behaviour still need addressing (bolichen97).

…on it

Local-directory app installs never executed the manifest's
setup.onInstall — only the registry path did — so a Node app
installed from a folder shipped without node_modules and its
backend could never start (kirodotdev#10583). install_app() now runs the
script sandboxed in the COPIED app dir, behind the same
app_execution_denied gate the registry path uses, and fails the
install closed (preserving any restored data/) when the script
fails, times out, or the sandbox is unavailable.

The dashboard enable route started the backend before onEnable
ran, so an onEnable that installs backend dependencies raced the
backend's first boot and lost; onEnable (and dependency
resolution) now complete before register/start_backend, and a
failing script rolls back before any backend process exists.

The CLI enable path skipped onEnable entirely, so the route's
behavior was unreachable from the terminal; it now mirrors the
route including the unsupported-OS skip and the client-install
advisory carve-out.

Fixes kirodotdev#10583

@dodgeblaster dodgeblaster left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stewarding review for #10583 (re-verified against origin/main @ 4d5cb477).

The bug this PR targets is real and still present on main. install_app() (now in src/kiro_crew/apps/manager_install.py:125, the entry for kirocrew app install <dir> and POST /api/apps/install) reads no setup/onInstall — git grep for onInstall|setup|run_lifecycle in that file returns nothing. The only execution site remains the registry path (src/kiro_crew/apps/registry_pipeline/install.py:838). The docs document the local skip as intended (docs/app-kit/manifest-reference.md:1008,1020; publishing-guide.md:169,197: "Not run for a local-path install; build first, then install"). So the behaviour the PR changes is a genuine, standing gap.

The approach direction is defensible. The PR runs onInstall on the local path behind the same app_execution_denied(action="install") gate the registry path uses, in the copied app dir (not the developer's source tree), fail-closed, and hardens write_app_secret (unlink-first + O_EXCL|O_NOFOLLOW) against the new "third-party code runs between gateway writes" exposure. That token_auth.py change strengthens rather than loosens the secret-write posture — the right instinct for this feature.

Why I am reviewing, not merging. This cannot land as-is, and the remaining decision is a maintainer's, not a worker's:

  1. It is a fork PR (atomsbaza, isCrossRepository: true), so I cannot push a rebase to the head branch and cannot merge it.
  2. It touches sensitive paths (src/kiro_crew/dashboard/token_auth.py, src/kiro_crew/security_posture.py). Sensitive Change Review is failing, which is structural for a fork PR touching those paths — by design, not a code defect. Clearing it requires a maintainer taking the change onto a branch of this repo (preserving authorship via Co-authored-by: + Supersedes #10599), running the real sandbox, and driving it green.
  3. It is CONFLICTING / DIRTY against current main — the author must rebase before anything else, and only the fork author can push that.
  4. CHANGES_REQUESTED stands (bolichen97, 2026-09-25) and is not cleared by anything a steward can do.
  5. The core design question #10583 was held on is still open for a maintainer: should a local-directory install run onInstall at all (the documented contract today is that it does not), and if so behind which execution gate and in which cwd? This PR answers "yes, behind the install execution policy, in the copied dir" — a reasonable answer, but the ruling is the maintainers' to make.

Recommendation. Keep #10583 open (the design decision + the maintainer takeover are not steward actions). If maintainers accept the "local installs run onInstall behind the install execution gate, in the copied app dir" direction, this PR is a strong starting point: take it over onto a repo branch, rebase onto current main, re-run the sensitive-path/sandbox gates, and address the open CHANGES_REQUESTED findings. Scope note matching the PR's own "Not a goal": onUpdate stays unexecuted and the onEnable-before-backend-start ordering is bundled in here — maintainers may want to confirm they want both in one change.

Steward review by a T1/T2 sweep worker. No push, no merge, no admin bypass — a fork PR touching sensitive paths needs a maintainer takeover.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork Pull request from a fork (external contributor) merge conflict Branch has merge conflicts with its base — author must resolve before merge needs-author-decision PR blocked on author input readiness: action required A blocking check or review needs attention

Projects

None yet

Development

Successfully merging this pull request may close these issues.

setup.onInstall command not executed during app installation

4 participants