Organization project governance (inactive queries / batch deletion / restore)
Overview and use cases
A set of project lifecycle governance capabilities for organization Owner: query inactive projects in the organization, initiate delayed batch deletion after a dry run precheck, query projects in the deletion lifecycle, and restore projects still in the pending_purge state. Both 2.6.0's agentbase-web-sdk@2.8.0 and agentbase-node-sdk@2.8.0 include the corresponding methods (the Projects service for Web/Node); controlled integrations without an SDK can use the equivalent REST API.
Prerequisites
| Item | Description |
|---|---|
| Role | The current account must be an Owner of the target organization; ordinary organization members have no permission |
| Authentication | Owner Session (preferred for interactive use), short-term Owner JWT (preferred for automation, account.createJWT issuance, default 15 minutes); an Organization API Key is only an option when the target environment has been delivered and provides projects.read/projects.write |
| Client | Management-plane requests point to the Console project (setProject('console') or the environment's actual Console project ID) and setOrganization(teamId) declare the organization (X-Appwrite-Organization header) |
| Scope | Query-type operations (inactive list, deletion list) require projects.read; batch deletion and restore require projects.write |
An ordinary project API Key cannot substitute for organization-level credentials; the existence of an organization Key method in the SDK does not mean the target instance exposes the corresponding creation entry point. When a Key is unavailable, governance is not blocked—use Session / JWT instead.
Usage workflow
Fixed workflow (deletion is a high-risk operation; do not automate it into “query results deleted directly”):
Query candidates: use
Projects.listInactiveByOrganizationto page through inactive projects and verify them manually.Fixed list: the Owner explicitly selects 1–50 project IDs and the audit reason.
Dry run precheck:
batchReleaseByOrganization({ dryRun: true }), then verify each project'sresultsandsummary(accepted/rejected/skipped).Formal submission after second confirmation:
dryRun: false, with the same list and the same reason.Track the deletion lifecycle: use
listDeletionsByOrganizationto viewpending_purge/purging/purge_failedsorted bydeletedAtdescending.Restore (optional): re-read the latest state, confirm the target project is still
pending_purge, then have the Owner specify a singleprojectIdand callrestoreDeletionByOrganization; a successful restore clears deletion metadata.
Console equivalent entry point: the organization “Project Cleanup” page <console-origin>/console/organization-{organizationId}/project-cleanup; the Console directly submits formal deletion (showing all accepted / partially accepted / rejected with a failure summary). Use the SDK / REST when per-project precheck results are needed.
Key parameters and returns
Method and REST mapping
| Operation | REST | Scope |
|---|---|---|
| Query inactive projects | GET /v1/teams/{teamId}/projects/inactive | projects.read |
| Precheck / batch delete | POST /v1/teams/{teamId}/projects/batch-release | projects.write |
| Query deletion lifecycle | GET /v1/teams/{teamId}/projects/deletions | projects.read |
| Restore pending-deletion project | DELETE /v1/teams/{teamId}/projects/{projectId}/deletion | projects.write |
The corresponding SDK methods are described in the operation sections below; they all belong to the Projects service of the Web/Node SDK.
Parameter essentials
All methods must pass teamId, whose value is the canonical Team ID corresponding to the organization; the Console-exposed organizationId cannot be used directly. The table below lists only the other parameters of each method, with each marked individually as required or not.
Inactive project query parameters
Method to call: Projects.listInactiveByOrganization.
| Parameter | Required | Description |
|---|---|---|
inactiveDays | Yes | Inactivity time threshold, range 1–365 days. |
graceDays | No | Grace period after project creation, default 7 days. |
limit | No | Items per page, range 1–500, default 100. |
cursor | No | When continuing to the next page, pass back the previous page's nextCursor as-is. |
Only configure the parameters above; do not pass filters such as criteria, signals, or preset. The response returns candidate projects and pagination info; for activity determination and the meaning of total, see “Response and activity semantics” below.
Precheck and batch deletion parameters
Method to call: Projects.batchReleaseByOrganization.
| Parameter | Required | Description |
|---|---|---|
projectIds | Yes | Array of project IDs, 1–50 per call, using the Owner-confirmed fixed list. |
dryRun | No | Pass true for precheck, false for formal submission. This page's workflow requires explicitly passing the value each time—precheck first, then submit after confirmation. |
reason | No | Audit reason, filled in per the workflow above; use the same reason for both precheck and formal submission. |
The response contains the request ID requestId, per-project results results, and a summary summary. The summary distinguishes accepted, rejected, and skipped; do not assume all projects were accepted just because the request succeeded.
Deletion lifecycle query parameters
Method to call: Projects.listDeletionsByOrganization.
| Parameter | Required | Description |
|---|---|---|
limit | No | Items per page, range 1–100, default 25. |
offset | No | Pagination offset. |
Returns the list of projects in the deletion lifecycle. Projects in the list are not necessarily restorable; their deletionStatus must be checked.
Pending-deletion project restore parameters
Method to call: Projects.restoreDeletionByOrganization.
| Parameter | Required | Description |
|---|---|---|
projectId | Yes | A single project explicitly specified by the Owner; its current state must be pending_purge. |
On success, status is restored and includes projectId and requestId.
Response and activity semantics
Inactivity determination uniformly uses the project document's
accessedAt(real project-level API requests, custom-domain requests resolved via routing, and real workloads such as Function executions / data source syncs / scheduled messages update it;/healthand routine maintenance scans do not). Writes have a merge window of about 24 hours; determination adds an equivalent safety margin on top ofinactiveDays; whenaccessedAtis absent,$createdAtis used as the baseline.The response contains
inactiveDays,projects[],total,scanned, andnextCursorwhen a next page exists;totalis the number of matches found by this bounded scan (each request scans at most 50 projects), not an organization-level exact total. Each candidate project carrieslastResourceActivityAt,inactiveSince, and more.Deletion list items contain
projectId,name,teamId,deletionStatus,deletedAt,purgeAt, and possibly absentdeletedBy,reason,requestId,error.
Errors and boundaries
teamIdmust be a canonical Team ID;setOrganization()/X-Appwrite-Organizationalso use that value. The Console-exposed organizationId cannot be used directly asteamId.Only
pending_purgeprojects are restorable;purging,purge_failed, or projects still normally active return 409; a nonexistent project or one not belonging to the current organization returns 404 (to prevent cross-organization enumeration).Restore is not a batch post-processing of the list API: each call restores only the single project explicitly specified by the Owner.
consoleprojects and projects already in the deletion lifecycle do not appear among inactive candidates.Formal submission distinguishes fully accepted, partially accepted, and fully rejected;
purge_faileditems remain in the deletion list with a failure summary.Do not automatically delete or restore based on dynamic query results; the dry run and the second confirmation are mandatory steps in the workflow.
SDK Category Differences
Web Client SDK: use an Owner Session in the browser; after
new Client().setEndpoint(...).setProject('console').setOrganization(teamId), call the four methods vianew Projects(client); do not place any organization Key.Node Server SDK: for short-term scripts use
account.createEmailPasswordSessionthenclient.setSession(session.secret).setOrganization(teamId), orsetJWT(...); in CI use a short-term Owner JWT.Console SDK: this capability is not exposed via Console SDK methods (the Console provides an equivalent page).
Java (Server/Console): the
Projectsclasses ofio.agentbase/io.agentbase.consolecontain the same four methods (listInactiveByOrganizationetc.); authentication andsetOrganizationusage are as above.
Examples by language
The following provides examples by language, item by item along the usage workflow; each card can switch languages (synced across the page).
Query inactive projects
listInactiveByOrganization Page through candidates, verify manually, then fix the list.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
const { Account, Client, Projects } = require('agentbase-node-sdk');
const teamId = process.env.APPBASE_ORGANIZATION_TEAM_ID; // canonical Team ID
const client = new Client()
.setEndpoint(process.env.APPBASE_ENDPOINT)
.setProject(process.env.APPWRITE_CONSOLE_PROJECT_ID || 'console'); // Management plane points to a Console project
const account = new Account(client);
const session = await account.createEmailPasswordSession({ // The current account must be the organization Owner
email: process.env.APPBASE_OWNER_EMAIL,
password: process.env.APPBASE_OWNER_PASSWORD
});
client.setSession(session.secret).setOrganization(teamId); // or setJWT(shortLivedOwnerJwt)
const projects = new Projects(client);
const page = await projects.listInactiveByOrganization({
teamId,
inactiveDays: 90, // Required, 1-365
graceDays: 7, // Optional, default 7
limit: 50 // Optional, 1-500, default 100
// cursor: pass back the previous page's nextCursor as-is
});
// page: { inactiveDays, projects[], total, scanned, nextCursor? }
// total is the match count of this bounded scan (at most 50 projects scanned per request), not the organization-level exact totalimport { Client, Projects } from 'agentbase-web-sdk'; // In-browser Owner Session; never place organization keys there
const teamId = 'canonical-team-id';
const organizationClient = new Client()
.setEndpoint(import.meta.env.VITE_APPBASE_ENDPOINT)
.setProject(import.meta.env.VITE_APPWRITE_CONSOLE_PROJECT_ID || 'console')
.setOrganization(teamId);
const projects = new Projects(organizationClient);
const candidates = await projects.listInactiveByOrganization({ teamId, inactiveDays: 90 });import io.agentbase.services.Projects;
// client is io.agentbase.Client: after setProject('console'), authenticate with an Owner Session / short-lived Owner JWT (setSession / setJWT),
// And call client.setOrganization(teamId) to declare the organization (X-Appwrite-Organization)
Projects projects = new Projects(client);
var page = projects.listInactiveByOrganization(
teamId,
90L, // Required, 1-365
7L, // Optional, default 7
50L, // Optional, 1-500, default 100
null); // cursor: pass back the previous page's nextCursor as-is
// page: { inactiveDays, projects[], total, scanned, nextCursor? }; total is the number of matches from the bounded scan, not an exact organization-wide totalfrom agentbase.services.projects import Projects
# client is a Server SDK Client: call set_project('console') then use Owner Session / short-lived Owner JWT (set_session / set_jwt),
# And call client.set_organization(team_id) to declare the organization (X-Appwrite-Organization)
projects = Projects(client)
page = projects.list_inactive_by_organization(
team_id=team_id,
inactive_days=90, # Required, 1-365
grace_days=7, # Optional, default 7
limit=50, # Optional, 1-500, default 100; pass the previous page's nextCursor as cursor verbatim
)
# page: { inactiveDays, projects[], total, scanned, nextCursor? }; total is the number of matches from the bounded scan, not an exact organization-wide totalprojects := agentbase.NewProjects(cl) // facade constructor; cl points to a Console project, with Owner credentials loaded via WithSession/WithJWT and the organization via WithOrganization(teamId)
page, err := projects.ListInactiveByOrganization(teamId, 90,
projects.WithListInactiveByOrganizationGraceDays(7), // Optional, default 7
projects.WithListInactiveByOrganizationLimit(50)) // Optional, 1-500, default 100; for Cursor, pass back the previous page's NextCursor as-is
// page: { InactiveDays, Projects[], Total, Scanned, NextCursor? }; InactiveDays is passed positionally, while GraceDays / Limit / Cursor use WithListInactiveByOrganization*curl -sS --get "$APPBASE_ENDPOINT/teams/$APPBASE_ORGANIZATION_TEAM_ID/projects/inactive" \
-H 'X-Appwrite-Project: console' \
-H "X-Appwrite-JWT: $APPBASE_OWNER_JWT" \
-H "X-Appwrite-Organization: $APPBASE_ORGANIZATION_TEAM_ID" \
--data-urlencode 'inactiveDays=90' \
--data-urlencode 'graceDays=7' \
--data-urlencode 'limit=50'
# In environments where an Organization Key has been delivered, you can switch to -H "X-Appwrite-Key: $APPBASE_ORGANIZATION_API_KEY" (X-Appwrite-Organization must still be kept)Dry run precheck and batch deletion
batchReleaseByOrganization: the Owner fixes 1–50 project IDs and an audit reason, first dryRun: true, then after second confirmation dryRun: false.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
// For client / projects initialization, see the previous card; projectIds is a fixed list scoped by the Owner (1-50 items), not selected directly in full from query results
const fixedProjectIds = ['project-a', 'project-b'];
const reason = '长期无资源活动,业务负责人已确认';
const preview = await projects.batchReleaseByOrganization({
teamId, projectIds: fixedProjectIds, dryRun: true, reason
});
// preview: { requestId, results[], summary: { accepted, rejected, skipped } }
if (preview.summary.rejected > 0 || preview.summary.skipped > 0) {
throw new Error('预检未全部通过,重新核对固定清单');
}
const submitted = await projects.batchReleaseByOrganization({
teamId, projectIds: fixedProjectIds, dryRun: false, reason // After secondary confirmation, formally submit the same checklist
});const preview = await projects.batchReleaseByOrganization({
teamId,
projectIds: candidates.projects.map((project) => project.projectId),
dryRun: true,
reason: '长期无资源活动,业务负责人已确认'
}); // The formal submission likewise calls with the fixed manifest + dryRun: false; the flow is the same as the Node tab// For projects / client construction see the previous card; projectIds is a fixed list scoped by the Owner (1-50 items), not selected wholesale from query results
var preview = projects.batchReleaseByOrganization(
teamId,
List.of("project-a", "project-b"),
true, // dryRun
"长期无资源活动,业务负责人已确认"); // reason
// preview: { requestId, results[], summary: { accepted, rejected, skipped } }
// If preflight does not fully pass, re-verify the fixed list; once passed and double-confirmed: same list, same reason, set dryRun to false for the formal submission# see previous card for projects / client construction; project_ids is a fixed list curated by the Owner (1-50 items), not a direct full selection from query results
preview = projects.batch_release_by_organization(
team_id=team_id,
project_ids=['project-a', 'project-b'],
dry_run=True,
reason='长期无资源活动,业务负责人已确认')
# preview: { requestId, results[], summary: { accepted, rejected, skipped } }
# If not all prechecks pass, recheck the fixed checklist; after passing and double confirmation: same checklist, same reason, submit formally with dry_run=False// For projects / cl construction see the previous card; projectIds is a fixed list scoped by the Owner (1-50 items), not selected wholesale from query results
preview, err := projects.BatchReleaseByOrganization(teamId, []string{"project-a", "project-b"},
projects.WithBatchReleaseByOrganizationDryRun(true),
projects.WithBatchReleaseByOrganizationReason("长期无资源活动,业务负责人已确认"))
// preview: { RequestId, Results[], Summary{Accepted, Rejected, Skipped} }
// If preflight does not fully pass, re-verify the fixed list; once passed and double-confirmed: same list, same reason, set DryRun to false for the formal submissioncurl -sS -X POST "$APPBASE_ENDPOINT/teams/$APPBASE_ORGANIZATION_TEAM_ID/projects/batch-release" \
-H 'X-Appwrite-Project: console' \
-H "X-Appwrite-JWT: $APPBASE_OWNER_JWT" \
-H "X-Appwrite-Organization: $APPBASE_ORGANIZATION_TEAM_ID" \
-H 'Content-Type: application/json' \
-d '{"projectIds":["project-a","project-b"],"dryRun":true,"reason":"长期无资源活动,业务负责人已确认"}'
# After prechecks pass and double confirmation: same checklist, same reason, formally submit with dryRun set to falseDeletion lifecycle and restore
listDeletionsByOrganization View pending_purge / purging / purge_failed sorted by deletedAt descending; only pending_purge items can be restored by the Owner specifying a single project.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
// For client / projects initialization, see the first card
const deletions = await projects.listDeletionsByOrganization({ teamId, limit: 25, offset: 0 });
// deletions.projects[]: { projectId, name, teamId, deletionStatus, deletedAt, purgeAt, ... }
const selectedProjectId = 'project-id-confirmed-by-owner'; // Owner must be specified explicitly; do not auto-select the first in the list
const selected = deletions.projects.find((p) => p.projectId === selectedProjectId);
if (!selected || selected.deletionStatus !== 'pending_purge') {
throw new Error('指定项目不在当前页,或已不可恢复');
}
const restored = await projects.restoreDeletionByOrganization({ teamId, projectId: selectedProjectId });
// On success returns { status: 'restored', projectId, requestId }; 409 means the status has changed — re-query instead of retryingconst deletions = await projects.listDeletionsByOrganization({ teamId, limit: 25, offset: 0 });
const selected = deletions.projects.find(
(project) => project.projectId === 'project-id-confirmed-by-owner'
);
if (!selected || selected.deletionStatus !== 'pending_purge') {
throw new Error('Owner 指定的项目不存在于当前页,或已不可恢复');
}
await projects.restoreDeletionByOrganization({ teamId, projectId: selected.projectId });var deletions = projects.listDeletionsByOrganization(teamId, 25L, 0L);
// deletions.projects[]: { projectId, name, teamId, deletionStatus, deletedAt, purgeAt, ... }
// Owner explicitly specifies a single project (do not auto-select the first in the list); re-read and confirm it is still pending_purge before restoring
var restored = projects.restoreDeletionByOrganization(teamId, "<projectId>");
// On success returns { status: 'restored', projectId, requestId }; 409 means the status has changed — re-query instead of retryingdeletions = projects.list_deletions_by_organization(team_id=team_id, limit=25, offset=0)
# deletions.projects[]: { projectId, name, teamId, deletionStatus, deletedAt, purgeAt, ... }
# Owner explicitly specifies a single project (do not auto-select the first in the list); re-read and confirm it is still pending_purge before restoring
restored = projects.restore_deletion_by_organization(team_id=team_id, project_id='<projectId>')
# On success returns { status: 'restored', projectId, requestId }; 409 means the status has changed — re-query instead of retryingdeletions, err := projects.ListDeletionsByOrganization(teamId,
projects.WithListDeletionsByOrganizationLimit(25),
projects.WithListDeletionsByOrganizationOffset(0))
// deletions.Projects[]: { ProjectId, Name, TeamId, DeletionStatus, DeletedAt, PurgeAt, ... }
// Owner explicitly specifies a single project (do not auto-select the first in the list); re-read and confirm it is still pending_purge before restoring
restored, err := projects.RestoreDeletionByOrganization(teamId, "<projectId>")
// On success returns { Status: "restored", ProjectId, RequestId }; 409 means the state has changed — re-query instead of retrying# Query the deletion lifecycle (deletedAt descending)
curl -sS --get "$APPBASE_ENDPOINT/teams/$APPBASE_ORGANIZATION_TEAM_ID/projects/deletions" \
-H 'X-Appwrite-Project: console' \
-H "X-Appwrite-JWT: $APPBASE_OWNER_JWT" \
-H "X-Appwrite-Organization: $APPBASE_ORGANIZATION_TEAM_ID" \
--data-urlencode 'limit=25' \
--data-urlencode 'offset=0'
# Restore: after confirming status is still pending_purge, the Owner specifies a single project
curl -sS -X DELETE "$APPBASE_ENDPOINT/teams/$APPBASE_ORGANIZATION_TEAM_ID/projects/$APPBASE_PROJECT_ID_TO_RESTORE/deletion" \
-H 'X-Appwrite-Project: console' \
-H "X-Appwrite-JWT: $APPBASE_OWNER_JWT" \
-H "X-Appwrite-Organization: $APPBASE_ORGANIZATION_TEAM_ID"Example Guide
Code examples by language are gathered in the language tree
examples/; complete code sequences for the pagination loop, dry run→confirmation→submission, and pre-restore state re-checking are inskills/ob-agentbase/references/project-inactivity-cleanup.md.