Token导航 LogoToken导航

Agent Skill · 待分类

twelve-factor(十二因数)

twelve-factor 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

twelve-factor 是待分类类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为权限未标注;许可证信息还不明确,第三方扫描已通过,按安装量在待分类类的 11,209 个 Skill 里排第 8,103。

总安装 321周安装 13GitHub Stars 643下载 101核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:twelve-factor(十二因数)
来源仓库:https://github.com/citypaul/.dotfiles
仓库路径:skills/twelve-factor
安装命令:
npx skills add https://github.com/citypaul/.dotfiles --skill twelve-factor
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/citypaul/.dotfiles --skill twelve-factor

这个 Skill 是做什么的

这个 Skill 的分类还没最终确定,用法以来源仓库的说明为准。

用于处理 GitHub 仓库、Issue 和 Pull Request 协作信息。适合在 Codex、Claude、Cursor、Gemini CLI 中整理代码变更和协作事项。可结合来源仓库和原始 README 核验具体用法。

安装命令:npx skills add https://github.com/citypaul/.dotfiles --skill twelve-factor 安装前建议确认权限范围和是否会触发文件读写操作。

来源仓库内路径:skills/twelve-factor

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/citypaul/.dotfiles --skill twelve-factor;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    权限没有明确标注,第一次使用时只给一个无关紧要的任务,观察它到底读了哪些文件和网络。

常见问题

6 条

twelve-factor 怎么安装?

在终端执行 npx skills add https://github.com/citypaul/.dotfiles --skill twelve-factor。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

twelve-factor 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

twelve-factor 需要什么权限?

权限级别没有明确标注。第一次使用时建议只给无关紧要的任务,观察它实际读写了哪些内容。

twelve-factor 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

twelve-factor 用的人多吗?

公开数据是累计安装 321 次,近一周安装 13 次,下载 101 次,GitHub 643 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

twelve-factor 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理待分类类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

待分类类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
infsh-cli

infsh CLI · Codex、Claude

4,374,576382权限未标注未明确未收录
ai-video-generation

AI 视频生成 · Codex、Claude

4,313,376382调用外部服务未明确有提醒
lark-openapi-explorer

云雀 OpenAPI 浏览器 · Codex、Claude

2,064,1209,011需要联网未明确有提醒
lark-workflow-standup-report

Lark 工作流程站立报告 · Codex、Claude

2,041,6328,978需要联网未明确通过
use-my-browser

使用我的浏览器 · Codex、Claude

1,848,49140操作浏览器未明确未通过
twelve-factor

十二因数 · 本页

321643权限未标注未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

name
twelve-factor
description
12-Factor App patterns for deployable applications. Use when configuring environment variables, connecting to backing services, structuring application startup/shutdown, or handling graceful shutdown and process signals. Applies to any deployed application (services, APIs, frontends, workers). Server-specific factors (port binding, concurrency, disposability) apply only to backend services.

Twelve-Factor App Patterns

Core factors (config, dependencies, backing services, logs) apply to any deployed application — services, frontends, workers, and CLI tools. Server-specific factors (port binding, concurrency, disposability) apply only to backend services that run as long-lived processes.

Based on 12factor.net. All 12 factors are covered below. Factors that primarily affect code (config, dependencies, backing services, stateless processes, disposability, logging, concurrency) get full treatment with code examples. Factors that are primarily operational (codebase, build/release/run) get brief guidance on the code-level implications.

See the typescript-strict skill for schema-first patterns at trust boundaries. See the testing skill for how to TDD these patterns — config validation, shutdown behavior, and backing service integration are all testable through behavior-driven tests.

When to Apply

  • Greenfield projects: All 12-factor rules are mandatory. Structure the application to follow every applicable factor from the start.
  • Brownfield projects: Aim to follow as many factors as possible. Adopt incrementally in this priority order:

1. Config (Factor III) — add env var validation without restructuring 2. Logs (Factor XI) — switch to structured stdout logging 3. Disposability (Factor IX) — add graceful shutdown handlers 4. Backing services (Factor IV) — abstract connections behind config URLs 5. Stateless processes (Factor VI) — migrate in-memory state to backing services

Codebase (Factor I)

One codebase tracked in revision control, many deploys. Each deployable service has its own codebase. Shared code between services is extracted into libraries managed via the package manager, not copy-pasted.

In a monorepo, each service should have its own entry point, its own deploy pipeline, and its own set of backing service connections. A single repo is fine as long as each service deploys independently.

Config (Factor III)

Store all configuration in environment variables. Never hardcode URLs, credentials, or per-environment values.

