示例
bare-os 3.9.3: cpuUsage
已验证示例 — npm bare-os 3.9.3: cpuUsage. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: package manifest specifies bare-os name, version 3.9.3, addon…
sha256:4f820bb12d76e21a0ff66c52820a749eef847d3007489f17b76195ffc6a5f9d6
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 1
- 构建过它的签名密钥
- 1
声明的环境
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 npm 10
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-08-27 |
案例
HOW- 目标
- verify cpuUsage in pkg:npm/bare-os@3.9.3
- 符号
-
- cpuUsage
- 环境
- node 22.23.2
- 创建时间
- 2026-08-27T09:38:03Z
契约
- package manifest specifies bare-os name, version 3.9.3, addon configuration, and Bare engine requirement
- declares CpuUsage interface and cpuUsage function accepting optional previous CpuUsage in index.d.ts
- native binding implements bare_os_cpu_usage querying process CPU times with uv_getrusage
- cpuUsage() returns current process user and system CPU times in microseconds
- cpuUsage(previous) calculates diff between current and previous user and system CPU times
文件
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
源代码
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: verify cpuUsage in pkg:npm/bare-os@3.9.3
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/bare-os@3.9.3
Demonstrate these symbols/APIs:
- cpuUsage
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:eade65e92af16f45bd5f43c3f37b5c20aea68bb715f36870bc0347dd92537621","contract":["package manifest specifies bare-os name, version 3.9.3, addon configuration, and Bare engine requirement","declares CpuUsage interface and cpuUsage function accepting optional previous CpuUsage in index.d.ts","native binding implements bare_os_cpu_usage querying process CPU times with uv_getrusage","cpuUsage() returns current process user and system CPU times in microseconds","cpuUsage(previous) calculates diff between current and previous user and system CPU times"],"goal":"verify cpuUsage in pkg:npm/bare-os@3.9.3","kind":"HOW","packages":["pkg:npm/bare-os@3.9.3"],"schemaVersion":1,"symbols":["cpuUsage"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/bare-os@3.9.3"],"schemaVersion":1,"subject":"pkg:npm/bare-os@3.9.3","symbols":["cpuUsage"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-bare-os-cpu-usage",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-bare-os-cpu-usage",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"bare-os": "3.9.3"
}
},
"node_modules/bare-os": {
"version": "3.9.3",
"resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.9.3.tgz",
"integrity": "sha512-fF4Q7QsyKVF5Rj0qvI8BgUNjqzC2JvQlpTaPLjVJVxYVUX5Zr9un+y3w1HmA4nNKdFmRBT8z/WmrjvXzXVerKQ==",
"license": "Apache-2.0",
"engines": {
"bare": ">=1.14.0"
}
}
}
}
{
"name": "sample-bare-os-cpu-usage",
"version": "1.0.0",
"private": true,
"type": "module",
"license": "MIT-0",
"dependencies": {
"bare-os": "3.9.3"
}
}
{
"schemaVersion": 1,
"goal": "verify cpuUsage in pkg:npm/bare-os@3.9.3",
"kind": "HOW",
"packages": [
"pkg:npm/bare-os@3.9.3"
],
"symbols": [
"cpuUsage"
]
}
import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
/**
* Validates that an object conforms to the bare-os CpuUsage interface.
*
* @param {unknown} usage - The CPU usage object to validate.
* @returns {boolean} True if usage contains finite non-negative numeric user and system properties.
* @throws {TypeError} If usage is not an object or user/system are not finite numbers.
*/
export function validateCpuUsage(usage) {
if (usage === null || typeof usage !== 'object') {
throw new TypeError(`CpuUsage must be an object. Received ${typeof usage}`);
}
const { user, system } = usage;
if (typeof user !== 'number' || !Number.isFinite(user) || user < 0) {
throw new TypeError(`Field "user" must be a non-negative finite number. Received ${typeof user} (${user})`);
}
if (typeof system !== 'number' || !Number.isFinite(system) || system < 0) {
throw new TypeError(`Field "system" must be a non-negative finite number. Received ${typeof system} (${system})`);
}
return true;
}
/**
* Calculates CPU time delta between two CpuUsage snapshots.
*
* @param {import('bare-os').CpuUsage} previous - Previous CPU usage snapshot.
* @param {import('bare-os').CpuUsage} current - Current CPU usage snapshot.
* @returns {{ user: number, system: number, total: number }}
*/
export function calculateCpuUsageDelta(previous, current) {
validateCpuUsage(previous);
validateCpuUsage(current);
const userDelta = Math.max(0, current.user - previous.user);
const systemDelta = Math.max(0, current.system - previous.system);
return {
user: userDelta,
system: systemDelta,
total: userDelta + systemDelta,
};
}
/**
* Formats CPU usage in microseconds to milliseconds and seconds for human-readable reporting.
*
* @param {import('bare-os').CpuUsage} usage - CPU usage in microseconds.
* @returns {{ userMs: number, systemMs: number, userSec: number, systemSec: number }}
*/
export function formatCpuUsage(usage) {
validateCpuUsage(usage);
return {
userMs: usage.user / 1000,
systemMs: usage.system / 1000,
userSec: usage.user / 1e6,
systemSec: usage.system / 1e6,
};
}
/**
* Reads bare-os package manifest.
*
* @returns {object} The parsed package.json manifest.
*/
export function getBareOsPackage() {
const pkgPath = require.resolve('bare-os/package');
return JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
}
/**
* Reads bare-os package source files and declarations.
*
* @returns {{ pkgDir: string, indexJs: string, indexDts: string, bindingC: string }}
*/
export function getBareOsSource() {
const pkgDir = path.dirname(require.resolve('bare-os/package'));
const indexJs = fs.readFileSync(path.join(pkgDir, 'index.js'), 'utf8');
const indexDts = fs.readFileSync(path.join(pkgDir, 'index.d.ts'), 'utf8');
const bindingC = fs.readFileSync(path.join(pkgDir, 'binding.c'), 'utf8');
return { pkgDir, indexJs, indexDts, bindingC };
}
/**
* Inspects bare-os cpuUsage API contract across JS wrapper, TS declarations, and C bindings.
*
* @returns {{ hasJsExport: boolean, hasJsDeltaCalculation: boolean, hasTsDeclaration: boolean, hasTsInterface: boolean, hasBindingRegistration: boolean, hasBindingFunction: boolean }}
*/
export function inspectCpuUsageApiContract() {
const { indexJs, indexDts, bindingC } = getBareOsSource();
const hasJsExport = indexJs.includes('exports.cpuUsage = function cpuUsage(previous)');
const hasJsDeltaCalculation =
indexJs.includes('user: current.user - previous.user') &&
indexJs.includes('system: current.system - previous.system');
const hasTsDeclaration = indexDts.includes('export function cpuUsage(previous?: CpuUsage): CpuUsage');
const hasTsInterface = indexDts.includes('export interface CpuUsage {\n user: number\n system: number\n}');
const hasBindingRegistration = bindingC.includes('V("cpuUsage", bare_os_cpu_usage)');
const hasBindingFunction =
bindingC.includes('bare_os_cpu_usage(js_env_t *env, js_callback_info_t *info)') &&
bindingC.includes('uv_getrusage(&usage)');
return {
hasJsExport,
hasJsDeltaCalculation,
hasTsDeclaration,
hasTsInterface,
hasBindingRegistration,
hasBindingFunction,
};
}
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import path from 'node:path';
import {
validateCpuUsage,
calculateCpuUsageDelta,
formatCpuUsage,
getBareOsPackage,
getBareOsSource,
inspectCpuUsageApiContract,
} from '../src/index.mjs';
const require = createRequire(import.meta.url);
// 1. Verify bare-os package manifest and metadata
const pkg = getBareOsPackage();
assert.equal(pkg.name, 'bare-os', 'Package name must be bare-os');
assert.equal(pkg.version, '3.9.3', 'Package version must be 3.9.3');
assert.equal(pkg.license, 'Apache-2.0', 'Package license must be Apache-2.0');
assert.equal(pkg.addon, true, 'Package must be marked as addon');
assert.equal(pkg.engines?.bare, '>=1.14.0', 'Package must specify Bare engine requirement >=1.14.0');
assert.ok(pkg.exports, 'Package must define exports map');
assert.equal(pkg.exports['.'].types, './index.d.ts', 'Root export must specify index.d.ts types');
assert.equal(pkg.exports['.'].default, './index.js', 'Root export must specify index.js default');
// 2. Verify TypeScript type definitions for cpuUsage
const { pkgDir, indexJs, indexDts, bindingC } = getBareOsSource();
assert.ok(
indexDts.includes('export interface CpuUsage {\n user: number\n system: number\n}'),
'index.d.ts must declare CpuUsage interface with user and system properties'
);
assert.ok(
indexDts.includes('export function cpuUsage(previous?: CpuUsage): CpuUsage'),
'index.d.ts must declare cpuUsage function accepting optional previous CpuUsage'
);
// 3. Verify JavaScript export and implementation in index.js
assert.ok(
indexJs.includes('exports.cpuUsage = function cpuUsage(previous)'),
'index.js must export cpuUsage function'
);
assert.ok(
indexJs.includes('const current = binding.cpuUsage()'),
'cpuUsage must call binding.cpuUsage()'
);
assert.ok(
indexJs.includes('user: current.user - previous.user'),
'cpuUsage must compute user CPU time difference when previous is provided'
);
assert.ok(
indexJs.includes('system: current.system - previous.system'),
'cpuUsage must compute system CPU time difference when previous is provided'
);
// 4. Verify C native binding implementation for cpuUsage
assert.ok(
bindingC.includes('bare_os_cpu_usage(js_env_t *env, js_callback_info_t *info)'),
'binding.c must implement bare_os_cpu_usage'
);
assert.ok(
bindingC.includes('uv_getrusage(&usage)'),
'binding.c must query process resource usage via uv_getrusage'
);
assert.ok(
bindingC.includes('V("cpuUsage", bare_os_cpu_usage)'),
'binding.c must register bare_os_cpu_usage under cpuUsage'
);
// 5. Verify contract inspection helper
const inspection = inspectCpuUsageApiContract();
assert.equal(inspection.hasJsExport, true, 'inspectCpuUsageApiContract reports JS export present');
assert.equal(inspection.hasJsDeltaCalculation, true, 'inspectCpuUsageApiContract reports JS delta calculation present');
assert.equal(inspection.hasTsDeclaration, true, 'inspectCpuUsageApiContract reports TS declaration present');
assert.equal(inspection.hasTsInterface, true, 'inspectCpuUsageApiContract reports TS interface present');
assert.equal(inspection.hasBindingRegistration, true, 'inspectCpuUsageApiContract reports binding registration present');
assert.equal(inspection.hasBindingFunction, true, 'inspectCpuUsageApiContract reports binding function present');
// 6. Verify runtime behavior of cpuUsage() and cpuUsage(previous)
const bindingPath = path.join(pkgDir, 'binding.js');
let simulatedProcessUsage = { user: 250000, system: 80000 };
require.cache[bindingPath] = {
id: bindingPath,
filename: bindingPath,
loaded: true,
exports: {
platform: process.platform,
arch: process.arch,
cpuUsage: () => ({ ...simulatedProcessUsage }),
},
};
const bareOs = require('bare-os');
assert.equal(typeof bareOs.cpuUsage, 'function', 'bare-os must export cpuUsage function');
// Test 6a: Calling cpuUsage() without previous usage returns current process CPU times
const usage1 = bareOs.cpuUsage();
assert.equal(typeof usage1, 'object', 'cpuUsage must return an object');
assert.equal(usage1.user, 250000, 'usage.user must match simulated user time in microseconds');
assert.equal(usage1.system, 80000, 'usage.system must match simulated system time in microseconds');
assert.equal(validateCpuUsage(usage1), true, 'usage1 must pass CpuUsage validation');
// Test 6b: Calling cpuUsage(previous) computes delta
simulatedProcessUsage = { user: 320000, system: 110000 };
const usageDiff = bareOs.cpuUsage(usage1);
assert.equal(usageDiff.user, 70000, 'diff.user must be 320000 - 250000 = 70000');
assert.equal(usageDiff.system, 30000, 'diff.system must be 110000 - 80000 = 30000');
assert.equal(validateCpuUsage(usageDiff), true, 'usageDiff must pass CpuUsage validation');
// Test 6c: Calling cpuUsage with zero previous
const usageDiffZero = bareOs.cpuUsage({ user: 0, system: 0 });
assert.equal(usageDiffZero.user, 320000, 'diff against zero must equal current user time');
assert.equal(usageDiffZero.system, 110000, 'diff against zero must equal current system time');
// 7. Verify helper functions: delta calculation and formatting
const helperDelta = calculateCpuUsageDelta(usage1, simulatedProcessUsage);
assert.equal(helperDelta.user, 70000, 'helper user delta matches');
assert.equal(helperDelta.system, 30000, 'helper system delta matches');
assert.equal(helperDelta.total, 100000, 'helper total delta matches');
const formatted = formatCpuUsage(usage1);
assert.equal(formatted.userMs, 250, 'user time in ms must be 250');
assert.equal(formatted.systemMs, 80, 'system time in ms must be 80');
assert.equal(formatted.userSec, 0.25, 'user time in seconds must be 0.25');
assert.equal(formatted.systemSec, 0.08, 'system time in seconds must be 0.08');
// Verify validation errors on invalid inputs
assert.throws(() => validateCpuUsage(null), TypeError);
assert.throws(() => validateCpuUsage({ user: 'invalid', system: 10 }), TypeError);
assert.throws(() => validateCpuUsage({ user: 10, system: -5 }), TypeError);
assert.throws(() => validateCpuUsage({ user: 10 }), TypeError);
console.log('Contract verification finished successfully for bare-os cpuUsage.');
原始种子者
匿名