From 2272a37e9e8763dae756a08d6280dc93768d38e6 Mon Sep 17 00:00:00 2001 From: Ted H Date: Thu, 15 Oct 2026 09:33:02 -0400 Subject: [PATCH 1/2] fix: preserve complete storefront catalog with paginated preview --- README.md | 10 +- contracts.lock.json | 8 +- packages/storefront-sdk/index.mjs | 12 +- scripts/freedom.mjs | 3 + scripts/verify-contracts.mjs | 26 +- tests/storefront.test.mjs | 47 +- vendor/freedom-platform/bundle.json | 24 +- vendor/freedom-platform/client.d.mts | 73 +-- vendor/freedom-platform/client.mjs | 24 +- vendor/freedom-platform/metadata.json | 5 +- vendor/freedom-platform/openapi.json | 203 ++++++- vendor/freedom-platform/protocol.mjs | 172 +++++- vendor/freedom-tooling/governance/README.md | 252 ++++++++ .../schemas/coding-context.schema.json | 176 ++++++ .../schemas/contract-pin-v1.schema.json | 42 ++ .../schemas/contract-pin-v2.schema.json | 105 ++++ .../governance/schemas/module.schema.json | 193 ++++++ .../schemas/release-proof.schema.json | 47 ++ .../schemas/release-set.schema.json | 269 ++++++++ .../schemas/release-trust.schema.json | 149 +++++ .../schemas/verifier-report.schema.json | 336 ++++++++++ .../packages/contribution-tools/cli.mjs | 74 +++ .../contribution-tools/consumer-libraries.mjs | 53 +- .../packages/contribution-tools/context.mjs | 322 ++++++++++ .../packages/contribution-tools/contracts.mjs | 213 +++++++ .../packages/contribution-tools/formats.mjs | 18 + .../contribution-tools/local-artifacts.mjs | 60 ++ .../packages/contribution-tools/pin-cli.mjs | 19 + .../contribution-tools/pinned-suites.mjs | 72 +++ .../repository-identity.mjs | 23 + .../contribution-tools/runtime-databases.mjs | 209 +++++++ .../runtime-file-weights.mjs | 328 ++++++++++ .../contribution-tools/runtime-suites.mjs | 75 +++ .../packages/contribution-tools/schema.mjs | 45 ++ .../contribution-tools/suite-runner.mjs | 574 ++++++++++++++++++ .../test-failure-diagnostic.mjs | 101 +++ .../contribution-tools/test-reporter.mjs | 122 ++++ .../packages/contribution-tools/verify.mjs | 60 ++ .../packages/contribution-tools/workspace.mjs | 72 +++ 39 files changed, 4505 insertions(+), 111 deletions(-) create mode 100644 scripts/freedom.mjs create mode 100644 vendor/freedom-tooling/governance/README.md create mode 100644 vendor/freedom-tooling/governance/schemas/coding-context.schema.json create mode 100644 vendor/freedom-tooling/governance/schemas/contract-pin-v1.schema.json create mode 100644 vendor/freedom-tooling/governance/schemas/contract-pin-v2.schema.json create mode 100644 vendor/freedom-tooling/governance/schemas/module.schema.json create mode 100644 vendor/freedom-tooling/governance/schemas/release-proof.schema.json create mode 100644 vendor/freedom-tooling/governance/schemas/release-set.schema.json create mode 100644 vendor/freedom-tooling/governance/schemas/release-trust.schema.json create mode 100644 vendor/freedom-tooling/governance/schemas/verifier-report.schema.json create mode 100644 vendor/freedom-tooling/packages/contribution-tools/cli.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/context.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/contracts.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/formats.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/local-artifacts.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/pin-cli.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/pinned-suites.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/repository-identity.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/runtime-databases.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/runtime-file-weights.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/runtime-suites.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/schema.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/suite-runner.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/test-failure-diagnostic.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/test-reporter.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/verify.mjs create mode 100644 vendor/freedom-tooling/packages/contribution-tools/workspace.mjs diff --git a/README.md b/README.md index 6783da3..05fe5aa 100644 --- a/README.md +++ b/README.md @@ -108,13 +108,15 @@ await requestSupply(client, listing, { idempotencyKey: supplyIntentKey }); | SDK 函式 | 共用 operation ID | 一致性 | | --- | --- | --- | -| `loadStorefront` | `listCatalog`, `listStores`, `listListings` | 從目前 session 讀取;依 storeId 篩選並排除不屬於已回傳商店的選品 | +| `loadStorefront` | `listCatalog`, `listStores`, `listListings` | 從目前 session 讀取;目錄依 `next_offset` 每頁最多 50 筆讀完,依 storeId 篩選並排除不屬於已回傳商店的選品 | | `createStore` | `createStore` | 明確傳入 idempotency key | | `selectProduct` | `createListing` | 保存 exact offer version;明確傳入 idempotency key | | `requestSupply` | `requestSupply` | 傳送 listing ID、已審閱 snapshot digest、aggregate version 與相同重試 key | API 驗證真正的使用者/社群/商店所有權。SDK 的篩選只是避免版面誤混資料,不是新的授權邊界。API 的拒絕、衝突與錯誤原樣交回 caller;SDK 不自動重試或生成新命令身分。版本衝突後重新讀取並讓人確認,新的操作才使用新 key。 +目錄讀取到 `next_offset: null` 才回傳完整工作區;後續任何一頁失敗,整次讀取會失敗,不把已取得的前幾頁當成完整目錄。空目錄仍正常回傳。使用更新後的 pinned client 核對平台協定,不略過版本相容性檢查。 + 供貨量是 snapshot 記錄,沒有庫存保留;`accepted` 是內部供貨演練確認,沒有代表完成正式簽署、QC 或可收款。所有目前顯示金額遵循中央契約的 1/100 單位。 ## 後續公開商店 @@ -132,12 +134,12 @@ import { loadConnectedStorefront } from './src/index.mjs'; const workspace = await loadConnectedStorefront({ origin: 'https://freetwai.com', token }); ``` -The token comes from the existing member-approved connection and must stay outside the repository. The existing session-based SDK and preview v1 bundle are unchanged. `consumer-libraries.lock.json` pins this new shared library separately; it is source provenance, not release approval or complete runtime coverage. Verify against an independently selected source SHA: +The token comes from the existing member-approved connection and must stay outside the repository. The session-based SDK uses its separately pinned preview bundle; `consumer-libraries.lock.json` preserves the shared read library's independent source pin. This is source provenance, not release approval or complete runtime coverage. Verify against an independently selected source SHA: ```sh -node scripts/verify-consumer-libraries.mjs FreeTWAI-AI/freedom-storefront EXPECTED_PLATFORM_SHA --source-root /path/to/freedom-platform +node scripts/verify-consumer-libraries.mjs FreeTWAI/freedom-storefront EXPECTED_PLATFORM_SHA --source-root /path/to/freedom-platform ``` -The repository argument is the historical provenance identity required by this pinned verifier and `consumer-libraries.lock.json`. Current GitHub and clone URLs use `FreeTWAI`. +The verifier accepts the current `FreeTWAI` repository identity while preserving the historical identity recorded in the library lock. Use that library's independently selected source SHA, not the preview bundle's source SHA. After the exact source commit is publicly available, use `--remote` instead of `--source-root /path/to/freedom-platform`. diff --git a/contracts.lock.json b/contracts.lock.json index 239919a..1a111f3 100644 --- a/contracts.lock.json +++ b/contracts.lock.json @@ -1,9 +1,9 @@ { "format": "freedom.contract-pin/v1", - "source_repository": "FreeTWAI-AI/freedom-platform", - "source_commit": "b221d2ba1bcf014dc785e95212455ba6f157ec6d", + "source_repository": "FreeTWAI/freedom-platform", + "source_commit": "1b1c3c111311659a64ab83fb4ea5683089b10560", "bundle_path": "contracts/preview/v1", "protocol": "freedom.preview/v1", - "protocol_sha256": "fe2ee45447f4a5e92c10e22307dee3b380d028acca04bac5278d3aeca0da7b3e", - "bundle_sha256": "835e9a898d3c10eaabd16c92cfeb25eae050f658814da3aec055f019a7245d3d" + "protocol_sha256": "41378c3b723f739cefdf8c53a82238b1e5d69cc13cdbf63b33a80d8080c807b2", + "bundle_sha256": "5272d0e15073dda83e9811f116a8f0c538bd843a7b0f56baccacc4a416eee19f" } diff --git a/packages/storefront-sdk/index.mjs b/packages/storefront-sdk/index.mjs index 550cff1..0aa2f3f 100644 --- a/packages/storefront-sdk/index.mjs +++ b/packages/storefront-sdk/index.mjs @@ -23,15 +23,23 @@ export async function loadStorefront(client, { storeId } = {}) { port(client); if (storeId !== undefined && (typeof storeId !== 'string' || !storeId.trim())) throw new TypeError('storeId must be a non-empty string.'); const [catalogResponse, storesResponse, listingsResponse] = await Promise.all([ - client.call('listCatalog'), client.call('listStores'), client.call('listListings'), + client.call('listCatalog', { query: { limit: 50, offset: 0 } }), client.call('listStores'), client.call('listListings'), ]); - const catalog = rows(catalogResponse, 'listCatalog'); + const catalog = [...rows(catalogResponse, 'listCatalog')]; const availableStores = rows(storesResponse, 'listStores'); const availableListings = rows(listingsResponse, 'listListings'); const stores = storeId === undefined ? availableStores : availableStores.filter(store => store.store_id === storeId); if (storeId !== undefined && stores.length !== 1) throw new Error('Requested store is unavailable in the current authenticated workspace.'); const visibleStoreIds = new Set(stores.map(store => store.store_id)); const listings = availableListings.filter(listing => visibleStoreIds.has(listing.store_id)); + let page = catalogResponse, offset = 0; + while (page.next_offset !== null) { + const nextOffset = page.next_offset; + if (!Number.isSafeInteger(nextOffset) || nextOffset <= offset) throw new TypeError('listCatalog returned an invalid next_offset.'); + page = await client.call('listCatalog', { query: { limit: 50, offset: nextOffset } }); + catalog.push(...rows(page, 'listCatalog')); + offset = nextOffset; + } return structuredClone({ schema_version: '1', mode: 'internal_preview', generated_at: new Date().toISOString(), store_id: storeId ?? null, catalog, stores, listings, diff --git a/scripts/freedom.mjs b/scripts/freedom.mjs new file mode 100644 index 0000000..25716c8 --- /dev/null +++ b/scripts/freedom.mjs @@ -0,0 +1,3 @@ +// Thin consumer entrypoint; implementation is exported from the central repo. +import { runFreedomCli } from '../vendor/freedom-tooling/packages/contribution-tools/cli.mjs'; +process.exitCode = await runFreedomCli(); diff --git a/scripts/verify-contracts.mjs b/scripts/verify-contracts.mjs index 514fb27..eaca808 100644 --- a/scripts/verify-contracts.mjs +++ b/scripts/verify-contracts.mjs @@ -1,23 +1,3 @@ -// Copied verifier, no writes. Contract authoring stays in freedom-platform. -import {readFile,readdir,lstat} from 'node:fs/promises'; -import {createHash} from 'node:crypto'; -import {resolve} from 'node:path'; -const root=process.cwd(),vendor=resolve(root,'vendor/freedom-platform'); -const lock=JSON.parse(await readFile(resolve(root,'contracts.lock.json'),'utf8')); -const hash=data=>createHash('sha256').update(data).digest('hex'); -if(!['FreeTWAI-AI/freedom-platform','FreeTWAI/freedom-platform'].includes(lock.source_repository)||!/^[a-f0-9]{40}$/.test(lock.source_commit)||lock.bundle_path!=='contracts/preview/v1')throw Error('Invalid canonical contract source'); -const manifestBytes=await readFile(resolve(vendor,'bundle.json')); -if(hash(manifestBytes)!==lock.bundle_sha256)throw Error('Contract bundle digest differs from lock'); -const bundle=JSON.parse(manifestBytes);if(bundle.protocol!==lock.protocol||bundle.protocol_sha256!==lock.protocol_sha256)throw Error('Protocol identity differs from lock'); -const expected=new Set(['bundle.json',...Object.keys(bundle.files)]); -async function walk(dir,prefix=''){for(const item of await readdir(dir,{withFileTypes:true})){const rel=prefix+item.name;if(item.isSymbolicLink())throw Error('Symlink not allowed in bundle');if(item.isDirectory())await walk(resolve(dir,item.name),rel+'/');else if(!expected.has(rel))throw Error(`Unexpected bundle file ${rel}`);}} -await walk(vendor); -const remote=process.argv.includes('--remote'); -for(const file of expected){ - if(file.split('/').some(p=>!p||p==='.'||p==='..')||!/^[-a-zA-Z0-9_./]+$/.test(file))throw Error('Invalid artifact path'); - const path=resolve(vendor,file);if(!(await lstat(path)).isFile())throw Error('Artifact must be a regular file'); - const local=await readFile(path);const declared=file==='bundle.json'?{sha256:lock.bundle_sha256}:bundle.files[file]; - if(hash(local)!==declared.sha256||(declared.bytes!==undefined&&local.byteLength!==declared.bytes))throw Error(`Modified canonical artifact ${file}`); - if(remote){const url=`https://raw.githubusercontent.com/FreeTWAI/freedom-platform/${lock.source_commit}/${lock.bundle_path}/${file}`;const response=await fetch(url,{redirect:'error',signal:AbortSignal.timeout(20000)});if(!response.ok)throw Error(`Cannot verify pinned artifact ${file}: ${response.status}`);const bytes=new Uint8Array(await response.arrayBuffer());if(bytes.byteLength>2_000_000||hash(bytes)!==declared.sha256)throw Error(`Pinned upstream differs: ${file}`);} -} -console.log(`Contract ${lock.protocol} at ${lock.source_commit.slice(0,12)}: ${expected.size} artifacts verified${remote?' against pinned GitHub source':''}.`); +// Consumer entrypoint; exported together with the central tooling, not a forked verifier. +import { runPinCli } from '../vendor/freedom-tooling/packages/contribution-tools/pin-cli.mjs'; +process.exitCode = await runPinCli(); diff --git a/tests/storefront.test.mjs b/tests/storefront.test.mjs index 9a51673..f2389f7 100644 --- a/tests/storefront.test.mjs +++ b/tests/storefront.test.mjs @@ -4,7 +4,7 @@ import { loadStorefront, createStore, selectProduct, requestSupply } from '../pa function workspace() { const data = { - listCatalog: { items: [{ product_id: 'product-a', current_offer: { offer_version_id: 'offer-v2' } }] }, + listCatalog: { items: [{ product_id: 'product-a', current_offer: { offer_version_id: 'offer-v2' } }], next_offset: null }, listStores: { items: [{ store_id: 'store-a' }, { store_id: 'store-b' }] }, listListings: { items: [{ listing_id: 'a', store_id: 'store-a' }, { listing_id: 'b', store_id: 'store-b' }, { listing_id: 'foreign', store_id: 'foreign-store' }] }, }; @@ -31,6 +31,51 @@ test('workspace without selection includes only listings attached to returned st assert.deepEqual((await loadStorefront(client)).listings.map(row => row.listing_id), ['a', 'b']); }); +test('workspace reads the complete catalog, including empty and exact-page endings', async () => { + for (const count of [0, 50, 101]) { + const { data } = workspace(); + const products = Array.from({ length: count }, (_, index) => ({ product_id: `product-${index}` })); + const offsets = [], pages = []; + const client = { async call(operation, options) { + if (operation !== 'listCatalog') return data[operation]; + assert.equal(options.query.limit, 50); + const { offset } = options.query; + offsets.push(offset); + const page = { items: products.slice(offset, offset + 50), next_offset: offset + 50 < count ? offset + 50 : null }; + pages.push(page); + return page; + } }; + const result = await loadStorefront(client, { storeId: 'store-a' }); + assert.deepEqual(result.catalog, products); + assert.deepEqual(offsets, count > 50 ? [0, 50, 100] : [0]); + assert.equal(pages[0].items.length, Math.min(count, 50)); + assert.deepEqual(result.listings.map(row => row.listing_id), ['a']); + } +}); + +test('a later catalog authorization failure rejects the whole workspace without retry', async () => { + const { data } = workspace(); + const failure = Object.assign(new Error('session expired'), { status: 401 }); + const offsets = []; + const client = { async call(operation, options) { + if (operation !== 'listCatalog') return data[operation]; + offsets.push(options.query.offset); + if (options.query.offset === 0) return { items: data.listCatalog.items, next_offset: 50 }; + throw failure; + } }; + await assert.rejects(loadStorefront(client), error => error === failure); + assert.deepEqual(offsets, [0, 50]); +}); + +test('invalid catalog continuation fails instead of returning partial data or looping', async () => { + for (const next_offset of [undefined, 0, -1, '50', 1.5]) { + const { client, data, calls } = workspace(); + data.listCatalog.next_offset = next_offset; + await assert.rejects(loadStorefront(client), /next_offset/); + assert.equal(calls.filter(row => row.operation === 'listCatalog').length, 1); + } +}); + test('unknown store and invalid API response fail closed', async () => { const { client, data } = workspace(); await assert.rejects(loadStorefront(client, { storeId: 'foreign-store' }), /unavailable/); diff --git a/vendor/freedom-platform/bundle.json b/vendor/freedom-platform/bundle.json index 3c2247b..94f3b35 100644 --- a/vendor/freedom-platform/bundle.json +++ b/vendor/freedom-platform/bundle.json @@ -1,32 +1,32 @@ { "format": "freedom.contract-bundle/v1", "protocol": "freedom.preview/v1", - "revision": "0.3.0", - "protocol_sha256": "fe2ee45447f4a5e92c10e22307dee3b380d028acca04bac5278d3aeca0da7b3e", + "revision": "0.4.1", + "protocol_sha256": "41378c3b723f739cefdf8c53a82238b1e5d69cc13cdbf63b33a80d8080c807b2", "files": { "openapi.json": { - "sha256": "898228553caf72955943a203a58ed0a06f8a36bc7266541593710c9f31d5dc8e", - "bytes": 80211 + "sha256": "3c536da7dbb75b692c83ae69976b0d782793f7b8383e69f65db97b3e4769a338", + "bytes": 84953 }, "metadata.json": { - "sha256": "465ce597d48b6e3cbce3569161706f82c9a4da8240dcd6a1a43ba7273bd158a3", - "bytes": 942 + "sha256": "4c6ef9306fc33aad342f3f344272b6b0abbe8aaade3ffdeb7cc486376b23903f", + "bytes": 963 }, "protocol.mjs": { - "sha256": "dbbf667907513ba16886de3f5c9183169aadca223cddfd7286ba10d471675c41", - "bytes": 35961 + "sha256": "1df7d91e0a5849f4c2d34a471e15ccfdd99bb62ae4f6bf941ceea729eea2ad34", + "bytes": 39341 }, "client.mjs": { - "sha256": "37138679c14966d3c6fb79a6766e63ad20875fea4f8d11f1dfd0e522737431f6", - "bytes": 6197 + "sha256": "f9b96369adc16be27febd0c63f73e4ae622f3738304240d0f801a890f18de50b", + "bytes": 7844 }, "schema.mjs": { "sha256": "337c263e292b5f62484b73fb0a522f7a88df94bf3f3b3e18d26f2299a0b49eeb", "bytes": 2321 }, "client.d.mts": { - "sha256": "0ad63e3bb690e60401e0a6a5b70ee2a5d807a9c05a4d907cd044f364d122c341", - "bytes": 8252 + "sha256": "ec7043bf91335f31f97a1e8fd01b75aa94e12f4d5b535595d2997529ceb59792", + "bytes": 9130 }, "schemas/project-manifest.schema.json": { "sha256": "dc845236fcac6160e3c7adc2690690dc24bd7c2553ac599013c03f745d400345", diff --git a/vendor/freedom-platform/client.d.mts b/vendor/freedom-platform/client.d.mts index 9c26863..d9a418c 100644 --- a/vendor/freedom-platform/client.d.mts +++ b/vendor/freedom-platform/client.d.mts @@ -30,6 +30,7 @@ export type Campaign = { "campaign_id": string; "title": string; "aggregate_vers export type ShareInput = { "channel": string; "share_url": string; "note"?: string }; export type Share = { "share_id": string; "verification_status": "self_reported"; [key: string]: unknown }; export type Work = { "work_item_id": string; "title": string; "aggregate_version": number; [key: string]: unknown }; +export type WorkPage = { "items": Array; "next_cursor": string | null }; export type Dashboard = { [key: string]: unknown }; export type GuildList = { "items": Array }; export type ProductList = { "items": Array }; @@ -37,45 +38,47 @@ export type StoreList = { "items": Array }; export type ListingList = { "items": Array }; export type AcceptanceList = { "items": Array }; export type ProjectList = { "items": Array }; -export type CampaignList = { "items": Array }; +export type CampaignList = { "items": Array; "next_offset": number | null }; export type WorkList = { "items": Array }; +export type CatalogPage = { "items": Array; "next_offset": number | null }; export type TrackList = { "items": Array<{ [key: string]: unknown }> }; export interface Operations { - getProtocol: { response: Protocol; body: never }; - getHealth: { response: Health; body: never }; - login: { response: Session; body: Login }; - logout: { response: LoggedOut; body: Empty }; - getSession: { response: Session; body: never }; - getPositioning: { response: Positioning; body: never }; - savePositioning: { response: Profile; body: SavePositioning }; - listCareerTracks: { response: TrackList; body: never }; - listGuilds: { response: GuildList; body: never }; - joinGuild: { response: Membership; body: Empty }; - leaveGuild: { response: Membership; body: Empty }; - listSupplierProducts: { response: ProductList; body: never }; - createSupplierProduct: { response: Product; body: ProductInput }; - createSupplierOffer: { response: Product; body: OfferInput }; - listCatalog: { response: ProductList; body: never }; - listStores: { response: StoreList; body: never }; - createStore: { response: Store; body: StoreInput }; - listListings: { response: ListingList; body: never }; - createListing: { response: Listing; body: ListingInput }; - requestSupply: { response: Listing; body: SnapshotInput }; - listSupplyRequests: { response: AcceptanceList; body: never }; - decideSupplyRequest: { response: Acceptance; body: DecisionInput }; - listProjects: { response: ProjectList; body: never }; - importProject: { response: Project; body: ProjectInput }; - refreshProject: { response: Project; body: Empty }; - reviseProject: { response: Project; body: ProjectMetadata }; - listCampaigns: { response: CampaignList; body: never }; - createCampaign: { response: Campaign; body: CampaignInput }; - reviseCampaign: { response: Campaign; body: CampaignMetadata }; - recordShare: { response: Campaign; body: ShareInput }; - listWorks: { response: WorkList; body: never }; - getDashboard: { response: Dashboard; body: never }; + getProtocol: { response: Protocol; body: never; query: never }; + getHealth: { response: Health; body: never; query: never }; + login: { response: Session; body: Login; query: never }; + logout: { response: LoggedOut; body: Empty; query: never }; + getSession: { response: Session; body: never; query: never }; + getPositioning: { response: Positioning; body: never; query: never }; + savePositioning: { response: Profile; body: SavePositioning; query: never }; + listCareerTracks: { response: TrackList; body: never; query: never }; + listGuilds: { response: GuildList; body: never; query: never }; + joinGuild: { response: Membership; body: Empty; query: never }; + leaveGuild: { response: Membership; body: Empty; query: never }; + listSupplierProducts: { response: ProductList; body: never; query: never }; + createSupplierProduct: { response: Product; body: ProductInput; query: never }; + createSupplierOffer: { response: Product; body: OfferInput; query: never }; + listCatalog: { response: CatalogPage; body: never; query: { "limit"?: number; "offset"?: number } }; + listStores: { response: StoreList; body: never; query: never }; + createStore: { response: Store; body: StoreInput; query: never }; + listListings: { response: ListingList; body: never; query: never }; + createListing: { response: Listing; body: ListingInput; query: never }; + requestSupply: { response: Listing; body: SnapshotInput; query: never }; + listSupplyRequests: { response: AcceptanceList; body: never; query: never }; + decideSupplyRequest: { response: Acceptance; body: DecisionInput; query: never }; + listProjects: { response: ProjectList; body: never; query: never }; + importProject: { response: Project; body: ProjectInput; query: never }; + refreshProject: { response: Project; body: Empty; query: never }; + reviseProject: { response: Project; body: ProjectMetadata; query: never }; + listCampaigns: { response: CampaignList; body: never; query: { "limit"?: number; "offset"?: number } }; + createCampaign: { response: Campaign; body: CampaignInput; query: never }; + reviseCampaign: { response: Campaign; body: CampaignMetadata; query: never }; + recordShare: { response: Campaign; body: ShareInput; query: never }; + listWorks: { response: WorkList; body: never; query: never }; + listWorksPage: { response: WorkPage; body: never; query: { "cursor"?: string; "scope"?: "all" | "open"; "search"?: string } }; + getDashboard: { response: Dashboard; body: never; query: never }; } export interface ClientOptions {baseUrl:string;appOrigin?:string;fetcher?:typeof fetch;cookie?:string;csrfToken?:string;timeoutMs?:number} -export interface CallOptions {params?:Record;body?:B;idempotencyKey?:string;version?:number} +export interface CallOptions {params?:Record;query?:Q;body?:B;idempotencyKey?:string;version?:number} export class PlatformError extends Error {status:number;code:string} -export class PlatformClient {constructor(options:ClientOptions);call(operationId:K,options?:CallOptions):Promise;assertCompatible():Promise;static loginDemo(options:ClientOptions & {email:string;password:string}):Promise} +export class PlatformClient {constructor(options:ClientOptions);call(operationId:K,options?:CallOptions):Promise;assertCompatible():Promise;static loginDemo(options:ClientOptions & {email:string;password:string}):Promise} export const protocol: {version:string;revision:string;operations:Record}; diff --git a/vendor/freedom-platform/client.mjs b/vendor/freedom-platform/client.mjs index a076de8..a298ed2 100644 --- a/vendor/freedom-platform/client.mjs +++ b/vendor/freedom-platform/client.mjs @@ -1,6 +1,15 @@ import { protocol, protocolSha256 } from './protocol.mjs'; import { assertShape } from './schema.mjs'; export { protocol } from './protocol.mjs'; +const objectConstructorSource=Function.prototype.toString.call(Object); +function isPlainRecord(value){ + if(value===null||typeof value!=='object')return false; + const prototype=Object.getPrototypeOf(value); + if(prototype===null||prototype===Object.prototype)return true; + if(Object.getPrototypeOf(prototype)!==null)return false; + const constructor=Object.getOwnPropertyDescriptor(prototype,'constructor')?.value; + return typeof constructor==='function'&&Function.prototype.toString.call(constructor)===objectConstructorSource; +} export class PlatformError extends Error { constructor(problem){super(problem.detail);this.name='PlatformError';this.status=problem.status;this.code=problem.code;} } @@ -16,13 +25,24 @@ export class PlatformClient { async assertCompatible(){ const info=await this.call('getProtocol');if(info.protocol_sha256!==protocolSha256)throw new TypeError('Platform protocol differs from the pinned contract; update deliberately');this.#compatible=true;return info; } - async call(operationId,{params={},body,idempotencyKey,version}={}){ + async call(operationId,options={}){ + const {body,idempotencyKey,version}=options; + const query=Object.hasOwn(options,'query')?options.query:undefined; + const ownParams=Object.hasOwn(options,'params')?options.params:undefined,params=ownParams===undefined?{}:ownParams; const op=Object.hasOwn(protocol.operations,operationId)?protocol.operations[operationId]:null;if(!op)throw new TypeError('Unknown operation'); if(operationId==='login')throw new TypeError('Use loginDemo for loopback fixtures; browser auth stays in Platform'); if(op.body)assertShape(body??{},protocol.schemas[op.body],protocol.schemas);else if(body!==undefined)throw new TypeError('GET operation cannot have a body'); + if(!isPlainRecord(params))throw new TypeError('Path parameters must be a plain object'); const expected=[...op.path.matchAll(/\{([^}]+)\}/g)].map(m=>m[1]); if(Object.keys(params).some(k=>!expected.includes(k)))throw new TypeError('Unknown path parameter'); - let path=op.path;for(const key of expected){const value=params[key];const pattern=key==='id'?/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i:/^[a-z][a-z0-9_]{1,100}$/;if(typeof value!=='string'||!pattern.test(value))throw new TypeError('Invalid path identifier');path=path.replace(`{${key}}`,encodeURIComponent(value));} + let path=op.path;for(const key of expected){const value=Object.hasOwn(params,key)?params[key]:undefined;const pattern=key==='id'?/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i:/^[a-z][a-z0-9_]{1,100}$/;if(typeof value!=='string'||!pattern.test(value))throw new TypeError('Invalid path identifier');path=path.replace(`{${key}}`,encodeURIComponent(value));} + if(query!==undefined&&!isPlainRecord(query))throw new TypeError('Query parameters must be a plain object'); + const expectedQuery=new Map((op.query??[]).map(item=>[item.name,item])); + if(!op.query&&query!==undefined)throw new TypeError('Operation does not accept query parameters'); + if(Object.keys(query??{}).some(name=>!expectedQuery.has(name)))throw new TypeError('Unknown query parameter'); + const search=new URLSearchParams(); + for(const [name,item]of expectedQuery){const value=query!==undefined&&Object.hasOwn(query,name)?query[name]:undefined;if(value===undefined){if(item.required)throw new TypeError('Required query parameter missing');continue;}assertShape(value,item.schema,protocol.schemas);search.set(name,String(value));} + if(search.size)path+='?'+search.toString(); if(op.idempotent&&!/^[A-Za-z0-9_-]{8,128}$/.test(idempotencyKey??''))throw new TypeError('Explicit Idempotency-Key required; reuse it only with the same request'); if(op.concurrency==='required'&&version===undefined)throw new TypeError('Expected version required'); if(version!==undefined&&(!Number.isSafeInteger(version)||version<1))throw new TypeError('Expected version must be a positive safe integer'); diff --git a/vendor/freedom-platform/metadata.json b/vendor/freedom-platform/metadata.json index 0507686..24543bd 100644 --- a/vendor/freedom-platform/metadata.json +++ b/vendor/freedom-platform/metadata.json @@ -1,7 +1,7 @@ { "protocol": "freedom.preview/v1", - "revision": "0.3.0", - "protocol_sha256": "fe2ee45447f4a5e92c10e22307dee3b380d028acca04bac5278d3aeca0da7b3e", + "revision": "0.4.1", + "protocol_sha256": "41378c3b723f739cefdf8c53a82238b1e5d69cc13cdbf63b33a80d8080c807b2", "operations": [ "getProtocol", "getHealth", @@ -34,6 +34,7 @@ "reviseCampaign", "recordShare", "listWorks", + "listWorksPage", "getDashboard" ], "authentication": "member_session_csrf", diff --git a/vendor/freedom-platform/openapi.json b/vendor/freedom-platform/openapi.json index 383abc2..2a7f1ce 100644 --- a/vendor/freedom-platform/openapi.json +++ b/vendor/freedom-platform/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.1.1", "info": { "title": "Freedom implemented member module API subset", - "version": "0.3.0", + "version": "0.4.1", "description": "Member-session module API subset. Registration/onboarding and scoped read-connections have separate interface documents. Public checkout, production OAuth and leased executors are not implemented by this bundle." }, "servers": [ @@ -804,14 +804,37 @@ "MemberSession": [] } ], - "parameters": [], + "parameters": [ + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 50, + "default": 20 + } + }, + { + "name": "offset", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "default": 0 + } + } + ], "responses": { "200": { "description": "Implemented preview response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ProductList" + "$ref": "#/components/schemas/CatalogPage" } } } @@ -1561,7 +1584,30 @@ "MemberSession": [] } ], - "parameters": [], + "parameters": [ + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 50, + "default": 20 + } + }, + { + "name": "offset", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "default": 0 + } + } + ], "responses": { "200": { "description": "Implemented preview response", @@ -1877,6 +1923,76 @@ "x-concurrency": "none" } }, + "/work-items/page": { + "get": { + "operationId": "listWorksPage", + "summary": "listWorksPage", + "security": [ + { + "MemberSession": [] + } + ], + "parameters": [ + { + "name": "cursor", + "in": "query", + "required": false, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 2048 + } + }, + { + "name": "scope", + "in": "query", + "required": false, + "schema": { + "enum": [ + "all", + "open" + ], + "default": "all" + } + }, + { + "name": "search", + "in": "query", + "required": false, + "schema": { + "type": "string", + "minLength": 0, + "maxLength": 2000, + "default": "" + } + } + ], + "responses": { + "200": { + "description": "Implemented preview response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkPage" + } + } + } + }, + "default": { + "description": "Structured problem; conflict is never automatically retried", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + } + } + }, + "x-idempotent-command": false, + "x-concurrency": "none" + } + }, "/dashboard": { "get": { "operationId": "getDashboard", @@ -3076,6 +3192,35 @@ ], "additionalProperties": true }, + "WorkPage": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Work" + }, + "maxItems": 24 + }, + "next_cursor": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 2048 + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "items", + "next_cursor" + ], + "additionalProperties": false + }, "Dashboard": { "type": "object" }, @@ -3176,11 +3321,25 @@ "type": "array", "items": { "$ref": "#/components/schemas/Campaign" - } + }, + "maxItems": 50 + }, + "next_offset": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] } }, "required": [ - "items" + "items", + "next_offset" ], "additionalProperties": false }, @@ -3199,6 +3358,35 @@ ], "additionalProperties": false }, + "CatalogPage": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Product" + }, + "maxItems": 50 + }, + "next_offset": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "items", + "next_offset" + ], + "additionalProperties": false + }, "TrackList": { "type": "object", "properties": { @@ -3219,7 +3407,8 @@ "MemberSession": { "type": "apiKey", "in": "cookie", - "name": "freedom_local_session" + "name": "__Host-freedom_session", + "description": "HTTPS: Secure, HttpOnly, SameSite=Strict, Path=/ and no Domain. Explicit local HTTP loopback deployments use freedom_local_session instead. Duplicate selected session cookies are rejected." } } } diff --git a/vendor/freedom-platform/protocol.mjs b/vendor/freedom-platform/protocol.mjs index e03be85..92a9611 100644 --- a/vendor/freedom-platform/protocol.mjs +++ b/vendor/freedom-platform/protocol.mjs @@ -1,7 +1,7 @@ // GENERATED. Change definition.mjs and rebuild in freedom-platform. export const protocol={ "version": "freedom.preview/v1", - "revision": "0.3.0", + "revision": "0.4.1", "api_prefix": "/api/v1", "operations": { "getProtocol": { @@ -147,12 +147,34 @@ export const protocol={ "listCatalog": { "method": "GET", "path": "/retail/catalog", - "response": "ProductList", + "response": "CatalogPage", "body": null, "concurrency": "none", "status": 200, "auth": true, - "idempotent": false + "idempotent": false, + "query": [ + { + "name": "limit", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 50, + "default": 20 + } + }, + { + "name": "offset", + "required": false, + "schema": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "default": 0 + } + } + ] }, "listStores": { "method": "GET", @@ -272,7 +294,29 @@ export const protocol={ "concurrency": "none", "status": 200, "auth": true, - "idempotent": false + "idempotent": false, + "query": [ + { + "name": "limit", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 50, + "default": 20 + } + }, + { + "name": "offset", + "required": false, + "schema": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "default": 0 + } + } + ] }, "createCampaign": { "method": "POST", @@ -314,6 +358,48 @@ export const protocol={ "auth": true, "idempotent": false }, + "listWorksPage": { + "method": "GET", + "path": "/work-items/page", + "response": "WorkPage", + "body": null, + "concurrency": "none", + "status": 200, + "auth": true, + "idempotent": false, + "query": [ + { + "name": "cursor", + "required": false, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 2048 + } + }, + { + "name": "scope", + "required": false, + "schema": { + "enum": [ + "all", + "open" + ], + "default": "all" + } + }, + { + "name": "search", + "required": false, + "schema": { + "type": "string", + "minLength": 0, + "maxLength": 2000, + "default": "" + } + } + ] + }, "getDashboard": { "method": "GET", "path": "/dashboard", @@ -1486,6 +1572,35 @@ export const protocol={ ], "additionalProperties": true }, + "WorkPage": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Work" + }, + "maxItems": 24 + }, + "next_cursor": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 2048 + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "items", + "next_cursor" + ], + "additionalProperties": false + }, "Dashboard": { "type": "object" }, @@ -1586,11 +1701,25 @@ export const protocol={ "type": "array", "items": { "$ref": "#/components/schemas/Campaign" - } + }, + "maxItems": 50 + }, + "next_offset": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] } }, "required": [ - "items" + "items", + "next_offset" ], "additionalProperties": false }, @@ -1609,6 +1738,35 @@ export const protocol={ ], "additionalProperties": false }, + "CatalogPage": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Product" + }, + "maxItems": 50 + }, + "next_offset": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "items", + "next_offset" + ], + "additionalProperties": false + }, "TrackList": { "type": "object", "properties": { @@ -1630,4 +1788,4 @@ export const protocol={ "public_checkout": false } ; -export const protocolSha256="fe2ee45447f4a5e92c10e22307dee3b380d028acca04bac5278d3aeca0da7b3e"; +export const protocolSha256="41378c3b723f739cefdf8c53a82238b1e5d69cc13cdbf63b33a80d8080c807b2"; diff --git a/vendor/freedom-tooling/governance/README.md b/vendor/freedom-tooling/governance/README.md new file mode 100644 index 0000000..e3340b6 --- /dev/null +++ b/vendor/freedom-tooling/governance/README.md @@ -0,0 +1,252 @@ +# Contract release verification and development context + +This directory defines the development schemas for the unified-foundation governance work. The first implementation verifies legacy preview pins and signed ReleaseSet pins locally. It does **not** configure a trusted publisher, GitHub protection, runtime authorization, or production signing. + +The source schemas are in [schemas](schemas). The shared implementation is in [packages/contribution-tools](../packages/contribution-tools); consumers receive exact committed copies through the existing export command. Do not create a second consumer-owned verifier or change the preview bundle to enable execution. + +## Local checks + +```sh +npm run test:governance +npm run contracts:build +git diff --exit-code -- contracts/preview/v1 packages/sdk +``` + +The tests use synthetic repositories, ephemeral in-memory signing keys and temporary files. They do not connect to a database, provider, R2 or GitHub. Existing preview bytes are used for compatibility tests. + +## Development entrypoints + +```sh +node scripts/freedom.mjs prepare --base-ref origin/main --scope assets,member-card +node scripts/freedom.mjs context --base-ref origin/main --paths apps/portal-web/src/modules/Membership.tsx +node scripts/freedom.mjs verify --base-ref origin/main --report .freedom/reports/current.json +``` + +Run from the repository root with Node 24. `prepare` writes an ignored, task-scoped context bundle; `context` prints the full applicable content when it fits a v1 bundle, or a chunk manifest for larger scopes; `verify` runs the implemented local checks and optionally saves a report. Exit codes are 0 (complete for the requested local scope), 1 (failed), and 2 (required evidence unavailable). None of these results is a trusted merge or execution authorization. + +Context contains repository/base/head, a hashed worktree identity, branch, staged and unstaged changes, untracked source, root and applicable nested AGENTS instructions, and both baseline and changed policy text. Contract pins/ReleaseSets include their public version information; dependency manifests are fingerprinted without copying potentially private registry settings. The bundle records `publisher_trust=unverified` and `library_usage=not_checked`, never that an Agent understood it. Regenerate after changing scope, base, lock, branch/worktree, or session; no receipt is committed into a shared JSON file. + +### Complete context across bounded chunks + +Small context still uses `freedom.coding-context/v1`, with the existing 512,000-byte content limit and a 512,000-byte serialized output limit. When the applicable context exceeds either limit, `prepare` and `context` automatically write a `freedom.coding-context-manifest/v1` and all its chunks into the ignored `.freedom/context///` directory. Scope is unchanged: baseline and candidate descriptors, nested instructions, reverse dependencies, and unknown-path full fallback are all retained. The manifest lists both revisions of every applicable instruction, their source digests, the baseline/candidate delta, selected baseline/candidate modules and dependencies, unknown paths, public contract content, and fingerprints of dependency manifests without disclosing their contents. + +For a repo-wide change, or a fresh worktree/session, start from that worktree's root: + +```sh +node scripts/freedom.mjs prepare --base-ref --paths AGENTS.md +node scripts/freedom.mjs context --manifest --chunk 0 +node scripts/freedom.mjs context --manifest --check complete +``` + +Read **every** chunk index from zero through `chunk_count - 1`, then run the completeness check. A manifest or the first fragment alone is not the complete rules. `prepare` prints the concrete first-chunk and completeness commands; `context` without `--manifest` prints the complete manifest. `--manifest` cannot be combined with a different base, path or scope: regenerate with `prepare` when any of those change. New subagents and other worktrees must prepare their own context; copying a delivery from another worktree is rejected. + +Every fragment is at most 65,536 bytes of intact UTF-8, including the original BOM if present. Every manifest and serialized chunk is at most 512,000 bytes. A delivery is limited to 1,024 sources, 1,024 chunks and 32,000,000 content bytes; each source read retains the existing 2,000,000-byte file limit. Oversized candidates fail explicitly instead of truncating or silently dropping rules. Public version-content projections have their own content digest alongside the original source digest. + +Chunk reads and completeness checks reconstruct the full applicable context from the current repository, baseline, HEAD, branch and worktree fingerprint. They verify the exact manifest and **all** expected chunks before returning anything, rejecting missing, modified, reordered, stale or foreign-worktree artifacts. Paths are generated by the tool and use the existing ignored-artifact writer and bounded nonsymlink reader. Chunks are written first and the manifest last; a partial failed write does not announce a complete delivery. The workspace is checked again before publication and after reading. + +The completeness result means that the current local artifacts contain the full selected rules; it does not assert that a human or agent has read or understood them. `publisher_trust=unverified`, `library_usage=not_checked` and local assurance remain unchanged. Missing instructions and unknown surfaces remain blockers with exit code 2, even if every available chunk is intact. `verify` uses the same full rule collection and validation without retaining document text, so a legitimate large context does not prevent suite selection; this does not change suite requirements or trust. + +Module descriptors use exact paths or directory `/**` patterns. Impact is the union of baseline and candidate descriptors plus reverse dependencies. Deleting, renaming or shrinking a descriptor cannot subtract baseline scope/tests. Unknown non-document paths select all modules and require a full fallback; missing baseline governance, missing instructions and unmapped surfaces remain explicit blockers. Descriptor references check file existence, **not** actual route registration or ACL behavior. + +The CI selector also counts a descriptor's own path when it is not already +covered. Keep that implicit entry within the existing 64-path schema bound; +64 unrelated explicit paths plus an uncovered descriptor is invalid, not a +reason to raise the limit or ignore the descriptor. Files wholly owned in one +dedicated directory may use its existing `/**` form without dropping coverage. +The member-card license directory uses that form instead of four individual +license entries. This broadens conservative impact coverage only; it changes +neither license bytes, runtime permissions nor baseline/candidate test unions. + +The descriptors do not constitute a complete runtime registration audit. The local suite adapters use fixed Node arguments, never descriptor shell commands or package hooks. `governance.unit` runs the contribution-tools tests without database credentials. Runtime adapters require operator-provisioned, disposable PostgreSQL and an **explicit** `TEST_DATABASE_URL` for the CLI, or `testDatabaseUrl` for the library; there is no database discovery or default fallback. Accepted URLs name an `fp_*` database on loopback, optionally with a single absolute Unix-socket `host` parameter. Passwords, remote hosts, duplicate/query connection overrides and non-test database names are rejected. This admission check does not establish that a server is disposable: the operator must provide an isolated test-only server, never a production service that happens to have a matching name. Runtime tests own fresh `fp_*` schemas/roles and their teardown; forced termination can leave test data to clean up on that disposable server. + +The fixed registry in `runtime-suites.mjs` maps these existing IDs: + +| Suite | Direct runtime test files (without `.test.ts`) | +| --- | --- | +| `runtime.command-core` | `command-core` | +| `runtime.resource-scopes` | `resource-scopes` | +| `runtime.scoped-member-command` | `scoped-member-command` | +| `runtime.avatar` | `avatar`, `image-runtime`, `image-cloudflare` | +| `runtime.member-card` | `member-ecard`, `member-directory`, `social-links`, `member-card-qr` | +| `runtime.work` | `flows`, `benefits`, `co-creation` | +| `runtime.work-privacy` | `work-privacy` | +| `runtime.personal-content` | `personal-content`, `community-relations`, `community-search`, `work-privacy` | +| `runtime.preview-protocol` | `preview-protocol` | +| `runtime.full` | All baseline runtime files **plus newly added** direct `tests/runtime/*.test.ts` files | + +`e2e.harness` is a separate fixed adapter. It is not a runtime file, so it is not a row in the table above. It runs exactly `scripts/run-e2e.test.mjs` with the same bounded Node reporter, the 60-second non-runtime budget, and no database environment. Neighboring `scripts/**/*.test.mjs` files are not discovered. Deleting that baseline is `suite_files_unavailable` (`not_run`), not a pass. An empty file, a zero-test run, or any skip, TODO, cancellation, or failure does not pass. The verifier report accepts that one `scripts/run-e2e.test.mjs` path and no other `scripts/` test path. This suite checks the Playwright orchestrator. It does not launch a browser. CI's `ui-e2e` job runs `npm run test:e2e` after `npm run build`; that job is the browser evidence, and `verify` does not substitute for it. + +| Suite | Fixed baseline | Budget | +| --- | --- | --- | +| `e2e.harness` | `scripts/run-e2e.test.mjs` only | 60 seconds, no database | + +`runLocalSuite(root, id, {testDatabaseUrl})` remains available from `verify.mjs`; `runLocalSuites(root, ids, {testDatabaseUrl})` and the default `verifyWorkspace(options, {testDatabaseUrl})` batch overlapping runtime selections into **one** Node/tsx invocation. Each file executes once even when full and subset IDs are selected; reports project each suite's file/case evidence from that invocation. There is no persistent cache across calls or source changes. Deleting a baseline file or a fixed subset file cannot become green; consumers without these producer suites receive `suite_files_unavailable`. New direct runtime test files are discovered automatically without first adding them to the baseline list. The tsx loader comes from the installed tooling's dependency resolution; no npm script is executed. + +The subprocess environment contains only the existing small OS/locale allowlist and, for runtime alone, the validated explicit test URL. Home/provider credentials, PG defaults, `DATABASE_URL`, Node preload hooks and parent test context are not inherited. Execution is bounded to 60 seconds for non-runtime adapters (`governance.unit`, the consumer adapters, and `e2e.harness`) and 15 minutes for runtime, with a 16 MB combined stdout/stderr cap; a library caller may only shorten the timeout. POSIX timeout kills the test process group (Windows kills the runner; use an external job/container boundary there). Timeout, process failure, malformed/incomplete reports, zero tests, skips, TODOs and cancellations cannot pass. Missing DB/loader/files and unknown IDs remain `not_run`; governance can still run when runtime has no DB. + +A custom reporter consumes [Node test events](https://nodejs.org/docs/latest-v24.x/api/test.html#event-testsummary). Reports record selected paths, per-file counts and case-identity digests/statuses, reconciling case totals with file and global counts. Case identities hash source location and runner IDs, not potentially sensitive test names; errors, assertions, stdout/stderr and the database URL are omitted. The evidence digest covers the sanitized structured reporter output. Aborted/malformed runs retain selected paths but cannot claim complete case evidence. This reporter is local, candidate-controlled code: structured events avoid accidental stdout/TAP confusion, **not adversarial spoofing**. These records are not authenticated host observations and are never fed into `verifyHostCandidate` automatically. The runner is not a security sandbox: local tests retain the current OS user's filesystem/network rights; untrusted PR code requires an isolated, secret-free runner and an independent harness/publisher. + +Separate `suite_events` retain describe/suite statuses, because Node's test counts exclude skipped suites. Any skipped/TODO/cancelled/failed suite also fails verification; suites never inflate the real test count. New approved runtime files should be added to the central baseline list to retain deletion protection in later revisions, even though new files run automatically on discovery. + +Runtime registration/behavior coverage and missing baseline governance remain explicit blockers even after every selected test passes. This increment does not close the actual surface-registration audit or enable trusted merge/execution authorization. + +The reviewed `consumer.agent-kit` adapter runs the real consumer's direct +`tests/*.test.mjs` files with the same bounded Node reporter and a fixed +`tests/workspace.test.mjs` deletion-protected baseline. It has no TypeScript +loader, package hooks or database environment; it uses the 60-second non-runtime +budget. New consumer tests are discovered, and missing/empty/skipped tests fail +closed. This is a local consumer regression check, not Agent execution authority, +an authenticated upstream release, or a replacement for surface auditing. + +During initial adoption, running against an `origin/main` without descriptors correctly returns `baseline_governance_unavailable`. Do not change the base to hide that result in PR evidence. Synthetic repositories with an established baseline test the successful path. The export command also supplies the same central context library and a thin `scripts/freedom.mjs` to consumers; each consumer must supply reviewed module descriptors and actual suite adapters. + +An explicit export, after committing all source files, remains: + +```sh +node scripts/export-contract-bundle.mjs /absolute/path/to/consumer +``` + +The destination must already exist and must not overlap the producer. Export checks committed bytes and destination paths before writing. It copies the preview bundle, central tooling and thin consumer entrypoints, then writes the existing v1 lock last. It does not remove unrelated files, commit, open a PR or push. Interruption can leave a partial export; rerun the same committed export and verify before using it. + +In a consumer, `node scripts/verify-contracts.mjs` returns structured JSON and exits 0 for the requested local verification, 1 for invalid input/integrity, or 2 for unavailable trust/source. `--remote` additionally compares v1 bytes with the exact pinned GitHub commit. v2 does not accept `--remote` as a replacement for publisher approval. + +## ReleaseSet and proof profile + +`freedom.release-set/v1` binds source SHA, artifact bytes/digests, contract families, libraries, policy revision, generator, fixtures and runtime profiles. Every artifact must be classified and every reference must resolve. Paths, counts and total bytes are bounded; absolute/traversal/Windows-special paths, case collisions, symlinks, hardlinks, extra files and missing files are rejected. + +The digest profile is `sha256-exact-bytes/v1`: SHA-256 of the exact UTF-8 manifest bytes. The authoring helper sorts object keys and artifact paths for repeatability, but this encoding is **not RFC 8785**. It does not change historical preview/SQL digests or select the future execution JCS implementation. + +`freedom.release-proof/v1` is detached. Ed25519 signs the UTF-8 bytes of `freedom.release-set-signature/v1` followed by one NUL byte and the exact manifest bytes. The signature uses unpadded canonical base64url. The public key must be an Ed25519 public JWK; no private key, HMAC key, arbitrary algorithm, jku or x5u is accepted. The implementation uses Node's native Ed25519 verification, with a null algorithm as required by its [crypto API](https://nodejs.org/docs/latest-v24.x/api/crypto.html#cryptoverifyalgorithm-data-key-signature-callback). + +This signature proves possession of an approved publisher key over a specific manifest. It does not itself prove a GitHub workflow ran. Workflow/provenance enforcement, secure signer custody and independent approval/revocation publication remain separate GOV-C/D work. + +## Independent trust input + +`verifyContractPin` accepts an operator-supplied `trustProfile`; it never discovers one in the candidate repository. The profile identifies environment, version, approved publisher keys, supported/withdrawn manifest digests and policy revisions. It expires, with a default maximum freshness window of 24 hours. The operator must obtain it from an authenticated, independently managed source. A self-consistent consumer hash and self-signed key are not approval. + +There is no production trust profile or private signing key in this repository. The bootstrap CLI intentionally has no `--trust` flag: v2 is unavailable there until a trusted host injects the approved policy through the library API. `fixture` environment results remain fixture evidence; every result has `assurance_level=local` and `execution_authorized=false`. + +The verifier checks only the supplied artifact set and policy. A build analyzer must independently collect actual library resolution records; `verifyLibraryResolution` validates those records but does not attest who collected them. `library_usage=not_checked` on a pin result is intentional. + +## Boundaries + +The governance validator implements only the fixed schema keyword subset used here and rejects unknown keywords. It is not a general JSON Schema engine and does not load candidate schemas or code. JSON parsing rejects duplicate keys, invalid UTF-8/surrogates, unsafe numbers and excessive depth/size. Errors expose stable codes, not input fragments or secret-bearing paths. + +Trusted CI must run the fixed verifier against an isolated, immutable checkout with no production secrets. Filesystem checks do not make a concurrently hostile workspace a sandbox. Local candidate tests and reports cannot publish trusted CI status. No new runtime endpoints, tables or execution permissions are enabled by this package. + +## GitHub Free repository CI review + +After the repository transfer, the central repository uses maintainer review of +CI controls. [.github/CODEOWNERS](../.github/CODEOWNERS) assigns both +`@teddashh` and `@detna-vibe-coding` to the ownership file itself, workflows, +local actions, selectors/runners, governance tooling, module descriptors and +the configuration those entrypoints load. Both accounts have repository admin +access, checked on 2026-10-13. Ordinary product UI files and product test files +are not covered by a blanket owner rule. + +The 2026-10-14 15:09 UTC readback of repository ruleset `main-baseline` +(`25011111`) confirms `require_code_owner_review` is enabled, with at least one +approval, stale-review dismissal, approval after the latest push, resolved review +threads, strict App-bound `verify`/`CodeQL` checks and no bypass actors. GitHub +uses the ownership file from the PR's base branch. The dated observation is in +[`current-state.json`](../docs/platform-plan/execution/unified-foundation/current-state.json) +under `governance_current`; the older organization workflow pins are historical. +Changes to CI controls still require an eligible non-author code owner. See +[GitHub's code owner rules](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners). + +This provides review enforcement for changes to CI controls. Required check +names and the reviewed runner's `job.workflow_sha` checkout do not restore the +old Enterprise organization rule that required a workflow from a fixed source. +Reviewers must inspect changes to workflow/selector/runner dependencies and +their exact-head evidence; a candidate cannot establish independent publisher +trust by supplying a report with the right name. + +Candidate application and test code still execute on the test runner. This is +not an independent sandbox, an authenticated observation publisher, or proof +that candidate tests cannot forge results. The local GOV-C boundary and future +publisher profiles below retain their existing limits. This central observation +does not establish the current protection of consumer repositories. + +## Host-owned verification boundary (local GOV-C increment) + +`packages/contribution-tools/trusted-ci.mjs` provides `verifyHostCandidate` for a +future independently managed host. It is deliberately absent from the consumer +export list and local CLI. The host must approve and load an immutable verifier +installation **before** accepting candidate data. `installedVerifierDigest()` +fingerprints the complete static module/schema import closure; comparing that +digest inside an already compromised process cannot establish trust. The host +also owns the Git executable, environment, object store, policy and observation +transport. Candidate runners must have no write access to any of them. + +The input has exactly five fields: + +- `objectRepository`: absolute path to a host-owned, complete bare Git object + repository populated through a separately authenticated, bounded acquisition + step. Do not point this at a candidate-created bare repository or copy its + configuration. This library performs no fetch or checkout. It disables replace + refs, ambient Git configuration and lazy fetches, rejects grafts/alternates, + and applies bounded Git subprocess time/output limits. +- `binding`: independently acquired repository, positive PR number, run ID, + exact base/head/candidate commits and candidate tree. A head candidate must + contain the base; an integration candidate must have exactly the base and head + as its ordered parents. This is a narrow local topology profile, not a claim + that every GitHub merge-queue topology is supported. +- `policyBytes` and `expectedPolicy`: independently approved exact policy bytes + and their revision/SHA-256. `freedom.trusted-ci-policy/v1` contains repository, + source repository/commit/ReleaseSet digest, verifier commit/install digest, + workflow identity/commit/publisher, nonempty required and fallback suite lists, + and the allowed suite ID/harness-digest registry. Unknown keys and arbitrary + commands are rejected. The host must independently enforce policy freshness + and revocation; candidate policy files cannot update this input. +- `observations`: records from an authenticated host adapter for an isolated + runner, **never** JSON artifacts supplied by the candidate. Each record binds + the full repository/PR/run/base/head/candidate/tree/source/ReleaseSet/policy/ + verifier tuple, expected workflow publisher/revision and harness digest. A + positive real test count, success, and zero failures/skips/cancellations are + required. The evidence digest identifies the adapter's retained evidence; it + is not a signature or proof of its origin. Missing suites return `unavailable`; + duplicate/unexpected suites, changed bindings and invalid results are rejected. + +The verifier recomputes changed paths from immutable tree entries, including +deletions, renames and mode-only changes. It unions baseline and candidate module +descriptors and reverse dependencies using the installed selector. Candidate +descriptor changes cannot subtract baseline tests or host-required suites; +paths without baseline ownership add host fallback suites even when a new or +expanded candidate descriptor claims them. Candidate descriptors are bounded data, +not executable policy. The candidate's v2 lock and manifest must match the +host-approved source and ReleaseSet digest. Actual immutable vendor blobs must +match the manifest/lock artifact paths, exact file set, byte counts and digests; +the detached proof must match its lock digest. This step does not replace the +existing detached-signature/publisher verification, actual source approval, library +resolution, route registration or behavioral tests; the independent host must +require the appropriate harnesses when integrating those checks. + +See `test/trusted-ci.test.mjs` under contribution-tools for the exact synthetic +host policy and adapter record shapes. The tests exercise fake `echo pass` +workflows/reports, a replaced candidate verifier, descriptor deletion/shrinking, +empty/unknown suites, zero/skipped/cancelled/failing tests, same-name wrong-source +workflows, changed harness/policy/base/run/tree/source, Git graph overrides and +candidate symlinks. Test fixtures mint observations directly to test the local +boundary; they do not authenticate an external runner. + +Reports retain `assurance_level=local`, `publisher_trust=unverified`, +`merge_authorized=false` and `execution_authorized=false`, even when all supplied +host observations pass this boundary. There is no authenticated CI adapter, +isolated runner provisioning, trusted check publication, GitHub protection, +production signing or completed GOV-C/D enforcement in this increment. Existing +local CLI and preview/v1 compatibility remain unchanged; this host-only profile +requires v2 source pins and does not silently promote preview/v1 to trusted CI. + +## Implementation evidence + +On 2026-10-02, the first local implementation passed 88 Node tests with no skips. The existing preview build regenerated 32 operations and 9 bundle artifacts with no changes under `contracts/preview/v1` or `packages/sdk`. + +The context increment passed 106 Node tests, zero skips, including baseline/candidate scope, deleted rules, nested context, branch/worktree changes, stale workspace/base, secret-free subprocess environment, bounded report writes, zero/skipped/forged test output and three independently initialized synthetic consumer repositories. Existing contract tests passed 659 cases with 4 pre-existing skips (clock cases with fewer than three schema paths). These fixtures do not mean the real Agent Kit, client or other consumer repos have been upgraded. + +The host-boundary increment passed 119 Node governance tests, zero skips, +including 13 new synthetic bare-repository/host-observation cases. The local +profile covers immutable candidate binding, pinned installed code/policy, +baseline-owned fallback and exact vendor integrity. It does not supply the +authenticated observations or GitHub enforcement described above. + +The evidence supports the local portions of GOV-01/02/03/22, path/input safety and v1 compatibility; it does not mark those full product requirements passed. Release-proof purpose tests are not execution-token tests. Three real consumer checkouts, TS/Rust conformance, Windows/macOS, trusted GitHub checks, production publishers and runtime rejection remain unverified. All source acceptance rows remain `not_run` until their complete required evidence exists. diff --git a/vendor/freedom-tooling/governance/schemas/coding-context.schema.json b/vendor/freedom-tooling/governance/schemas/coding-context.schema.json new file mode 100644 index 0000000..6700eef --- /dev/null +++ b/vendor/freedom-tooling/governance/schemas/coding-context.schema.json @@ -0,0 +1,176 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://freetwai.com/contracts/governance/coding-context/v1", + "title": "Freedom coding-context development schema", + "type": "object", + "properties": { + "workspace_id": { "type": "string", "pattern": "^[a-f0-9]{64}$" }, + "branch": { "type": "string", "minLength": 1, "maxLength": 240 }, + "publisher_trust": { "const": "unverified" }, + "library_usage": { "const": "not_checked" }, + "version_inputs": { + "type": "array", "minItems": 0, "maxItems": 32, + "items": { + "type": "object", "additionalProperties": false, + "required": ["path", "revision", "sha256", "bytes"], + "properties": { + "path": { "type": "string", "minLength": 1, "maxLength": 240 }, + "revision": { "enum": ["base", "candidate"] }, + "sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" }, + "bytes": { "type": "integer", "minimum": 0, "maximum": 2000000 }, + "content": { "type": "string", "maxLength": 2000000 } + } + } + }, + "format": { + "const": "freedom.coding-context/v1" + }, + "assurance_level": { + "const": "local" + }, + "task_id": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "repository": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "base_commit": { + "type": "string", + "pattern": "^[a-f0-9]{40}$" + }, + "head_commit": { + "type": "string", + "pattern": "^[a-f0-9]{40}$" + }, + "workspace_sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "requested_paths": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[-a-zA-Z0-9_./]+$" + }, + "minItems": 0, + "maxItems": 4096, + "uniqueItems": true + }, + "changed_paths": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[-a-zA-Z0-9_./]+$" + }, + "minItems": 0, + "maxItems": 4096, + "uniqueItems": true + }, + "module_ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "minItems": 0, + "maxItems": 1024, + "uniqueItems": true + }, + "documents": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[-a-zA-Z0-9_./]+$" + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "bytes": { + "type": "integer", + "minimum": 0, + "maximum": 2000000 + }, + "content": { + "type": "string", + "maxLength": 2000000 + }, + "revision": { + "enum": [ + "base", + "candidate" + ] + } + }, + "required": [ + "path", + "sha256", + "bytes", + "content", + "revision" + ], + "additionalProperties": false + }, + "minItems": 0, + "maxItems": 1024 + }, + "tests": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "minItems": 0, + "maxItems": 1024, + "uniqueItems": true + }, + "blockers": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "minItems": 0, + "maxItems": 1024, + "uniqueItems": true + } + }, + "required": [ + "workspace_id", "branch", "version_inputs", "publisher_trust", "library_usage", + "format", + "assurance_level", + "task_id", + "repository", + "base_commit", + "head_commit", + "workspace_sha256", + "requested_paths", + "changed_paths", + "module_ids", + "documents", + "tests", + "blockers" + ], + "additionalProperties": false +} diff --git a/vendor/freedom-tooling/governance/schemas/contract-pin-v1.schema.json b/vendor/freedom-tooling/governance/schemas/contract-pin-v1.schema.json new file mode 100644 index 0000000..fc382d5 --- /dev/null +++ b/vendor/freedom-tooling/governance/schemas/contract-pin-v1.schema.json @@ -0,0 +1,42 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://freetwai.com/contracts/governance/contract-pin-v1/v1", + "title": "Freedom contract-pin-v1 development schema", + "type": "object", + "properties": { + "format": { + "const": "freedom.contract-pin/v1" + }, + "source_repository": { + "enum": ["FreeTWAI/freedom-platform", "FreeTWAI-AI/freedom-platform"] + }, + "source_commit": { + "type": "string", + "pattern": "^[a-f0-9]{40}$" + }, + "bundle_path": { + "const": "contracts/preview/v1" + }, + "protocol": { + "const": "freedom.preview/v1" + }, + "protocol_sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "bundle_sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + } + }, + "required": [ + "format", + "source_repository", + "source_commit", + "bundle_path", + "protocol", + "protocol_sha256", + "bundle_sha256" + ], + "additionalProperties": false +} diff --git a/vendor/freedom-tooling/governance/schemas/contract-pin-v2.schema.json b/vendor/freedom-tooling/governance/schemas/contract-pin-v2.schema.json new file mode 100644 index 0000000..69d7e16 --- /dev/null +++ b/vendor/freedom-tooling/governance/schemas/contract-pin-v2.schema.json @@ -0,0 +1,105 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://freetwai.com/contracts/governance/contract-pin-v2/v1", + "title": "Freedom contract-pin-v2 development schema", + "type": "object", + "properties": { + "format": { + "const": "freedom.contract-pin/v2" + }, + "source_repository": { + "enum": ["FreeTWAI/freedom-platform", "FreeTWAI-AI/freedom-platform"] + }, + "source_commit": { + "type": "string", + "pattern": "^[a-f0-9]{40}$" + }, + "release_set": { + "type": "object", + "properties": { + "path": { + "const": "release-set.json" + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + } + }, + "required": [ + "path", + "sha256" + ], + "additionalProperties": false + }, + "proof": { + "type": "object", + "properties": { + "path": { + "const": "release-set.proof.json" + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + } + }, + "required": [ + "path", + "sha256" + ], + "additionalProperties": false + }, + "profiles": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "minItems": 1, + "maxItems": 32, + "uniqueItems": true + }, + "artifacts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[-a-zA-Z0-9_./]+$" + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "bytes": { + "type": "integer", + "minimum": 0, + "maximum": 2000000 + } + }, + "required": [ + "path", + "sha256", + "bytes" + ], + "additionalProperties": false + }, + "minItems": 1, + "maxItems": 1024 + } + }, + "required": [ + "format", + "source_repository", + "source_commit", + "release_set", + "proof", + "profiles", + "artifacts" + ], + "additionalProperties": false +} diff --git a/vendor/freedom-tooling/governance/schemas/module.schema.json b/vendor/freedom-tooling/governance/schemas/module.schema.json new file mode 100644 index 0000000..2810372 --- /dev/null +++ b/vendor/freedom-tooling/governance/schemas/module.schema.json @@ -0,0 +1,193 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://freetwai.com/contracts/governance/module/v1", + "title": "Freedom module development schema", + "type": "object", + "properties": { + "format": { + "const": "freedom.module/v1" + }, + "module_id": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "owner_role": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "owned_paths": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[-a-zA-Z0-9_./*]+$" + }, + "minItems": 1, + "maxItems": 64, + "uniqueItems": true + }, + "public_exports": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[-a-zA-Z0-9_./]+$" + }, + "minItems": 0, + "maxItems": 64, + "uniqueItems": true + }, + "dependencies": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "minItems": 0, + "maxItems": 64, + "uniqueItems": true + }, + "contract_families": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "minItems": 0, + "maxItems": 32, + "uniqueItems": true + }, + "client_profiles": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "minItems": 0, + "maxItems": 32, + "uniqueItems": true + }, + "instructions": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[-a-zA-Z0-9_./]+$" + }, + "minItems": 1, + "maxItems": 64, + "uniqueItems": true + }, + "invariants": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "minItems": 0, + "maxItems": 128, + "uniqueItems": true + }, + "tests": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "minItems": 1, + "maxItems": 128, + "uniqueItems": true + }, + "surfaces": { + "type": "array", + "items": { + "type": "object", + "properties": { + "surface_id": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "kind": { + "enum": [ + "page", + "http", + "scheduled", + "queue", + "mcp", + "native", + "cli" + ] + }, + "entry": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[-a-zA-Z0-9_./]+$" + }, + "operations": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "minItems": 1, + "maxItems": 64, + "uniqueItems": true + }, + "auth_profile": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + } + }, + "required": [ + "surface_id", + "kind", + "entry", + "operations", + "auth_profile" + ], + "additionalProperties": false + }, + "minItems": 0, + "maxItems": 256 + } + }, + "required": [ + "format", + "module_id", + "owner_role", + "owned_paths", + "public_exports", + "dependencies", + "contract_families", + "client_profiles", + "instructions", + "invariants", + "tests", + "surfaces" + ], + "additionalProperties": false +} diff --git a/vendor/freedom-tooling/governance/schemas/release-proof.schema.json b/vendor/freedom-tooling/governance/schemas/release-proof.schema.json new file mode 100644 index 0000000..c329f7f --- /dev/null +++ b/vendor/freedom-tooling/governance/schemas/release-proof.schema.json @@ -0,0 +1,47 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://freetwai.com/contracts/governance/release-proof/v1", + "title": "Freedom release-proof development schema", + "type": "object", + "properties": { + "format": { + "const": "freedom.release-proof/v1" + }, + "algorithm": { + "const": "Ed25519" + }, + "purpose": { + "const": "freedom.release-set" + }, + "publisher_id": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "kid": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "manifest_sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "signature": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{86}$" + } + }, + "required": [ + "format", + "algorithm", + "purpose", + "publisher_id", + "kid", + "manifest_sha256", + "signature" + ], + "additionalProperties": false +} diff --git a/vendor/freedom-tooling/governance/schemas/release-set.schema.json b/vendor/freedom-tooling/governance/schemas/release-set.schema.json new file mode 100644 index 0000000..e48c0b0 --- /dev/null +++ b/vendor/freedom-tooling/governance/schemas/release-set.schema.json @@ -0,0 +1,269 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://freetwai.com/contracts/governance/release-set/v1", + "title": "Freedom release-set development schema", + "type": "object", + "properties": { + "format": { + "const": "freedom.release-set/v1" + }, + "digest_profile": { + "const": "sha256-exact-bytes/v1" + }, + "release_set_id": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "source_repository": { + "enum": ["FreeTWAI/freedom-platform", "FreeTWAI-AI/freedom-platform"] + }, + "source_commit": { + "type": "string", + "pattern": "^[a-f0-9]{40}$" + }, + "trust_profile_version": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._+-]*$" + }, + "artifacts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[-a-zA-Z0-9_./]+$" + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "bytes": { + "type": "integer", + "minimum": 0, + "maximum": 2000000 + } + }, + "required": [ + "path", + "sha256", + "bytes" + ], + "additionalProperties": false + }, + "minItems": 1, + "maxItems": 1024 + }, + "contracts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "family": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "version": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._+-]*$" + }, + "artifacts": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[-a-zA-Z0-9_./]+$" + }, + "minItems": 1, + "maxItems": 1024, + "uniqueItems": true + } + }, + "required": [ + "family", + "version", + "artifacts" + ], + "additionalProperties": false + }, + "minItems": 1, + "maxItems": 32 + }, + "libraries": { + "type": "array", + "items": { + "type": "object", + "properties": { + "library_id": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "version": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._+-]*$" + }, + "runtime_profiles": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "minItems": 1, + "maxItems": 32, + "uniqueItems": true + }, + "artifacts": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[-a-zA-Z0-9_./]+$" + }, + "minItems": 1, + "maxItems": 1024, + "uniqueItems": true + } + }, + "required": [ + "library_id", + "version", + "runtime_profiles", + "artifacts" + ], + "additionalProperties": false + }, + "minItems": 1, + "maxItems": 64 + }, + "policy": { + "type": "object", + "properties": { + "revision": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._+-]*$" + }, + "artifacts": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[-a-zA-Z0-9_./]+$" + }, + "minItems": 1, + "maxItems": 1024, + "uniqueItems": true + } + }, + "required": [ + "revision", + "artifacts" + ], + "additionalProperties": false + }, + "generator": { + "type": "object", + "properties": { + "version": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._+-]*$" + }, + "artifacts": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[-a-zA-Z0-9_./]+$" + }, + "minItems": 1, + "maxItems": 1024, + "uniqueItems": true + } + }, + "required": [ + "version", + "artifacts" + ], + "additionalProperties": false + }, + "fixtures": { + "type": "object", + "properties": { + "version": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._+-]*$" + }, + "artifacts": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[-a-zA-Z0-9_./]+$" + }, + "minItems": 1, + "maxItems": 1024, + "uniqueItems": true + } + }, + "required": [ + "version", + "artifacts" + ], + "additionalProperties": false + }, + "profiles": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "minItems": 1, + "maxItems": 32, + "uniqueItems": true + } + }, + "required": [ + "format", + "digest_profile", + "release_set_id", + "source_repository", + "source_commit", + "trust_profile_version", + "artifacts", + "contracts", + "libraries", + "policy", + "generator", + "fixtures", + "profiles" + ], + "additionalProperties": false +} diff --git a/vendor/freedom-tooling/governance/schemas/release-trust.schema.json b/vendor/freedom-tooling/governance/schemas/release-trust.schema.json new file mode 100644 index 0000000..d0dff71 --- /dev/null +++ b/vendor/freedom-tooling/governance/schemas/release-trust.schema.json @@ -0,0 +1,149 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://freetwai.com/contracts/governance/release-trust/v1", + "title": "Freedom release-trust development schema", + "type": "object", + "properties": { + "format": { + "const": "freedom.release-trust/v1" + }, + "version": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._+-]*$" + }, + "environment": { + "enum": [ + "fixture", + "staging", + "production" + ] + }, + "issued_at": { + "type": "string", + "minLength": 1, + "maxLength": 24, + "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$" + }, + "expires_at": { + "type": "string", + "minLength": 1, + "maxLength": 24, + "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$" + }, + "keys": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kid": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "publisher_id": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "source_repository": { + "enum": ["FreeTWAI/freedom-platform", "FreeTWAI-AI/freedom-platform"] + }, + "purpose": { + "const": "freedom.release-set" + }, + "public_jwk": { + "type": "object", + "properties": { + "kty": { + "const": "OKP" + }, + "crv": { + "const": "Ed25519" + }, + "x": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{43}$" + } + }, + "required": [ + "kty", + "crv", + "x" + ], + "additionalProperties": false + }, + "not_before": { + "type": "string", + "minLength": 1, + "maxLength": 24, + "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$" + }, + "not_after": { + "type": "string", + "minLength": 1, + "maxLength": 24, + "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$" + } + }, + "required": [ + "kid", + "publisher_id", + "source_repository", + "purpose", + "public_jwk", + "not_before", + "not_after" + ], + "additionalProperties": false + }, + "minItems": 1, + "maxItems": 32 + }, + "releases": { + "type": "array", + "items": { + "type": "object", + "properties": { + "manifest_sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "policy_revision": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._+-]*$" + }, + "state": { + "enum": [ + "supported", + "withdrawn" + ] + } + }, + "required": [ + "manifest_sha256", + "policy_revision", + "state" + ], + "additionalProperties": false + }, + "minItems": 1, + "maxItems": 1024 + } + }, + "required": [ + "format", + "version", + "environment", + "issued_at", + "expires_at", + "keys", + "releases" + ], + "additionalProperties": false +} diff --git a/vendor/freedom-tooling/governance/schemas/verifier-report.schema.json b/vendor/freedom-tooling/governance/schemas/verifier-report.schema.json new file mode 100644 index 0000000..a259d1b --- /dev/null +++ b/vendor/freedom-tooling/governance/schemas/verifier-report.schema.json @@ -0,0 +1,336 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://freetwai.com/contracts/governance/verifier-report/v1", + "title": "Freedom verifier-report development schema", + "type": "object", + "properties": { + "format": { + "const": "freedom.verifier-report/v1" + }, + "assurance_level": { + "const": "local" + }, + "repository": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "base_commit": { + "type": "string", + "pattern": "^[a-f0-9]{40}$" + }, + "head_commit": { + "type": "string", + "pattern": "^[a-f0-9]{40}$" + }, + "workspace_sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "status": { + "enum": [ + "passed", + "failed", + "unavailable" + ] + }, + "scope": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "minItems": 0, + "maxItems": 1024, + "uniqueItems": true + }, + "checks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "check_id": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "status": { + "enum": [ + "passed", + "failed", + "not_run" + ] + }, + "reason": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "test_count": { + "type": "integer", + "minimum": 0 + }, + "selected_files": { + "type": "array", "minItems": 1, "maxItems": 512, "uniqueItems": true, + "items": { "type": "string", "pattern": "^(tests/runtime/[a-z][a-z0-9_-]*\\.test\\.ts|tests/[a-z][a-z0-9_-]*\\.test\\.mjs|packages/contribution-tools/test/[a-z][a-z0-9-]*\\.test\\.mjs|scripts/run-e2e\\.test\\.mjs)$", "maxLength": 240 } + }, + "test_files": { + "type": "array", + "minItems": 1, + "maxItems": 512, + "items": { + "type": "object", + "properties": { + "path": { "type": "string", "pattern": "^(tests/runtime/[a-z][a-z0-9_-]*\\.test\\.ts|tests/[a-z][a-z0-9_-]*\\.test\\.mjs|packages/contribution-tools/test/[a-z][a-z0-9-]*\\.test\\.mjs|scripts/run-e2e\\.test\\.mjs)$", "maxLength": 240 }, + "counts": { + "type": "object", + "properties": { + "tests": { "type": "integer", "minimum": 0 }, + "passed": { "type": "integer", "minimum": 0 }, + "failed": { "type": "integer", "minimum": 0 }, + "cancelled": { "type": "integer", "minimum": 0 }, + "skipped": { "type": "integer", "minimum": 0 }, + "todo": { "type": "integer", "minimum": 0 } + }, + "required": ["tests", "passed", "failed", "cancelled", "skipped", "todo"], + "additionalProperties": false + }, + "suite_events": { + "type": "array", "minItems": 0, "maxItems": 20000, + "items": { + "type": "object", + "properties": { + "case_sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" }, + "status": { "enum": ["passed", "failed", "cancelled", "skipped", "todo"] } + }, + "required": ["case_sha256", "status"], + "additionalProperties": false + } + }, + "cases": { + "type": "array", "minItems": 0, "maxItems": 20000, + "items": { + "type": "object", + "properties": { + "case_sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" }, + "status": { "enum": ["passed", "failed", "cancelled", "skipped", "todo"] } + }, + "required": ["case_sha256", "status"], + "additionalProperties": false + } + } + }, + "required": ["path", "counts", "cases", "suite_events"], + "additionalProperties": false + } + }, + "shards": { + "type": "array", + "maxItems": 4, + "items": { + "type": "object", + "properties": { + "selected_files": { + "type": "array", + "minItems": 1, + "maxItems": 512, + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^(tests/runtime/[a-z][a-z0-9_-]*\\.test\\.ts|tests/[a-z][a-z0-9_-]*\\.test\\.mjs|packages/contribution-tools/test/[a-z][a-z0-9-]*\\.test\\.mjs)$", + "maxLength": 240 + } + }, + "evidence_sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "reason": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "test_files": { + "type": "array", + "minItems": 1, + "maxItems": 512, + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "pattern": "^(tests/runtime/[a-z][a-z0-9_-]*\\.test\\.ts|tests/[a-z][a-z0-9_-]*\\.test\\.mjs|packages/contribution-tools/test/[a-z][a-z0-9-]*\\.test\\.mjs)$", + "maxLength": 240 + }, + "counts": { + "type": "object", + "properties": { + "tests": { + "type": "integer", + "minimum": 0 + }, + "passed": { + "type": "integer", + "minimum": 0 + }, + "failed": { + "type": "integer", + "minimum": 0 + }, + "cancelled": { + "type": "integer", + "minimum": 0 + }, + "skipped": { + "type": "integer", + "minimum": 0 + }, + "todo": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "tests", + "passed", + "failed", + "cancelled", + "skipped", + "todo" + ], + "additionalProperties": false + }, + "suite_events": { + "type": "array", + "minItems": 0, + "maxItems": 20000, + "items": { + "type": "object", + "properties": { + "case_sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "status": { + "enum": [ + "passed", + "failed", + "cancelled", + "skipped", + "todo" + ] + } + }, + "required": [ + "case_sha256", + "status" + ], + "additionalProperties": false + } + }, + "cases": { + "type": "array", + "minItems": 0, + "maxItems": 20000, + "items": { + "type": "object", + "properties": { + "case_sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "status": { + "enum": [ + "passed", + "failed", + "cancelled", + "skipped", + "todo" + ] + } + }, + "required": [ + "case_sha256", + "status" + ], + "additionalProperties": false + } + } + }, + "required": [ + "path", + "counts", + "cases", + "suite_events" + ], + "additionalProperties": false + } + }, + "exit_code": { + "type": "integer" + }, + "termination_signal": { + "type": "string", + "pattern": "^[A-Z0-9]+$", + "maxLength": 32 + } + }, + "required": [ + "selected_files", + "evidence_sha256", + "reason" + ], + "additionalProperties": false + } + }, + "database_cleanup_verified": { + "type": "boolean" + }, + "evidence_sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + } + }, + "required": [ + "check_id", + "status", + "reason" + ], + "additionalProperties": false + }, + "minItems": 1, + "maxItems": 1024 + }, + "blockers": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._/-]*$" + }, + "minItems": 0, + "maxItems": 1024, + "uniqueItems": true + } + }, + "required": [ + "format", + "assurance_level", + "repository", + "base_commit", + "head_commit", + "workspace_sha256", + "status", + "scope", + "checks", + "blockers" + ], + "additionalProperties": false +} diff --git a/vendor/freedom-tooling/packages/contribution-tools/cli.mjs b/vendor/freedom-tooling/packages/contribution-tools/cli.mjs new file mode 100644 index 0000000..c7cbb6a --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/cli.mjs @@ -0,0 +1,74 @@ +import { buildContext, CONTEXT_LIMITS, writeContextDelivery, readContextDelivery } from './context.mjs'; +import { verifyWorkspace } from './verify.mjs'; +import { writeLocalArtifact, validateArtifactOutputPath } from './local-artifacts.mjs'; +import { VerificationError, safeFailure } from './errors.mjs'; + +function parseArgs(args) { + const [command, ...rest] = args; + if (!['prepare', 'context', 'verify'].includes(command)) throw new VerificationError('unknown_command'); + const options = { baseRef: 'origin/main', requestedPaths: [], scopes: [] }, seen = new Set(); + let report, manifestPath, chunkIndex, complete = false; + for (let index = 0; index < rest.length; index += 2) { + const flag = rest[index], value = rest[index + 1]; + if (!value || value.startsWith('--') || seen.has(flag)) throw new VerificationError('invalid_arguments'); + seen.add(flag); + if (flag === '--base-ref') options.baseRef = value; + else if (flag === '--scope') options.scopes = value.split(','); + else if (flag === '--paths') options.requestedPaths = value.split(','); + else if (flag === '--report' && command === 'verify') report = value; + else if (flag === '--manifest' && command === 'context') manifestPath = value; + else if (flag === '--chunk' && command === 'context' && /^(0|[1-9][0-9]{0,3})$/.test(value)) chunkIndex = Number(value); + else if (flag === '--check' && command === 'context' && value === 'complete') complete = true; + else throw new VerificationError('invalid_arguments'); + } + if (manifestPath || chunkIndex !== undefined || complete) { + if (!manifestPath || complete === (chunkIndex !== undefined) + || ['--base-ref', '--scope', '--paths'].some(flag => seen.has(flag))) throw new VerificationError('invalid_arguments'); + } + return { command, options, report, manifestPath, chunkIndex, complete }; +} + +export async function runFreedomCli(args = process.argv.slice(2), repositoryRoot = process.cwd()) { + try { + const { command, options, report: reportPath, manifestPath, chunkIndex, complete } = parseArgs(args); + if (manifestPath) { + const result = await readContextDelivery(repositoryRoot, manifestPath, { chunkIndex, complete }); + console.log(JSON.stringify(result.value)); + return result.blockers.length ? 2 : 0; + } + if (reportPath) validateArtifactOutputPath(reportPath); + if (command === 'verify') { + const report = await verifyWorkspace({ repositoryRoot, ...options }, { testDatabaseUrl: process.env.TEST_DATABASE_URL }); + if (reportPath) await writeLocalArtifact(repositoryRoot, reportPath, report); + console.log(JSON.stringify(report)); + return report.status === 'passed' ? 0 : report.status === 'unavailable' ? 2 : 1; + } + let context; + try { + ({ context } = await buildContext({ repositoryRoot, ...options })); + if (Buffer.byteLength(JSON.stringify(context, null, 2) + '\n') > CONTEXT_LIMITS.bundle_bytes) throw new VerificationError('context_size_limit'); + } catch (error) { + if (error.code !== 'context_size_limit') throw error; + const built = await writeContextDelivery({ repositoryRoot, ...options }); + console.log(JSON.stringify(command === 'context' ? built.manifest : { + format: built.manifest.format, assurance_level: 'local', context_path: built.manifestPath, + delivery_id: built.manifest.delivery_id, binding: built.manifest.binding, chunk_count: built.chunks.length, + read_chunk: `node scripts/freedom.mjs context --manifest ${built.manifestPath} --chunk 0`, + check_complete: `node scripts/freedom.mjs context --manifest ${built.manifestPath} --check complete`, + })); + return built.context.blockers.length ? 2 : 0; + } + if (command === 'context') console.log(JSON.stringify(context)); + else { + const path = await writeLocalArtifact(repositoryRoot, `.freedom/context/${context.task_id}/bundle.json`, context); + console.log(JSON.stringify({ format: context.format, assurance_level: 'local', context_path: path, + task_id: context.task_id, base_commit: context.base_commit, head_commit: context.head_commit, + module_ids: context.module_ids, tests: context.tests, blockers: context.blockers })); + } + return context.blockers.length ? 2 : 0; + } catch (error) { + const failure = safeFailure(error); + console.log(JSON.stringify({ format: 'freedom.cli-error/v1', assurance_level: 'local', ...failure })); + return failure.status === 'unavailable' ? 2 : 1; + } +} diff --git a/vendor/freedom-tooling/packages/contribution-tools/consumer-libraries.mjs b/vendor/freedom-tooling/packages/contribution-tools/consumer-libraries.mjs index a229316..668edb9 100644 --- a/vendor/freedom-tooling/packages/contribution-tools/consumer-libraries.mjs +++ b/vendor/freedom-tooling/packages/contribution-tools/consumer-libraries.mjs @@ -1,3 +1,4 @@ +import {matchesRecordedRepository,isPlatformSourceRepository,repositoryTransport} from './repository-identity.mjs'; import { execFileSync } from 'node:child_process'; import { readBounded, parseJson, sha256, readRemoteBounded } from './io.mjs'; import { requireCondition as check } from './errors.mjs'; @@ -5,18 +6,39 @@ import { verificationEnvironment } from './process-env.mjs'; // This is a source distribution map. It is not ReleaseSet approval or usage evidence. export const CONSUMER_LIBRARIES = Object.freeze({ - 'FreeTWAI-AI/freedom-agent-kit': ['packages/sdk/member-workspace.mjs'], - 'FreeTWAI-AI/freedom-storefront': [ + 'FreeTWAI/freedom-agent-kit': ['packages/sdk/member-workspace.mjs'], + 'FreeTWAI/freedom-storefront': [ 'packages/client-connections/read-client.mjs', 'packages/client-connections/storefront-workspace.mjs', ], - 'FreeTWAI-AI/freedom-supplier-client': [ + 'FreeTWAI/freedom-supplier-client': [ 'packages/client-connections/read-client.mjs', 'packages/client-connections/supplier-workspace.mjs', ], }); export const LIBRARY_LOCK = 'consumer-libraries.lock.json'; export const LIBRARY_PREFIX = 'vendor/freedom-libraries/'; +export const LEGACY_LIBRARY_PROFILE = 'legacy-v1'; +export const AGENT_KIT_DEVICE_LIBRARY_PROFILE = 'agent-kit-device-v1'; +export const AGENT_KIT_DEVICE_CLI_LIBRARY_PROFILE = 'agent-kit-device-cli-v1'; +const deviceLibraries = Object.freeze([ + 'packages/sdk/member-workspace.mjs', + 'packages/sdk/machine-device-client.mjs', +]); + +/** The host/operator selects a fixed profile; a candidate lock never selects it. */ +export function consumerLibraryProfile(repository, expectedLibraryProfile = LEGACY_LIBRARY_PROFILE) { + check(Object.hasOwn(CONSUMER_LIBRARIES, repository), 'unsupported_library_consumer'); + if (expectedLibraryProfile === LEGACY_LIBRARY_PROFILE) { + return { id: LEGACY_LIBRARY_PROFILE, format: 'freedom.consumer-libraries/v1', paths: CONSUMER_LIBRARIES[repository] }; + } + check(repository === 'FreeTWAI/freedom-agent-kit' + && [AGENT_KIT_DEVICE_LIBRARY_PROFILE, AGENT_KIT_DEVICE_CLI_LIBRARY_PROFILE].includes(expectedLibraryProfile), 'unsupported_library_profile'); + if (expectedLibraryProfile === AGENT_KIT_DEVICE_LIBRARY_PROFILE) return { id: expectedLibraryProfile, format: 'freedom.consumer-libraries/v2', paths: deviceLibraries }; + return { id: expectedLibraryProfile, format: 'freedom.consumer-libraries/v2', + paths: [...deviceLibraries, 'packages/sdk/machine-device-cli.mjs'], + entrypoints: [{ source: 'scripts/repository-bootstrap/agent-kit-device-cli.mjs', target: 'src/device-cli.mjs' }] }; +} export function sourceGit(root, args) { return execFileSync('git', ['--no-optional-locks', '-c', 'core.fsmonitor=false', ...args], { @@ -26,16 +48,17 @@ export function sourceGit(root, args) { } /** Verify with a host-selected expected commit; self-declared lock digests are insufficient. */ -export async function verifyConsumerLibraries(root, { expectedSourceCommit, repository, sourceRoot, remote = false, fetcher } = {}) { +export async function verifyConsumerLibraries(root, { expectedSourceCommit, expectedLibraryProfile, repository, sourceRoot, remote = false, fetcher } = {}) { check(/^[a-f0-9]{40}$/.test(expectedSourceCommit ?? ''), 'expected_library_source_required'); - check(Object.hasOwn(CONSUMER_LIBRARIES, repository), 'unsupported_library_consumer'); + const profile = consumerLibraryProfile(repository, expectedLibraryProfile); check(Boolean(sourceRoot) !== remote, 'one_library_source_required'); const lock = parseJson(await readBounded(root, LIBRARY_LOCK)); - check(lock.format === 'freedom.consumer-libraries/v1' - && lock.source_repository === 'FreeTWAI-AI/freedom-platform' - && lock.source_commit === expectedSourceCommit && lock.repository === repository, 'library_source_mismatch'); - const expected = CONSUMER_LIBRARIES[lock.repository]; - check(Object.hasOwn(CONSUMER_LIBRARIES, lock.repository) && Array.isArray(lock.files) + check(isPlatformSourceRepository(lock.source_repository) + && lock.source_commit === expectedSourceCommit && matchesRecordedRepository(lock.repository, repository), 'library_source_mismatch'); + check(lock.format === profile.format && (profile.id === LEGACY_LIBRARY_PROFILE + ? !Object.hasOwn(lock, 'profile') : lock.profile === profile.id), 'library_profile_mismatch'); + const expected = profile.paths; + check(Array.isArray(lock.files) && lock.files.length === expected.length, 'library_profile_mismatch'); for (const [index, path] of expected.entries()) { const file = lock.files[index]; @@ -46,9 +69,15 @@ export async function verifyConsumerLibraries(root, { expectedSourceCommit, repo check(bytes.length === file.bytes && sha256(bytes) === file.sha256, 'library_bytes_mismatch'); const source = sourceRoot ? sourceGit(sourceRoot, ['show', `${expectedSourceCommit}:${path}`]) - : await readRemoteBounded(`https://raw.githubusercontent.com/${lock.source_repository}/${expectedSourceCommit}/${path}`, fetcher); + : await readRemoteBounded(`https://raw.githubusercontent.com/${repositoryTransport(lock.source_repository)}/${expectedSourceCommit}/${path}`, fetcher); check(source.equals(bytes), 'library_source_bytes_mismatch'); } - return { repository: lock.repository, source_commit: expectedSourceCommit, files_verified: expected.length, + for (const { source: path, target } of profile.entrypoints ?? []) { + const bytes = await readBounded(root, target); + const source = sourceRoot ? sourceGit(sourceRoot, ['show', `${expectedSourceCommit}:${path}`]) + : await readRemoteBounded(`https://raw.githubusercontent.com/${repositoryTransport(lock.source_repository)}/${expectedSourceCommit}/${path}`, fetcher); + check(source.equals(bytes), 'library_entry_source_mismatch'); + } + return { repository: lock.repository, source_commit: expectedSourceCommit, library_profile: profile.id, files_verified: expected.length + (profile.entrypoints?.length ?? 0), verification: 'source_bytes_only', library_usage: 'not_checked', publisher_trust: 'unverified' }; } diff --git a/vendor/freedom-tooling/packages/contribution-tools/context.mjs b/vendor/freedom-tooling/packages/contribution-tools/context.mjs new file mode 100644 index 0000000..bb04bc3 --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/context.mjs @@ -0,0 +1,322 @@ +import { artifactPath, readBounded, parseJson, sha256 } from './io.mjs'; +import { parseFormat, validateFormat } from './formats.mjs'; +import { inspectWorkspace, readRevisionFile } from './workspace.mjs'; +import { VerificationError, requireCondition as check } from './errors.mjs'; +import { validateReleaseSet } from './contracts.mjs'; +import { readLocalArtifact, writeLocalArtifact } from './local-artifacts.mjs'; + +export const ROOT_INSTRUCTIONS = ['AGENTS.md', 'README.md', 'CONTRIBUTING.md']; +export const isModuleDescriptorPath = path => path === 'freedom.module.json' || path.endsWith('/freedom.module.json'); +export function validateDescriptor(value) { + validateFormat('moduleDescriptor', value); + for (const path of value.owned_paths) { + const prefix = path.endsWith('/**') ? path.slice(0, -3) : path; + artifactPath(prefix); + check(!prefix.includes('*'), 'invalid_module_pattern'); + } + for (const path of [...value.public_exports, ...value.instructions, ...value.surfaces.map(surface => surface.entry)]) artifactPath(path); + check(new Set(value.surfaces.map(surface => surface.surface_id)).size === value.surfaces.length, 'duplicate_surface'); + return value; +} + +export function owns(descriptor, path) { + return descriptor.owned_paths.some(pattern => pattern.endsWith('/**') + ? path.startsWith(pattern.slice(0, -2)) : path === pattern); +} + +export function selectImpact({ baseline, candidate, changedPaths, requestedPaths = [], scopes = [] }) { + const descriptors = [...baseline, ...candidate], modules = new Set(), unknown = []; + const known = new Set(descriptors.map(item => item.module_id)); + for (const scope of scopes) { + check(known.has(scope), 'unknown_module_scope'); + modules.add(scope); + } + for (const path of new Set([...changedPaths, ...requestedPaths])) { + artifactPath(path); + const matched = descriptors.filter(item => owns(item, path)); + for (const item of matched) modules.add(item.module_id); + if (ROOT_INSTRUCTIONS.includes(path)) for (const id of known) modules.add(id); + if (!matched.length && !/^docs\/.*\.md$/.test(path) && !ROOT_INSTRUCTIONS.includes(path)) unknown.push(path); + } + // Renamed/deleted/shrunk candidate globs cannot subtract the baseline's impact. + if (unknown.length) for (const id of known) modules.add(id); + let grew = true; + while (grew) { + grew = false; + for (const item of descriptors) if (!modules.has(item.module_id) && item.dependencies.some(id => modules.has(id))) { + modules.add(item.module_id); grew = true; + } + } + const selected = descriptors.filter(item => modules.has(item.module_id)); + return { module_ids: [...modules].sort(), tests: [...new Set(selected.flatMap(item => item.tests))].sort(), + instructions: [...new Set(selected.flatMap(item => item.instructions))].sort(), unknown_paths: [...new Set(unknown)].sort() }; +} + +async function descriptorsFor(workspace, revision) { + const paths = (revision === 'base' ? workspace.base_paths : workspace.candidate_paths).filter(isModuleDescriptorPath); + check(paths.length <= 256, 'module_limit'); + const descriptors = []; + for (const path of paths) { + let bytes; + if (revision === 'base') bytes = readRevisionFile(workspace, path); + else { + try { bytes = await readBounded(workspace.root, path); } + catch (error) { if (error.code === 'artifact_missing') continue; throw error; } + } + const descriptor = validateDescriptor(parseFormat('moduleDescriptor', bytes)); + // A descriptor change always selects its own previous/new module. + descriptors.push({ ...descriptor, owned_paths: [...descriptor.owned_paths, path] }); + } + check(new Set(descriptors.map(item => item.module_id)).size === descriptors.length, 'duplicate_module'); + const known = new Set(descriptors.map(item => item.module_id)); + for (const item of descriptors) check(item.dependencies.every(id => known.has(id)), 'module_dependency_missing'); + const active = new Set(), done = new Set(), byId = new Map(descriptors.map(item => [item.module_id, item])); + const visit = id => { + check(!active.has(id), 'module_dependency_cycle'); + if (done.has(id)) return; + active.add(id); + for (const dependency of byId.get(id).dependencies) visit(dependency); + active.delete(id); done.add(id); + }; + for (const id of known) visit(id); + return descriptors; +} + +function allowedInstruction(path) { + artifactPath(path); + check(ROOT_INSTRUCTIONS.includes(path) || path === 'DESIGN.md' || path.endsWith('/AGENTS.md') || /^(docs|modules|packages|contracts|governance)\/.*\.md$/.test(path) + || path === 'vendor/freedom-tooling/governance/README.md', 'instruction_path_denied'); + check(!path.split('/').some(part => part.startsWith('.')), 'instruction_path_denied'); +} + +async function versionInputs(workspace, consume) { + const inputs = []; + const paths = ['contracts.lock.json', 'contracts/preview/v1/bundle.json', 'vendor/freedom-platform/bundle.json', + 'vendor/freedom-platform/release-set.json', 'package.json', 'package-lock.json', 'Cargo.lock']; + for (const path of paths) for (const revision of ['base', 'candidate']) { + if (!(revision === 'base' ? workspace.base_paths : workspace.candidate_paths).includes(path)) continue; + let bytes; + try { bytes = revision === 'base' ? readRevisionFile(workspace, path) : await readBounded(workspace.root, path); } + catch (error) { if (revision === 'candidate' && error.code === 'artifact_missing') continue; throw error; } + const input = { path, revision, sha256: sha256(bytes), bytes: bytes.length }; + // Only fixed, public contract formats are copied. Dependency manifests/locks + // are fingerprinted, not dumped into context (they can contain registry URLs). + if (!['package.json', 'package-lock.json', 'Cargo.lock'].includes(path)) { + const data = parseJson(bytes); + if (path === 'contracts.lock.json') validateFormat(data.format === 'freedom.contract-pin/v1' ? 'lockV1' : 'lockV2', data); + else if (path.endsWith('/release-set.json')) validateReleaseSet(data); + else { + check(data.format === 'freedom.contract-bundle/v1' && data.protocol === 'freedom.preview/v1' + && typeof data.protocol_sha256 === 'string' && /^[a-f0-9]{64}$/.test(data.protocol_sha256), 'invalid_preview_bundle'); + // Preview metadata is not a ReleaseSet or an execution authorization. + input.content = JSON.stringify({ format: data.format, protocol: data.protocol, protocol_sha256: data.protocol_sha256 }); + } + input.content ??= bytes.toString('utf8'); + } + if (consume && input.content !== undefined) { consume('version', input); delete input.content; } + inputs.push(input); + } + return inputs; +} + +async function collectContext({ repositoryRoot, baseRef = 'origin/main', requestedPaths = [], scopes = [], repository }, consume) { + check(Array.isArray(requestedPaths) && requestedPaths.length <= 4096 && Array.isArray(scopes) && scopes.length <= 256, 'invalid_arguments'); + for (const path of requestedPaths) artifactPath(path); + for (const scope of scopes) check(typeof scope === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,159}$/.test(scope) + && !/[\r\n]/.test(scope), 'invalid_module_scope'); + const workspace = await inspectWorkspace(repositoryRoot, baseRef); + if (!repository) { + const pkg = parseJson(await readBounded(workspace.root, 'package.json')); + // Reviewed existing scoped consumer names; this labels local context, never + // authenticates a remote repository or grants publisher trust. + const scopedNames = { '@freetwai/agent-kit': 'freedom-agent-kit', '@freetwai/freedom-storefront': 'freedom-storefront' }; + const name = Object.hasOwn(scopedNames, pkg.name) ? scopedNames[pkg.name] : pkg.name; + check(typeof name === 'string' && /^freedom-[a-z-]+$/.test(name) && !/[\r\n]/.test(name), 'repository_identity_required'); + repository = 'FreeTWAI/' + name; + } + const baseline = await descriptorsFor(workspace, 'base'), candidate = await descriptorsFor(workspace, 'candidate'); + const impact = selectImpact({ baseline, candidate, changedPaths: workspace.changed_paths, requestedPaths, scopes }); + const blockers = [], documents = [], seen = new Set(); let totalBytes = 0; + if (!baseline.length) blockers.push('baseline_governance_unavailable'); + if (!candidate.length) blockers.push('candidate_governance_unavailable'); + if (impact.unknown_paths.length) blockers.push('surface_unmapped'); + const sharedInstructions = ['contracts/README.md', 'vendor/freedom-tooling/governance/README.md'] + .filter(path => workspace.base_paths.includes(path) || workspace.candidate_paths.includes(path)); + const relevantPaths = [...workspace.changed_paths, ...requestedPaths, ...[...baseline, ...candidate] + .filter(item => impact.module_ids.includes(item.module_id)).flatMap(item => item.owned_paths.map(path => path.replace(/\/\*\*$/, '/')))]; + const nestedInstructions = [...workspace.base_paths, ...workspace.candidate_paths].filter(path => path.endsWith('/AGENTS.md') + && relevantPaths.some(target => target.startsWith(path.slice(0, -'AGENTS.md'.length)))); + const instructions = [...new Set([...ROOT_INSTRUCTIONS, ...sharedInstructions, ...nestedInstructions, ...impact.instructions])]; + for (const path of instructions) { + allowedInstruction(path); + for (const revision of ['base', 'candidate']) { + if (revision === 'base' && !workspace.base_paths.includes(path)) { + if (ROOT_INSTRUCTIONS.includes(path) || baseline.some(item => impact.module_ids.includes(item.module_id) && item.instructions.includes(path))) { + blockers.push('baseline_instruction_missing'); + } + continue; + } + let bytes; + try { bytes = revision === 'base' ? readRevisionFile(workspace, path) : await readBounded(workspace.root, path); } + catch (error) { + if (revision === 'candidate' && error.code === 'artifact_missing') { blockers.push('instruction_missing'); continue; } + throw error; + } + const digest = sha256(bytes), identity = path + ':' + digest; + if (!consume && seen.has(identity)) continue; + seen.add(identity); totalBytes += bytes.length; + if (!consume) check(totalBytes <= 512_000, 'context_size_limit'); + let content; + try { content = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes); } + catch { throw new VerificationError('invalid_instruction_encoding'); } + const document = { path, revision, sha256: digest, bytes: bytes.length, content }; + if (consume) consume('instruction', document); + else documents.push(document); + } + } + // Descriptors cite policies, not new ACLs. Existence is not behavior coverage. + for (const descriptor of candidate) if (impact.module_ids.includes(descriptor.module_id)) { + for (const entry of [...descriptor.public_exports, ...descriptor.surfaces.map(surface => surface.entry)]) { + await readBounded(workspace.root, entry); + } + } + const context = { format: 'freedom.coding-context/v1', assurance_level: 'local', + task_id: 'task-' + sha256(JSON.stringify([workspace.base_commit, workspace.head_commit, workspace.workspace_sha256, requestedPaths, scopes])).slice(0, 16), + repository, workspace_id: workspace.workspace_id, branch: workspace.branch, + base_commit: workspace.base_commit, head_commit: workspace.head_commit, + workspace_sha256: workspace.workspace_sha256, requested_paths: [...new Set(requestedPaths)].sort(), changed_paths: workspace.changed_paths, + module_ids: impact.module_ids, documents, version_inputs: await versionInputs(workspace, consume), + publisher_trust: 'unverified', library_usage: 'not_checked', + tests: impact.tests, blockers: [...new Set(blockers)].sort() }; + if (!consume) check(totalBytes + context.version_inputs.reduce((sum, input) => sum + Buffer.byteLength(input.content ?? ''), 0) <= 512_000, 'context_size_limit'); + validateFormat('codingContext', context); + const after = await inspectWorkspace(workspace.root, baseRef); + check(after.workspace_sha256 === workspace.workspace_sha256, 'workspace_changed_during_context'); + return { context, workspace, baseline, candidate, impact }; +} + +export const CONTEXT_LIMITS = Object.freeze({ + bundle_bytes: 512_000, artifact_bytes: 512_000, chunk_content_bytes: 65_536, + sources: 1024, chunks: 1024, total_content_bytes: 32_000_000, +}); +const jsonBytes = value => Buffer.from(JSON.stringify(value, null, 2) + '\n'); +function boundedArtifact(value) { + const bytes = jsonBytes(value); + check(bytes.length <= CONTEXT_LIMITS.artifact_bytes, 'context_artifact_size_limit'); + return bytes; +} +function contentBudget() { + let count = 0, bytes = 0; + return input => { + check(++count <= CONTEXT_LIMITS.sources, 'context_source_limit'); + bytes += Buffer.byteLength(input.content); + check(bytes <= CONTEXT_LIMITS.total_content_bytes, 'context_total_size_limit'); + }; +} + +// The original small-bundle API retains its cap and schema. Metadata collection +// still reads/validates every applicable rule, without retaining its full text. +export async function buildContext(options) { return collectContext(options); } +export async function buildContextMetadata(options) { + const admit = contentBudget(); + const built = await collectContext(options, (_kind, input) => admit(input)); + boundedArtifact(built.context); + return built; +} + +export async function buildContextDelivery(options) { + const request = { baseRef: options.baseRef ?? 'origin/main', + requestedPaths: Array.isArray(options.requestedPaths) ? [...options.requestedPaths] : options.requestedPaths ?? [], + scopes: Array.isArray(options.scopes) ? [...options.scopes] : options.scopes ?? [], + ...(options.repository === undefined ? {} : { repository: options.repository }) }; + const sources = [], parts = [], admit = contentBudget(); + const built = await collectContext({ ...request, repositoryRoot: options.repositoryRoot }, (kind, input) => { + admit(input); + const { content, ...source } = input, bytes = Buffer.from(content); + const first = parts.length, sourceIndex = sources.length; + for (let start = 0; start < bytes.length || start === 0;) { + let end = Math.min(start + CONTEXT_LIMITS.chunk_content_bytes, bytes.length); + // A fragment is complete UTF-8, including any BOM; no replacement or trim. + while (end < bytes.length && (bytes[end] & 0xc0) === 0x80) end--; + const fragment = bytes.subarray(start, end); + check(parts.length < CONTEXT_LIMITS.chunks, 'context_chunk_limit'); + parts.push({ source_index: sourceIndex, offset: start, bytes: fragment.length, + sha256: sha256(fragment), content: fragment.toString('utf8') }); + if (end === bytes.length) break; + start = end; + } + sources.push({ kind, ...source, content_bytes: bytes.length, content_sha256: sha256(bytes), + first_chunk: first, chunk_count: parts.length - first }); + }); + const { documents: _documents, format: _format, ...binding } = built.context; + const selectedModules = descriptors => descriptors.filter(item => binding.module_ids.includes(item.module_id)) + .map(item => ({ module_id: item.module_id, dependencies: [...item.dependencies].sort() })); + const selection = { unknown_paths: built.impact.unknown_paths, + baseline_modules: selectedModules(built.baseline), candidate_modules: selectedModules(built.candidate) }; + const deliveryId = sha256(JSON.stringify({ binding, request, selection, sources })); + const directory = `.freedom/context/${binding.task_id}/${deliveryId}`; + const chunks = parts.map((part, index) => { + const source = sources[part.source_index]; + const value = { format: 'freedom.coding-context-chunk/v1', assurance_level: 'local', delivery_id: deliveryId, + index, source: { kind: source.kind, path: source.path, revision: source.revision, sha256: source.sha256, bytes: source.bytes, + commit: source.revision === 'base' ? binding.base_commit : binding.head_commit, + workspace_sha256: source.revision === 'candidate' ? binding.workspace_sha256 : null }, ...part }; + const bytes = boundedArtifact(value); + return { path: `${directory}/chunk-${index}.json`, value, sha256: sha256(bytes), bytes: bytes.length }; + }); + const paths = [...new Set(sources.filter(source => source.kind === 'instruction').map(source => source.path))]; + const delta = paths.map(path => { + const base = sources.find(source => source.kind === 'instruction' && source.path === path && source.revision === 'base'); + const candidate = sources.find(source => source.kind === 'instruction' && source.path === path && source.revision === 'candidate'); + return { path, status: !base ? 'added' : !candidate ? 'missing_candidate' : base.sha256 === candidate.sha256 ? 'unchanged' : 'changed', + base_sha256: base?.sha256 ?? null, candidate_sha256: candidate?.sha256 ?? null }; + }); + const manifest = { format: 'freedom.coding-context-manifest/v1', assurance_level: 'local', delivery_id: deliveryId, + request, binding, selection, limits: CONTEXT_LIMITS, sources, delta, + chunks: chunks.map(({ path, sha256, bytes }, index) => ({ index, path, sha256, bytes })) }; + boundedArtifact(manifest); + return { ...built, manifest, manifestPath: `${directory}/manifest.json`, chunks }; +} + +async function unchangedDelivery(repositoryRoot, built) { + const current = await inspectWorkspace(repositoryRoot, built.manifest.request.baseRef); + check(current.workspace_sha256 === built.context.workspace_sha256, 'stale_context_delivery'); +} + +export async function writeContextDelivery(options) { + const built = await buildContextDelivery(options); + for (const chunk of built.chunks) await writeLocalArtifact(built.workspace.root, chunk.path, chunk.value); + await unchangedDelivery(built.workspace.root, built); + // The manifest is the final publication marker. A partial write never emits it. + await writeLocalArtifact(built.workspace.root, built.manifestPath, built.manifest); + await unchangedDelivery(built.workspace.root, built); + return built; +} + +export async function readContextDelivery(repositoryRoot, manifestPath, { chunkIndex, complete = false } = {}) { + check(typeof manifestPath === 'string' && /^\.freedom\/context\/task-[a-f0-9]{16}\/[a-f0-9]{64}\/manifest\.json$/.test(manifestPath), 'context_manifest_path_denied'); + check(complete === true && chunkIndex === undefined || complete === false && Number.isSafeInteger(chunkIndex) && chunkIndex >= 0, + 'invalid_context_read'); + const storedBytes = await readLocalArtifact(repositoryRoot, manifestPath, CONTEXT_LIMITS.artifact_bytes); + const stored = parseJson(storedBytes, { maxBytes: CONTEXT_LIMITS.artifact_bytes }); + check(stored.format === 'freedom.coding-context-manifest/v1' && stored.request && typeof stored.request === 'object' + && !Array.isArray(stored.request) && Object.keys(stored.request).every(key => ['baseRef', 'requestedPaths', 'scopes', 'repository'].includes(key)) + && typeof stored.request.baseRef === 'string' && Array.isArray(stored.request.requestedPaths) && Array.isArray(stored.request.scopes), 'invalid_context_manifest'); + // A self-consistent local digest is not trusted evidence. Recompute complete + // scope and bytes from this workspace; never follow candidate-supplied paths. + const built = await buildContextDelivery({ ...stored.request, repositoryRoot }); + check(manifestPath === built.manifestPath && storedBytes.equals(boundedArtifact(built.manifest)), 'stale_or_modified_context_manifest'); + if (!complete) check(chunkIndex < built.chunks.length, 'context_chunk_out_of_range'); + for (const chunk of built.chunks) { + const bytes = await readLocalArtifact(repositoryRoot, chunk.path, CONTEXT_LIMITS.artifact_bytes); + check(bytes.length === chunk.bytes && sha256(bytes) === chunk.sha256, 'context_chunk_mismatch'); + } + await unchangedDelivery(repositoryRoot, built); + // Detect a manifest replaced while checking the source or the other chunks. + check((await readLocalArtifact(repositoryRoot, manifestPath, CONTEXT_LIMITS.artifact_bytes)).equals(storedBytes), 'context_manifest_changed'); + const value = complete ? { format: 'freedom.coding-context-completeness/v1', assurance_level: 'local', + delivery_id: built.manifest.delivery_id, binding: built.manifest.binding, + complete: built.context.blockers.length === 0, sources: built.manifest.sources.length, chunks: built.chunks.length, + publisher_trust: 'unverified', library_usage: 'not_checked' } : built.chunks[chunkIndex].value; + return { value, blockers: built.context.blockers }; +} diff --git a/vendor/freedom-tooling/packages/contribution-tools/contracts.mjs b/vendor/freedom-tooling/packages/contribution-tools/contracts.mjs new file mode 100644 index 0000000..b85a143 --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/contracts.mjs @@ -0,0 +1,213 @@ +import { createPublicKey, verify } from 'node:crypto'; +import { resolve } from 'node:path'; +import { VerificationError, requireCondition as check } from './errors.mjs'; +import { assertSchema } from './schema.mjs'; +import { parseFormat, validateFormat } from './formats.mjs'; +import { artifactPath, uniquePaths, readBounded, listArtifacts, readRemoteBounded, + parseJson, sha256, MAX_ARTIFACTS, MAX_TOTAL_BYTES } from './io.mjs'; + +export const CANONICAL_REPOSITORY = 'FreeTWAI/freedom-platform'; +const SIGNING_DOMAIN = Buffer.from('freedom.release-set-signature/v1\0', 'utf8'); +const fileDigest = { type: 'object', required: ['sha256', 'bytes'], additionalProperties: false, + properties: { sha256: { type: 'string', pattern: '^[a-f0-9]{64}$' }, + bytes: { type: 'integer', minimum: 0, maximum: 2_000_000 } } }; +const legacyBundleSchema = { + type: 'object', required: ['format', 'protocol', 'revision', 'protocol_sha256', 'files'], additionalProperties: false, + properties: { + format: { const: 'freedom.contract-bundle/v1' }, protocol: { const: 'freedom.preview/v1' }, + revision: { type: 'string', minLength: 1, maxLength: 80, pattern: '^[a-zA-Z0-9][a-zA-Z0-9._+-]*$' }, + protocol_sha256: { type: 'string', pattern: '^[a-f0-9]{64}$' }, + files: { type: 'object', additionalProperties: fileDigest }, + }, +}; + +function uniqueBy(items, field, code) { + check(new Set(items.map(item => item[field])).size === items.length, code); +} + +export function validateReleaseSet(manifest) { + validateFormat('releaseSet', manifest); + const paths = uniquePaths(manifest.artifacts.map(artifact => artifact.path)); + check(!paths.has('release-set.json') && !paths.has('release-set.proof.json'), 'self_referential_release'); + check(manifest.artifacts.reduce((sum, item) => sum + item.bytes, 0) <= MAX_TOTAL_BYTES, 'artifact_total_limit'); + uniqueBy(manifest.contracts, 'family', 'duplicate_contract_family'); + uniqueBy(manifest.libraries, 'library_id', 'duplicate_library'); + const references = new Set(); + for (const component of [...manifest.contracts, ...manifest.libraries, manifest.policy, manifest.generator, manifest.fixtures]) { + for (const path of component.artifacts) { + artifactPath(path); + check(paths.has(path), 'missing_release_artifact'); + references.add(path); + } + } + check(paths.size === references.size, 'unclassified_release_artifact'); + for (const library of manifest.libraries) { + check(library.runtime_profiles.every(profile => manifest.profiles.includes(profile)), 'unknown_runtime_profile'); + } + return manifest; +} + +// This signature profile signs exact published bytes with an explicit domain, +// not reserialized JSON or the historical preview/SQL digest algorithm. +export function releaseSigningBytes(manifestBytes) { + const manifest = parseJson(manifestBytes); + validateReleaseSet(manifest); + return Buffer.concat([SIGNING_DOMAIN, Buffer.from(manifestBytes)]); +} + +// Authoring helper only: no signing, fetching, publication or consumer writes. +export async function buildReleaseSet({ artifactRoot, artifactPaths, metadata }) { + const paths = [...uniquePaths(artifactPaths)].sort(), artifacts = []; + for (const path of paths) { + const bytes = await readBounded(artifactRoot, path); + artifacts.push({ path, bytes: bytes.length, sha256: sha256(bytes) }); + } + check(metadata && !Object.hasOwn(metadata, 'artifacts'), 'authoring_artifacts_are_derived'); + const manifest = validateReleaseSet({ ...metadata, artifacts }); + const sort = value => Array.isArray(value) ? value.map(sort) + : value !== null && typeof value === 'object' + ? Object.fromEntries(Object.keys(value).sort().map(key => [key, sort(value[key])])) : value; + // Deterministic authoring encoding, NOT RFC 8785 or the execution digest. + return Buffer.from(JSON.stringify(sort(manifest), null, 2) + '\n'); +} + +function time(value) { + const parsed = Date.parse(value); + check(Number.isFinite(parsed) && new Date(parsed).toISOString() === value, 'invalid_trust_time'); + return parsed; +} + +export function verifyReleaseProof(manifestBytes, proofBytes, { + // Supplied only by the verifier's operator, never resolved from candidate files. + trustProfile, environment = 'production', now = Date.now(), maxTrustAgeMs = 86_400_000, +} = {}) { + const manifest = validateReleaseSet(parseJson(manifestBytes)); + const proof = parseFormat('proof', proofBytes), digest = sha256(manifestBytes); + check(proof.manifest_sha256 === digest, 'proof_subject_mismatch'); + if (!trustProfile) throw new VerificationError('release_trust_unavailable', true); + validateFormat('trust', trustProfile); + check(['fixture', 'staging', 'production'].includes(environment), 'invalid_environment'); + check(trustProfile.environment === environment, 'trust_environment_mismatch'); + check(trustProfile.version === manifest.trust_profile_version, 'trust_version_mismatch'); + check(Number.isFinite(now) && Number.isSafeInteger(maxTrustAgeMs) && maxTrustAgeMs > 0, 'invalid_trust_time'); + const issued = time(trustProfile.issued_at), expires = time(trustProfile.expires_at); + check(expires > issued && expires - issued <= maxTrustAgeMs, 'invalid_trust_window'); + if (now < issued || now >= expires || now - issued > maxTrustAgeMs) { + throw new VerificationError('release_trust_stale', true); + } + uniqueBy(trustProfile.keys, 'kid', 'duplicate_trust_key'); + check(new Set(trustProfile.keys.map(key => key.public_jwk.x)).size === trustProfile.keys.length, 'duplicate_trust_key'); + uniqueBy(trustProfile.releases, 'manifest_sha256', 'duplicate_release_status'); + const supported = trustProfile.releases.find(item => item.manifest_sha256 === digest); + check(supported, 'release_not_approved'); + check(supported.state === 'supported', 'release_withdrawn'); + check(supported.policy_revision === manifest.policy.revision, 'policy_revision_mismatch'); + const signer = trustProfile.keys.find(item => item.kid === proof.kid); + check(signer && signer.publisher_id === proof.publisher_id && signer.source_repository === manifest.source_repository, + 'publisher_not_approved'); + check(now >= time(signer.not_before) && now < time(signer.not_after), 'signing_key_inactive'); + const publicBytes = Buffer.from(signer.public_jwk.x, 'base64url'), signature = Buffer.from(proof.signature, 'base64url'); + check(publicBytes.length === 32 && publicBytes.toString('base64url') === signer.public_jwk.x, + 'invalid_public_key'); + check(signature.length === 64 && signature.toString('base64url') === proof.signature, 'invalid_signature'); + let valid = false; + try { + const key = createPublicKey({ key: signer.public_jwk, format: 'jwk' }); + check(key.asymmetricKeyType === 'ed25519', 'invalid_public_key'); + valid = verify(null, releaseSigningBytes(manifestBytes), key, signature); + } catch { throw new VerificationError('invalid_signature'); } + check(valid, 'invalid_signature'); + return { manifest, manifest_sha256: digest, publisher_id: signer.publisher_id, + publisher_trust: environment === 'fixture' ? 'fixture' : 'operator_approved', environment }; +} + +export async function verifyArtifactSet(root, declarations) { + const expected = uniquePaths(declarations.map(item => item.path)); + check(declarations.reduce((sum, item) => sum + item.bytes, 0) <= MAX_TOTAL_BYTES, 'artifact_total_limit'); + const actual = await listArtifacts(root); + check(actual.length === expected.size && actual.every(path => expected.has(path)), 'artifact_set_mismatch'); + for (const artifact of declarations) { + const bytes = await readBounded(root, artifact.path); + check(bytes.byteLength === artifact.bytes && sha256(bytes) === artifact.sha256, 'artifact_integrity_mismatch'); + } + return declarations.length; +} + +export async function verifyLegacyPin({ repositoryRoot, vendorPath = 'vendor/freedom-platform', lock, + remote = false, fetcher } = {}) { + validateFormat('lockV1', lock); + artifactPath(vendorPath); + // Read through repositoryRoot as well, so a symlinked vendor parent cannot escape. + const manifestBytes = await readBounded(repositoryRoot, vendorPath + '/bundle.json'); + check(sha256(manifestBytes) === lock.bundle_sha256, 'bundle_digest_mismatch'); + const bundle = assertSchema(parseJson(manifestBytes), legacyBundleSchema); + check(bundle.protocol === lock.protocol && bundle.protocol_sha256 === lock.protocol_sha256, 'protocol_mismatch'); + const artifacts = Object.entries(bundle.files).map(([path, metadata]) => ({ path, ...metadata })); + check(artifacts.length > 0 && artifacts.length <= MAX_ARTIFACTS, 'artifact_limit'); + uniquePaths(['bundle.json', ...artifacts.map(item => item.path)]); + const all = [{ path: 'bundle.json', bytes: manifestBytes.length, sha256: lock.bundle_sha256 }, ...artifacts]; + const count = await verifyArtifactSet(resolve(repositoryRoot, vendorPath), all); + if (remote) for (const artifact of all) { + const bytes = await readRemoteBounded(`https://raw.githubusercontent.com/${CANONICAL_REPOSITORY}/${lock.source_commit}/${lock.bundle_path}/${artifact.path}`, fetcher); + check(bytes.length === artifact.bytes && sha256(bytes) === artifact.sha256, 'pinned_source_mismatch'); + } + return { format: 'freedom.pin-verification/v1', assurance_level: 'local', status: 'passed', + profile: 'legacy_preview', source_commit: lock.source_commit, protocol: lock.protocol, + artifact_count: count, publisher_trust: 'unverified', remote_source_checked: remote, + execution_authorized: false }; +} + +export async function verifyContractPin({ repositoryRoot, vendorPath = 'vendor/freedom-platform', + remote = false, fetcher, ...proofOptions } = {}) { + const lock = parseJson(await readBounded(repositoryRoot, 'contracts.lock.json')); + if (lock.format === 'freedom.contract-pin/v1') return verifyLegacyPin({ repositoryRoot, vendorPath, lock, remote, fetcher }); + validateFormat('lockV2', lock); + check(!remote, 'remote_v2_not_supported'); + artifactPath(vendorPath); + uniquePaths(lock.artifacts.map(item => item.path)); + const manifestBytes = await readBounded(repositoryRoot, vendorPath + '/' + lock.release_set.path); + const proofBytes = await readBounded(repositoryRoot, vendorPath + '/' + lock.proof.path); + check(sha256(manifestBytes) === lock.release_set.sha256 && sha256(proofBytes) === lock.proof.sha256, 'release_pin_mismatch'); + const validated = verifyReleaseProof(manifestBytes, proofBytes, proofOptions), manifest = validated.manifest; + check(lock.source_repository === manifest.source_repository && lock.source_commit === manifest.source_commit, 'source_commit_mismatch'); + check(lock.profiles.every(profile => manifest.profiles.includes(profile)), 'unknown_runtime_profile'); + const pinned = new Map(lock.artifacts.map(item => [item.path, item])); + check(pinned.size === manifest.artifacts.length && manifest.artifacts.every(item => { + const pin = pinned.get(item.path); + return pin && pin.sha256 === item.sha256 && pin.bytes === item.bytes; + }), 'artifact_pin_mismatch'); + const all = [...manifest.artifacts, + { path: lock.release_set.path, sha256: lock.release_set.sha256, bytes: manifestBytes.length }, + { path: lock.proof.path, sha256: lock.proof.sha256, bytes: proofBytes.length }]; + const count = await verifyArtifactSet(resolve(repositoryRoot, vendorPath), all); + // The approved publisher attests the built artifacts; --remote is a legacy + // source comparison, not an alternate way to approve a v2 release. + return { format: 'freedom.pin-verification/v1', assurance_level: 'local', status: 'passed', + profile: 'release_set', release_set_id: manifest.release_set_id, manifest_sha256: validated.manifest_sha256, + source_commit: manifest.source_commit, artifact_count: count, publisher_trust: validated.publisher_trust, + environment: validated.environment, remote_source_checked: false, execution_authorized: false, + library_usage: 'not_checked' }; +} + +// Receives resolution records from a build analyzer, not package.json alone. +// This checks the records; collecting a trustworthy graph is a separate gate. +export function verifyLibraryResolution(manifest, profile, records) { + validateReleaseSet(manifest); + check(manifest.profiles.includes(profile), 'unknown_runtime_profile'); + check(Array.isArray(records) && records.length > 0 && records.length <= MAX_ARTIFACTS, 'resolution_unavailable'); + const libraries = new Map(manifest.libraries.map(item => [item.library_id, item])); + const artifacts = new Map(manifest.artifacts.map(item => [item.path, item])); + const seen = new Set(); + for (const record of records) { + assertSchema(record, { type: 'object', required: ['library_id', 'version', 'artifact_path', 'sha256'], additionalProperties: false, + properties: { library_id: { type: 'string' }, version: { type: 'string' }, artifact_path: { type: 'string' }, sha256: { type: 'string' } } }); + const library = libraries.get(record.library_id), artifact = artifacts.get(record.artifact_path); + check(library && library.version === record.version && library.runtime_profiles.includes(profile), 'incompatible_library_resolution'); + check(artifact && library.artifacts.includes(record.artifact_path) && artifact.sha256 === record.sha256, 'library_integrity_mismatch'); + seen.add(record.library_id); + } + for (const library of manifest.libraries.filter(item => item.runtime_profiles.includes(profile))) { + check(seen.has(library.library_id), 'missing_library_resolution'); + } + return { status: 'passed', assurance_level: 'local', library_count: seen.size }; +} diff --git a/vendor/freedom-tooling/packages/contribution-tools/formats.mjs b/vendor/freedom-tooling/packages/contribution-tools/formats.mjs new file mode 100644 index 0000000..1e0127b --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/formats.mjs @@ -0,0 +1,18 @@ +import releaseSet from '../../governance/schemas/release-set.schema.json' with { type: 'json' }; +import lockV1 from '../../governance/schemas/contract-pin-v1.schema.json' with { type: 'json' }; +import lockV2 from '../../governance/schemas/contract-pin-v2.schema.json' with { type: 'json' }; +import proof from '../../governance/schemas/release-proof.schema.json' with { type: 'json' }; +import trust from '../../governance/schemas/release-trust.schema.json' with { type: 'json' }; +import moduleDescriptor from '../../governance/schemas/module.schema.json' with { type: 'json' }; +import codingContext from '../../governance/schemas/coding-context.schema.json' with { type: 'json' }; +import verifierReport from '../../governance/schemas/verifier-report.schema.json' with { type: 'json' }; +import { assertSchema } from './schema.mjs'; +import { parseJson } from './io.mjs'; +import { requireCondition as check } from './errors.mjs'; + +const schemas = { releaseSet, lockV1, lockV2, proof, trust, moduleDescriptor, codingContext, verifierReport }; +export function validateFormat(name, value) { + check(Object.hasOwn(schemas, name), 'unknown_format'); + return assertSchema(value, schemas[name]); +} +export function parseFormat(name, bytes) { return validateFormat(name, parseJson(bytes)); } diff --git a/vendor/freedom-tooling/packages/contribution-tools/local-artifacts.mjs b/vendor/freedom-tooling/packages/contribution-tools/local-artifacts.mjs new file mode 100644 index 0000000..77234d4 --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/local-artifacts.mjs @@ -0,0 +1,60 @@ +import { constants } from 'node:fs'; +import { lstat, mkdir, open, rename, unlink } from 'node:fs/promises'; +import { randomUUID } from 'node:crypto'; +import { resolve, dirname } from 'node:path'; +import { artifactPath, readBounded } from './io.mjs'; +import { requireCondition as check } from './errors.mjs'; +import { git } from './workspace.mjs'; + +// Only ignored task artifacts can be written. This is not a general file writer. +export function validateArtifactOutputPath(path) { + artifactPath(path); + check(/^\.freedom\/(?:context|reports)\/[a-zA-Z0-9._/-]+\.json$/.test(path), 'report_path_denied'); +} + +function requireIgnored(root, path) { + let pattern; + try { pattern = git(root, ['check-ignore', '--no-index', '--non-matching', '--verbose', '-z', '--stdin'], 4096, path + '\0') + .toString().split('\0')[2]; } + catch { /* Ignore status must be established for both writes and reads. */ } + check(typeof pattern === 'string' && pattern.length > 0 && !pattern.startsWith('!'), 'context_artifacts_must_be_ignored'); +} + +export async function readLocalArtifact(root, path, maxBytes) { + validateArtifactOutputPath(path); + requireIgnored(root, path); + return readBounded(root, path, maxBytes); +} + +export async function writeLocalArtifact(root, path, value) { + validateArtifactOutputPath(path); + let current = resolve(root); + const rootStat = await lstat(current); + check(rootStat.isDirectory() && !rootStat.isSymbolicLink(), 'unsafe_artifact_root'); + for (const part of path.split('/').slice(0, -1)) { + current = resolve(current, part); + try { await mkdir(current, { mode: 0o700 }); } + catch (error) { if (error.code !== 'EEXIST') throw error; } + const stat = await lstat(current); + check(stat.isDirectory() && !stat.isSymbolicLink(), 'unsafe_report_directory'); + } + const target = resolve(root, path); + try { + const stat = await lstat(target); + check(stat.isFile() && !stat.isSymbolicLink() && stat.nlink === 1, 'unsafe_report_target'); + } catch (error) { if (error.code !== 'ENOENT') throw error; } + // An ignored directory is an actual Git property, not just a naming convention. + requireIgnored(root, path); + const temporary = resolve(dirname(target), '.' + randomUUID() + '.tmp'); + let handle; + try { + handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600); + await handle.writeFile(JSON.stringify(value, null, 2) + '\n'); + await handle.close(); handle = undefined; + await rename(temporary, target); + } finally { + await handle?.close(); + await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); + } + return path; +} diff --git a/vendor/freedom-tooling/packages/contribution-tools/pin-cli.mjs b/vendor/freedom-tooling/packages/contribution-tools/pin-cli.mjs new file mode 100644 index 0000000..5f1e636 --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/pin-cli.mjs @@ -0,0 +1,19 @@ +import { verifyContractPin } from './contracts.mjs'; +import { safeFailure, VerificationError } from './errors.mjs'; + +export async function runPinCli(args = process.argv.slice(2), repositoryRoot = process.cwd()) { + try { + if (args.some(arg => arg !== '--remote') || new Set(args).size !== args.length) { + throw new VerificationError('invalid_arguments'); + } + // No candidate-provided trust file/root flag. v2 without an operator's + // trust injection deliberately reports unavailable in this bootstrap CLI. + const result = await verifyContractPin({ repositoryRoot, remote: args.includes('--remote') }); + console.log(JSON.stringify(result)); + return 0; + } catch (error) { + const failure = safeFailure(error); + console.log(JSON.stringify({ format: 'freedom.pin-verification/v1', assurance_level: 'local', ...failure })); + return failure.status === 'unavailable' ? 2 : 1; + } +} diff --git a/vendor/freedom-tooling/packages/contribution-tools/pinned-suites.mjs b/vendor/freedom-tooling/packages/contribution-tools/pinned-suites.mjs new file mode 100644 index 0000000..2b69217 --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/pinned-suites.mjs @@ -0,0 +1,72 @@ +// Reviewed host data. Package scripts, globs and descriptors never change a suite. +// A directory suite runs its baseline plus every candidate file in its directory +// that matches its pattern: a candidate can add tests but cannot drop a baseline +// file. To remove or rename a baseline test, edit its baseline here on main in a +// reviewed PR. CI runs the pinned copy (job.workflow_sha), so the change applies +// from the next central pin upgrade, and the old file must stay until then. + +const paths = (dir, ext, text) => Object.freeze(text.trim().split(/\s+/).map(name => `${dir}/${name}${ext}`)); + +const GOVERNANCE_BASELINE = paths('packages/contribution-tools/test', '.test.mjs', ` +agent-kit-device-fixture agent-kit-device-profile behavior-harness-adversarial behavior-harness +behavior-supervisor checkout-repositories consumer-entry-coverage consumer-libraries +consumer-runtime-recipe consumer-source-profiles consumer-workspace context contracts +directory-build export github-app-publisher github-behavior-host github-consumer-host +github-consumer-profiles github-trusted-adapter io machine-device-cli pinned-e2e pinned-suite runtime-matrix +runtime-sharding runtime-weights suite-runner supervisor-create-lifecycle surface-adversarial surface-audit +test-reporter-progress trusted-ci +`); + +const SKILL_CLIENT_BASELINE = paths('packages/skill-upload-client/test', '.test.mjs', ` +cli +`); + +const WORKER_BASELINE = paths('tests/worker', '.test.ts', ` +authority-hardening authority-http-protocol avatar-assets broker-ingest-worker broker-worker-sql +broker-worker credential-ingest-diagnostic event-banner-assets event-highlight-assets +event-video-assets fetch-redirect github-sync-scheduled guide-pack-assets maintainer-scheduled +media-accepted-formats media-object-io media-operator-caller media-operator-images-worker +media-operator-private-worker media-operator-worker migration-maintenance +openrouter-acceptance-guard openrouter-native-owner-harness openrouter-provider +private-ai-composition private-ai-ingest private-ai-key-correspondence private-ai-native-owner-flow +private-ai-service-binding service-cover-assets share-go skill-image-assets social-preview-assets +social-thumbnail-assets workerd +`); + +const DEPLOY_PREFLIGHT_BASELINE = paths('deploy/cloudflare/test', '.test.mjs', ` +broker-wrangler guide-r2-purposes isolated-candidate media-caller media-restore-container +media-wrangler migration-operator migration-plan migration-reviewed-privileges preflight +release-agent-connections release-bootstrap-session release-bootstrap-status +release-compatibility-adversarial release-compatibility release-credential-broker +release-credential-ingest release-device-authorization release-domain-media release-execution-run +release-history-floor-adversarial release-member-device-management release-member-model-settings +release-member-prerequisites release-model-result release-model-step release-runtime-enrollment +shop-key-policy +`); + +const CONTRACTS_PYTEST_BASELINE = Object.freeze([ + ...paths('docs/platform-plan/contracts/tests', '.py', ` +test_client_credential_manifest test_domain_skill_overlay_contract test_five_clock_invariants +test_github_mock_semantics test_low_ops_contracts test_membership_submission_contract +test_portable_bundle_boundaries test_repository_manifest_identity test_retract_contract_parity +test_retracted_receipt_replay test_reviewer_appointment_entitlement test_settlement_execution_modes +test_work_reviewer_capacity test_xp_projection_rebuild + `), + ...paths('docs/platform-plan/execution/tools/tests', '.py', ` +test_check_package_dag test_check_specs + `) +].sort()); + +export const PINNED_SUITES = Object.freeze({ + 'ci.governance-unit': Object.freeze({ directory: 'packages/contribution-tools/test', pattern: /^[a-z][a-z0-9-]*\.test\.mjs$/, baseline: GOVERNANCE_BASELINE, loader: 'node', database: false, timeoutMs: 300000, env: Object.freeze([]) }), + 'ci.selector-unit': Object.freeze({ files: Object.freeze(['scripts/ci/select-affected-jobs.test.mjs', 'scripts/ci/guild-presentation-profile.test.mjs']), loader: 'node', database: false, timeoutMs: 180000, env: Object.freeze([]) }), + 'ci.skill-client-unit': Object.freeze({ directory: 'packages/skill-upload-client/test', pattern: /^[a-z][a-z0-9_-]*\.test\.mjs$/, baseline: SKILL_CLIENT_BASELINE, loader: 'node', database: false, timeoutMs: 180000, env: Object.freeze([]) }), + 'ci.worker-unit': Object.freeze({ directory: 'tests/worker', pattern: /^[a-z][a-z0-9_-]*\.test\.ts$/, baseline: WORKER_BASELINE, loader: 'tsx', database: true, timeoutMs: 900000, env: Object.freeze(['HOME', 'FREEDOM_WORKERD_BUNDLE_DIR']) }), + 'ci.deploy-preflight': Object.freeze({ directory: 'deploy/cloudflare/test', pattern: /^[a-z][a-z0-9_-]*\.test\.mjs$/, baseline: DEPLOY_PREFLIGHT_BASELINE, loader: 'node', database: false, timeoutMs: 180000, env: Object.freeze([]) }), + 'ci.migration-postgres': Object.freeze({ files: Object.freeze(['tests/integration/migration-plan-postgres.test.ts', 'tests/integration/migration-entrypoints-postgres.test.ts', 'tests/runtime/migration-runner-plan.test.ts']), loader: 'tsx', database: false, timeoutMs: 600000, env: Object.freeze(['HOME', 'DOCKER_HOST', 'DOCKER_CONFIG']) }), + 'ci.consumer-repositories': Object.freeze({ files: Object.freeze(['tests/integration/repositories.test.ts', 'tests/integration/consumer-libraries.test.ts']), loader: 'tsx', database: true, timeoutMs: 600000, env: Object.freeze(['HOME', 'FREEDOM_REPOSITORIES_ROOT', 'FREEDOM_CONSUMER_SOURCE_COMMIT', 'FREEDOM_AGENT_KIT_ROOT', 'FREEDOM_STOREFRONT_ROOT', 'FREEDOM_SUPPLIER_CLIENT_ROOT', 'FREEDOM_SUPPLIER_SOURCE_COMMIT']) }), + 'ci.runtime-union-integration': Object.freeze({ files: Object.freeze(['tests/contribution-tools/runtime-union.integration.test.mjs']), loader: 'node', database: false, timeoutMs: 600000, env: Object.freeze([]) }), + 'ci.runtime-sharding-integration': Object.freeze({ files: Object.freeze(['tests/contribution-tools/runtime-sharding.integration.test.mjs']), loader: 'node', database: true, timeoutMs: 600000, env: Object.freeze([]) }), + 'ci.contracts-pytest': Object.freeze({ directories: Object.freeze(['docs/platform-plan/contracts/tests', 'docs/platform-plan/execution/tools/tests']), pattern: /^test_[a-z0-9_]+\.py$/, baseline: CONTRACTS_PYTEST_BASELINE, loader: 'pytest', database: false, timeoutMs: 300000, env: Object.freeze(['HOME']) }), + 'ci.pinned-pytest-integration': Object.freeze({ files: Object.freeze(['tests/contribution-tools/pinned-pytest.integration.test.mjs']), loader: 'node', database: false, timeoutMs: 300000, env: Object.freeze([]) }) +}); diff --git a/vendor/freedom-tooling/packages/contribution-tools/repository-identity.mjs b/vendor/freedom-tooling/packages/contribution-tools/repository-identity.mjs new file mode 100644 index 0000000..fe8ac12 --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/repository-identity.mjs @@ -0,0 +1,23 @@ +// Only the reviewed repository-set transport changes. Published manifests, +// signatures, source commits and vendor bytes keep their recorded identity. +export const PLATFORM_REPOSITORY = 'FreeTWAI/freedom-platform'; +export const HISTORICAL_PLATFORM_REPOSITORY = 'FreeTWAI-AI/freedom-platform'; +const names = ['freedom-platform', '.github', 'freedom-agent-kit', + 'freedom-growth-automation', 'freedom-project-page', 'freedom-project-template', + 'freedom-skill-registry', 'freedom-storefront', 'freedom-supplier-client']; +const transports = new Map(names.map(name => ['FreeTWAI-AI/' + name, 'FreeTWAI/' + name])); +transports.set('FreeTWAI-AI/FreeTWAI-AI.github.io', 'FreeTWAI/FreeTWAI.github.io'); +const current = new Set(transports.values()); + +export function repositoryTransport(recorded) { + if (current.has(recorded)) return recorded; + if (transports.has(recorded)) return transports.get(recorded); + throw Error('unsupported_repository_transport'); +} +export function matchesRecordedRepository(recorded, repository) { + // The host's actual identity must be current; aliases apply only to records. + return current.has(repository) && (recorded === repository || transports.get(recorded) === repository); +} +export function isPlatformSourceRepository(recorded) { + return recorded === PLATFORM_REPOSITORY || recorded === HISTORICAL_PLATFORM_REPOSITORY; +} diff --git a/vendor/freedom-tooling/packages/contribution-tools/runtime-databases.mjs b/vendor/freedom-tooling/packages/contribution-tools/runtime-databases.mjs new file mode 100644 index 0000000..e8df9d4 --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/runtime-databases.mjs @@ -0,0 +1,209 @@ +import { createRequire } from 'node:module'; +import { randomBytes } from 'node:crypto'; +import { resolve } from 'node:path'; +import fs from 'node:fs'; + +// Only bounded, reviewed vocabulary reaches CI logs. Never serialize errors, +// connection URLs, database names, SQL, or server detail/message fields. +export function runtimeCleanupDiagnostic(phase, result, error, elapsedMs) { + const phases = ['owner_close', 'cleaner_connect', 'cleaner_identity', 'owner_stop', + 'database_owner', 'database_stop', 'database_stop_readback', 'drop', + 'cleaner_close', 'verifier_connect', 'verifier_identity', 'cleaner_stop', 'absence', 'verifier_close']; + const results = ['unknown_ack', 'rejected', 'failed', 'unverified', 'verified_absent', 'no_owned_names']; + const codes = ['cleanup_deadline', 'cleanup_identity', 'owner_backend_unsettled', + 'database_backend_unsettled', 'ownership_mismatch', 'cleaner_identity_missing', + 'verification_budget_exhausted', 'database_present']; + const sqlstates = ['57014', '57P01', '55006', '42501', '3D000', '08006', '08003', '53300', '53200', '58030']; + const messages = {'Query read timeout': 'query_read_timeout', + 'Connection terminated unexpectedly': 'connection_terminated', + 'Connection terminated': 'connection_terminated', 'timeout expired': 'connection_timeout'}; + const code = error == null ? 'none' : sqlstates.includes(error.code) ? error.code + : codes.includes(error.message) ? error.message + : Object.hasOwn(messages, error.message) ? messages[error.message] : 'unclassified'; + return {event: 'runtime_database_cleanup', phase: phases.includes(phase) ? phase : 'unknown', + result: results.includes(result) ? result : 'unverified', code, + elapsed_ms: Number.isFinite(elapsedMs) ? Math.max(0, Math.min(20000, Math.floor(elapsedMs))) : 0}; +} + +// Admission checks are not proof that a database is disposable. Its operator +// must provision an isolated test-only server; this library never discovers one. +export function isDisposableDatabaseUrl(value) { + if (typeof value !== 'string' || value.length > 2048 || /[\s\\\0]/.test(value)) return false; + try { + const url = new URL(value); + if (!['postgres:', 'postgresql:'].includes(url.protocol) || url.hash || url.password + || !/^[a-z_][a-z0-9_]{0,62}$/.test(url.username) + || !/^\/fp_[a-z0-9_]{1,59}$/.test(url.pathname) + || !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) + || (url.port && (Number(url.port) < 1 || Number(url.port) > 65535))) return false; + const entries = [...url.searchParams]; + if (entries.length === 0) return true; + if (entries.length !== 1 || entries[0][0] !== 'host') return false; + const socket = entries[0][1]; + return /^\/[a-zA-Z0-9_./-]+$/.test(socket) && resolve(socket) === socket && socket !== '/'; + } catch { return false; } +} + + +// The caller must explicitly provide a disposable, local test server. Each +// invocation owns only these fresh databases; it never drops the supplied DB. +export async function createRuntimeDatabases(baseUrl, count, provisionTimeoutMs = 20_000) { + if (![1, 2, 4].includes(count)) throw Error('invalid_runtime_shards'); + if (!Number.isSafeInteger(provisionTimeoutMs) || provisionTimeoutMs < 1 || provisionTimeoutMs > 20_000) throw Error('invalid_provision_timeout'); + const provisionDeadline = performance.now() + provisionTimeoutMs; + if (!isDisposableDatabaseUrl(baseUrl)) throw Error('test_database_rejected'); + const { Client } = createRequire(import.meta.url)('pg'); + const prefix = `fp_suite_${process.pid}_${randomBytes(8).toString('hex')}`; + const connection = (application_name, limits = {}) => { + const client = new Client({ connectionString: baseUrl, connectionTimeoutMillis: 2000, + query_timeout: 2000, statement_timeout: 2000, application_name, ...limits }); + client.on('error', () => { /* query/cleanup failures never print connection details */ }); + return client; + }; + const ownerApplication = prefix + '_owner', client = connection(ownerApplication, { connectionTimeoutMillis: Math.min(2000, provisionTimeoutMs) }); + const names = [], urls = []; + let owner, ownerPid; + const quote = value => '"' + value.replaceAll('"', '""') + '"'; + async function close(connection, maximum = 1000) { + let timer; + const ended = await Promise.race([connection.end().then(() => true, () => false), + new Promise(done => { timer = setTimeout(() => done(false), Math.max(0, maximum)); })]); + clearTimeout(timer); + if (!ended) connection.connection?.stream?.destroy(); + return ended; + } + async function cleanup() { + // One absolute 20s budget, inside the suite's unchanged 24s cleanup reserve. + // In particular, DROP may wait for a checkpoint; it must not inherit the + // short metadata-query timeout or gain an unbounded per-database budget. + const started = performance.now(); + const deadline = started + 20_000; + let phase = 'owner_close'; + const diagnostic = (result, error) => { + // Initialize Node's lazy pipe handle before raw writes. Otherwise an inherited + // blocking fd can stall before Node configures the pipe as nonblocking. + // A tiny synchronous fd write makes EPIPE catchable here; stream.write + // can emit an uncaught asynchronous error after returning successfully. + // Logging must never change cleanup success, failure, or its deadline. + try { + const fd = process.stderr.fd; + // Linux CI exposes the actual open-file flags. If nonblocking output + // cannot be proved, omit this optional diagnostic rather than stall. + if (process.platform !== 'linux') return; + const flags = /^flags:\s+([0-7]+)$/m.exec(fs.readFileSync(`/proc/self/fdinfo/${fd}`, 'utf8')); + if (!flags || !(Number.parseInt(flags[1], 8) & fs.constants.O_NONBLOCK)) return; + fs.writeSync(fd, JSON.stringify(runtimeCleanupDiagnostic(phase, result, error, performance.now() - started)) + '\n'); + } + catch { /* A closed diagnostic stream cannot change cleanup semantics. */ } + }; + const remaining = () => Math.floor(deadline - performance.now()); + async function boundedQuery(c, text, values = [], maximum = 2000) { + const milliseconds = Math.min(maximum, remaining() - 100); + if (milliseconds <= 0) throw Error('cleanup_deadline'); + await c.query({ text: "SELECT set_config('statement_timeout',$1,false)", + values: [String(milliseconds)], query_timeout: Math.min(1000, remaining()) }); + const timeout = Math.min(milliseconds + 50, remaining()); + if (timeout <= 0) throw Error('cleanup_deadline'); + return c.query({ text, values, query_timeout: timeout }); + } + async function identity(c) { + const row = (await boundedQuery(c, 'SELECT current_database() AS database, current_user AS owner, session_user AS session, pg_backend_pid() AS pid')).rows[0]; + if (row?.database !== new URL(baseUrl).pathname.slice(1) || row.owner !== owner || row.session !== owner) throw Error('cleanup_identity'); + return row.pid; + } + async function stop(c, pid, application) { + const rows = (await boundedQuery(c, 'SELECT pg_terminate_backend(pid,1000) AS stopped FROM pg_stat_activity WHERE pid=$1 AND usename=$2 AND application_name=$3', [pid, owner, application])).rows; + if (rows.some(row => row.stopped !== true)) { + // A backend may leave between pg_stat_activity and termination. Only + // a fresh absence observation can reconcile a false acknowledgement. + const live = await boundedQuery(c, 'SELECT 1 FROM pg_stat_activity WHERE pid=$1 AND usename=$2 AND application_name=$3', [pid, owner, application]); + if (live.rowCount) throw Error('owner_backend_unsettled'); + } + } + // CREATE may commit with an unknown ACK. Its exact nonce-bound owner must + // stop before we consider any pre-registered name on a fresh connection. + await close(client, Math.min(1000, remaining())); + if (!names.length) { diagnostic('no_owned_names'); return true; } + const cleanupApplication = prefix + '_cleanup'; + const cleaner = connection(cleanupApplication, { connectionTimeoutMillis: Math.max(1, Math.min(2000, remaining())) }); + let okay = true, cleanerPid; + try { + phase = 'cleaner_connect'; await cleaner.connect(); + phase = 'cleaner_identity'; cleanerPid = await identity(cleaner); + phase = 'owner_stop'; await stop(cleaner, ownerPid, ownerApplication); + for (const [index, name] of names.entries()) { + phase = 'database_owner'; + const found = await boundedQuery(cleaner, 'SELECT pg_get_userbyid(datdba) AS owner FROM pg_database WHERE datname=$1', [name]); + if (!found.rows.length) continue; + if (found.rows[0].owner !== owner) { okay = false; diagnostic('rejected', Error('ownership_mismatch')); continue; } + phase = 'database_stop'; + const stopped = await boundedQuery(cleaner, 'SELECT pg_terminate_backend(pid,1000) AS stopped FROM pg_stat_activity WHERE datname=$1 AND pid<>pg_backend_pid()', [name]); + if (stopped.rows.some(row => row.stopped !== true)) { + phase = 'database_stop_readback'; + const live = await boundedQuery(cleaner, 'SELECT 1 FROM pg_stat_activity WHERE datname=$1 AND pid<>pg_backend_pid()', [name]); + if (live.rowCount) throw Error('database_backend_unsettled'); + } + // Share the remaining cleanup budget across registered databases while + // reserving four seconds for fresh reconciliation. Disk deletion can + // exceed six seconds even when the checkpoint has already completed. + const dropBudget = Math.floor((remaining() - 4000) / (names.length - index)); + phase = 'drop'; + try { await boundedQuery(cleaner, `DROP DATABASE ${quote(name)}`, [], dropBudget); } + catch (error) { diagnostic('unknown_ack', error); /* Fresh reconciliation is still required. */ } + } + } catch (error) { okay = false; diagnostic('failed', error); } + phase = 'cleaner_close'; + await close(cleaner, Math.min(1000, remaining())); + // Never equate an ACK (or its absence) to proof of deletion. Settle the + // exact cleanup backend, then positively verify every owned name absent. + // An identity/ownership failure above cannot be converted into success. + if (!okay || !cleanerPid || remaining() <= 1000) { + diagnostic('unverified', Error(!okay ? 'unclassified' : !cleanerPid ? 'cleaner_identity_missing' : 'verification_budget_exhausted')); + return false; + } + const verifier = connection(prefix + '_verify', { connectionTimeoutMillis: Math.min(2000, remaining()) }); + try { + phase = 'verifier_connect'; await verifier.connect(); + phase = 'verifier_identity'; await identity(verifier); + phase = 'cleaner_stop'; await stop(verifier, cleanerPid, cleanupApplication); + phase = 'absence'; + const found = await boundedQuery(verifier, 'SELECT datname FROM pg_database WHERE datname=ANY($1)', [names]); + const verified = found.rowCount === 0 && remaining() > 0; + diagnostic(verified ? 'verified_absent' : 'unverified', verified ? undefined : Error(found.rowCount ? 'database_present' : 'cleanup_deadline')); + return verified; + } catch (error) { diagnostic('failed', error); return false; } + finally { phase = 'verifier_close'; await close(verifier, Math.min(1000, remaining())); } + } + + async function provisionQuery(text, values = [], maximum = 2000) { + const budget = Math.min(maximum, Math.floor(provisionDeadline - performance.now())); + if (budget <= 0) throw Error('provision_deadline'); + return client.query({ text, values, query_timeout: budget }); + } + try { + await client.connect(); + const identity = await provisionQuery('SELECT current_database() AS database, current_user AS owner, session_user AS session, pg_backend_pid() AS pid'); + owner = identity.rows[0].owner; ownerPid = identity.rows[0].pid; + const supplied = new URL(baseUrl); + if (identity.rows[0].database !== supplied.pathname.slice(1) || owner !== supplied.username + || owner !== identity.rows[0].session) throw Error('runtime_database_identity'); + for (let index = 0; index < count; index++) { + const name = `${prefix}_${index}`; + const existing = await provisionQuery('SELECT 1 FROM pg_database WHERE datname=$1', [name]); + if (existing.rowCount) throw Error('runtime_database_collision'); + names.push(name); // register BEFORE CREATE, including unknown acknowledgements + const createTimeout = Math.min(6000, Math.floor(provisionDeadline - performance.now()) - 100); + if (createTimeout <= 0) throw Error('provision_deadline'); + await provisionQuery("SELECT set_config('statement_timeout',$1,false)", [String(createTimeout)]); + await provisionQuery(`CREATE DATABASE ${quote(name)} OWNER ${quote(owner)} TEMPLATE template0`, [], createTimeout + 50); + await provisionQuery("SET statement_timeout=2000"); + const url = new URL(baseUrl); url.pathname = '/' + name; urls.push(url.href); + } + if (performance.now() >= provisionDeadline) throw Error('provision_deadline'); + return { urls, cleanup }; + } catch { + const error = Error('runtime_database_provision_failed'); + error.cleanupVerified = await cleanup(); + throw error; + } +} diff --git a/vendor/freedom-tooling/packages/contribution-tools/runtime-file-weights.mjs b/vendor/freedom-tooling/packages/contribution-tools/runtime-file-weights.mjs new file mode 100644 index 0000000..cf911c0 --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/runtime-file-weights.mjs @@ -0,0 +1,328 @@ +// Reviewed scheduling estimates only, never pass evidence or caller input. +// Complete file-progress segments: disk rehearsal38000643429 partitions0-5 and38003118152 partitions0,2,3,5 (2026-10-09); both runs are unsuccessful. +// Rule: per-file minimum of serial completed-file progress deltas across the listed hosted +// runs, rounded up to whole seconds (at least 1). Files not listed use the default. +// Generated by scripts/ci/derive-runtime-weights.mjs; see packages/contribution-tools/runtime-matrix.md. +export const DEFAULT_RUNTIME_FILE_WEIGHT = 10; +export const RUNTIME_FILE_WEIGHTS = Object.freeze({ + 'tests/runtime/admin-access-session.test.ts': 1, + 'tests/runtime/admin-access-sync.test.ts': 21, + 'tests/runtime/admin-access.test.ts': 1, + 'tests/runtime/admin-appointments.test.ts': 14, + 'tests/runtime/admin-guild-candidates.test.ts': 12, + 'tests/runtime/admin-sync-worker.test.ts': 1, + 'tests/runtime/agent-commerce-key-expiry.test.ts': 13, + 'tests/runtime/agent-commerce.test.ts': 19, + 'tests/runtime/agent-connections-adversarial.test.ts': 11, + 'tests/runtime/agent-connections.test.ts': 16, + 'tests/runtime/ai-sister-guides.test.ts': 29, + 'tests/runtime/asset-authority-compatibility.test.ts': 1, + 'tests/runtime/asset-engine.test.ts': 13, + 'tests/runtime/asset-http-range.test.ts': 1, + 'tests/runtime/asset-lifecycle-races.test.ts': 28, + 'tests/runtime/asset-lifecycle.test.ts': 14, + 'tests/runtime/asset-maintenance.test.ts': 33, + 'tests/runtime/asset-media-profiles.test.ts': 2, + 'tests/runtime/asset-r2.test.ts': 2, + 'tests/runtime/asset-storage.test.ts': 1, + 'tests/runtime/auth-pruning.test.ts': 20, + 'tests/runtime/avatar-bridge.test.ts': 27, + 'tests/runtime/avatar-command-compat.test.ts': 65, + 'tests/runtime/avatar-upload.test.ts': 28, + 'tests/runtime/avatar.test.ts': 18, + 'tests/runtime/benefits.test.ts': 12, + 'tests/runtime/bootstrap-contracts.test.ts': 1, + 'tests/runtime/bootstrap-http-contracts.test.ts': 1, + 'tests/runtime/bootstrap-http.test.ts': 17, + 'tests/runtime/bootstrap-issuer.test.ts': 1, + 'tests/runtime/bootstrap-proof.test.ts': 1, + 'tests/runtime/bootstrap-session-contracts.test.ts': 1, + 'tests/runtime/bootstrap-session-proof.test.ts': 1, + 'tests/runtime/bootstrap-sessions-adversarial.test.ts': 54, + 'tests/runtime/bootstrap-sessions.test.ts': 6, + 'tests/runtime/bootstrap-status-adversarial.test.ts': 16, + 'tests/runtime/bootstrap-status.test.ts': 28, + 'tests/runtime/chat-content.test.ts': 11, + 'tests/runtime/chat-sticker-send.test.ts': 1, + 'tests/runtime/client-connections.test.ts': 16, + 'tests/runtime/co-creation.test.ts': 18, + 'tests/runtime/command-core.test.ts': 18, + 'tests/runtime/commerce.test.ts': 12, + 'tests/runtime/community-discovery.test.ts': 10, + 'tests/runtime/community-relations.test.ts': 12, + 'tests/runtime/community-search.test.ts': 7, + 'tests/runtime/credential-broker-adversarial.test.ts': 23, + 'tests/runtime/credential-broker-crypto.test.ts': 4, + 'tests/runtime/credential-broker-store.test.ts': 14, + 'tests/runtime/credential-ingest-adversarial.test.ts': 127, + 'tests/runtime/credential-ingest-authorizations.test.ts': 28, + 'tests/runtime/credential-ingest-broker.test.ts': 1, + 'tests/runtime/credential-ingest-process.test.ts': 18, + 'tests/runtime/credential-ingest-rate-budget.test.ts': 47, + 'tests/runtime/credential-setup-ui.test.ts': 1, + 'tests/runtime/development-access-grant-race.test.ts': 9, + 'tests/runtime/development-access.test.ts': 10, + 'tests/runtime/development-map.test.ts': 2, + 'tests/runtime/device-authorizations-adversarial.test.ts': 18, + 'tests/runtime/device-authorizations.test.ts': 49, + 'tests/runtime/device-pairing-contracts.test.ts': 1, + 'tests/runtime/device-pairing-proof.test.ts': 1, + 'tests/runtime/direct-message-receipts.test.ts': 1, + 'tests/runtime/domain-media-gc.test.ts': 20, + 'tests/runtime/domain-media-policy-grants.test.ts': 5, + 'tests/runtime/e2e-auth-isolation.test.ts': 5, + 'tests/runtime/event-banner-assets.test.ts': 15, + 'tests/runtime/event-create-rate-limit.test.ts': 10, + 'tests/runtime/event-highlight-assets.test.ts': 20, + 'tests/runtime/event-highlights.test.ts': 20, + 'tests/runtime/event-video-assets.test.ts': 16, + 'tests/runtime/events-past.test.ts': 10, + 'tests/runtime/execution-authority-adversarial.test.ts': 16, + 'tests/runtime/execution-prerequisites.test.ts': 21, + 'tests/runtime/execution-runs-adversarial.test.ts': 25, + 'tests/runtime/execution-runs-grants.test.ts': 7, + 'tests/runtime/execution-runs.test.ts': 27, + 'tests/runtime/execution-state-adversarial.test.ts': 1, + 'tests/runtime/execution-state.test.ts': 1, + 'tests/runtime/fixed-behavior-harness.test.ts': 6, + 'tests/runtime/flows.test.ts': 26, + 'tests/runtime/freedom_env.test.ts': 1, + 'tests/runtime/game-console-feed.test.ts': 1, + 'tests/runtime/game-console-routing.test.ts': 1, + 'tests/runtime/game-console.test.ts': 1, + 'tests/runtime/generator-drift.test.ts': 1, + 'tests/runtime/github-app-setup.test.ts': 23, + 'tests/runtime/github-history.test.ts': 6, + 'tests/runtime/github-identity.test.ts': 19, + 'tests/runtime/github-repository-read.test.ts': 1, + 'tests/runtime/github-social-routes.test.ts': 14, + 'tests/runtime/github-social-store.test.ts': 1, + 'tests/runtime/github-social.test.ts': 22, + 'tests/runtime/github-sync.test.ts': 11, + 'tests/runtime/guide-anchors.test.ts': 1, + 'tests/runtime/guide-pack-assets.test.ts': 14, + 'tests/runtime/guild-category-preferences.test.ts': 31, + 'tests/runtime/guild-entry-questions.test.ts': 11, + 'tests/runtime/guild-experts.test.ts': 22, + 'tests/runtime/guild-launchpad-contracts.test.ts': 11, + 'tests/runtime/guild-launchpad-deadline.test.ts': 51, + 'tests/runtime/guild-launchpad-journey.test.ts': 12, + 'tests/runtime/guild-launchpad-profiles.test.ts': 12, + 'tests/runtime/guild-launchpad.test.ts': 23, + 'tests/runtime/guild-member-tiers.test.ts': 13, + 'tests/runtime/guild-preferences.test.ts': 18, + 'tests/runtime/guild-profile.test.ts': 8, + 'tests/runtime/guild-workspace.test.ts': 23, + 'tests/runtime/hosted-direct-orders.test.ts': 55, + 'tests/runtime/hosted-order-contracts.test.ts': 1, + 'tests/runtime/hosted-order-http-contracts.test.ts': 1, + 'tests/runtime/hosted-order-http.test.ts': 11, + 'tests/runtime/hosted-order-ui.test.ts': 1, + 'tests/runtime/hosted-seller-order-ui.test.ts': 1, + 'tests/runtime/hosted-seller-orders.test.ts': 21, + 'tests/runtime/hosted-store-isolation.test.ts': 7, + 'tests/runtime/hosted-store-media-contracts.test.ts': 1, + 'tests/runtime/hosted-store-offering.test.ts': 12, + 'tests/runtime/hosted-store-photo.test.ts': 19, + 'tests/runtime/hosted-store.test.ts': 27, + 'tests/runtime/identity-member.test.ts': 19, + 'tests/runtime/image-cloudflare.test.ts': 19, + 'tests/runtime/image-runtime.test.ts': 15, + 'tests/runtime/json-wire.test.ts': 1, + 'tests/runtime/launchpad-profile-defaults.test.ts': 1, + 'tests/runtime/link-preview-egress.test.ts': 1, + 'tests/runtime/link-preview.test.ts': 1, + 'tests/runtime/login-lockout-recovery.test.ts': 17, + 'tests/runtime/machine-device-client.test.ts': 63, + 'tests/runtime/machine-model-broker.test.ts': 44, + 'tests/runtime/machine-model-execution.test.ts': 10, + 'tests/runtime/machine-model-http.test.ts': 14, + 'tests/runtime/machine-model-revocation.test.ts': 23, + 'tests/runtime/machine-text-authority.test.ts': 23, + 'tests/runtime/machine-text-proof.test.ts': 1, + 'tests/runtime/maintainer-worker.test.ts': 1, + 'tests/runtime/media-accepted-formats-playback.test.ts': 3, + 'tests/runtime/media-backup-archive.test.ts': 1, + 'tests/runtime/media-backup-coordinator.test.ts': 6, + 'tests/runtime/media-backup-daily.test.ts': 1, + 'tests/runtime/media-backup-evidence.test.ts': 10, + 'tests/runtime/media-backup-retention.test.ts': 1, + 'tests/runtime/media-backup-transfer.test.ts': 1, + 'tests/runtime/media-domain-bridge.test.ts': 24, + 'tests/runtime/media-inventory.test.ts': 8, + 'tests/runtime/media-recovery-bundle.test.ts': 1, + 'tests/runtime/media-session-recovery.test.ts': 1, + 'tests/runtime/media-verify.test.ts': 19, + 'tests/runtime/member-blocking.test.ts': 16, + 'tests/runtime/member-card-qr.test.ts': 1, + 'tests/runtime/member-channel-access.test.ts': 21, + 'tests/runtime/member-channels-core.test.ts': 18, + 'tests/runtime/member-communications.test.ts': 18, + 'tests/runtime/member-connections.test.ts': 13, + 'tests/runtime/member-device-bootstrap-adversarial.test.ts': 7, + 'tests/runtime/member-device-bootstrap-http.test.ts': 20, + 'tests/runtime/member-device-browser.test.ts': 21, + 'tests/runtime/member-device-client.test.ts': 1, + 'tests/runtime/member-directory.test.ts': 14, + 'tests/runtime/member-ecard.test.ts': 14, + 'tests/runtime/member-execution-contracts.test.ts': 1, + 'tests/runtime/member-execution-http-adversarial.test.ts': 23, + 'tests/runtime/member-execution-http-contracts.test.ts': 2, + 'tests/runtime/member-execution-http.test.ts': 15, + 'tests/runtime/member-experience.test.ts': 15, + 'tests/runtime/member-model-http-adversarial.test.ts': 21, + 'tests/runtime/member-model-http.test.ts': 11, + 'tests/runtime/member-model-settings-adversarial.test.ts': 48, + 'tests/runtime/member-model-settings-process.test.ts': 71, + 'tests/runtime/member-model-settings.test.ts': 15, + 'tests/runtime/member-service-cursor.test.ts': 9, + 'tests/runtime/member-services.test.ts': 10, + 'tests/runtime/member-session-lifecycle.test.ts': 13, + 'tests/runtime/member-skill-registration.test.ts': 6, + 'tests/runtime/message-image-ack.test.ts': 1, + 'tests/runtime/message-image-preview.test.ts': 1, + 'tests/runtime/message-image-upload-reader.test.ts': 1, + 'tests/runtime/message-images.test.ts': 26, + 'tests/runtime/migration-runner-plan.test.ts': 1, + 'tests/runtime/model-adapter-common.test.ts': 1, + 'tests/runtime/model-adapter-independent.test.ts': 1, + 'tests/runtime/model-adapter-registry.test.ts': 1, + 'tests/runtime/model-broker-authorizations.test.ts': 19, + 'tests/runtime/model-broker-bridge-adversarial.test.ts': 136, + 'tests/runtime/model-broker-bridge.test.ts': 1, + 'tests/runtime/model-broker-client.test.ts': 56, + 'tests/runtime/model-broker-process.test.ts': 15, + 'tests/runtime/model-byok-adapter.test.ts': 1, + 'tests/runtime/model-claude-adapter.test.ts': 1, + 'tests/runtime/model-cli-probe.test.ts': 4, + 'tests/runtime/model-codex-adapter.test.ts': 1, + 'tests/runtime/model-step-adversarial.test.ts': 22, + 'tests/runtime/model-step-contracts.test.ts': 1, + 'tests/runtime/model-step-revocation-races.test.ts': 14, + 'tests/runtime/model-step-service.test.ts': 18, + 'tests/runtime/module-capacity.test.ts': 9, + 'tests/runtime/module-instance-archive.test.ts': 35, + 'tests/runtime/module-instance-lifecycle.test.ts': 51, + 'tests/runtime/module-provisioning.test.ts': 36, + 'tests/runtime/module-registry-review.test.ts': 101, + 'tests/runtime/module-registry-rls-runtime-role.test.ts': 10, + 'tests/runtime/module-registry-schema.test.ts': 22, + 'tests/runtime/module-registry.test.ts': 17, + 'tests/runtime/native-text-invocation.test.ts': 1, + 'tests/runtime/native-text-process.test.ts': 4, + 'tests/runtime/newcomer-guide-dialogue.test.ts': 1, + 'tests/runtime/newcomer-guides.test.ts': 1, + 'tests/runtime/notification-events.test.ts': 9, + 'tests/runtime/onboarding-diagnostics.test.ts': 1, + 'tests/runtime/onboarding.test.ts': 34, + 'tests/runtime/openrouter-byok.test.ts': 1, + 'tests/runtime/opensource-marketing.test.ts': 18, + 'tests/runtime/opensource-skill-books.test.ts': 20, + 'tests/runtime/operator-avatar-backfill.test.ts': 16, + 'tests/runtime/operator-banner-social-backfill.test.ts': 20, + 'tests/runtime/operator-event-video-backfill.test.ts': 17, + 'tests/runtime/operator-media-backfill.test.ts': 15, + 'tests/runtime/operator-media-runtime-grants.test.ts': 5, + 'tests/runtime/operator-skill-highlight-backfill.test.ts': 27, + 'tests/runtime/organization-project-editing.test.ts': 18, + 'tests/runtime/page-github.test.ts': 7, + 'tests/runtime/page-issue-label.test.ts': 1, + 'tests/runtime/page-tools-notification.test.ts': 1, + 'tests/runtime/password-hash.test.ts': 6, + 'tests/runtime/password-recovery.test.ts': 7, + 'tests/runtime/platform-admin.test.ts': 27, + 'tests/runtime/platform-credentials.test.ts': 11, + 'tests/runtime/platform-json-body.test.ts': 1, + 'tests/runtime/portal-build-benchmark.test.ts': 1, + 'tests/runtime/portal-client-recovery.test.ts': 1, + 'tests/runtime/positioning-action-card.test.ts': 1, + 'tests/runtime/positioning.test.ts': 13, + 'tests/runtime/preview-protocol.test.ts': 7, + 'tests/runtime/private-ai-path.test.ts': 1, + 'tests/runtime/private-ai-preflight.test.ts': 2, + 'tests/runtime/private-policy-grants.test.ts': 5, + 'tests/runtime/private-result-races.test.ts': 7, + 'tests/runtime/private-result-schema.test.ts': 23, + 'tests/runtime/private-results.test.ts': 38, + 'tests/runtime/private-work-commands.test.ts': 35, + 'tests/runtime/private-work-http-adversarial.test.ts': 22, + 'tests/runtime/private-work-http.test.ts': 8, + 'tests/runtime/private-work-policy-adversarial.test.ts': 12, + 'tests/runtime/private-work-policy.test.ts': 7, + 'tests/runtime/production-dossier.test.ts': 1, + 'tests/runtime/published-skills.test.ts': 1, + 'tests/runtime/repo-author-claims.test.ts': 19, + 'tests/runtime/repo-maintainer-admin.test.ts': 10, + 'tests/runtime/repo-maintainer-claims.test.ts': 19, + 'tests/runtime/repo-maintainer-guild.test.ts': 14, + 'tests/runtime/repo-maintainer-handoff.test.ts': 11, + 'tests/runtime/repo-maintainer-policy.test.ts': 1, + 'tests/runtime/repo-maintainer-sync.test.ts': 12, + 'tests/runtime/repo-maintainer-webhook.test.ts': 6, + 'tests/runtime/resource-scopes.test.ts': 30, + 'tests/runtime/runtime-proof.test.ts': 1, + 'tests/runtime/runtime-registration-adversarial.test.ts': 10, + 'tests/runtime/runtime-registration-contracts.test.ts': 1, + 'tests/runtime/runtime-registration-grants.test.ts': 6, + 'tests/runtime/runtime-registration.test.ts': 19, + 'tests/runtime/scoped-command-context.test.ts': 1, + 'tests/runtime/scoped-member-command.test.ts': 19, + 'tests/runtime/scoped-member-domain-revalidation.test.ts': 13, + 'tests/runtime/scoped-tenant-domain-revalidation.test.ts': 10, + 'tests/runtime/session-cookie-security.test.ts': 13, + 'tests/runtime/share-promotion.test.ts': 26, + 'tests/runtime/sharing-authoring.test.ts': 1, + 'tests/runtime/sharing-flags.test.ts': 1, + 'tests/runtime/shop-key-exit.test.ts': 20, + 'tests/runtime/shop-service-command.test.ts': 15, + 'tests/runtime/shop-service-identity.test.ts': 13, + 'tests/runtime/showcase-drafts.test.ts': 1, + 'tests/runtime/skill-book-guides.test.ts': 1, + 'tests/runtime/skill-book-upstreams.test.ts': 1, + 'tests/runtime/skill-collaboration.test.ts': 1, + 'tests/runtime/skill-discovery.test.ts': 7, + 'tests/runtime/skill-share-content.test.ts': 1, + 'tests/runtime/skill-sharing.test.ts': 1, + 'tests/runtime/skill-submission-upgrades.test.ts': 15, + 'tests/runtime/skill-submissions.test.ts': 16, + 'tests/runtime/skill-upload-chat.test.ts': 1, + 'tests/runtime/skill-upload-client.test.ts': 8, + 'tests/runtime/social-feed.test.ts': 17, + 'tests/runtime/social-links.test.ts': 10, + 'tests/runtime/social-post-task.test.ts': 1, + 'tests/runtime/social-preview-assets.test.ts': 23, + 'tests/runtime/social-share.test.ts': 1, + 'tests/runtime/social-thumbnail-assets.test.ts': 14, + 'tests/runtime/squad-invitations.test.ts': 16, + 'tests/runtime/storefront-presentation-contracts.test.ts': 1, + 'tests/runtime/storefront-product-photo-core.test.ts': 1, + 'tests/runtime/storefront-product-photo-sql.test.ts': 19, + 'tests/runtime/tenant-authority-policy-grants.test.ts': 5, + 'tests/runtime/tenant-authorization.test.ts': 12, + 'tests/runtime/tenant-data-catalog.test.ts': 16, + 'tests/runtime/tenant-data-isolation.test.ts': 7, + 'tests/runtime/tenant-high-risk-verification.test.ts': 14, + 'tests/runtime/tenant-instance-permissions.test.ts': 26, + 'tests/runtime/tenant-list-cursor.test.ts': 1, + 'tests/runtime/tenant-membership-identity.test.ts': 10, + 'tests/runtime/tenant-ownership-transfer.test.ts': 55, + 'tests/runtime/tenant-ownership.test.ts': 20, + 'tests/runtime/tenant-policy-operator.test.ts': 8, + 'tests/runtime/tenant-read-deadline.test.ts': 24, + 'tests/runtime/tenant-recovery.test.ts': 62, + 'tests/runtime/tenant-rls-b2a-runtime-role.test.ts': 27, + 'tests/runtime/tenant-rls-retarget.test.ts': 8, + 'tests/runtime/tenant-rls-runtime-role.test.ts': 7, + 'tests/runtime/tenant-route-matrix.test.ts': 21, + 'tests/runtime/tenant-snapshot-evidence-rls.test.ts': 1, + 'tests/runtime/tenant-transaction.test.ts': 1, + 'tests/runtime/tenant-work-authority-races.test.ts': 41, + 'tests/runtime/tenant-work-schema.test.ts': 8, + 'tests/runtime/tenant-work.test.ts': 48, + 'tests/runtime/verification-test-data.test.ts': 8, + 'tests/runtime/verify-guild-work.test.ts': 14, + 'tests/runtime/work-privacy.test.ts': 21, + 'tests/runtime/work-result-client.test.ts': 1, + 'tests/runtime/worker-adapter.test.ts': 8, + 'tests/runtime/worker-private-ai-ingest.test.ts': 7, +}); diff --git a/vendor/freedom-tooling/packages/contribution-tools/runtime-suites.mjs b/vendor/freedom-tooling/packages/contribution-tools/runtime-suites.mjs new file mode 100644 index 0000000..56a58cd --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/runtime-suites.mjs @@ -0,0 +1,75 @@ +// Central, reviewed suite IDs only. Descriptor data never supplies executable +// paths, arguments or commands. Full coverage retains this baseline and also +// discovers new direct *.test.ts files; deleting baseline tests is not a pass. +const paths = names => names.map(name => `tests/runtime/${name}.test.ts`); +export const RUNTIME_SUITES = Object.freeze(Object.fromEntries(Object.entries({ + 'runtime.command-core': ['command-core'], + 'runtime.guild-blocks': ['guild-blocks'], + 'runtime.guild-presentation': ['guild-blocks', 'guild-launchpad', 'guild-launchpad-contracts', 'guild-launchpad-profiles', 'launchpad-profile-defaults'], + 'runtime.resource-scopes': ['resource-scopes'], + 'runtime.scoped-member-command': ['scoped-member-command'], + 'runtime.avatar': ['avatar', 'image-runtime', 'image-cloudflare'], + 'runtime.member-card': ['member-ecard', 'member-directory', 'social-links', 'member-card-qr'], + 'runtime.member-reporting': ['member-reporting'], + 'runtime.work': ['flows', 'benefits', 'co-creation'], + 'runtime.work-privacy': ['work-privacy'], + 'runtime.personal-content': ['personal-content', 'community-relations', 'community-search', 'work-privacy'], + 'runtime.preview-protocol': ['preview-protocol'], + 'runtime.event-outcomes': ['event-outcomes', 'squad-outcomes', 'event-highlights', 'event-highlight-assets', 'worker-adapter'], +}).map(([id, names]) => [id, Object.freeze(paths(names))]))); + +// Reviewed consumer adapters share the same bounded reporter/process runner. +// They never invoke package scripts or receive the producer's database URL. +export const NODE_CONSUMER_SUITES = Object.freeze({ + 'consumer.agent-kit': Object.freeze({ directory: 'tests', baseline: Object.freeze(['tests/workspace.test.mjs']) }), + 'consumer.storefront': Object.freeze({ directory: 'tests', baseline: Object.freeze(['tests/read-client.test.mjs', 'tests/storefront.test.mjs', 'tests/templates.test.mjs']) }), +}); + +// Fixed producer files. No directory discovery, package hook, or database URL. +// The list is host code; a descriptor cannot add or replace a path. +export const FIXED_NODE_SUITES = Object.freeze({ + 'e2e.harness': Object.freeze(['scripts/run-e2e.test.mjs']), +}); + +export const FULL_RUNTIME_BASELINE = Object.freeze(paths(` +newcomer-guides newcomer-guide-dialogue guide-anchors guide-pack-assets +chat-content direct-message-receipts member-card-qr member-session-lifecycle +admin-access-session admin-access-sync admin-access admin-appointments admin-guild-candidates admin-sync-worker +agent-commerce agent-connections agent-connections-adversarial asset-authority-compatibility asset-engine asset-lifecycle-races asset-lifecycle asset-maintenance asset-r2 asset-storage asset-media-profiles media-inventory media-backup-coordinator avatar avatar-bridge +avatar-command-compat avatar-upload benefits bootstrap-contracts bootstrap-http bootstrap-http-contracts bootstrap-issuer bootstrap-proof bootstrap-session-contracts bootstrap-session-proof bootstrap-sessions bootstrap-sessions-adversarial bootstrap-status bootstrap-status-adversarial client-connections co-creation +command-core commerce community-search credential-ingest-authorizations credential-ingest-broker credential-ingest-process credential-ingest-adversarial credential-broker-store credential-broker-crypto credential-broker-adversarial development-access-grant-race development-access development-map device-authorizations device-authorizations-adversarial device-pairing-contracts device-pairing-proof e2e-auth-isolation +event-highlights events-past execution-authority-adversarial execution-prerequisites execution-runs execution-runs-adversarial execution-runs-grants execution-state execution-state-adversarial fixed-behavior-harness flows freedom_env game-console-feed game-console-routing game-console +generator-drift github-app-setup github-history github-identity github-repository-read github-social-routes github-social-store +github-social github-sync guild-category-preferences guild-entry-questions guild-experts guild-member-tiers guild-preferences guild-profile +guild-workspace guild-launchpad guild-launchpad-contracts guild-launchpad-deadline identity-member image-cloudflare image-runtime link-preview maintainer-worker member-execution-contracts member-execution-http member-execution-http-adversarial member-execution-http-contracts member-channel-access +member-blocking member-reporting member-channels-core member-communications member-connections member-directory member-ecard member-experience +model-broker-authorizations model-broker-bridge model-broker-client model-broker-process model-broker-bridge-adversarial +model-step-service model-step-contracts model-step-adversarial member-model-http member-model-http-adversarial +member-model-settings member-model-settings-adversarial member-model-settings-process +member-device-bootstrap-http member-device-bootstrap-adversarial member-device-browser member-device-client +machine-text-proof machine-text-authority scoped-command-context private-ai-path +machine-model-execution machine-model-http machine-model-revocation machine-model-broker +agent-commerce-key-expiry shop-service-command shop-service-identity shop-key-exit +model-adapter-common model-adapter-independent model-adapter-registry model-byok-adapter model-claude-adapter model-cli-probe model-codex-adapter +member-services member-skill-registration notification-events onboarding-diagnostics onboarding opensource-marketing +page-github page-issue-label page-tools-notification password-hash password-recovery email-change platform-admin platform-credentials +portal-client-recovery positioning preview-protocol private-policy-grants private-result-races private-result-schema private-results private-work-commands private-work-http private-work-http-adversarial private-work-policy private-work-policy-adversarial published-skills repo-author-claims repo-maintainer-admin +repo-maintainer-claims repo-maintainer-guild repo-maintainer-handoff repo-maintainer-policy repo-maintainer-sync +repo-maintainer-webhook resource-scopes runtime-proof runtime-registration runtime-registration-adversarial runtime-registration-contracts runtime-registration-grants scoped-member-command scoped-member-domain-revalidation scoped-tenant-domain-revalidation share-promotion skill-book-guides skill-book-upstreams +skill-collaboration skill-discovery skill-share-content skill-sharing skill-submission-upgrades skill-submissions +skill-upload-chat skill-upload-client social-links squad-invitations tenant-authority-policy-grants tenant-authorization tenant-data-catalog tenant-data-isolation tenant-high-risk-verification tenant-instance-permissions tenant-membership-identity tenant-ownership tenant-ownership-transfer tenant-policy-operator tenant-read-deadline tenant-recovery tenant-rls-b2a-runtime-role tenant-rls-runtime-role tenant-snapshot-evidence-rls tenant-transaction tenant-work tenant-work-authority-races tenant-work-schema verification-test-data work-privacy work-result-client worker-adapter tenant-rls-retarget tenant-route-matrix module-registry module-registry-review module-registry-rls-runtime-role module-provisioning module-capacity module-registry-schema module-instance-lifecycle module-instance-archive +guild-launchpad-journey +ai-sister-guides asset-http-range auth-pruning community-discovery credential-ingest-rate-budget credential-setup-ui domain-media-gc domain-media-policy-grants +event-banner-assets event-create-rate-limit event-highlight-assets event-video-assets link-preview-egress login-lockout-recovery machine-device-client media-accepted-formats-playback +media-backup-archive media-backup-daily media-backup-evidence media-backup-retention media-backup-transfer media-domain-bridge media-recovery-bundle media-session-recovery +media-verify member-service-cursor migration-runner-plan model-step-revocation-races native-text-invocation native-text-process openrouter-byok operator-avatar-backfill +operator-banner-social-backfill operator-event-video-backfill operator-media-backfill operator-media-runtime-grants operator-skill-highlight-backfill organization-project-editing platform-json-body private-ai-preflight +session-cookie-security social-preview-assets social-thumbnail-assets verify-guild-work worker-private-ai-ingest +storefront-presentation-contracts hosted-store-media-contracts hosted-store-photo-state hosted-store-photo storefront-product-photo-core storefront-product-photo-sql storefront-product-photo-native hosted-store hosted-store-isolation hosted-order-contracts hosted-order-http hosted-order-http-contracts hosted-seller-orders hosted-seller-order-ui hosted-order-ui hosted-direct-orders hosted-store-offering +guild-launchpad-profiles launchpad-profile-defaults production-dossier positioning-action-card +message-images message-image-ack message-image-upload-reader message-image-preview json-wire +personal-content community-relations first-participation social-feed social-post-edit social-share notification-preferences +event-participation-api event-participation-reminders event-reminders-delivery event-waitlist +event-outcomes squad-outcomes +participation-metrics +`.trim().split(/\s+/)).sort()); diff --git a/vendor/freedom-tooling/packages/contribution-tools/schema.mjs b/vendor/freedom-tooling/packages/contribution-tools/schema.mjs new file mode 100644 index 0000000..1b095e0 --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/schema.mjs @@ -0,0 +1,45 @@ +import { VerificationError, requireCondition as check } from './errors.mjs'; + +// Implements only the keywords used by the fixed governance schemas. This is not +// the preview validator, nor a general-purpose evaluator of candidate schemas. +const keywords = new Set(['$schema', '$id', 'title', 'description', 'type', 'const', 'enum', + 'properties', 'required', 'additionalProperties', 'items', 'minItems', 'maxItems', + 'uniqueItems', 'minLength', 'maxLength', 'pattern', 'minimum', 'maximum']); + +export function assertSchema(value, schema) { + check(Object.keys(schema).every(key => keywords.has(key)), 'unsupported_schema_keyword'); + if ('const' in schema) check(value === schema.const, 'schema_violation'); + if (schema.enum) check(schema.enum.includes(value), 'schema_violation'); + const kind = schema.type; + if (kind) { + const valid = kind === 'object' ? value !== null && typeof value === 'object' && !Array.isArray(value) + : kind === 'array' ? Array.isArray(value) : kind === 'integer' ? Number.isSafeInteger(value) + : kind === 'null' ? value === null : typeof value === kind; + check(valid, 'schema_violation'); + } + if (typeof value === 'string') { + const length = [...value].length; + check(value.isWellFormed() && length >= (schema.minLength ?? 0) + && length <= (schema.maxLength ?? Infinity), 'schema_violation'); + if (schema.pattern) { + const match = new RegExp(schema.pattern, 'u').exec(value); + check(match && match[0].length === value.length, 'schema_violation'); + } + } + if (typeof value === 'number') check(Number.isFinite(value) + && value >= (schema.minimum ?? -Infinity) && value <= (schema.maximum ?? Infinity), 'schema_violation'); + if (Array.isArray(value)) { + check(value.length >= (schema.minItems ?? 0) && value.length <= (schema.maxItems ?? Infinity), 'schema_violation'); + // Governance uniqueItems are primitive ID/path arrays, not arbitrary objects. + if (schema.uniqueItems) check(new Set(value).size === value.length, 'schema_violation'); + for (const item of value) if (schema.items) assertSchema(item, schema.items); + } else if (value !== null && typeof value === 'object') { + for (const key of schema.required ?? []) check(Object.hasOwn(value, key), 'schema_violation'); + for (const [key, item] of Object.entries(value)) { + if (Object.hasOwn(schema.properties ?? {}, key)) assertSchema(item, schema.properties[key]); + else if (schema.additionalProperties === false) throw new VerificationError('schema_violation'); + else if (typeof schema.additionalProperties === 'object') assertSchema(item, schema.additionalProperties); + } + } + return value; +} diff --git a/vendor/freedom-tooling/packages/contribution-tools/suite-runner.mjs b/vendor/freedom-tooling/packages/contribution-tools/suite-runner.mjs new file mode 100644 index 0000000..71f6f13 --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/suite-runner.mjs @@ -0,0 +1,574 @@ +import { createFailureDiagnosticDecoder } from './test-failure-diagnostic.mjs'; +import { spawn, spawnSync } from 'node:child_process'; +import { readdir, mkdtemp, writeFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { createRequire } from 'node:module'; +import { resolve, join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { readBounded, parseJson, sha256 } from './io.mjs'; +import { createRuntimeDatabases, isDisposableDatabaseUrl } from './runtime-databases.mjs'; +import { verificationEnvironment } from './process-env.mjs'; +import { RUNTIME_SUITES, FULL_RUNTIME_BASELINE, NODE_CONSUMER_SUITES, FIXED_NODE_SUITES } from './runtime-suites.mjs'; +import { PINNED_SUITES } from './pinned-suites.mjs'; +import { RUNTIME_FILE_WEIGHTS, DEFAULT_RUNTIME_FILE_WEIGHT } from './runtime-file-weights.mjs'; + +import { createProgressDecoder } from './test-reporter.mjs'; + +const MAX_OUTPUT = 16_000_000, MAX_FILES = 512; +const COUNT_KEYS = ['tests', 'passed', 'failed', 'cancelled', 'skipped', 'todo']; +const reporter = fileURLToPath(new URL('./test-reporter.mjs', import.meta.url)); +const result = (id, status, reason) => ({ check_id: id, status, reason }); + +export { isDisposableDatabaseUrl } from './runtime-databases.mjs'; + +async function suiteFiles(root, id) { + let files; + if (id === 'governance.unit') { + files = (await readdir(resolve(root, 'packages/contribution-tools/test'))) + .filter(name => /^[a-z][a-z0-9-]*\.test\.mjs$/.test(name)).sort() + .map(name => 'packages/contribution-tools/test/' + name); + } else if (Object.hasOwn(NODE_CONSUMER_SUITES, id)) { + const { directory, baseline } = NODE_CONSUMER_SUITES[id]; + const found = (await readdir(resolve(root, directory))) + .filter(name => /^[a-z][a-z0-9_-]*\.test\.mjs$/.test(name)).map(name => directory + '/' + name); + files = [...new Set([...baseline, ...found])].sort(); + } else if (Object.hasOwn(FIXED_NODE_SUITES, id)) { + files = [...FIXED_NODE_SUITES[id]]; + } else if (id === 'runtime.full') { + const found = (await readdir(resolve(root, 'tests/runtime'))) + .filter(name => /^[a-z][a-z0-9_-]*\.test\.ts$/.test(name)).map(name => 'tests/runtime/' + name); + files = [...new Set([...FULL_RUNTIME_BASELINE, ...found])].sort(); + } else files = RUNTIME_SUITES[id]; + if (files.length > MAX_FILES) throw new Error('file_limit'); + for (const path of files) await readBounded(root, path); + return files; +} + +// No shell, package hooks, inherited NODE_OPTIONS, test context, credentials, +// or default database URL. Kill the isolated process group on POSIX timeout. +async function execute(root, files, loader, extraEnv, timeoutMs, signal) { + const diagnosticEpoch = performance.now(); + let sources = [], sourceBytes = 0; + try { + for (const path of files) { + const bytes = await readBounded(root,path); sourceBytes += bytes.length; + if (sourceBytes > 32_000_000) throw Error('progress_source_limit'); + sources.push({path,source_sha256:sha256(bytes),source_lines:bytes.toString('utf8').split('\n').length}); + } + } catch { sources = []; /* progress is optional, never final result evidence */ } + return new Promise(done => { + let loaderPath; + try { if (loader === 'tsx') loaderPath = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href; } + catch { done({ reason: 'runtime_loader_unavailable' }); return; } + const args = [...(loader === 'tsx' ? ['--import', loaderPath] : []), '--test', '--test-concurrency=1', + '--test-reporter=' + reporter, ...files]; + const env = verificationEnvironment(); + if (extraEnv) Object.assign(env, extraEnv); + if (sources.length === files.length) env.FREEDOM_TEST_PROGRESS_FILES = JSON.stringify(files); + const group = process.platform !== 'win32'; + const child = spawn(process.execPath, args, { cwd: root, env, detached: group, stdio: ['ignore', 'pipe', 'pipe', 'pipe', 'pipe'] }); + const diagnostic = record => { try { process.stderr.write('freedom.test-progress ' + JSON.stringify(record) + '\n'); } catch { /* diagnostics never affect admission */ } }; + const progress = sources.length === files.length ? createProgressDecoder(sources, diagnostic) : { + push() {}, finish: () => ({schema:'freedom.test-file-progress-summary/v1',selected_count:files.length,started_count:0,completed_count:0,incomplete:true}), + }; + child.stdio[3].on('data', bytes => progress.push(bytes)); + child.stdio[3].on('error', () => {}); + const failureDiagnostic=createFailureDiagnosticDecoder(sources,record=>{try{process.stderr.write('freedom.test-failure-diagnostic '+JSON.stringify(record)+'\n');}catch{}}); + child.stdio[4].on('data',bytes=>failureDiagnostic.push(bytes)); + child.stdio[4].on('error',()=>{}); + let size = 0, output = [], reason; + const stop = code => { + reason ??= code; + try { if (group && child.pid) process.kill(-child.pid, 'SIGKILL'); else child.kill('SIGKILL'); } catch { /* already exited */ } + }; + const abort = () => stop('test_cancelled'); + signal?.addEventListener('abort', abort, { once: true }); + if (signal?.aborted) abort(); + const timer = setTimeout(() => stop('test_timeout'), Math.max(1,timeoutMs - (performance.now() - diagnosticEpoch))); + child.stdout.on('data', bytes => { + size += bytes.length; + if (size > MAX_OUTPUT) stop('test_output_limit'); + else output.push(bytes); + }); + child.stderr.on('data', bytes => { size += bytes.length; if (size > MAX_OUTPUT) stop('test_output_limit'); }); + child.on('error', () => { reason ??= 'test_process_failed'; }); + child.on('close', (code, terminationSignal) => { + clearTimeout(timer); + diagnostic(progress.finish()); + signal?.removeEventListener('abort', abort); + done({ output: Buffer.concat(output), reason, exit_code: code, termination_signal: terminationSignal, failed: code !== 0 || terminationSignal !== null }); + }); + }); +} + +function countsValid(counts) { + return counts && COUNT_KEYS.every(key => Number.isSafeInteger(counts[key]) && counts[key] >= 0) + && Number.isSafeInteger(counts.suites) && counts.suites >= 0 + && counts.tests === COUNT_KEYS.slice(1).reduce((sum, key) => sum + counts[key], 0); +} + +function evidenceFor(raw, files) { + const expected = new Set(files), seen = new Set(), ids = new Set(); + if (typeof raw.success !== 'boolean' || !countsValid(raw.counts) || !Array.isArray(raw.files) + || raw.files.length !== files.length || !Array.isArray(raw.cases) || !Array.isArray(raw.suites)) return; + const evidence = []; + for (const item of raw.files) { + if (!expected.has(item.file) || seen.has(item.file) || typeof item.success !== 'boolean' || !countsValid(item.counts)) return; + seen.add(item.file); + const cases = raw.cases.filter(entry => entry.file === item.file); + const suites = raw.suites.filter(entry => entry.file === item.file); + if (cases.length !== item.counts.tests || cases.length > 20_000 || suites.length !== item.counts.suites || suites.length > 20_000) return; + for (const entry of [...cases, ...suites]) { + if (!/^[a-f0-9]{64}$/.test(entry.case_sha256) || !COUNT_KEYS.slice(1).includes(entry.status) || ids.has(entry.case_sha256)) return; + ids.add(entry.case_sha256); + } + if (COUNT_KEYS.slice(1).some(key => item.counts[key] !== cases.filter(entry => entry.status === key).length)) return; + evidence.push({ path: item.file, counts: Object.fromEntries(COUNT_KEYS.map(key => [key, item.counts[key]])), + cases: cases.map(({ case_sha256, status }) => ({ case_sha256, status })), + suite_events: suites.map(({ case_sha256, status }) => ({ case_sha256, status })) }); + } + if ([...raw.cases, ...raw.suites].some(item => !expected.has(item.file)) + || raw.counts.suites !== raw.suites.length + || COUNT_KEYS.some(key => raw.counts[key] !== evidence.reduce((n, file) => n + file.counts[key], 0))) return; + return evidence.sort((a, b) => a.path.localeCompare(b.path)); +} + +// Only runRuntimePartition passes a larger cap; caller options cannot raise it. +async function runGroup(root, selections, runtime, options, cap = runtime ? 900_000 : 60_000) { + const files = [...new Set(selections.flatMap(item => item.files))].sort(); + const timeout = options.timeoutMs ?? cap; + if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > cap) { + return selections.map(({ id }) => result(id, 'not_run', 'invalid_suite_timeout')); + } + const full = runtime && selections.some(item => item.id === 'runtime.full'); + const shardCount = full ? (options.runtimeShards ?? 4) : 1; + if (![1, 2, 4].includes(shardCount) || (!runtime && shardCount !== 1 && options.runtimeShards !== undefined)) { + return selections.map(({ id }) => result(id, 'not_run', 'invalid_runtime_shards')); + } + if (runtime && shardCount > 1) return runSharded(root, selections, files, options, timeout, shardCount); + const ran = await execute(root, files, runtime ? 'tsx' : 'node', runtime ? { TEST_DATABASE_URL: options.testDatabaseUrl } : {}, timeout, options.signal); + const failure = reason => selections.map(({ id, files: selected_files }) => ({ + ...result(id, reason === 'runtime_loader_unavailable' ? 'not_run' : 'failed', reason), selected_files, + })); + if (ran.reason) return failure(ran.reason).map(item => ({ ...item, evidence_sha256: sha256(ran.output ?? Buffer.alloc(0)) })); + let raw, evidence; + try { raw = parseJson(ran.output, { maxBytes: MAX_OUTPUT, maxNodes: 500_000 }); evidence = evidenceFor(raw, files); } + catch { return failure('invalid_test_results'); } + if (!evidence) return failure('incomplete_test_results'); + const evidence_sha256 = sha256(ran.output); + return selections.map(({ id, files: selected }) => { + const test_files = evidence.filter(item => selected.includes(item.path)); + const test_count = test_files.reduce((count, item) => count + item.counts.tests, 0); + // Any process-level failure fails the batch, even if one subset passed. + const passed = !ran.failed && raw.success && raw.files.every(file => file.success) + && test_files.every(file => file.counts.tests > 0 && file.counts.tests === file.counts.passed + && file.suite_events.every(event => event.status === 'passed')); + return { ...result(id, passed ? 'passed' : 'failed', passed ? 'tests_executed' : ran.failed ? 'test_process_failed' : 'incomplete_test_results'), + test_count, evidence_sha256, selected_files: selected, test_files }; + }); +} + +// Deterministic longest-estimated-first allocation, then original file order +// within each serial process. Full local runner and matrix producer/aggregate +// use this same function; no selected file is dropped or split. +export function partitionRuntimeFiles(files, count) { + if (![1, 2, 4, 6].includes(count) || files.length < count || new Set(files).size !== files.length) throw Error('invalid_runtime_partition'); + const loads = Array(count).fill(0), assignments = new Map(); + const ordered = files.map((path, index) => ({path, index, weight: RUNTIME_FILE_WEIGHTS[path] ?? DEFAULT_RUNTIME_FILE_WEIGHT})) + .sort((a, b) => b.weight - a.weight || a.index - b.index); + for (const {path, weight} of ordered) { + let target = 0; + for (let i = 1; i < count; i++) if (loads[i] < loads[target]) target = i; + assignments.set(path, target); loads[target] += weight; + } + return Array.from({ length: count }, (_, index) => files.filter(path => assignments.get(path) === index)); +} + +async function runSharded(root, selections, files, options, timeout, count) { + const deadline = performance.now() + timeout; + let databases, partitions, shards = [], cleanup = false; + let reason; + try { + partitions = partitionRuntimeFiles(files, count); + databases = await createRuntimeDatabases(options.testDatabaseUrl, count, + Math.max(1, Math.min(20_000, Math.floor(deadline - performance.now() - 24_000)))); + // Reserve bounded cleanup time within the original global budget. + const remaining = deadline - performance.now() - 24_000; + if (remaining <= 0 || options.signal?.aborted) reason = options.signal?.aborted ? 'test_cancelled' : 'test_timeout'; + else shards = await Promise.all(partitions.map(async (selected, index) => { + const ran = await execute(root, selected, 'tsx', { TEST_DATABASE_URL: databases.urls[index] }, remaining, options.signal); + let raw, evidence; + if (!ran.reason) try { + raw = parseJson(ran.output, { maxBytes: MAX_OUTPUT, maxNodes: 500_000 }); + evidence = evidenceFor(raw, selected); + } catch { /* invalid evidence fails closed */ } + return { selected_files: selected, evidence_sha256: sha256(ran.output ?? Buffer.alloc(0)), + ...(Number.isInteger(ran.exit_code) ? { exit_code: ran.exit_code } : {}), + ...(ran.termination_signal ? { termination_signal: ran.termination_signal } : {}), + reason: ran.reason ?? (!evidence ? 'incomplete_test_results' : ran.failed || !raw.success || raw.files.some(file => !file.success) ? 'test_process_failed' : 'tests_executed'), + ...(evidence ? { test_files: evidence } : {}) }; + })); + } catch (error) { reason = 'runtime_database_provision_failed'; cleanup = error.cleanupVerified === true; } + finally { if (databases) cleanup = await databases.cleanup(); } + if (databases && !cleanup) reason = 'runtime_database_cleanup_failed'; + if (performance.now() > deadline) reason = 'test_timeout'; + reason ??= shards.find(shard => shard.reason !== 'tests_executed')?.reason; + const evidence = shards.flatMap(shard => shard.test_files ?? []).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0); + const covered = evidence.map(file => file.path); + const cases = evidence.flatMap(file => [...file.cases, ...file.suite_events].map(event => event.case_sha256)); + if (!reason && (JSON.stringify(covered) !== JSON.stringify(files) || new Set(cases).size !== cases.length)) reason = 'incomplete_test_results'; + if (!reason && evidence.some(file => file.counts.tests === 0 || file.counts.tests !== file.counts.passed || file.suite_events.some(event => event.status !== 'passed'))) reason = 'incomplete_test_results'; + const evidence_sha256 = sha256(Buffer.from(JSON.stringify(shards.map(shard => ({ selected_files: shard.selected_files, evidence_sha256: shard.evidence_sha256 }))))); + if (performance.now() > deadline) reason = 'test_timeout'; + return selections.map(({ id, files: selected }) => { + const test_files = evidence.filter(file => selected.includes(file.path)); + return { ...result(id, reason ? 'failed' : 'passed', reason ?? 'tests_executed'), + selected_files: selected, ...(test_files.length ? { test_files } : {}), test_count: test_files.reduce((sum, file) => sum + file.counts.tests, 0), + evidence_sha256, shards, database_cleanup_verified: cleanup }; + }); +} + +export async function runLocalSuites(root, ids, options = {}) { + const results = new Map(), governance = [], fixedNode = [], runtime = []; + for (const id of [...new Set(ids)].sort()) { + const isRuntime = id === 'runtime.full' || Object.hasOwn(RUNTIME_SUITES, id); + const isFixedNode = Object.hasOwn(FIXED_NODE_SUITES, id); + if (id !== 'governance.unit' && !isRuntime && !Object.hasOwn(NODE_CONSUMER_SUITES, id) && !isFixedNode) { results.set(id, result(id, 'not_run', 'suite_adapter_unavailable')); continue; } + if (isRuntime && !isDisposableDatabaseUrl(options.testDatabaseUrl)) { + results.set(id, result(id, 'not_run', options.testDatabaseUrl === undefined ? 'test_database_required' : 'test_database_rejected')); continue; + } + let files; + try { files = await suiteFiles(root, id); } + catch { results.set(id, result(id, 'not_run', 'suite_files_unavailable')); continue; } + if (!files.length) { results.set(id, { ...result(id, 'failed', 'empty_test_set'), test_count: 0 }); continue; } + (isRuntime ? runtime : isFixedNode ? fixedNode : governance).push({ id, files }); + } + // Fixed-file suites stay in their own non-runtime group so they keep the + // 60-second budget and a planner failure does not fail governance.unit. + for (const [selected, isRuntime] of [[governance, false], [fixedNode, false], [runtime, true]]) { + if (selected.length) for (const item of await runGroup(root, selected, isRuntime, isRuntime ? options : { ...options, runtimeShards: 1 })) results.set(item.check_id, item); + } + return [...results.values()].sort((a, b) => a.check_id.localeCompare(b.check_id)); +} + +export async function runLocalSuite(root, id, options = {}) { + return (await runLocalSuites(root, [id], options))[0]; +} + +const PINNED_OPTION_KEYS = Object.freeze(['testDatabaseUrl', 'env', 'timeoutMs', 'signal']); + +async function runPytestSuiteDefinition(root, id, files, suite, extraEnv, timeoutMs, options) { + const deadline = performance.now() + timeoutMs; + const failure = (reason, evidence_reason) => ({ ...result(id, 'failed', reason), + selected_files: files, test_count: 0, ...(evidence_reason ? { evidence_reason } : {}) }); + let temp; + try { + temp = await mkdtemp(join(tmpdir(), 'fp-pinned-')); + const junit = join(temp, 'junit.xml'), expected = join(temp, 'expected.json'); + await writeFile(expected, JSON.stringify(files)); + const config = join(temp, 'pytest.ini'); + await writeFile(config, '[pytest]\n'); + const args = ['-I', '-B', '-m', 'pytest', '-q', '-c', config, '--rootdir', resolve(root), '--noconftest', + '-p', 'no:cacheprovider', '-o', 'junit_family=xunit1', '--junitxml', junit, ...files]; + // The environment allowlist already excludes PYTEST_ADDOPTS and PYTEST_PLUGINS. + const env = { ...verificationEnvironment(), ...extraEnv, PYTHONDONTWRITEBYTECODE: '1', PYTEST_DISABLE_PLUGIN_AUTOLOAD: '1' }; + if (options.signal?.aborted) return failure('test_cancelled'); + if (performance.now() >= deadline) return failure('test_timeout'); + const ran = await new Promise(done => { + const group = process.platform !== 'win32'; + const child = spawn('python3', args, { cwd: root, env, detached: group, stdio: 'ignore' }); + let reason; + const stop = code => { + reason ??= code; + try { if (group && child.pid) process.kill(-child.pid, 'SIGKILL'); else child.kill('SIGKILL'); } catch { /* already exited */ } + }; + const abort = () => stop('test_cancelled'); + options.signal?.addEventListener('abort', abort, { once: true }); + if (options.signal?.aborted) abort(); + const timer = setTimeout(() => stop('test_timeout'), Math.max(1, deadline - performance.now())); + child.once('error', () => { reason ??= 'test_process_failed'; }); + child.once('close', (code, terminationSignal) => { + clearTimeout(timer); + options.signal?.removeEventListener('abort', abort); + done({ reason, failed: code !== 0 || terminationSignal !== null }); + }); + }); + if (ran.reason || ran.failed) return failure(ran.reason ?? 'test_process_failed'); + if (options.signal?.aborted) return failure('test_cancelled'); + if (performance.now() >= deadline) return failure('test_timeout'); + const helperPath = fileURLToPath(new URL('../../scripts/ci/pinned_pytest_evidence.py', import.meta.url)); + const helper = spawnSync('python3', ['-I', helperPath, '--junit', junit, '--expected', expected], + { cwd: root, env: verificationEnvironment(), encoding: 'utf8', + timeout: Math.max(1, Math.min(30000, Math.floor(deadline - performance.now()))), maxBuffer: MAX_OUTPUT }); + if (performance.now() >= deadline) return failure('test_timeout'); + let parsed; + try { parsed = parseJson(Buffer.from(helper.stdout ?? ''), { maxBytes: MAX_OUTPUT, maxNodes: 500_000 }); } + catch { return failure('invalid_test_results'); } + if (parsed.ok === false) return failure('incomplete_test_results', + typeof parsed.reason === 'string' && /^[a-z_]+$/.test(parsed.reason) ? parsed.reason : 'invalid_evidence_reason'); + if (helper.status !== 0 || parsed.ok !== true || !Array.isArray(parsed.files) + || !Number.isSafeInteger(parsed.total) || parsed.total < 1) return failure('incomplete_test_results'); + const test_files = parsed.files.map(file => ({ path: file.path, + counts: { tests: file.tests, passed: file.passed, failed: 0, cancelled: 0, skipped: 0, todo: 0 }, + cases: file.cases, suite_events: [] })); + const ids = new Set(); + if (JSON.stringify(test_files.map(file => file.path)) !== JSON.stringify(files) + || test_files.some(file => !Number.isSafeInteger(file.counts.tests) || file.counts.tests < 1 + || file.counts.tests !== file.counts.passed || !Array.isArray(file.cases) + || file.cases.length !== file.counts.tests || file.cases.some(entry => { + if (!entry || entry.status !== 'passed' || !/^[a-f0-9]{64}$/.test(entry.case_sha256) || ids.has(entry.case_sha256)) return true; + ids.add(entry.case_sha256); return false; + })) || parsed.total !== ids.size) return failure('incomplete_test_results'); + return { ...result(id, 'passed', 'tests_executed'), test_count: parsed.total, + evidence_sha256: sha256(Buffer.from(helper.stdout)), selected_files: files, test_files }; + } catch { + return failure('incomplete_test_results'); + } finally { + if (temp) try { await rm(temp, { recursive: true, force: true }); } + catch { return failure('incomplete_test_results'); } + } +} + +export async function runPinnedSuiteDefinition(root, id, suite, options = {}) { + for (const key of Object.keys(options)) { + if (!PINNED_OPTION_KEYS.includes(key)) return result(id, 'not_run', 'invalid_pinned_suite_options'); + } + + if (!suite || typeof suite !== 'object' || !Object.isFrozen(suite)) { + return result(id, 'not_run', 'suite_adapter_unavailable'); + } + + const allowedSuiteKeys = ['files', 'directory', 'directories', 'pattern', 'baseline', 'loader', 'database', 'timeoutMs', 'env']; + for (const key of Object.keys(suite)) { + if (!allowedSuiteKeys.includes(key)) return result(id, 'not_run', 'suite_adapter_unavailable'); + } + + const directoryKeys = ['directory', 'directories', 'pattern', 'baseline'].filter(key => Object.hasOwn(suite, key)); + const validShape = Object.hasOwn(suite, 'files') + ? directoryKeys.length === 0 && Array.isArray(suite.files) + : (directoryKeys.length === 3 && typeof suite.directory === 'string' && suite.pattern instanceof RegExp && Array.isArray(suite.baseline)) || + (directoryKeys.length === 3 && Array.isArray(suite.directories) && suite.directories.length > 0 && suite.directories.every(d => typeof d === 'string') && suite.pattern instanceof RegExp && Array.isArray(suite.baseline) && suite.baseline.every(f => suite.directories.some(d => f.startsWith(d + '/')))); + if (!validShape) return result(id, 'not_run', 'suite_adapter_unavailable'); + + let files = []; + if (suite.files) { + files = [...suite.files]; + } else { + const dirs = suite.directories || [suite.directory]; + try { + const foundFiles = []; + for (const dir of dirs) { + const found = await readdir(resolve(root, dir)); + foundFiles.push(...found.filter(name => suite.pattern.test(name)).map(name => dir + '/' + name)); + } + files = [...new Set([...suite.baseline, ...foundFiles])].sort(); + } catch { + return result(id, 'not_run', 'suite_files_unavailable'); + } + } + + files = [...new Set(files)].sort(); + if (files.length > MAX_FILES) return result(id, 'not_run', 'suite_files_unavailable'); + + try { + for (const path of files) { + await readBounded(root, path); + } + } catch { + return result(id, 'not_run', 'suite_files_unavailable'); + } + + if (files.length === 0) return { ...result(id, 'failed', 'empty_test_set'), test_count: 0, selected_files: files }; + + if (suite.database) { + if (!isDisposableDatabaseUrl(options.testDatabaseUrl)) { + return result(id, 'not_run', options.testDatabaseUrl === undefined ? 'test_database_required' : 'test_database_rejected'); + } + } + + const timeoutMs = options.timeoutMs !== undefined ? options.timeoutMs : suite.timeoutMs; + if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > suite.timeoutMs) { + return result(id, 'not_run', 'invalid_suite_timeout'); + } + + const extraEnv = {}; + if (suite.database) { + extraEnv.TEST_DATABASE_URL = options.testDatabaseUrl; + } + if (suite.env && options.env) { + for (const name of suite.env) { + if (options.env[name] !== undefined) extraEnv[name] = options.env[name]; + } + } + + if (suite.loader === 'pytest') { + return runPytestSuiteDefinition(root, id, files, suite, extraEnv, timeoutMs, options); + } + + const ran = await execute(root, files, suite.loader, extraEnv, timeoutMs, options.signal); + const failure = reason => ({ + ...result(id, reason === 'runtime_loader_unavailable' ? 'not_run' : 'failed', reason), + selected_files: files, + }); + if (ran.reason) return { ...failure(ran.reason), evidence_sha256: sha256(ran.output ?? Buffer.alloc(0)) }; + + let raw, evidence; + try { + raw = parseJson(ran.output, { maxBytes: MAX_OUTPUT, maxNodes: 500_000 }); + evidence = evidenceFor(raw, files); + } catch { + return failure('invalid_test_results'); + } + if (!evidence) return failure('incomplete_test_results'); + + const evidence_sha256 = sha256(ran.output); + const test_count = evidence.reduce((count, item) => count + item.counts.tests, 0); + + const passed = !ran.failed && raw.success && raw.files.every(file => file.success) + && evidence.every(file => file.counts.tests > 0 && file.counts.tests === file.counts.passed + && file.suite_events.every(event => event.status === 'passed')); + + return { + ...result(id, passed ? 'passed' : 'failed', passed ? 'tests_executed' : ran.failed ? 'test_process_failed' : 'incomplete_test_results'), + test_count, + evidence_sha256, + selected_files: files, + test_files: evidence + }; +} + +export async function runPinnedSuite(root, id, options = {}) { + for (const key of Object.keys(options)) { + if (!PINNED_OPTION_KEYS.includes(key)) return result(id, 'not_run', 'invalid_pinned_suite_options'); + } + + const suite = PINNED_SUITES[id]; + if (!suite) return result(id, 'not_run', 'suite_adapter_unavailable'); + + return runPinnedSuiteDefinition(root, id, suite, options); +} + +const PARTITION_SCHEMA = 'freedom.runtime-partition/v1'; +// Finite matrix capacity, including provisioning and verified cleanup. Hosted +// observations on 2026-10-15 put the same 55 files about 20% slower and the +// projected full partition beyond 1,224s. Keep legacy four-partition behavior; +// six hosts get 1,500s including the unchanged 24s cleanup reserve. +const PARTITION_BUDGET_MS = Object.freeze({ 4: 1_200_000, 6: 1_500_000 }); +// Queueing can serialize all six hosts: allow six full partition budgets plus +// 30 minutes of bounded queue gaps. CI scopes artifacts to one run attempt; +// this wall span does not extend any partition's execution/cleanup deadline. +const MATRIX_WINDOW_MS = Object.freeze({ 4: 1_800_000, 6: 6 * 1_500_000 + 1_800_000 }); +const identical = (a, b) => JSON.stringify(a) === JSON.stringify(b); +const strictKeys = (value, keys) => value && typeof value === 'object' && !Array.isArray(value) && + Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key)); +function partitionCheck(value, code) { if (!value) throw Error(code); } + +export async function runtimeSourceManifest(root) { + const git = spawnSync('git', ['rev-parse', '--verify', 'HEAD'], { cwd: root, env: verificationEnvironment(), encoding: 'utf8', timeout: 5000, maxBuffer: 4096 }); + const candidate_commit = git.stdout?.trim(); + const clean = spawnSync('git', ['diff', '--quiet', 'HEAD', '--'], {cwd:root,env:verificationEnvironment(),timeout:5000,maxBuffer:4096}); + partitionCheck(clean.status === 0, 'runtime_source_changed'); + partitionCheck(git.status === 0 && /^[a-f0-9]{40}$/.test(candidate_commit), 'runtime_candidate_unavailable'); + const files = await suiteFiles(root, 'runtime.full'); + const full_source_manifest = []; + for (const path of files) full_source_manifest.push({ path, source_sha256: sha256(await readBounded(root, path)) }); + return { candidate_commit, full_source_manifest, + manifest_sha256: sha256(Buffer.from(JSON.stringify(full_source_manifest))) }; +} + +// A matrix fragment is never a runtime.full result. Own one fresh nonce DB and +// one serial test process, including provisioning/cleanup inside its partition budget. +export async function runRuntimePartition(root, options = {}) { + const count = options.partitionCount; + partitionCheck([4, 6].includes(count) && Number.isInteger(options.partitionIndex) && + options.partitionIndex >= 0 && options.partitionIndex < count, 'invalid_runtime_partition'); + partitionCheck(Object.keys(options).every(key => ['partitionCount','partitionIndex','testDatabaseUrl','signal'].includes(key)), 'invalid_runtime_partition_options'); + const budget = PARTITION_BUDGET_MS[count]; + const started_at = new Date().toISOString(), deadline = performance.now() + budget; + const source = await runtimeSourceManifest(root); + const selected = partitionRuntimeFiles(source.full_source_manifest.map(file => file.path), count)[options.partitionIndex]; + const check_id = `runtime.partition.${options.partitionIndex}`; + let databases, cleanup = false, report; + try { + partitionCheck(isDisposableDatabaseUrl(options.testDatabaseUrl), 'test_database_rejected'); + databases = await createRuntimeDatabases(options.testDatabaseUrl, 1, Math.max(1, Math.min(20_000, Math.floor(deadline - performance.now() - 24_000)))); + const remaining = Math.floor(deadline - performance.now() - 24_000); + if (remaining <= 0) throw Error('test_timeout'); + [report] = await runGroup(root, [{id: check_id, files: selected}], true, + {testDatabaseUrl: databases.urls[0], timeoutMs: remaining, runtimeShards: 1, signal: options.signal}, budget); + } catch (error) { + cleanup = error.cleanupVerified === true; + const allowed = ['test_database_rejected','test_timeout']; + report = result(check_id, 'failed', allowed.includes(error.message) ? error.message : 'runtime_database_provision_failed'); + } finally { if (databases) cleanup = await databases.cleanup(); } + report = { ...report, selected_files: selected, database_cleanup_verified: cleanup }; + if (!cleanup) report = { ...report, status: 'failed', reason: 'runtime_database_cleanup_failed' }; + try { if (!identical(source, await runtimeSourceManifest(root))) report = {...report,status:'failed',reason:'runtime_source_changed'}; } + catch { report = {...report,status:'failed',reason:'runtime_source_changed'}; } + if (performance.now() > deadline) report = {...report,status:'failed',reason:'test_timeout'}; + return { schema: PARTITION_SCHEMA, check_id, partition_index: options.partitionIndex, partition_count: count, + ...source, started_at, ended_at: new Date().toISOString(), database_cleanup_verified: cleanup, report }; +} + +/** Diagnostic candidate artifacts are untrusted. Recompute selection and reject + * incomplete evidence; passing aggregation does not authenticate a host gate. */ +export async function aggregateRuntimePartitions(root, fragments, options = {}) { + const failure = reason => ({check_id:'runtime.full',status:'failed',reason,gate_enforced:false,merge_authorized:false}); + try { + partitionCheck(Object.keys(options).every(key => ['partitionCount'].includes(key)) && [4, 6].includes(options.partitionCount ?? 4), 'runtime_partition_options_invalid'); + const numPartitions = options.partitionCount ?? 4; + partitionCheck(Array.isArray(fragments) && fragments.length === numPartitions, 'runtime_partitions_missing'); + const source = await runtimeSourceManifest(root); + const partitions = partitionRuntimeFiles(source.full_source_manifest.map(file => file.path), numPartitions); + const seen = new Set(), identities = new Set(); let started = Infinity, ended = -Infinity; + const files = [], ordered = []; + for (const fragment of fragments) { + partitionCheck(strictKeys(fragment, ['schema','check_id','partition_index','partition_count','candidate_commit','full_source_manifest','manifest_sha256','started_at','ended_at','database_cleanup_verified','report']), 'runtime_partition_schema'); + const index = fragment.partition_index; + partitionCheck(fragment.schema === PARTITION_SCHEMA && fragment.partition_count === numPartitions && Number.isInteger(index) && index >= 0 && index < numPartitions && !seen.has(index), 'runtime_partition_identity'); + seen.add(index); + partitionCheck(fragment.check_id === `runtime.partition.${index}` && fragment.candidate_commit === source.candidate_commit && + fragment.manifest_sha256 === source.manifest_sha256 && identical(fragment.full_source_manifest, source.full_source_manifest), 'runtime_partition_source_mismatch'); + for (const [key, value] of [['started_at',fragment.started_at],['ended_at',fragment.ended_at]]) { + const timestamp = Date.parse(value); + partitionCheck(typeof value === 'string' && Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value, 'runtime_partition_clock'); + if (key === 'started_at') started = Math.min(started,timestamp); else ended = Math.max(ended,timestamp); + } + const fragStarted = Date.parse(fragment.started_at); + const fragEnded = Date.parse(fragment.ended_at); + partitionCheck(fragEnded >= fragStarted, 'runtime_partition_clock'); + partitionCheck(fragEnded - fragStarted <= PARTITION_BUDGET_MS[numPartitions], 'runtime_partition_window_exceeded'); + const report = fragment.report; + partitionCheck(strictKeys(report, ['check_id','status','reason','test_count','evidence_sha256','selected_files','test_files','database_cleanup_verified']) && + report.check_id === fragment.check_id && report.status === 'passed' && report.reason === 'tests_executed' && + fragment.database_cleanup_verified === true && report.database_cleanup_verified === true && + /^[a-f0-9]{64}$/.test(report.evidence_sha256) && identical(report.selected_files,partitions[index]) && + Array.isArray(report.test_files) && report.test_files.length === partitions[index].length, 'runtime_partition_incomplete'); + const selected = new Set(partitions[index]), covered = new Set(); let count = 0; + for (const file of report.test_files) { + partitionCheck(strictKeys(file,['path','counts','cases','suite_events']) && selected.has(file.path) && !covered.has(file.path), 'runtime_partition_file_union'); + covered.add(file.path); + partitionCheck(strictKeys(file.counts,COUNT_KEYS) && COUNT_KEYS.every(key => Number.isSafeInteger(file.counts[key]) && file.counts[key] >= 0) && + file.counts.tests > 0 && file.counts.tests === file.counts.passed && COUNT_KEYS.slice(2).every(key => file.counts[key] === 0) && + Array.isArray(file.cases) && file.cases.length === file.counts.tests && Array.isArray(file.suite_events), 'runtime_partition_counts'); + for (const event of [...file.cases,...file.suite_events]) { + partitionCheck(strictKeys(event,['case_sha256','status']) && /^[a-f0-9]{64}$/.test(event.case_sha256) && event.status === 'passed' && !identities.has(event.case_sha256), 'runtime_partition_case_union'); + identities.add(event.case_sha256); + } + count += file.counts.tests; files.push(file); + } + partitionCheck(Number.isSafeInteger(report.test_count) && report.test_count === count && count > 0, 'runtime_partition_counts'); + ordered[index] = fragment; + } + partitionCheck(ended - started <= MATRIX_WINDOW_MS[numPartitions], 'runtime_full_window_exceeded'); + files.sort((a,b) => a.path.localeCompare(b.path)); + partitionCheck(identical(files.map(file => file.path), source.full_source_manifest.map(file => file.path)), 'runtime_partition_file_union'); + partitionCheck(identical(source,await runtimeSourceManifest(root)), 'runtime_source_changed'); + return {check_id:'runtime.full',status:'passed',reason:'tests_executed',gate_enforced:false,merge_authorized:false, + ...source, started_at:new Date(started).toISOString(),ended_at:new Date(ended).toISOString(), + selected_files:files.map(file => file.path),test_files:files,test_count:files.reduce((sum,file)=>sum+file.counts.tests,0), + database_cleanup_verified:true,partition_count:numPartitions, + evidence_sha256:sha256(Buffer.from(JSON.stringify(ordered))), + partition_evidence_sha256:ordered.map(fragment=>fragment.report.evidence_sha256)}; + } catch (error) { return failure(/^runtime_[a-z_]+$/.test(error?.message ?? '') ? error.message : 'runtime_partition_invalid'); } +} diff --git a/vendor/freedom-tooling/packages/contribution-tools/test-failure-diagnostic.mjs b/vendor/freedom-tooling/packages/contribution-tools/test-failure-diagnostic.mjs new file mode 100644 index 0000000..4b20403 --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/test-failure-diagnostic.mjs @@ -0,0 +1,101 @@ +import { relative, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { parseJson } from './io.mjs'; + +const PATHS = ['tests/runtime/model-broker-bridge-adversarial.test.ts','tests/runtime/media-verify.test.ts','tests/runtime/credential-ingest-process.test.ts','tests/runtime/credential-ingest-adversarial.test.ts','tests/runtime/member-model-settings-process.test.ts','tests/runtime/credential-ingest-rate-budget.test.ts']; +const SCHEMA = 'freedom.test-failure-diagnostic/v1'; +const MAX_BYTES = 262144, MAX_LINE = 2048, MAX_RECORDS = 64; +const NAMES = ['AssertionError','TypeError','Error','unknown']; +const CODES = ['ERR_ASSERTION','ERR_TEST_FAILURE','unknown']; +const CLASSES = ['sql_wait_not_observed','asset_read_not_reached','expiry_assertion','assertion_failed','fetch_failed','custody_outcome_unconfirmed','operation_timeout','unknown']; +const hash = v => typeof v==='string' && /^[a-f0-9]{64}$(?![\s\S])/.test(v); +const exact = (v,keys) => v && typeof v==='object' && !Array.isArray(v) && Object.keys(v).length===keys.length && keys.every(k=>Object.hasOwn(v,k)); +const comparisonValue = v => typeof v==='boolean' || Number.isSafeInteger(v)&&Math.abs(v)<=20000; +const INGEST_PHASES=['browser_context','issue','navigation_blank','navigation_submit','navigation_wait','screenshot','key_fill','consent_check','submit_click','ack_wait','broker_wait','owner_read','owner_assert','page_close']; +const INGEST_STATES=['not_seen','request','response','failed']; +const validIngest=d=>exact(d,['phase','prepare_state','prepare_status','secret_state','secret_status','custody']) + &&['not_checked','absent','one_active','multiple_active','unavailable'].includes(d.custody)&&INGEST_PHASES.includes(d.phase)&&INGEST_STATES.includes(d.prepare_state)&&INGEST_STATES.includes(d.secret_state) + &&[d.prepare_status,d.secret_status].every(v=>v===null||Number.isInteger(v)&&v>=100&&v<=599); +/** Fixture-only bounded annotations. Never replace the original Error/TimeoutError. */ +export function createIngestBrowserDiagnostic(){ + const state={phase:'browser_context',prepare_state:'not_seen',prepare_status:null,secret_state:'not_seen',secret_status:null,custody:'not_checked'}; + return Object.freeze({phase(value){if(INGEST_PHASES.includes(value))state.phase=value;}, + observe(kind,event,status=null){if(!['prepare','secret'].includes(kind)||!INGEST_STATES.includes(event)||!(status===null||Number.isInteger(status)&&status>=100&&status<=599))return; + state[kind+'_state']=event;if(status!==null)state[kind+'_status']=status;}, + custody(value){if(['absent','one_active','multiple_active','unavailable'].includes(value))state.custody=value;}, + annotate(error){try{if(error&&typeof error==='object')Object.defineProperty(error,'freedom_ingest',{value:{...state},enumerable:true,configurable:true});}catch{}return error;} + }); +} +function sourcesMap(sources) { + return new Map(sources.filter(s=>PATHS.includes(s.path)).map(s=>[s.path,s])); +} +function detail(error) { + const chain=[];for(let e=error;e&&chain.length<4;e=e.cause)chain.push(e); + const actual=chain.find(e=>e.code==='ERR_ASSERTION')??chain.find(e=>NAMES.includes(e.name))??{}; + const message=typeof actual.message==='string'&&actual.message.length<=8192?actual.message:''; + const message_class=['Actual SQL wait was not observed','Actual SQL wait not observed'].includes(message)?'sql_wait_not_observed' + :message==='actual asset read must reach the trusted port before deadline'?'asset_read_not_reached' + :actual.code==='ERR_ASSERTION'&&/assert\(\s*expires\s*>\s*Date\.now\(\)\s*\)/.test(message)?'expiry_assertion' + :actual.code==='ERR_ASSERTION'&&actual.expected==='committed'?'custody_outcome_unconfirmed' + :chain.some(e=>e.name==='TimeoutError')?'operation_timeout' + :actual.code==='ERR_ASSERTION'?'assertion_failed':message==='fetch failed'?'fetch_failed':'unknown'; + const ingest=chain.map(e=>e.freedom_ingest).find(validIngest); + return {error_name:NAMES.includes(actual.name)?actual.name:'unknown',error_code:CODES.includes(actual.code)?actual.code:'unknown',message_class,...(ingest?{ingest:{...ingest}}:{}), + ...(chain.some(e=>e.code==='UND_ERR_SOCKET')?{cause_code:'UND_ERR_SOCKET'}:{}), + ...(actual.code==='ERR_ASSERTION'&&comparisonValue(actual.actual)&&comparisonValue(actual.expected)?{comparison:{actual:actual.actual,expected:actual.expected}}:{})}; +} +function validDetail(d) { + return exact(d,['error_name','error_code','message_class',...(Object.hasOwn(d??{},'cause_code')?['cause_code']:[]),...(Object.hasOwn(d??{},'comparison')?['comparison']:[]),...(Object.hasOwn(d??{},'ingest')?['ingest']:[])]) + &&NAMES.includes(d.error_name)&&CODES.includes(d.error_code)&&CLASSES.includes(d.message_class) + &&(!Object.hasOwn(d,'ingest')||validIngest(d.ingest)) + &&(!Object.hasOwn(d,'cause_code')||d.cause_code==='UND_ERR_SOCKET') + &&(!Object.hasOwn(d,'comparison')||d.error_code==='ERR_ASSERTION'&&exact(d.comparison,['actual','expected'])&&comparisonValue(d.comparison.actual)&&comparisonValue(d.comparison.expected)); +} +// Inspect a bounded stack only for this exact selected, source-hashed file. +// Other file names, paths, messages, columns and stack text never leave the child. +// A helper failure may yield the same-file caller line, not the helper assertion. +function failureSourceLine(error,path,source,fallback) { + const absolute=resolve(process.cwd(),path),prefixes=[absolute,pathToFileURL(absolute).href]; + const chain=[];for(let e=error;e&&chain.length<4;e=e.cause)chain.push(e); + for(const e of chain.reverse()) { + if(typeof e.stack!=='string'||e.stack.length>8192)continue; + for(const frame of e.stack.split('\n').slice(1,25)) { + if(!/^\s+at /.test(frame))continue; + for(const prefix of prefixes) { + const start=frame.indexOf(prefix+':');if(start<0)continue; + const before=frame.slice(0,start); + if(!/^(?:\s+at |\s+at [^()\r\n]*\()$/.test(before))continue; + const match=/^([1-9][0-9]{0,6}):[1-9][0-9]{0,6}\)?$/.exec(frame.slice(start+prefix.length+1)); + const line=match?Number(match[1]):0; + if(line>=1&&line<=source.source_lines)return line; + } + } + } + return Number.isSafeInteger(fallback)&&fallback>=1&&fallback<=source.source_lines?fallback:undefined; +} +/** No raw messages, names, stack, env, bodies or object actual/expected values. */ +export function createFailureDiagnosticEmitter(sources,write,caseDigest) { + const selected=sourcesMap(sources);let records=0,bytes=0; + return event=>{try{ + const d=event.data,path=typeof d?.file==='string'?relative(process.cwd(),d.file):''; + if(event.type!=='test:fail'||d.details?.type!=='test'||d.skip!==undefined||d.todo!==undefined||!selected.has(path)||records>=MAX_RECORDS)return; + const source=selected.get(path),source_line=failureSourceLine(d.details.error,path,source,d.line); + const value={schema:SCHEMA,path,source_sha256:source.source_sha256,case_sha256:caseDigest(d,path),...(source_line!==undefined?{source_line}:{}),detail:detail(d.details.error)}; + const line=JSON.stringify(value)+'\n',size=Buffer.byteLength(line);if(size>MAX_LINE||bytes+size>MAX_BYTES)return; + bytes+=size;records++;write(line); + }catch{/* Diagnostic failure has no influence on the primary report. */}}; +} +export function createFailureDiagnosticDecoder(sources,emit) { + const selected=sourcesMap(sources),seen=new Set();let pending=Buffer.alloc(0),bytes=0,disabled=false; + return Object.freeze({push(chunk){if(disabled)return;bytes+=chunk.length;if(bytes>MAX_BYTES){disabled=true;pending=Buffer.alloc(0);return;} + pending=Buffer.concat([pending,chunk]);let end; + while((end=pending.indexOf(10))!==-1){const line=pending.subarray(0,end);pending=pending.subarray(end+1);try{ + if(line.length>MAX_LINE||seen.size>=MAX_RECORDS)continue; + const r=parseJson(line,{maxBytes:MAX_LINE,maxDepth:4,maxNodes:32}),source=selected.get(r.path); + if(!source||!exact(r,['schema','path','source_sha256','case_sha256','detail',...(Object.hasOwn(r,'source_line')?['source_line']:[])])||r.schema!==SCHEMA||r.source_sha256!==source.source_sha256||!hash(r.case_sha256)||seen.has(r.case_sha256)||!validDetail(r.detail) + ||Object.hasOwn(r,'source_line')&&(!Number.isSafeInteger(r.source_line)||r.source_line<1||!Number.isSafeInteger(source.source_lines)||r.source_line>source.source_lines))continue; + seen.add(r.case_sha256);emit({schema:SCHEMA,path:r.path,source_sha256:r.source_sha256,case_sha256:r.case_sha256,...(Object.hasOwn(r,'source_line')?{source_line:r.source_line}:{}),detail:{error_name:r.detail.error_name,error_code:r.detail.error_code,message_class:r.detail.message_class,...(r.detail.ingest?{ingest:{...r.detail.ingest}}:{}),...(r.detail.cause_code?{cause_code:r.detail.cause_code}:{}),...(r.detail.comparison?{comparison:{actual:r.detail.comparison.actual,expected:r.detail.comparison.expected}}:{})}}); + }catch{/* Invalid untrusted sideband is discarded. */}} + if(pending.length>MAX_LINE){disabled=true;pending=Buffer.alloc(0);} + }}); +} diff --git a/vendor/freedom-tooling/packages/contribution-tools/test-reporter.mjs b/vendor/freedom-tooling/packages/contribution-tools/test-reporter.mjs new file mode 100644 index 0000000..432e619 --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/test-reporter.mjs @@ -0,0 +1,122 @@ +import { createFailureDiagnosticEmitter } from './test-failure-diagnostic.mjs'; +import { createHash } from 'node:crypto'; +import { relative } from 'node:path'; +import { writeSync } from 'node:fs'; +import { artifactPath, parseJson, readBounded, sha256 } from './io.mjs'; + + +const PROGRESS_SCHEMA = 'freedom.test-file-progress/v1'; +const PROGRESS_MAX_BYTES = 1_048_576, PROGRESS_MAX_LINE = 2048, PROGRESS_MAX_FILES = 512, PROGRESS_MAX_FAILURES = 64; +// The longest test process is one hosted four-partition runtime fragment (suite-runner PARTITION_BUDGET_MS). +const PROGRESS_MAX_ELAPSED_MS = 1_200_000; +const FAILURE_TYPES = ['testCodeFailure','hookFailed','testTimeoutFailure','cancelledByParent','testAborted','subtestsFailed','unknown']; +const caseDigest = (d,file) => createHash('sha256').update(JSON.stringify([file,d.details.type,d.line,d.column,d.nesting,d.testNumber,d.testId,d.parentId])).digest('hex'); +const PROGRESS_COUNTS = ['tests','passed','failed','cancelled','skipped','todo','suites']; +const validCounts = c => c && typeof c==='object' && !Array.isArray(c) + && Object.keys(c).length===PROGRESS_COUNTS.length && PROGRESS_COUNTS.every(k=>Number.isSafeInteger(c[k])&&c[k]>=0&&c[k]<=20_000) + && c.tests===['passed','failed','cancelled','skipped','todo'].reduce((n,k)=>n+c[k],0); +function progressPath(path) { artifactPath(path); if (!/\.test\.(?:ts|mjs)$/.test(path)) throw Error('invalid_progress_path'); return path; } +/** Parent validates every byte before emitting a fresh, closed diagnostic. These + * candidate-process records never participate in final result admission. */ +export function createProgressDecoder(expectedSources, emit) { + const expected=new Map(expectedSources.map(({path,source_sha256,source_lines})=>[progressPath(path),{source_sha256,source_lines}])); + if(expected.size!==expectedSources.length||expected.size>PROGRESS_MAX_FILES||[...expected.values()].some(d=>! /^[a-f0-9]{64}$/.test(d.source_sha256)||(d.source_lines!==undefined&&(!Number.isSafeInteger(d.source_lines)||d.source_lines<1))))throw Error('invalid_progress_selection'); + const started=new Set(),completed=new Set(),failures=new Set();let bytes=0,records=0,completedFailures=0,pending=Buffer.alloc(0),invalid=false,exhausted=false; + function record(line){ + if(++records>PROGRESS_MAX_FILES*2+PROGRESS_MAX_FAILURES){invalid=true;exhausted=true;return;} + try{ + const r=parseJson(line,{maxBytes:PROGRESS_MAX_LINE,maxDepth:3,maxNodes:32}); + const failed=r.event==='failed_case'; + const keys=failed?['schema','event','path','source_sha256','elapsed_ms','case_sha256','failure_type',...(Object.hasOwn(r,'source_line')?['source_line']:[])]:r.event==='started'?['schema','event','path','source_sha256','elapsed_ms']:['schema','event','path','source_sha256','elapsed_ms','counts']; + if(Object.keys(r).length!==keys.length||!keys.every(k=>Object.hasOwn(r,k))||r.schema!==PROGRESS_SCHEMA||!['started','completed','failed_case'].includes(r.event) + ||!expected.has(r.path)||expected.get(r.path).source_sha256!==r.source_sha256||!Number.isSafeInteger(r.elapsed_ms)||r.elapsed_ms<0||r.elapsed_ms>PROGRESS_MAX_ELAPSED_MS + ||(r.event==='started'?started.has(r.path):!started.has(r.path)||completed.has(r.path)||(!failed&&!validCounts(r.counts))) + ||(failed&&(!/^[a-f0-9]{64}$(?![\s\S])/.test(r.case_sha256)||failures.has(r.case_sha256)||failures.size>=PROGRESS_MAX_FAILURES||!FAILURE_TYPES.includes(r.failure_type) + ||(Object.hasOwn(r,'source_line')&&(!Number.isSafeInteger(r.source_line)||r.source_line<1||expected.get(r.path).source_lines===undefined||r.source_line>expected.get(r.path).source_lines)))))throw Error(); + (failed?failures:r.event==='started'?started:completed).add(failed?r.case_sha256:r.path); + if(r.event==='completed')completedFailures+=r.counts.failed+r.counts.cancelled; + // Reconstruct rather than relay parsed bytes or unknown candidate fields. + emit({schema:PROGRESS_SCHEMA,event:r.event,path:r.path,source_sha256:r.source_sha256,elapsed_ms:r.elapsed_ms, + ...(failed?{case_sha256:r.case_sha256,failure_type:r.failure_type,...(Object.hasOwn(r,'source_line')?{source_line:r.source_line}:{})}:r.event==='completed'?{counts:Object.fromEntries(PROGRESS_COUNTS.map(k=>[k,r.counts[k]]))}:{})}); + }catch{invalid=true;} + } + return Object.freeze({ + push(chunk){if(exhausted)return;bytes+=chunk.length;if(bytes>PROGRESS_MAX_BYTES){invalid=true;exhausted=true;pending=Buffer.alloc(0);return;} + pending=Buffer.concat([pending,chunk]);let newline; + while(!exhausted&&(newline=pending.indexOf(10))!==-1){const line=pending.subarray(0,newline);pending=pending.subarray(newline+1);if(line.length>PROGRESS_MAX_LINE){invalid=true;continue;}record(line);} + if(pending.length>PROGRESS_MAX_LINE){invalid=true;exhausted=true;pending=Buffer.alloc(0);} + }, + finish(){return {schema:'freedom.test-file-progress-summary/v1',selected_count:expected.size,started_count:started.size,completed_count:completed.size,incomplete:invalid||pending.length>0||completed.size!==expected.size||failures.size!==completedFailures};}, + }); +} +async function fileProgress() { + const epoch=performance.now();let selected; + try{ + if(typeof process.env.FREEDOM_TEST_PROGRESS_FILES!=='string')return ()=>{}; + const paths=parseJson(process.env.FREEDOM_TEST_PROGRESS_FILES,{maxBytes:131_072,maxDepth:2,maxNodes:514}); + if(!Array.isArray(paths)||paths.length>PROGRESS_MAX_FILES||new Set(paths).size!==paths.length)throw Error(); + selected=new Map();let total=0; + for(const path of paths){progressPath(path);const bytes=await readBounded(process.cwd(),path);total+=bytes.length;if(total>32_000_000)throw Error();selected.set(path,{digest:sha256(bytes),lines:bytes.toString('utf8').split('\n').length});} + }catch{return ()=>{};} + const started=new Set(),completed=new Set();let records=0,total=0,failureCount=0,disabled=false; + return event=>{ + if(disabled)return; + const d=event.data,path=typeof d?.file==='string'?relative(process.cwd(),d.file):''; + if(!selected.has(path))return; + const start=event.type==='test:dequeue'&&d.entryFile===undefined&&d.nesting===0; + const complete=event.type==='test:summary'&&started.has(path); + const failed=event.type==='test:fail'&&d.details?.type==='test'&&d.skip===undefined&&d.todo===undefined&&started.has(path)&&!completed.has(path); + if(failed&&failureCount++>=PROGRESS_MAX_FAILURES)return; + if((!start&&!complete&&!failed)||(start&&started.has(path))||(complete&&completed.has(path)))return; + const counts=complete?Object.fromEntries(PROGRESS_COUNTS.map(k=>[k,d.counts?.[k]])):undefined; + if(complete&&!validCounts(counts))return; + if(!failed)(start?started:completed).add(path); + const type=d.details?.error?.failureType; + const sourceLine=Number.isSafeInteger(d.line)&&d.line>=1&&d.line<=selected.get(path).lines?d.line:undefined; + const value={schema:PROGRESS_SCHEMA,event:failed?'failed_case':start?'started':'completed',path,source_sha256:selected.get(path).digest,elapsed_ms:Math.min(PROGRESS_MAX_ELAPSED_MS,Math.max(0,Math.floor(performance.now()-epoch))), + ...(failed?{case_sha256:caseDigest(d,path),failure_type:FAILURE_TYPES.includes(type)?type:'unknown',...(sourceLine!==undefined?{source_line:sourceLine}:{})}:complete?{counts}:{})}; + const line=JSON.stringify(value)+'\n';total+=Buffer.byteLength(line); + if(++records>PROGRESS_MAX_FILES*2+PROGRESS_MAX_FAILURES||total>PROGRESS_MAX_BYTES){disabled=true;return;} + try{writeSync(3,line);}catch{disabled=true;} + }; +} + +async function failureDiagnostics() { + try { + const paths=parseJson(process.env.FREEDOM_TEST_PROGRESS_FILES,{maxBytes:131072,maxDepth:2,maxNodes:514}); + if(!Array.isArray(paths)||paths.length>512)return ()=>{}; + const sources=[]; + for(const path of ['tests/runtime/model-broker-bridge-adversarial.test.ts','tests/runtime/media-verify.test.ts','tests/runtime/credential-ingest-process.test.ts','tests/runtime/credential-ingest-adversarial.test.ts','tests/runtime/member-model-settings-process.test.ts','tests/runtime/credential-ingest-rate-budget.test.ts']) { + if(!paths.includes(path))continue; + const bytes=await readBounded(process.cwd(),path); + sources.push({path,source_sha256:sha256(bytes),source_lines:bytes.toString('utf8').split('\n').length}); + } + return createFailureDiagnosticEmitter(sources,line=>writeSync(4,line),caseDigest); + }catch{return ()=>{};} +} + +// Structured events avoid accidental TAP/stdout confusion, not hostile-code +// spoofing: this reporter and the tests still run in a candidate-controlled +// local checkout. Never promote these records to authenticated host observations. +export default async function* report(source) { + const files = [], cases = [], suites = []; + const progress = await fileProgress(); + const failureDiagnostic = await failureDiagnostics(); + for await (const event of source) { + progress(event); + failureDiagnostic(event); + if (['test:pass', 'test:fail'].includes(event.type) && ['test', 'suite'].includes(event.data.details?.type)) { + const d = event.data; + const file = typeof d.file === 'string' ? relative(process.cwd(), d.file) : ''; + const status = d.skip !== undefined ? 'skipped' : d.todo !== undefined ? 'todo' : event.type === 'test:pass' ? 'passed' + : ['cancelledByParent', 'testAborted', 'testTimeoutFailure'].includes(d.details.error?.failureType) ? 'cancelled' : 'failed'; + // Locations and runner identifiers, never test names, assertion text, + // exception messages, stdout, database URLs or ambient environment. + (d.details.type === 'suite' ? suites : cases).push({ file, case_sha256: caseDigest(d,file), status }); + } + if (event.type !== 'test:summary') continue; + const { file, counts, success } = event.data; + if (file) files.push({ file: relative(process.cwd(), file), counts, success }); + else yield JSON.stringify({ counts, success, files, cases, suites }) + '\n'; + } +} diff --git a/vendor/freedom-tooling/packages/contribution-tools/verify.mjs b/vendor/freedom-tooling/packages/contribution-tools/verify.mjs new file mode 100644 index 0000000..53fa935 --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/verify.mjs @@ -0,0 +1,60 @@ +import { buildContextMetadata } from './context.mjs'; +import { inspectWorkspace, resolveCommit } from './workspace.mjs'; +import { readBounded, parseJson, sha256 } from './io.mjs'; +import { validateFormat } from './formats.mjs'; +import { verifyContractPin } from './contracts.mjs'; +import { safeFailure, requireCondition as check } from './errors.mjs'; +import { runLocalSuites } from './suite-runner.mjs'; +export { runLocalSuite, runLocalSuites } from './suite-runner.mjs'; + +async function contractCheck(workspace) { + try { + if (workspace.candidate_paths.includes('contracts.lock.json')) { + await verifyContractPin({ repositoryRoot: workspace.root }); + return { check_id: 'contracts', status: 'passed', reason: 'local_pin_integrity' }; + } + if (workspace.candidate_paths.includes('contracts/preview/v1/bundle.json')) { + const bundle = parseJson(await readBounded(workspace.root, 'contracts/preview/v1/bundle.json')); + check(bundle.format === 'freedom.contract-bundle/v1' && bundle.files && typeof bundle.files === 'object', 'invalid_preview_bundle'); + for (const [path, declared] of Object.entries(bundle.files)) { + const bytes = await readBounded(workspace.root, 'contracts/preview/v1/' + path); + check(bytes.length === declared.bytes && sha256(bytes) === declared.sha256, 'artifact_integrity_mismatch'); + } + check(Object.keys(bundle.files).length > 0, 'empty_preview_bundle'); + return { check_id: 'contracts', status: 'passed', reason: 'producer_preview_bytes_only' }; + } + return { check_id: 'contracts', status: 'not_run', reason: 'contract_source_missing' }; + } catch (error) { + const failure = safeFailure(error); + return { check_id: 'contracts', status: failure.status === 'unavailable' ? 'not_run' : 'failed', reason: failure.code }; + } +} + +export async function verifyWorkspace(options, { suiteRunner, testDatabaseUrl } = {}) { + const built = await buildContextMetadata(options), { workspace, context, impact } = built; + const checks = [{ check_id: 'descriptors', status: 'passed', reason: 'schema_and_references_checked' }, await contractCheck(workspace)]; + for (const blocker of context.blockers) checks.push({ check_id: blocker, status: 'not_run', reason: blocker }); + const suites = new Set(impact.tests); + if (impact.unknown_paths.length) { + suites.add('governance.unit'); suites.add('runtime.full'); + } + const codeChanged = workspace.changed_paths.some(path => /\.(?:[cm]?[jt]sx?|rs|sql|jsonc?)$/.test(path)); + if (codeChanged && !suites.size) checks.push({ check_id: 'coverage', status: 'not_run', reason: 'surface_unmapped' }); + if (suiteRunner) { + for (const id of [...suites].sort()) checks.push(await suiteRunner(workspace.root, id)); + } else checks.push(...await runLocalSuites(workspace.root, [...suites], { testDatabaseUrl })); + const runtimeChanged = impact.module_ids.some(id => id !== 'governance') || impact.unknown_paths.length > 0; + if (runtimeChanged) checks.push({ check_id: 'runtime.surface-coverage', status: 'not_run', reason: 'registration_behavior_audit_required' }); + const current = await inspectWorkspace(workspace.root, workspace.base_commit); + if (current.workspace_sha256 !== workspace.workspace_sha256) checks.push({ check_id: 'workspace', status: 'failed', reason: 'workspace_changed_during_verification' }); + if (resolveCommit(workspace.root, options.baseRef ?? 'origin/main') !== workspace.base_commit) { + checks.push({ check_id: 'base', status: 'failed', reason: 'base_changed_during_verification' }); + } + const status = checks.some(item => item.status === 'failed') ? 'failed' + : checks.some(item => item.status === 'not_run') ? 'unavailable' : 'passed'; + const report = { format: 'freedom.verifier-report/v1', assurance_level: 'local', repository: context.repository, + base_commit: workspace.base_commit, head_commit: workspace.head_commit, workspace_sha256: workspace.workspace_sha256, + status, scope: impact.module_ids, checks, blockers: [...new Set(checks.filter(item => item.status !== 'passed').map(item => item.reason))].sort() }; + validateFormat('verifierReport', report); + return report; +} diff --git a/vendor/freedom-tooling/packages/contribution-tools/workspace.mjs b/vendor/freedom-tooling/packages/contribution-tools/workspace.mjs new file mode 100644 index 0000000..80c1bc8 --- /dev/null +++ b/vendor/freedom-tooling/packages/contribution-tools/workspace.mjs @@ -0,0 +1,72 @@ +import { execFileSync } from 'node:child_process'; +import { lstat, realpath } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { artifactPath, readBounded, sha256 } from './io.mjs'; +import { VerificationError, requireCondition as check } from './errors.mjs'; +import { verificationEnvironment } from './process-env.mjs'; + +export function git(root, args, maxBuffer = 4_000_000, input) { + try { + return execFileSync('git', ['--no-optional-locks', '-c', 'core.fsmonitor=false', ...args], { + cwd: root, maxBuffer, input, env: verificationEnvironment(), stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], + }); + } catch { throw new VerificationError('git_state_unavailable', true); } +} + +export function resolveCommit(root, ref) { + check(typeof ref === 'string' && ref.length <= 160 && /^[a-zA-Z0-9][a-zA-Z0-9_./~-]*$/.test(ref) + && !/[\r\n]/.test(ref), 'invalid_base_ref'); + const sha = git(root, ['rev-parse', '--verify', '--end-of-options', ref + '^{commit}']).toString().trim(); + check(/^[a-f0-9]{40}$/.test(sha), 'invalid_source_commit'); + return sha; +} + +function paths(bytes) { + const result = bytes.toString('utf8').split('\0').filter(Boolean); + check(result.length <= 8192, 'workspace_path_limit'); + for (const path of result) artifactPath(path); + return result; +} + +export async function inspectWorkspace(root, baseRef) { + const repositoryRoot = resolve(root); + check(git(repositoryRoot, ['rev-parse', '--show-prefix']).toString().trim() === '', 'run_from_repository_root'); + const base = resolveCommit(repositoryRoot, baseRef), head = resolveCommit(repositoryRoot, 'HEAD'); + const workspaceId = sha256(await realpath(repositoryRoot)); + // rev-parse returns HEAD for detached checkouts. Do not expose local paths. + const branch = git(repositoryRoot, ['rev-parse', '--abbrev-ref', 'HEAD']).toString().trim(); + const tracked = paths(git(repositoryRoot, ['ls-files', '-z'])); + const untracked = paths(git(repositoryRoot, ['ls-files', '--others', '--exclude-standard', '-z'])); + const baseFiles = paths(git(repositoryRoot, ['ls-tree', '-rz', '--name-only', base])); + const changes = new Set([ + ...paths(git(repositoryRoot, ['diff', '--no-ext-diff', '--no-textconv', '--no-renames', '--name-only', '-z', base, '--'])), + ...paths(git(repositoryRoot, ['diff', '--cached', '--no-ext-diff', '--no-textconv', '--no-renames', '--name-only', '-z', base, '--'])), + ...untracked, + ]); + const flags = git(repositoryRoot, ['ls-files', '-v', '-z']).toString().split('\0').filter(Boolean); + check(flags.every(line => line.startsWith('H ')), 'unsupported_index_flags'); + check(!tracked.some(path => path.startsWith('.freedom/')), 'context_artifacts_must_not_be_tracked'); + const index = git(repositoryRoot, ['ls-files', '--stage', '-z']); + const changed = [...changes].sort(), fileStates = []; + for (const path of changed) { + check(!path.split('/').some(part => part === '.env' || part.startsWith('.env.') && part !== '.env.example'), 'secret_path_changed'); + try { + await lstat(resolve(repositoryRoot, path)); + fileStates.push([path, sha256(await readBounded(repositoryRoot, path))]); + } catch (error) { + if (error.code === 'ENOENT') fileStates.push([path, 'deleted']); + else throw error; + } + } + return { root: repositoryRoot, workspace_id: workspaceId, branch, base_commit: base, head_commit: head, changed_paths: changed, + tracked_paths: tracked, candidate_paths: [...new Set([...tracked, ...untracked])].sort(), base_paths: baseFiles, + workspace_sha256: sha256(JSON.stringify({ workspaceId, branch, base, head, index: sha256(index), files: fileStates })) }; +} + +export function readRevisionFile(workspace, path) { + artifactPath(path); + check(workspace.base_paths.includes(path), 'baseline_file_missing'); + const entry = git(workspace.root, ['ls-tree', workspace.base_commit, '--', path]).toString(); + check(entry.startsWith('100644 blob ') || entry.startsWith('100755 blob '), 'baseline_file_not_regular'); + return git(workspace.root, ['show', `${workspace.base_commit}:${path}`], 2_000_000); +} From 3fbe600869b78904c7b9f99322914523ebc341c4 Mon Sep 17 00:00:00 2001 From: Ted H Date: Thu, 15 Oct 2026 10:05:47 -0400 Subject: [PATCH 2/2] fix: refresh canonical contribution tooling and local context artifacts --- contracts.lock.json | 2 +- .../packages/contribution-tools/context.mjs | 7 ++++++- .../packages/contribution-tools/suite-runner.mjs | 8 ++++++-- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/contracts.lock.json b/contracts.lock.json index 1a111f3..08f1aa7 100644 --- a/contracts.lock.json +++ b/contracts.lock.json @@ -1,7 +1,7 @@ { "format": "freedom.contract-pin/v1", "source_repository": "FreeTWAI/freedom-platform", - "source_commit": "1b1c3c111311659a64ab83fb4ea5683089b10560", + "source_commit": "e09fe06f3393c64e04afd6475dd6c427b3dab127", "bundle_path": "contracts/preview/v1", "protocol": "freedom.preview/v1", "protocol_sha256": "41378c3b723f739cefdf8c53a82238b1e5d69cc13cdbf63b33a80d8080c807b2", diff --git a/vendor/freedom-tooling/packages/contribution-tools/context.mjs b/vendor/freedom-tooling/packages/contribution-tools/context.mjs index bb04bc3..6b6dc0a 100644 --- a/vendor/freedom-tooling/packages/contribution-tools/context.mjs +++ b/vendor/freedom-tooling/packages/contribution-tools/context.mjs @@ -129,7 +129,12 @@ async function collectContext({ repositoryRoot, baseRef = 'origin/main', request const pkg = parseJson(await readBounded(workspace.root, 'package.json')); // Reviewed existing scoped consumer names; this labels local context, never // authenticates a remote repository or grants publisher trust. - const scopedNames = { '@freetwai/agent-kit': 'freedom-agent-kit', '@freetwai/freedom-storefront': 'freedom-storefront' }; + const scopedNames = { + '@freetwai/agent-kit': 'freedom-agent-kit', + '@freetwai/freedom-storefront': 'freedom-storefront', + '@freetwai/freedom-growth-automation': 'freedom-growth-automation', + '@freetwai/freedom-skill-registry': 'freedom-skill-registry', + }; const name = Object.hasOwn(scopedNames, pkg.name) ? scopedNames[pkg.name] : pkg.name; check(typeof name === 'string' && /^freedom-[a-z-]+$/.test(name) && !/[\r\n]/.test(name), 'repository_identity_required'); repository = 'FreeTWAI/' + name; diff --git a/vendor/freedom-tooling/packages/contribution-tools/suite-runner.mjs b/vendor/freedom-tooling/packages/contribution-tools/suite-runner.mjs index 71f6f13..e18c47d 100644 --- a/vendor/freedom-tooling/packages/contribution-tools/suite-runner.mjs +++ b/vendor/freedom-tooling/packages/contribution-tools/suite-runner.mjs @@ -466,8 +466,12 @@ function partitionCheck(value, code) { if (!value) throw Error(code); } export async function runtimeSourceManifest(root) { const git = spawnSync('git', ['rev-parse', '--verify', 'HEAD'], { cwd: root, env: verificationEnvironment(), encoding: 'utf8', timeout: 5000, maxBuffer: 4096 }); const candidate_commit = git.stdout?.trim(); - const clean = spawnSync('git', ['diff', '--quiet', 'HEAD', '--'], {cwd:root,env:verificationEnvironment(),timeout:5000,maxBuffer:4096}); - partitionCheck(clean.status === 0, 'runtime_source_changed'); + // Untracked source can be imported by a committed test without appearing in + // its manifest. Only ignored artifacts may remain outside the candidate. + const clean = spawnSync('git', ['--no-optional-locks', '-c', 'core.fsmonitor=false', 'status', + '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=none'], + {cwd:root,env:verificationEnvironment(),timeout:5000,maxBuffer:4096}); + partitionCheck(clean.status === 0 && !clean.error && clean.stdout?.length === 0, 'runtime_source_changed'); partitionCheck(git.status === 0 && /^[a-f0-9]{40}$/.test(candidate_commit), 'runtime_candidate_unavailable'); const files = await suiteFiles(root, 'runtime.full'); const full_source_manifest = [];