Validate config at startup with a schema. Fail fast if config is invalid:

import { z } from 'zod';

const ConfigSchema = z.object({
  PORT: z.coerce.number().default(3000),
  DATABASE_URL: z.string().url(),
  REDIS_URL: z.string().url(),
  API_URL: z.string().url(),
  LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
  API_KEY: z.string().min(1),
  SENTRY_DSN: z.string().url().optional(),
  ALLOWED_ORIGINS: z.string().default('').transform((s) => s === '' ? [] : s.split(',')),
});

type Config = z.infer<typeof ConfigSchema>;

export const createConfig = (env: Record<string, string | undefined> = process.env): Config => {
  const result = ConfigSchema.safeParse(env);
  if (!result.success) {
    console.error(JSON.stringify({ level: 'error', message: 'Invalid config', errors: result.error.flatten() }));
    process.exit(1);
  }
  return result.data;
};

Inject config via options objects — never import process.env deep in the call tree:

const UserSchema = z.object({ id: z.string(), name: z.string(), email: z.string().email() });
type User = z.infer<typeof UserSchema>;

export const createUserService = ({ config }: { config: Pick<Config, 'API_URL'> }) => ({
  async getUser(id: string): Promise<User> {
    const response = await fetch(`${config.API_URL}/users/${id}`);
    if (!response.ok) throw new Error(`Failed to fetch user: ${response.status}`);
    const data: unknown = await response.json();
    return UserSchema.parse(data);
  },
});

Provide .env.example as documentation (never .env with real values):

PORT=3000
DATABASE_URL=postgres://localhost:5432/myapp
REDIS_URL=redis://localhost:6379
API_URL=http://localhost:8080
LOG_LEVEL=info
API_KEY=your-api-key-here
SENTRY_DSN=
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173

Config Anti-Patterns

const DB_HOST = 'prod-db.internal.example.com';

if (process.env.NODE_ENV === 'production') {
  connectTo('prod-db');
} else {
  connectTo('localhost');
}

const config = require(`./config.${process.env.NODE_ENV}.json`);

Why these are wrong: Config that varies by deploy belongs in env vars, not code. Environment-name branching creates combinatorial explosion and breaks dev/prod parity.

Dependencies (Factor II)

Explicitly declare all dependencies. Never rely on implicit system-wide packages.

import which from 'which';

export const checkSystemDependencies = (required: readonly string[]) => {
  const missing = required.filter((cmd) => !which.sync(cmd, { nothrow: true }));
  if (missing.length > 0) {
    throw new Error(`Missing required system dependencies: ${missing.join(', ')}`);
  }
};

Rules:

  • Every dependency in package.json (or equivalent manifest)
  • Lockfile (package-lock.json, pnpm-lock.yaml) committed to repo
  • Dependencies are isolated — the app does not leak from or depend on the system environment (use node_modules, not global installs)
  • No exec('imagemagick ...') or child_process calls to assumed system tools
  • If a system tool is required, document it explicitly and check for it at startup

Backing Services (Factor IV)

Treat every backing service (database, cache, queue, email, storage) as an attached resource identified by a URL in config.

export const createApp = ({ config }: { config: Pick<Config, 'DATABASE_URL' | 'REDIS_URL'> }) => {
  const db = createDbPool({ connectionString: config.DATABASE_URL });
  const cache = createRedisClient({ url: config.REDIS_URL });

  return {
    db,
    cache,
    async shutdown() {
      await Promise.all([db.end(), cache.quit()]);
    },
  } as const;
};

The code makes no distinction between local and third-party services. Swapping a local PostgreSQL for a managed cloud database requires only a config change, never a code change.

For projects using hexagonal architecture, backing services map naturally to ports (interfaces) and adapters (implementations). See the hexagonal-architecture skill.

Stateless Processes (Factor VI)

Execute the app as stateless, share-nothing processes. Any data that must persist lives in a backing service.

export const createSessionStore = <T>({
  redis,
  schema,
}: {
  redis: RedisClient;
  schema: z.ZodType<T>;
}) => ({
  async get(sessionId: string): Promise<T | undefined> {
    const data = await redis.get(`session:${sessionId}`);
    return data ? schema.parse(JSON.parse(data)) : undefined;
  },
  async set({ sessionId, data, ttlSeconds }: { sessionId: string; data: T; ttlSeconds: number }) {
    await redis.setex(`session:${sessionId}`, ttlSeconds, JSON.stringify(data));
  },
});

Stateless Anti-Patterns

