# Package lifecycle: reuse, execute, fork, or create

Use this guide to decide whether to reuse existing behavior, explore with
`execute`, or create durable repo-backed package code. Use it before scheduling
new package behavior.

## Choose the smallest durable surface

### Invoke an existing package or capability

Search first. If a built-in capability or saved package already does the work,
invoke it instead of creating another implementation.

- Call discovered built-in capabilities through `kody` in `execute`.
- For a saved package export whose package name is known when the code is
  written, use a static `kody:@scope/package/export` import — the default for
  package reuse from `execute` and from other packages. Ad hoc execute bundles
  per call, so static imports from execute always see the current published
  version.
- When the target's name is data, use `import(specifier)` for a caller-owned or
  forked module. Exactly-once work uses workflows.

This is the default for an established operation whose behavior should stay
owned by its existing capability or package.

### Use `execute` for temporary one-off exploration

Use `execute` when the code is disposable: inspect an API response, test an
assumption, transform a small result, or run a one-time operation after any
required confirmation.

Keep the module focused and return structured evidence. Do not treat the
ephemeral module as the durable source for behavior that must be maintained,
reused, or evolved.

Ad hoc `execute` runs with the signed-in user's ambient authority: it can call
discovered capabilities through `kody`. A saved package is the
declared-authority unit. Secret mounts, host approval, integration allowlists,
and `kody.dependencies` are the request, and agents cannot widen those. Outbound
emissions (email, paid APIs, third-party writes) are not invertible; use a
package `dryRun` and fresh user confirmation before a live mutation.

### Fork a close public package before creating

Community listings are excluded from general `search`. When you need durable
reusable behavior and nothing in the user's account fits, call `communitySearch`
for a close public package.

If a listing is close to the user's goal:

1. Inspect it with `communityGet`.
2. Fork with `communityFork` (or point the user at one-click install on the
   listing detail page).
3. Review the forked source, adapt it to the user's intent (including human
   `README.md` / `## Intent` and agent `AGENTS.md`), then publish. Publish
   checks require both files.

Do not reimplement from scratch when a public package is already close. Create a
new package only when no suitable listing exists.

### Create a repo-backed package

Create or extend a saved package when behavior is reusable, expected to evolve,
or needs a named package-owned schedule that evolves with its implementation,
and no suitable community listing (or existing saved package) covers it. If the
implementation needs a library that does not fit a Worker isolate, keep this
package as the orchestrator and offload the heavy process — see
[Offload work that does not fit a Worker isolate](/docs/heavy-work-offload). The
repo rooted at `package.json` is the durable source of truth. Package exports
form the callable surface, while jobs, subscriptions, retrievers, and apps
remain package-owned behavior.

