Compare commits

..

5 Commits

Author SHA1 Message Date
codex-bot 8c5d838944 Add infinite canvas workspace with local drafts and connected nodes 2026-10-29 19:50:59 +08:00
Zayden-Jung f490543853 Merge pull request 'Keep image retention policy checks on main only' (#18) from codex/retention-main-only into main
Wiki image retention checks / retention-policy (push) Has been cancelled
Reviewed-on: #18
2026-10-29 11:22:47 +00:00
codex-bot b94c1e43f1 Keep image retention checks on main updates only 2026-10-29 19:02:45 +08:00
Zayden-Jung 9a603cf87e Merge pull request 'Retain wiki rollback images and expire unused CI images' (#17) from codex/wiki-image-retention into main
Wiki image retention checks / retention-policy (push) Has been cancelled
waterfall-wiki CI and deployment / verify-and-deploy (push) Successful in 40m26s
Reviewed-on: #17
2026-10-29 10:48:15 +00:00
codex-bot dbc3ad8c69 Retain verified wiki releases and expire unused CI images
Wiki image retention checks / retention-policy (pull_request) Successful in 52s
2026-10-29 18:43:57 +08:00
11 changed files with 537 additions and 16 deletions
+9 -15
View File
@@ -8,6 +8,7 @@ on:
- 'Dockerfile' - 'Dockerfile'
- 'compose.yml' - 'compose.yml'
- 'scripts/deploy.sh' - 'scripts/deploy.sh'
- 'scripts/wiki-image-lifecycle.py'
- 'scripts/infra.sh' - 'scripts/infra.sh'
- 'scripts/auth-admin.sh' - 'scripts/auth-admin.sh'
- 'scripts/integration.sh' - 'scripts/integration.sh'
@@ -22,19 +23,12 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Validate configuration - name: Build, verify, deploy and retain wiki images
run: docker compose --env-file apps/waterfall-wiki/.env.example config --quiet
- name: Build and verify waterfall-wiki
run: docker build --target integration -t "waterfall-wiki-tests:${{ gitea.sha }}" .
- name: Verify retained character originals
run: docker run --rm --entrypoint node "waterfall-wiki-tests:${{ gitea.sha }}" --test tests/character-pack.test.mjs
- name: Build runtime
run: docker build --target runtime -t "waterfall-wiki:${{ gitea.sha }}" .
- name: Integration stack
env: env:
WATERFALL_WIKI_IMAGE: waterfall-wiki:${{ gitea.sha }} RELEASE_SHA: ${{ gitea.sha }}
WATERFALL_WIKI_TEST_IMAGE: waterfall-wiki-tests:${{ gitea.sha }} run: |
run: bash scripts/integration.sh if [ "$(id -u)" -eq 0 ]; then
- name: Deploy waterfall-wiki python3 scripts/wiki-image-lifecycle.py ci --sha "$RELEASE_SHA"
if: gitea.ref == 'refs/heads/main' && gitea.event_name == 'push' else
run: bash scripts/deploy.sh "${{ gitea.sha }}" sudo -n python3 scripts/wiki-image-lifecycle.py ci --sha "$RELEASE_SHA"
fi
@@ -0,0 +1,19 @@
name: Wiki image retention checks
on:
push:
branches: [main]
paths:
- 'scripts/wiki-image-lifecycle.py'
- 'tests/test_wiki_image_lifecycle.py'
- '.gitea/workflows/wiki-image-retention-checks.yml'
jobs:
retention-policy:
if: gitea.ref == 'refs/heads/main' && gitea.event_name == 'push'
runs-on: ces-control
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
- name: Check retention without building or accessing the Docker daemon
run: |
bash -n scripts/deploy.sh
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -p 'test_wiki_image_lifecycle.py' -v
+2
View File
@@ -1,4 +1,5 @@
FROM node:24-bookworm-slim AS base FROM node:24-bookworm-slim AS base
LABEL io.entroia.project="waterfall-wiki"
ENV NEXT_TELEMETRY_DISABLED=1 ENV NEXT_TELEMETRY_DISABLED=1
WORKDIR /app WORKDIR /app
RUN apt-get update \ RUN apt-get update \
@@ -6,6 +7,7 @@ RUN apt-get update \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
FROM base AS dependencies FROM base AS dependencies
LABEL io.entroia.wiki.build="true"
RUN corepack enable && corepack prepare pnpm@11.25.0 --activate RUN corepack enable && corepack prepare pnpm@11.25.0 --activate
COPY apps/waterfall-wiki/pnpm-lock.yaml ./ COPY apps/waterfall-wiki/pnpm-lock.yaml ./
COPY pnpm-workspace.yaml /tmp/monorepo-policy.yaml COPY pnpm-workspace.yaml /tmp/monorepo-policy.yaml
@@ -0,0 +1,4 @@
// Run against an already started Studio. BASE_URL is the origin, including port.
const {chromium}=require('playwright-core');
const assert=require('node:assert/strict');
(async()=>{const browser=await chromium.launch({channel:'chrome',headless:true});try{const page=await browser.newPage({viewport:{width:1440,height:1000}});const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto((process.env.BASE_URL||'http://localhost:3018')+'/studio/infinite_canvas');await page.getByRole('heading',{name:'无限画布 / Infinite canvas'}).waitFor();assert.equal(await page.locator('article').count(),3);await page.getByRole('button',{name:'添加笔记',exact:true}).click();assert.equal(await page.locator('article').count(),4);await page.getByLabel('节点名称').fill('Smoke note');await page.getByLabel('笔记内容').fill('A saved idea');await page.reload();await page.getByText('Smoke note',{exact:true}).first().waitFor();assert.equal(await page.locator('article').count(),4);await page.getByText('Smoke note',{exact:true}).first().click();await page.getByRole('button',{name:'删除节点',exact:true}).click();assert.equal(await page.locator('article').count(),3);await page.getByRole('button',{name:'撤销',exact:true}).click();assert.equal(await page.locator('article').count(),4);await page.getByRole('button',{name:'适应画布'}).click();const card=page.locator('article').last();const before=await card.getAttribute('style');const box=await card.locator('div').first().boundingBox();await page.mouse.move(box.x+70,box.y+20);await page.mouse.down();await page.mouse.move(box.x+120,box.y+45,{steps:5});await page.mouse.up();assert.notEqual(await card.getAttribute('style'),before);const download=page.waitForEvent('download');await page.getByRole('button',{name:'导出项目'}).click();assert.equal((await download).suggestedFilename(),'studio-canvas.json');if(process.env.SCREENSHOT_DIR)await page.screenshot({path:process.env.SCREENSHOT_DIR+'/canvas-desktop.png'});await page.setViewportSize({width:390,height:844});assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));if(process.env.SCREENSHOT_DIR)await page.screenshot({path:process.env.SCREENSHOT_DIR+'/canvas-mobile.png',fullPage:true});assert.deepEqual(errors,[]);console.log('Canvas browser smoke passed: create, edit, restore, delete, undo, fit, export, mobile.')}finally{await browser.close()}})().catch(e=>{console.error(e);process.exitCode=1});
@@ -0,0 +1,35 @@
import Head from 'next/head';
import {useEffect,useRef,useState} from 'react';
import {ArrowLeft,Plus,MousePointer2,Hand,ImagePlus,Type,Workflow,Undo2,Redo2,Minus,Maximize,Download,Upload,Trash2,Link2,Sparkles,ChevronRight} from 'lucide-react';
import s from '../../styles/infinite-canvas.module.css';
type Card={id:string;kind:'text'|'image'|'prompt';title:string;text:string;x:number;y:number;image?:string};
type Doc={version:1;cards:Card[];links:[string,string][]};
const initial:Doc={version:1,cards:[{id:'brief',kind:'text',title:'01 / 创意简报',text:'把日常,拍成一场电影。\n\n一段关于城市清晨的视觉散文。低饱和色彩、自然光与细腻颗粒,让每一帧都有呼吸感。',x:70,y:140},{id:'reference',kind:'image',title:'02 / 视觉参考',text:'晨光 · 建筑 · 胶片质感\n上传你的参考图片',x:460,y:80},{id:'shot',kind:'prompt',title:'03 / 镜头构思',text:'清晨,阳光穿过窗边的植物,落在安静的房间里。缓慢推进镜头,35mm 胶片,温暖柔和的光线。',x:850,y:160}],links:[['brief','reference'],['reference','shot']]};
const key='studio.infinite-canvas.v1';
function valid(v:unknown):v is Doc{const d=v as Doc;return !!d&&d.version===1&&Array.isArray(d.cards)&&d.cards.length<=80&&d.cards.every(c=>c&&typeof c.id==='string'&&c.id.length<100&&['text','image','prompt'].includes(c.kind)&&typeof c.title==='string'&&c.title.length<=200&&typeof c.text==='string'&&c.text.length<=10000&&Number.isFinite(c.x)&&Number.isFinite(c.y)&&Math.abs(c.x)<100000&&Math.abs(c.y)<100000&&(!c.image||(/^data:image\/(png|jpeg|webp);base64,/.test(c.image)&&c.image.length<3000000)))&&new Set(d.cards.map(c=>c.id)).size===d.cards.length&&Array.isArray(d.links)&&d.links.length<=200&&d.links.every(l=>Array.isArray(l)&&l.length===2&&l[0]!==l[1]&&l.every(id=>d.cards.some(c=>c.id===id)));}
export default function InfiniteCanvas(){
const [doc,setDoc]=useState<Doc>(initial),[selected,select]=useState('shot'),[zoom,setZoom]=useState(.8),[pan,setPan]=useState({x:0,y:0}),[tool,setTool]=useState('select'),[past,setPast]=useState<Doc[]>([]),[future,setFuture]=useState<Doc[]>([]),[status,setStatus]=useState('示例项目 · 尚未保存'),[ready,setReady]=useState(false),[email,setEmail]=useState(''),[link,setLink]=useState('');
const file=useRef<HTMLInputElement>(null),json=useRef<HTMLInputElement>(null),viewport=useRef<HTMLDivElement>(null),drag=useRef<{id:string;x:number;y:number;ox:number;oy:number;before:Doc}|null>(null);
const active=doc.cards.find(c=>c.id===selected);
useEffect(()=>{try{const raw=localStorage.getItem(key);if(raw){const d=JSON.parse(raw);if(valid(d)){setDoc(d);setStatus('已恢复本机草稿')}}}catch{setStatus('草稿读取失败,可导入 JSON 恢复')}setReady(true);fetch('/api/account/session').then(r=>r.ok?r.json():null).then(d=>setEmail(d?.user?.email||'')).catch(()=>{});},[]);
useEffect(()=>{if(!ready)return;try{localStorage.setItem(key,JSON.stringify(doc));setStatus('已保存到此浏览器')}catch{setStatus('本机空间不足,请导出项目备份')}},[doc,ready]);
function commit(next:Doc){setPast(p=>[...p.slice(-29),doc]);setFuture([]);setDoc(next)}
function add(kind:Card['kind'],image?:string){if(doc.cards.length>=80){setStatus('最多 80 个节点');return}const id=Array.from(crypto.getRandomValues(new Uint8Array(16)),b=>b.toString(16).padStart(2,'0')).join('');const rect=viewport.current?.getBoundingClientRect();commit({...doc,cards:[...doc.cards,{id,kind,title:kind==='text'?'灵感笔记':kind==='image'?'参考素材':'生成提示词',text:'',x:((rect?.width||700)/2-pan.x)/zoom-160,y:(160-pan.y)/zoom,image}]});select(id)}
function change(field:'title'|'text',value:string){commit({...doc,cards:doc.cards.map(c=>c.id===selected?{...c,[field]:value}:c)})}
function undo(){if(!past.length)return;setFuture(f=>[doc,...f]);setDoc(past[past.length-1]);setPast(p=>p.slice(0,-1))}
function redo(){if(!future.length)return;setPast(p=>[...p,doc]);setDoc(future[0]);setFuture(f=>f.slice(1))}
function fit(){const el=viewport.current;if(!el||!doc.cards.length)return;const minX=Math.min(...doc.cards.map(c=>c.x)),minY=Math.min(...doc.cards.map(c=>c.y));const w=Math.max(...doc.cards.map(c=>c.x+320))-minX,h=Math.max(...doc.cards.map(c=>c.y+350))-minY;const z=Math.max(.2,Math.min(1,(el.clientWidth-80)/w,(el.clientHeight-100)/h));setZoom(z);setPan({x:(el.clientWidth-w*z)/2-minX*z,y:(el.clientHeight-h*z)/2-minY*z})}
function exportDoc(){const url=URL.createObjectURL(new Blob([JSON.stringify(doc,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='studio-canvas.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)}
return <main className={s.app}><Head><title>无限画布 · Studio</title><meta name="description" content="在无限画布上组织灵感、参考素材与镜头提示词"/></Head>
<header className={s.header}><a href="/studio" className={s.back} aria-label="返回 Studio"><ArrowLeft size={18}/></a><a href="/studio" className={s.brand}>STUDIO<span>✳</span></a><i/><span className={s.crumb}>工作空间 <ChevronRight size={13}/></span><strong>未命名的灵感宇宙</strong><span className={s.badge}>本机草稿</span><div className={s.spacer}/><a href="/account">{email||'登录账户'}</a><button className={s.export} onClick={exportDoc}><Download size={15}/>导出项目</button></header>
<div className={s.workspace}><nav className={s.rail} aria-label="画布工具"><button title="选择工具" aria-label="选择工具" aria-pressed={tool==='select'} onClick={()=>setTool('select')}><MousePointer2/></button><button title="移动画布" aria-label="移动画布" aria-pressed={tool==='hand'} onClick={()=>setTool('hand')}><Hand/></button><hr/><button title="添加笔记" aria-label="添加笔记" onClick={()=>add('text')}><Type/></button><button title="上传图片" aria-label="上传图片" onClick={()=>file.current?.click()}><ImagePlus/></button><button title="添加提示词" aria-label="添加提示词" onClick={()=>add('prompt')}><Sparkles/></button><button title="导入项目" aria-label="导入项目" onClick={()=>json.current?.click()}><Upload/></button><div className={s.spacer}/><span>∞</span></nav>
<section className={s.canvasArea}><div className={s.canvasTitle}><span className={s.eyebrow}>YOUR IDEAS, CONNECTED</span><h1>无限画布<span> / Infinite canvas</span></h1><p>从一个灵感,连接所有可能。</p></div>
<div className={s.viewport} ref={viewport} onWheel={e=>{if(e.ctrlKey||e.metaKey){setZoom(z=>Math.max(.2,Math.min(2,z-e.deltaY*.002)))}else setPan(p=>({x:p.x-e.deltaX,y:p.y-e.deltaY}))}} onPointerDown={e=>{if(e.target===e.currentTarget||tool==='hand'){e.currentTarget.setPointerCapture(e.pointerId);drag.current={id:'pan',x:e.clientX,y:e.clientY,ox:pan.x,oy:pan.y,before:doc}}}} onPointerMove={e=>{const d=drag.current;if(!d)return;if(d.id==='pan')setPan({x:d.ox+e.clientX-d.x,y:d.oy+e.clientY-d.y});else setDoc({...d.before,cards:d.before.cards.map(c=>c.id===d.id?{...c,x:d.ox+(e.clientX-d.x)/zoom,y:d.oy+(e.clientY-d.y)/zoom}:c)})}} onPointerUp={()=>{const d=drag.current;if(d&&d.id!=='pan'){setPast(p=>[...p.slice(-29),d.before]);setFuture([])}drag.current=null}} onPointerCancel={()=>{drag.current=null}}>
<div className={s.world} style={{transform:`translate(${pan.x}px,${pan.y}px) scale(${zoom})`}}><svg className={s.wires} aria-hidden="true">{doc.links.map(([a,b])=>{const from=doc.cards.find(c=>c.id===a),to=doc.cards.find(c=>c.id===b);if(!from||!to)return null;return <path key={a+b} d={`M ${from.x+320} ${from.y+150} C ${from.x+365} ${from.y+150},${to.x-45} ${to.y+150},${to.x} ${to.y+150}`}/>})}</svg>
{doc.cards.map(c=><article key={c.id} className={`${s.card} ${selected===c.id?s.selected:''}`} style={{left:c.x,top:c.y}} onClick={()=>select(c.id)}><div className={s.cardHead} onPointerDown={e=>{if(tool==='hand')return;e.stopPropagation();viewport.current?.setPointerCapture(e.pointerId);select(c.id);drag.current={id:c.id,x:e.clientX,y:e.clientY,ox:c.x,oy:c.y,before:doc}}}><span>{c.kind==='text'?<Type size={15}/>:c.kind==='image'?<ImagePlus size={15}/>:<Sparkles size={15}/>} {c.title}</span><span>⠿</span></div>{c.kind==='image'?<div className={s.image} onClick={()=>{select(c.id);file.current?.click()}}>{c.image?<img src={c.image} alt={c.title}/>:<><div className={s.landscape}><span>REF.</span><b>光的形状</b><small>LIGHT / SPACE / EMOTION</small></div><span className={s.sample}>示例占位 · 点击上传参考图</span></>}</div>:<div className={s.cardBody}><span className={s.nodeType}>{c.kind==='prompt'?'PROMPT / 提示词':'NOTE / 灵感笔记'}</span><p>{c.text||'选择节点,在右侧写下你的想法。'}</p></div>}{c.kind==='prompt'&&<div className={s.disconnected}>○ 模型服务未接入 · 仅编辑提示词</div>}<footer>{c.kind==='image'?'视觉素材':c.kind==='prompt'?'镜头设计':'创作起点'}<span className={s.port}/></footer></article>)}
</div></div><div className={s.canvasBottom}><span role="status">● {status}</span><div className={s.controls}><button aria-label="撤销" disabled={!past.length} onClick={undo}><Undo2 size={16}/></button><button aria-label="重做" disabled={!future.length} onClick={redo}><Redo2 size={16}/></button><i/><button aria-label="缩小" onClick={()=>setZoom(z=>Math.max(.2,z-.1))}><Minus size={16}/></button><span>{Math.round(zoom*100)}%</span><button aria-label="放大" onClick={()=>setZoom(z=>Math.min(2,z+.1))}><Plus size={16}/></button><button aria-label="适应画布" onClick={fit}><Maximize size={16}/></button></div></div></section>
<aside className={s.inspector}><div className={s.panelHeading}><Workflow size={17}/><strong>节点属性</strong><span>{doc.cards.length} 个节点</span></div>{active?<><span className={s.eyebrow}>INSPECTOR</span><h2>{active.kind==='prompt'?'把想法描述清楚':active.kind==='image'?'让参考彼此连接':'记录灵感的起点'}</h2><label>节点名称<input maxLength={200} value={active.title} onChange={e=>change('title',e.target.value)}/></label><label>{active.kind==='prompt'?'画面描述':'笔记内容'}<textarea maxLength={10000} value={active.text} onChange={e=>change('text',e.target.value)} placeholder="写下你的创作想法…"/></label>{active.kind==='image'&&<button className={s.wide} onClick={()=>file.current?.click()}><ImagePlus size={16}/>选择参考图片</button>}{active.kind==='prompt'&&<div className={s.notice}><Sparkles size={18}/><strong>为下一次创作做好准备</strong><p>提示词可保存在项目中。当前没有连接模型服务,暂不支持 AI 图片或视频生成。</p></div>}<label>连接到<select value={link} onChange={e=>setLink(e.target.value)}><option value="">选择目标节点</option>{doc.cards.filter(c=>c.id!==selected).map(c=><option key={c.id} value={c.id}>{c.title}</option>)}</select></label><button className={s.wide} disabled={!link} onClick={()=>{if(!doc.links.some(l=>l[0]===selected&&l[1]===link))commit({...doc,links:[...doc.links,[selected,link]]});setLink('')}}><Link2 size={16}/>连接节点</button>{doc.links.filter(l=>l.includes(selected)).map(([a,b])=><button className={s.connection} key={a+b} onClick={()=>commit({...doc,links:doc.links.filter(l=>l[0]!==a||l[1]!==b)})}>↗ {doc.cards.find(c=>c.id===(a===selected?b:a))?.title} <span>断开 ×</span></button>)}<button className={s.delete} onClick={()=>{commit({...doc,cards:doc.cards.filter(c=>c.id!==selected),links:doc.links.filter(l=>!l.includes(selected))});select('')}}><Trash2 size={15}/>删除节点</button></>:<><h2>给灵感留一点空间</h2><p>选择画布中的节点来编辑,或从左侧添加新内容。</p><button className={s.wide} onClick={()=>add('text')}><Plus size={16}/>添加笔记</button></>}<div className={s.help}>拖动节点标题移动节点<br/>滚轮平移 · Ctrl / ⌘ + 滚轮缩放<br/>草稿仅存于当前浏览器,请及时导出。</div></aside></div>
<input hidden ref={file} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const f=e.target.files?.[0];e.target.value='';if(!f)return;if(!['image/png','image/jpeg','image/webp'].includes(f.type)||f.size>2000000){setStatus('请选择 2MB 以内的 PNG、JPEG 或 WebP');return}const reader=new FileReader();reader.onload=()=>{const image=String(reader.result);if(active?.kind==='image')commit({...doc,cards:doc.cards.map(c=>c.id===selected?{...c,image}:c)});else add('image',image)};reader.readAsDataURL(f)}}/>
<input hidden ref={json} type="file" accept="application/json,.json" onChange={async e=>{const f=e.target.files?.[0];e.target.value='';if(!f)return;try{if(f.size>15000000)throw Error();const d=JSON.parse(await f.text());if(!valid(d))throw Error();commit(d);select(d.cards[0]?.id||'');setPan({x:0,y:0});setStatus('项目已导入')}catch{setStatus('无法导入:项目格式错误或文件过大')}}}/>
</main>;
}
File diff suppressed because one or more lines are too long
+23
View File
@@ -0,0 +1,23 @@
# Infinite canvas plan
Scope: only /studio/infinite_canvas, its CSS module, browser interaction checks. Based on main f490543 in isolated worktree. No homepage, graphic, shared authentication or deployment changes.
## Research before implementation
- Baseline server screenshot captured 2026-10-29: existing server requires dynamic-code authentication before route access. Do not bypass it.
- Internet image search: AI infinite canvas ComfyUI RunningHub interface; reviewed workflow canvas and media card arrangements. No unlicensed product screenshots copied into product.
- https://jimeng.jianying.com — prompt-driven creation, image references, canvas.
- https://klingai.com — attempted primary source; robots denied access. No unsupported detailed claims.
- https://hailuoai.video — reference input and media-first exploration.
- https://www.liblib.art and https://www.liblib.tv — Liblib/LibTV reference targets; client-rendered content limits source inspection.
- https://docs.comfy.org/interface/overview — explicit node workflow and workspace regions.
- https://www.runninghub.cn — canvas-oriented creation and reusable workflows.
- https://github.com/bergside/awesome-design-skills — reference catalogue; apply deliberate typography, spacing, accessible controls and consistent hierarchy, without installing external skills.
## Design and behavior
Dark graphite creation desk with warm lime accent. Narrow left tool rail, large dotted canvas, editable right inspector and floating zoom controls. Start with a clearly labelled sample storyboard: brief → reference → shot plan. Native drag and zoom, selection, editable text/prompt cards, image upload, visible links, add/delete, undo/redo, fit view. Persist bounded browser-local drafts and export/import portable JSON. Images remain local. No simulated generation; generation cards explicitly say model service is not connected. Account link uses existing /account and GET /api/account/session contract.
## Validation
Local TypeScript and existing tests; local build explicitly authorized for this task. Browser checks for desktop/mobile, creation, drag, undo, reload, JSON export and disconnected AI notice. Clean owned screenshots, build directories and temporary dependency links before delivery. Push branch and open PR against main; no merge or deployment.
## Results
TypeScript passed; existing 10 tests passed. Project-local Next CLI webpack build passed. Default Turbopack cannot resolve dependencies outside isolated worktree; webpack standalone tracing warns about the temporary dependency symlinks, so deployment artifact completeness is not claimed. Browser smoke passed on desktop and mobile. No deployment performed.
+61
View File
@@ -0,0 +1,61 @@
# Wiki image retention on ces-control
Wiki CI builds one runtime image and one integration-test image per revision. Web
and worker share the runtime image. Tags can share an image ID; displayed image
sizes include shared layers and must not be added to estimate reclaimed space.
## Policy
- Retain the current release and the two preceding distinct successful releases.
`scripts/deploy.sh` records success in `/opt/prompt/successful-releases` only after
all existing deployment checks pass. The ledger is replaced atomically.
- The first three successful deployments bootstrap this ledger. Until then,
retain all runtime images, since old release directories alone do not prove
successful deployment. No historical success is guessed from directory dates.
- Keep the test images corresponding to retained runtime releases: Studio verification
and publishing scripts use them as operational tools. Remove other successful
job test images unless a container still references them or their image ID has
another protected tag.
- Retain other runtime/test/build images for at least 72 hours for debugging.
Expired runtime images outside the three retained releases become eligible.
- Remove expired project/build-labelled exited containers only with no mounts.
Remove expired project-labelled untagged image intermediates where Docker allows.
- Always preserve images referenced by any running, created or stopped container.
This can deliberately keep more than three runtime versions.
- Preserve foreign tags/digests, unlabelled intermediates and legacy
`prompt:*` images. Legacy images require a separate reviewed migration list.
- Never use global prune, force image/container removal, or volume deletion.
Database, object storage, backups and release directories are outside this tool.
## Preview and apply
Run from the reviewed checkout on the confirmed ces-control host:
```sh
sudo python3 scripts/wiki-image-lifecycle.py preview
sudo python3 scripts/wiki-image-lifecycle.py apply
```
The default command is preview. Both print keep/delete reasons, image IDs and tags.
Preview reads Docker metadata and may create empty lock files, but never changes
Docker state. Both commands refuse to proceed if the current release metadata or
success ledger is invalid. They also refuse while another cooperating build or
deployment holds the locks.
The workflow invokes `ci --sha <full-sha>` once on main. A single exclusive
`/opt/prompt/.image-lifecycle.lock` spans builds, integration, deployment and
cleanup. Cleanup also takes the existing `.deploy.lock`, protecting manual
`deploy.sh` invocations. Use this CI entrypoint for manual builds too; raw Docker
commands and old workflow revisions do not participate in this lock. Allow old
wiki jobs to finish before first enabling apply. Other projects are out of scope.
Cleanup runs after both success and failure. Errors are reported without changing
the original build/deployment status or rolling back healthy services. Referenced
images and Docker refusal are reported and retained. Failed CI does not record a
successful release and does not immediately remove that job's test image.
After the user merges to main, policy checks run Python tests and shell syntax
checks on ces-control without building or touching Docker. The full application
build/integration/deployment also runs only on main updates, subject to its path
filters. PR events and manual dispatch do not trigger either workflow. No local
builds are needed.
+5 -1
View File
@@ -17,7 +17,7 @@ test "$(git -c safe.directory="$PWD" rev-parse HEAD)" = "$RELEASE_SHA"
LATEST_MAIN=$(git -c safe.directory="$PWD" ls-remote origin refs/heads/main | cut -f1) LATEST_MAIN=$(git -c safe.directory="$PWD" ls-remote origin refs/heads/main | cut -f1)
if [ "$LATEST_MAIN" != "$RELEASE_SHA" ]; then if [ "$LATEST_MAIN" != "$RELEASE_SHA" ]; then
git -c safe.directory="$PWD" fetch origin main git -c safe.directory="$PWD" fetch origin main
if ! git -c safe.directory="$PWD" diff --quiet "$RELEASE_SHA" origin/main -- apps/waterfall-wiki Dockerfile compose.yml scripts/deploy.sh scripts/infra.sh scripts/integration.sh scripts/auth-admin.sh .gitea/workflows/waterfall-wiki.yml pnpm-workspace.yaml; then if ! git -c safe.directory="$PWD" diff --quiet "$RELEASE_SHA" origin/main -- apps/waterfall-wiki Dockerfile compose.yml scripts/deploy.sh scripts/wiki-image-lifecycle.py scripts/infra.sh scripts/integration.sh scripts/auth-admin.sh .gitea/workflows/waterfall-wiki.yml pnpm-workspace.yaml; then
echo 'Skipping deployment: Wiki has a newer commit'; exit 0 echo 'Skipping deployment: Wiki has a newer commit'; exit 0
fi fi
fi fi
@@ -135,6 +135,10 @@ if command -v systemctl >/dev/null; then
if systemctl is-active --quiet prompt.service || systemctl is-active --quiet prompt-worker.service; then echo 'Legacy host service is unexpectedly running'; false; fi if systemctl is-active --quiet prompt.service || systemctl is-active --quiet prompt-worker.service; then echo 'Legacy host service is unexpectedly running'; false; fi
fi fi
echo "Full Docker deployment verified: web+worker+postgres+objects port=$PORT release=$RELEASE_SHA" echo "Full Docker deployment verified: web+worker+postgres+objects port=$PORT release=$RELEASE_SHA"
# Register only after every deployment check succeeded; ledger failure retains old images.
if ! python3 scripts/wiki-image-lifecycle.py record-success --sha "$RELEASE_SHA"; then
echo "Warning: successful-release ledger update failed; runtime cleanup stays conservative" >&2
fi
# Read-only network diagnostics: a private address alone is not a public entrypoint. # Read-only network diagnostics: a private address alone is not a public entrypoint.
echo "Host: $(hostname)" echo "Host: $(hostname)"
hostname -I || true hostname -I || true
+210
View File
@@ -0,0 +1,210 @@
#!/usr/bin/env python3
"""Wiki-only image retention. Preview is the default; never prune the daemon."""
import argparse
from contextlib import contextmanager
from datetime import datetime, timezone
import fcntl
import json
import os
from pathlib import Path
import re
import subprocess
import sys
SHA = re.compile(r"^[0-9a-f]{40}$")
PROJECT = "io.entroia.project"
ROOT = Path("/opt/prompt")
TTL = 3 * 86400
def run(args, **kwargs):
return subprocess.run(args, check=True, text=True, **kwargs)
def output(args):
return run(args, stdout=subprocess.PIPE).stdout
def timestamp(value):
return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
@contextmanager
def lock(path):
# Fail rather than wait behind a build and consume the workflow timeout.
with open(path, "a") as handle:
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise RuntimeError(f"Busy: {path}; no cleanup performed")
yield
def history(root):
path = root / "successful-releases"
values = path.read_text().splitlines() if path.exists() else []
if any(not SHA.fullmatch(value) for value in values):
raise RuntimeError("Invalid successful-releases ledger; refusing cleanup")
return list(dict.fromkeys(values))
def current_sha(root):
path = root / "current" / "release.env"
if not path.is_file():
raise RuntimeError("Missing current/release.env; refusing cleanup")
values = [line.split("=", 1)[1] for line in path.read_text().splitlines()
if line.startswith("RELEASE_SHA=")]
if len(values) != 1 or not SHA.fullmatch(values[0]):
raise RuntimeError("Invalid current release SHA; refusing cleanup")
return values[0]
def record(root, sha):
if current_sha(root) != sha:
raise RuntimeError("Only the verified current release can be recorded")
values = [sha] + [item for item in history(root) if item != sha]
temp = root / ".successful-releases.next"
temp.write_text("\n".join(values) + "\n")
os.replace(temp, root / "successful-releases")
def decision(image, referenced, retained, ready, now, completed_test=None):
"""Return keep/delete with a reviewable reason; all tags must be in scope."""
tags = image.get("RepoTags") or []
labels = image.get("Config", {}).get("Labels") or {}
if image["Id"] in referenced:
return "keep", "container reference (including stopped containers)"
parsed = []
for tag in tags:
repo, _, sha = tag.rpartition(":")
if repo not in ("waterfall-wiki", "waterfall-wiki-tests") or not SHA.fullmatch(sha):
return "keep", "foreign or non-release tag"
parsed.append((repo, sha))
if any(digest.partition("@")[0] not in ("waterfall-wiki", "waterfall-wiki-tests")
for digest in image.get("RepoDigests") or []):
return "keep", "foreign registry digest retained conservatively"
if any(sha in retained for _, sha in parsed):
return "keep", "retained release or its operational test image"
if any(repo == "waterfall-wiki" for repo, _ in parsed) and not ready:
return "keep", "bootstrap: fewer than three successful releases recorded"
if parsed and all(repo == "waterfall-wiki-tests" and sha == completed_test
for repo, sha in parsed):
return "delete", "this job's tests completed successfully"
if now - timestamp(image["Created"]) < TTL:
return "keep", "three-day build/debug window"
if parsed:
return "delete", "expired project release/test image"
if labels.get(PROJECT) == "waterfall-wiki":
return "delete", "expired project-labelled intermediate image"
return "keep", "unlabelled image: ownership unknown"
def container_expired(container, now):
labels = container.get("Config", {}).get("Labels") or {}
return (labels.get(PROJECT) == "waterfall-wiki"
and labels.get("io.entroia.wiki.build") == "true"
and container["State"]["Status"] == "exited"
and not container.get("Mounts")
and now - timestamp(container["Created"]) >= TTL)
def containers():
ids = output(["docker", "ps", "-aq"]).split()
return json.loads(output(["docker", "inspect", *ids])) if ids else []
def image_ids():
# Include labelled build intermediates, but never enumerate foreign image metadata.
ids = set()
for name in ("waterfall-wiki", "waterfall-wiki-tests"):
ids.update(output(["docker", "image", "ls", "-aq", "--no-trunc", name]).split())
ids.update(output(["docker", "image", "ls", "-aq", "--no-trunc", "--filter",
f"label={PROJECT}=waterfall-wiki"]).split())
return sorted(ids)
def cleanup(root, apply=False, completed_test=None):
# CI holds the image lock throughout build, integration, deployment and cleanup.
# Taking the deployment lock also protects direct/manual deployment invocations.
with lock(root / ".deploy.lock"):
successes = history(root)
retained = set(successes[:3]) | {current_sha(root)}
ready = len(successes) >= 3
now = datetime.now(timezone.utc).timestamp()
print("APPLY" if apply else "PREVIEW", "retained releases:", sorted(retained), flush=True)
for container in containers():
if container_expired(container, now):
print("delete-container", container["Id"], "expired, project-labelled, no mounts", flush=True)
if apply:
fresh = json.loads(output(["docker", "inspect", container["Id"]]))[0]
if container_expired(fresh, now):
run(["docker", "container", "rm", container["Id"]])
referenced = {item["Image"] for item in containers()}
ids = image_ids()
images = json.loads(output(["docker", "image", "inspect", *ids])) if ids else []
for image in images:
image_id = image["Id"]
action, reason = decision(image, referenced, retained, ready, now, completed_test)
print(action, image_id, json.dumps(image.get("RepoTags") or []), reason, flush=True)
if apply and action == "delete":
# Recheck references and tags immediately before removal. No -f or volume operations.
fresh = json.loads(output(["docker", "image", "inspect", image_id]))[0]
refs = {item["Image"] for item in containers()}
if decision(fresh, refs, retained, ready, now, completed_test)[0] != "delete":
continue
for target in fresh.get("RepoTags") or [image_id]:
result = subprocess.run(["docker", "image", "rm", target], text=True)
if result.returncode:
print("skip", target, "Docker refused removal; retained", flush=True)
break
def ci(root, sha):
"""One lock spans the whole job; failed build images get a three-day grace."""
env = dict(os.environ, WATERFALL_WIKI_IMAGE=f"waterfall-wiki:{sha}",
WATERFALL_WIKI_TEST_IMAGE=f"waterfall-wiki-tests:{sha}")
code = 1
try:
run(["docker", "compose", "--env-file", "apps/waterfall-wiki/.env.example", "config", "--quiet"])
run(["docker", "build", "--target", "integration", "-t", env["WATERFALL_WIKI_TEST_IMAGE"], "."])
run(["docker", "run", "--rm", "--entrypoint", "node", env["WATERFALL_WIKI_TEST_IMAGE"],
"--test", "tests/character-pack.test.mjs"])
run(["docker", "build", "--target", "runtime", "-t", env["WATERFALL_WIKI_IMAGE"], "."])
run(["bash", "scripts/integration.sh"], env=env)
run(["bash", "scripts/deploy.sh", sha], env=env)
code = 0
except subprocess.CalledProcessError as error:
code = error.returncode
finally:
try:
cleanup(root, apply=True, completed_test=sha if code == 0 else None)
except Exception as error:
# Housekeeping must not mask the build/deployment result or roll back healthy services.
print(f"Cleanup failed; images retained for later retry: {error}", file=sys.stderr)
return code
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", nargs="?", choices=("preview", "apply", "record-success", "ci"), default="preview")
parser.add_argument("--sha")
args = parser.parse_args()
if args.command in ("ci", "record-success") and not SHA.fullmatch(args.sha or ""):
parser.error("--sha must be a full lowercase Git SHA")
if args.command == "record-success":
# Called at the end of deploy.sh while its deployment lock is still held.
record(ROOT, args.sha)
return 0
with lock(ROOT / ".image-lifecycle.lock"):
if args.command == "ci":
return ci(ROOT, args.sha)
cleanup(ROOT, apply=args.command == "apply")
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except Exception as error:
print(str(error), file=sys.stderr)
sys.exit(1)
+168
View File
@@ -0,0 +1,168 @@
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location(
"lifecycle", Path(__file__).resolve().parents[1] / "scripts/wiki-image-lifecycle.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
NOW = m.timestamp("2026-10-29T12:00:00Z")
A, B, C, D = [letter * 40 for letter in "abcd"]
def image(tags=None, labels=None, created="2026-10-20T12:00:00Z"):
return {"Id": "sha256:example", "RepoTags": tags or [], "RepoDigests": [],
"Created": created, "Config": {"Labels": labels or {}}}
class RetentionTests(unittest.TestCase):
def decide(self, item, referenced=(), retained=(A, B, C), ready=True, completed=None):
return m.decision(item, set(referenced), set(retained), ready, NOW, completed)[0]
def test_current_and_two_previous_survive(self):
for sha in (A, B, C):
self.assertEqual(self.decide(image([f"waterfall-wiki:{sha}"])), "keep")
self.assertEqual(self.decide(image([f"waterfall-wiki:{D}"])), "delete")
def test_retained_release_test_images_remain_available_to_studio_tools(self):
for sha in (A, B, C):
self.assertEqual(self.decide(image([f"waterfall-wiki-tests:{sha}"]), completed=sha), "keep")
def test_stopped_container_reference_survives(self):
self.assertEqual(self.decide(image([f"waterfall-wiki:{D}"]),
referenced=("sha256:example",)), "keep")
def test_all_tags_of_shared_retained_image_survive(self):
self.assertEqual(self.decide(image([f"waterfall-wiki:{A}", f"waterfall-wiki:{D}"])), "keep")
def test_foreign_and_legacy_tags_survive(self):
for tag in (f"prompt:{D}", f"other-app:{D}", "waterfall-wiki:local"):
self.assertEqual(self.decide(image([tag, f"waterfall-wiki:{D}"])), "keep")
def test_bootstrap_never_deletes_runtime(self):
self.assertEqual(self.decide(image([f"waterfall-wiki:{D}"]), ready=False), "keep")
def test_failed_job_debug_window(self):
for repo in ("waterfall-wiki", "waterfall-wiki-tests"):
self.assertEqual(self.decide(image([f"{repo}:{D}"], created="2026-10-28T12:00:00Z")), "keep")
def test_successful_job_test_image_can_be_removed_immediately(self):
item = image([f"waterfall-wiki-tests:{D}"], created="2026-10-29T11:00:00Z")
self.assertEqual(self.decide(item, completed=D), "delete")
self.assertEqual(self.decide(item), "keep")
def test_expired_tests_dont_require_release_ledger(self):
self.assertEqual(self.decide(image([f"waterfall-wiki-tests:{D}"]), ready=False), "delete")
def test_only_owned_dangling_images_are_candidates(self):
self.assertEqual(self.decide(image()), "keep")
self.assertEqual(self.decide(image(labels={m.PROJECT: "other"})), "keep")
self.assertEqual(self.decide(image(labels={m.PROJECT: "waterfall-wiki"})), "delete")
def test_registry_digest_is_conservatively_retained(self):
item = image([f"waterfall-wiki:{D}"])
item["RepoDigests"] = ["registry.example/wiki@sha256:abc"]
self.assertEqual(self.decide(item), "keep")
def test_local_containerd_digest_does_not_disable_expiry(self):
item = image([f"waterfall-wiki-tests:{D}"])
item["RepoDigests"] = ["waterfall-wiki-tests@sha256:example"]
self.assertEqual(self.decide(item), "delete")
def test_failed_container_requires_ownership_age_and_no_mounts(self):
item = {"Config": {"Labels": {m.PROJECT: "waterfall-wiki", "io.entroia.wiki.build": "true"}},
"State": {"Status": "exited"}, "Mounts": [], "Created": "2026-10-20T12:00:00Z"}
self.assertTrue(m.container_expired(item, NOW))
for key, value in (("Mounts", [{"Type": "volume"}]),
("State", {"Status": "running"}),
("Created", "2026-10-29T11:00:00Z"),
("Config", {"Labels": {}})):
self.assertFalse(m.container_expired(dict(item, **{key: value}), NOW))
def test_failed_ci_preserves_original_exit_and_debug_images(self):
error = m.subprocess.CalledProcessError(7, ["docker", "build"])
with patch.object(m, "run", side_effect=error), patch.object(m, "cleanup") as cleanup:
self.assertEqual(m.ci(Path("/unused"), D), 7)
cleanup.assert_called_once_with(Path("/unused"), apply=True, completed_test=None)
def test_cleanup_error_does_not_turn_failed_ci_into_success(self):
error = m.subprocess.CalledProcessError(7, ["docker", "build"])
with patch.object(m, "run", side_effect=error), \
patch.object(m, "cleanup", side_effect=RuntimeError("busy")):
self.assertEqual(m.ci(Path("/unused"), D), 7)
def test_success_only_cleans_tests_after_deployment(self):
events = []
with patch.object(m, "run", side_effect=lambda args, **kw: events.append(args)), \
patch.object(m, "cleanup", side_effect=lambda *a, **kw: events.append(kw)):
self.assertEqual(m.ci(Path("/unused"), D), 0)
self.assertEqual(events[-2], ["bash", "scripts/deploy.sh", D])
self.assertEqual(events[-1], {"apply": True, "completed_test": D})
def test_busy_lock_refuses_work(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "lock"
with m.lock(path):
with self.assertRaisesRegex(RuntimeError, "Busy"):
with m.lock(path):
self.fail("Second holder entered lock")
def test_only_current_verified_sha_can_be_recorded_and_order_is_unique(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "current").mkdir()
(root / "current/release.env").write_text(f"RELEASE_SHA={A}\n")
(root / "successful-releases").write_text(f"{B}\n{A}\n{C}\n")
m.record(root, A)
self.assertEqual(m.history(root), [A, B, C])
with self.assertRaises(RuntimeError):
m.record(root, D)
(root / "successful-releases").write_text("bad-ledger\n")
with self.assertRaises(RuntimeError):
m.history(root)
def test_preview_has_no_docker_mutations(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
item = image([f"waterfall-wiki-tests:{D}"])
with patch.object(m, "history", return_value=[A, B, C]), \
patch.object(m, "current_sha", return_value=A), \
patch.object(m, "containers", return_value=[]), \
patch.object(m, "image_ids", return_value=[item["Id"]]), \
patch.object(m, "output", return_value=json.dumps([item])), \
patch.object(m, "run") as run, patch.object(m.subprocess, "run") as mutate:
m.cleanup(root)
run.assert_not_called()
mutate.assert_not_called()
def test_cleanup_rechecks_container_reference_before_removal(self):
with tempfile.TemporaryDirectory() as directory:
item = image([f"waterfall-wiki-tests:{D}"])
with patch.object(m, "history", return_value=[A, B, C]), \
patch.object(m, "current_sha", return_value=A), \
patch.object(m, "containers", side_effect=[[], [], [{"Image": item["Id"]}]]), \
patch.object(m, "image_ids", return_value=[item["Id"]]), \
patch.object(m, "output", return_value=json.dumps([item])), \
patch.object(m.subprocess, "run") as mutate:
m.cleanup(Path(directory), apply=True)
mutate.assert_not_called()
def test_cleanup_never_forces_or_removes_volumes(self):
with tempfile.TemporaryDirectory() as directory:
item = image([f"waterfall-wiki-tests:{D}"])
with patch.object(m, "history", return_value=[A, B, C]), \
patch.object(m, "current_sha", return_value=A), \
patch.object(m, "containers", return_value=[]), \
patch.object(m, "image_ids", return_value=[item["Id"]]), \
patch.object(m, "output", return_value=json.dumps([item])), \
patch.object(m.subprocess, "run") as mutate:
mutate.return_value.returncode = 0
m.cleanup(Path(directory), apply=True)
mutate.assert_called_once_with(["docker", "image", "rm", f"waterfall-wiki-tests:{D}"], text=True)
if __name__ == "__main__":
unittest.main()