const sessions = new Map<string, UserSession>();

app.post('/upload', (req, res) => {
  fs.writeFileSync(`/tmp/uploads/${req.file.name}`, req.file.data);
});

let requestCount = 0;
app.use(() => { requestCount++; });

setInterval(() => sendReport(), 60_000);

Why these are wrong: In-memory state is lost on restart and invisible to other process instances. Local filesystem state cannot be shared across processes. In-process schedulers run in only one instance. Use backing services (Redis, S3, database) and external schedulers instead.

See the functional skill for immutable data patterns that naturally support statelessness.

Concurrency (Factor VIII)

Scale out via the process model. Design the app so work can be divided across process types.

// web.ts — handles HTTP requests
const config = createConfig();
const app = createApp({ config });
await startServer({ app, config });

// worker.ts — processes background jobs from a queue backed by Redis
const config = createConfig();
const queue = createQueueConsumer({ url: config.REDIS_URL });
await queue.process('email', sendEmail);
await queue.process('report', generateReport);

Rules:

  • Separate entry points for each process type (web, worker, scheduler)
  • HTTP handlers dispatch background work to a queue, never process it inline
  • Each process type scales independently
  • Use a Procfile or equivalent to define process types
web: node dist/web.js
worker: node dist/worker.js

Disposability (Factor IX)

Maximize robustness with fast startup and graceful shutdown.

Health Check Endpoints

export const createHealthRoutes = ({ db }: { db: DbPool }) => ({
  '/health': async () => ({ status: 'ok' }),
  '/ready': async () => {
    await db.query('SELECT 1');
    return { status: 'ready' };
  },
});

Graceful Shutdown

const SHUTDOWN_TIMEOUT_MS = 30_000;

export const startServer = async ({ app, config }: { app: App; config: Pick<Config, 'PORT'> }) => {
  const server = app.listen(config.PORT);

  const shutdown = async (signal: 'SIGTERM' | 'SIGINT') => {
    const forceExit = setTimeout(() => process.exit(1), SHUTDOWN_TIMEOUT_MS);

    try {
      await new Promise<void>((resolve) => server.close(() => resolve()));
      await app.shutdown();
      clearTimeout(forceExit);
      process.exit(0);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : String(err);
      const stack = err instanceof Error ? err.stack : undefined;
      console.error(JSON.stringify({ level: 'error', message: 'Shutdown error', signal, error: message, stack }));
      process.exit(1);
    }
  };

  process.on('SIGTERM', () => shutdown('SIGTERM'));
  process.on('SIGINT', () => shutdown('SIGINT'));

  return server;
};

Rules:

  • Handle SIGTERM and SIGINT for graceful shutdown
  • Set a drain timeout — force exit if shutdown hangs
  • Await server.close() to drain in-flight connections
  • Close database pools, Redis connections, queue consumers
  • Exit with non-zero code on shutdown failure
  • Keep startup fast — defer heavy initialization to first request if needed
  • Design background jobs to be reentrant/idempotent so interrupted work can be safely retried
  • Provide /health and /ready endpoints for orchestrator probes

Logs (Factor XI)

Treat logs as event streams. Write structured output to stdout. Never route or store logs from within the app.

For internet-facing servers, RFC 6302 (BCP 162) specifies minimum logging requirements: source and destination addresses and ports, timestamps (preferably UTC), and transport protocol. These should be captured at the server/framework level in addition to application-level structured logging.

Semantic Requirements

Regardless of which logging library or implementation a project uses, all loggers must satisfy these properties:

  • Structured output — logs are machine-parseable (JSON preferred), not free-form strings
  • stdout/stderr only — the app never writes to log files, never configures file transports
  • Standard levels — at minimum: debug, info, warn, error — configurable via environment
  • Contextual data — logs accept structured metadata (key-value pairs), not just message strings
  • Timestamp included — every log entry includes an ISO 8601 timestamp
  • Request correlation — include a requestId or trace ID to correlate logs across a single request

Projects may use any logging library (pino, winston with console transport, OpenTelemetry, custom) as long as these semantics are met. The specific interface may vary per project. If an existing logger is missing levels or structured data support, it should be adapted to meet these requirements.

Example (illustrative — adapt to project conventions)

const LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 } as const;