Recurring schedules belong on a saved package under `package.json#kody.jobs`.
Deferred one-shot work uses `workflows.create({ runAt })` from `execute` or
package runtime. See [Workflows](https://github.com/kentcdodds/kody/blob/main/docs/use/workflows.md).

Use `guide: "package_authoring"` for package shape, required `README.md` +
`AGENTS.md`, README `## Intent`, per-export JSDoc (search Purpose), visibility
guidance (personal-details hygiene before going public), and the secret-using
package approval checklist (`pending_secret_package_approvals` is non-null only
for unadopted community-forked packages; prefer `communityForkAdopt` after
review, or bulk approval URLs when present). Use `guide: "package_apps"` when
authoring or debugging a hosted package app, community fork of an app, or
session handoff. Use `guide: "platform_efficiency"` for the unique Dynamic
Worker day cost model (stated once; not copied into package docs).

When the OAuth token is coarser than the intended export — Gmail can send
whenever it can create a draft — publish a thin package that only performs the
allowed call, then lock it. Load `locked_gmail_drafts` for that pattern.

## Signals to escalate from `execute` to a package

Move the behavior into a package when one or more of these become true:

- the user will run it again or other package code should reuse it
- it needs a named package-owned schedule that should evolve with the
  implementation, or another durable surface such as a subscription, service,
  app, workflow entrypoint, or package-owned storage
- the logic needs tests, multiple files, dependencies, review, or version
  history
- inputs, output, error handling, or integration behavior will evolve
- a one-off script has already been copied, repaired, or rerun
- you are calling a third-party **product** API with raw integration auth
  helpers (`createAuthenticatedFetch` or equivalent) beyond a cheap smoke test —
  **integrations = auth; packages = how agents should call the product**. Search
  for an existing wrapper package first, then `communitySearch`, then fork or
  create a thin helpers package

Do not create a package merely to wrap one clear call to an existing capability
or package export. One-shot reminders and deferred work belong in workflows, not
a new package.

## Choose an authoring lane

### Git lane for coding agents

When a normal filesystem and git client are available:

1. Call `packageGetGitRemote`. For a new package, pass `create: true` and a new
   `kody_id`; for an existing package, omit `create`.
2. Run the returned setup commands and clone into a temporary directory. Those
   commands set local git `user.email` and `user.name` from `git_author` (the
   signed-in Kody account). Do not invent a git identity.
3. Edit and test through the normal local development loop.
4. Commit and push the package repository.
5. Publish the pushed head with `packagePublishExternalPush`.

This lane supports binary assets, multi-file changes, local tests, and normal
git review.

### Tool-only lane

Without local filesystem or git access:

1. Create the complete UTF-8 text package with `packageSave`, or inspect an
   existing package with `packageGet`.
2. Use `repoOpenSession`, `repoEditFiles`, `repoCommit`, and `repoRunChecks` for
   repo-backed edits and validation.
3. Publish with `repoPublishSession`.

If the work needs binary assets, broad refactors, or a substantial local
build/test loop, explain that it fits a coding-capable agent and confirm before
continuing in the tool-only lane.

## Test the scheduled wrapper before enabling its schedule

Scheduled behavior should not be its first real execution. Package job manifests
do not supply params to their entrypoints, so structure the package with:

- a shared implementation that accepts explicit input
- an optional callable export that passes representative input to that
  implementation
- a no-argument scheduled wrapper that loads its own current configuration and
  calls the same implementation

Make the no-argument scheduled wrapper callable through `package.json.exports`,
point the package job entry at that wrapper, and initially declare the
package-owned job with `"enabled": false`.

After package checks and publishing succeed:

1. Inspect the published package and export contracts.
2. Call the scheduled wrapper from authenticated `execute` with a static import
   and no extra arguments. This verifies the same no-input contract the
   scheduler uses.
3. Optionally invoke the underlying callable export with representative input:
   realistic field shapes, boundary values, and the same configuration
   references the wrapper will load. Never put plaintext secrets in params.
4. Validate the structured results and the intended durable or external effects.
   Exercise an expected failure path when the operation is risky.
5. Only then change the job to `"enabled": true`, publish again, and verify the
   package/job detail reflects the enabled schedule.

   Republishing a package whose job still says `"enabled": false` does not
   disable a job that is already running. Manifest `enabled` is the create-time
   default and can turn a job on; use `jobUpdate` (or a package pause/resume
   export) to turn one off. This keeps fleet-wide package publishes from
   silently stopping a sweeper that an operator already enabled.

Example test call:

```ts
import scheduledReport from 'kody:@kentcdodds/daily-report/scheduled-report'

export default async function main() {
	return await scheduledReport()
}
```

For exports that send messages, write remote records, charge accounts, or make
other external mutations, prefer a package-specific `dryRun` input. Implement it
so the export performs validation and returns a preview while skipping the
mutation. `dryRun` is a package contract, not an automatic Kody runtime flag;
test the dry-run path first.

Immediately before any live external mutation, obtain explicit user confirmation
that identifies the target and scope of the mutation. Do not infer confirmation
from an earlier request, a successful dry run, or the agent's own assessment.
After confirmation, perform only the confirmed call, then report the result.
Require fresh confirmation if the target or scope changes.

Keep the schedule disabled when representative testing is inconclusive,
credentials or host approval are missing, the result is unexpected, or the live
mutation has not been explicitly confirmed by the user.

## Delete a package

`packageDelete` permanently removes a saved package the signed-in user owns. Do
not call it because a package is unused, failing, or over quota unless the owner
explicitly asked to delete that package.

1. Load the package with `packageGet` or `packageList`.
2. Show the owner the package name and that delete removes jobs, storage,
   secrets, tokens, the public listing if one exists, and Artifacts repos.
   Existing forks keep their copies. This cannot be undone.
3. Wait for the owner to type the package name.
4. Call `packageDelete` with `package_id` and `confirm_name` matching that name
   exactly. The capability refuses and names the expected value when
   `confirm_name` is missing or wrong.

People can delete from `/@username/{kodyId}/settings`: choose **Delete
package**, then type the package name in the modal.

Hiding (`packageUpdate` `changes.hidden`) and making a package private are not
deletion.

## Evolve the durable behavior

For later changes, inspect the current repo, preserve the package's intent,
update tests and docs with the implementation, and repeat the disabled
schedule/export test when the scheduled path or its inputs change. Publish only
checked commits; do not patch generated runtime state as a substitute for
changing the package source.