export const createLogger = ({ config }: { config: Pick<Config, 'LOG_LEVEL'> }) => {
  const shouldLog = (level: keyof typeof LOG_LEVELS) =>
    LOG_LEVELS[level] >= LOG_LEVELS[config.LOG_LEVEL];

  const log = (level: keyof typeof LOG_LEVELS, message: string, data?: Record<string, unknown>) => {
    if (!shouldLog(level)) return;
    const output = JSON.stringify({ timestamp: new Date().toISOString(), level, message, context: data });
    (level === 'error' ? console.error : console.log)(output);
  };

  return {
    debug: (message: string, data?: Record<string, unknown>) => log('debug', message, data),
    info: (message: string, data?: Record<string, unknown>) => log('info', message, data),
    warn: (message: string, data?: Record<string, unknown>) => log('warn', message, data),
    error: (message: string, data?: Record<string, unknown>) => log('error', message, data),
  };
};

Logging Anti-Patterns

import fs from 'fs';
fs.appendFileSync('/var/log/app.log', message);

import winston from 'winston';
const logger = winston.createLogger({
  transports: [new winston.transports.File({ filename: 'error.log' })],
});

console.log(`User ${userId} logged in`);

Why these are wrong: File transports mean the app is routing its own logs. Unstructured string interpolation produces logs that cannot be parsed or queried. The execution environment (container orchestrator, PaaS) captures stdout and routes it to the appropriate destination.

Build, Release, Run (Factor V)

Strictly separate build and run stages. Config is injected at release/run time, never baked into the build.

Code-level implications:

  • No environment-specific build outputs — the same build artifact deploys to every environment
  • Config comes from env vars at runtime, not from compile-time substitution
  • Releases are immutable — code changes require a new build, not runtime patching

Port Binding (Factor VII)

The app is self-contained and exports its service by binding to a port.

const server = app.listen(config.PORT, () => {
  logger.info('Server started', { port: config.PORT });
});

Do not rely on runtime injection of a web server (e.g., a separate Apache/Nginx process serving your app). The app includes its own HTTP server library as a dependency.

Dev/Prod Parity (Factor X)

Keep development and production as similar as possible. Use the same type of backing services in all environments.

Rules:

  • If production uses PostgreSQL, develop against PostgreSQL (not SQLite)
  • If production uses Redis, develop against Redis (not in-memory maps)
  • Use containers (Docker Compose) to run backing services locally
  • Config schema validation (Factor III) catches mismatches at startup

Admin Processes (Factor XII)

Run admin tasks (migrations, data fixes, console sessions) as one-off processes using the same codebase and config.

const config = createConfig();
const db = createDbPool({ connectionString: config.DATABASE_URL });
try {
  await runMigrations(db);
} finally {
  await db.end();
}

Admin scripts live in the repo alongside application code (e.g. scripts/migrate.ts). They are not separate tools or ad-hoc shell commands. Admin processes run in an identical environment to the app — same release, same config, same dependencies.

Testing 12-Factor Patterns

12-factor patterns are testable through behavior-driven tests:

  • Config: test that createConfig throws on missing required vars and returns correct defaults
  • Disposability: test that shutdown closes all connections (inject test doubles for db/cache)
  • Backing services: test that services work with any backing service URL (inject via config)
  • Statelessness: test that request handlers do not depend on prior request state

Config injection via options objects makes all of these patterns naturally testable without mocking process.env or global state. See the testing skill for factory patterns and behavior-driven test examples.

Checklist

  • [ ] One codebase per deployable service; shared code extracted as libraries
  • [ ] Same build artifact deploys to every environment (no env-specific builds)
  • [ ] All config comes from environment variables, validated at startup with a schema
  • [ ] Startup fails fast with a clear error message if config is invalid
  • [ ] .env.example documents required variables (no real credentials)
  • [ ] All dependencies explicitly declared in manifest with lockfile committed
  • [ ] Backing services connected via config URLs, swappable without code changes
  • [ ] No in-memory session state, no local filesystem state between requests
  • [ ] Separate entry points for web and worker process types
  • [ ] SIGTERM/SIGINT handlers with drain timeout for graceful shutdown
  • [ ] Database pools and connections closed on shutdown
  • [ ] /health and /ready endpoints for orchestrator probes
  • [ ] Logs written as structured JSON to stdout, no file transports
  • [ ] Logs include request correlation IDs
  • [ ] App binds to a port from config, includes its own HTTP server
  • [ ] Same backing service types used in development and production
  • [ ] Admin scripts live in the repo and use the same config/dependencies

平台分布

Codex

35.94%
按下载量换算36

Claude

29.42%
按下载量换算30

Cursor

17.65%
按下载量换算18

Gemini CLI

9.18%
按下载量换算9

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

权限未标注

当前来源未能明确判断权限范围,默认进入异常复核队列。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills