poad 2.74.0 → 2.75.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.74.0",
3
+ "version": "2.75.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.5.0",
6
6
  "main": "index.js",
package/project/cli.js CHANGED
@@ -71,8 +71,8 @@ module.exports = {
71
71
  types: 'TypeScript types of the database for createClient<Database>() (out=src/types/database.ts, role=authenticated|anon|service_role)',
72
72
  env: 'TypeScript types of the public variables (PUBLIC_*) for poad.env (out=src/types/poad-env.ts)',
73
73
  },
74
- migrate: 'Apply pending migrations of poad/migrations and named queries of poad/queries (poad start does it too)',
75
- migration: 'Database migrations: migration new <name>, migration list',
74
+ migrate: 'Apply pending migrations of poad/migrations and named queries of poad/queries (poad start does it too); migrate list | pull | renumber <version> | --pending [--env <name>]: the folder against poad.io',
75
+ migration: 'Database migrations: migration new <name>, migration list [--env <name>], migration pull [--env <name>] (the migrations of poad.io missing from the folder)',
76
76
  functions: 'Functions of the project (JS/TS, served on /functions/v1/<name>): new, list, types',
77
77
  function: 'Alias of poad functions',
78
78
  flows: 'Flows of the project (automations in poad/flows/<name>.json, engine 0.18.0+, needs Valkey): new, list, run, runs, show, cancel; --env <name> for poad.io',
package/project/deploy.js CHANGED
@@ -20,7 +20,38 @@ const FAILED = ['failed', 'error', 'cancelled', 'canceled', 'refused'];
20
20
 
21
21
  const names = (list) => (Array.isArray(list) ? list : []).map((m) => (typeof m === 'string' ? m : m && (m.name || m.version || m.file || m.migration)) || '?');
22
22
  const errorsOf = (list) =>
23
- (Array.isArray(list) ? list : []).map((e) => (typeof e === 'string' ? { migration: null, message: e } : { migration: (e && (e.migration || e.name || e.version || e.file)) || null, message: String((e && (e.message || e.error)) || 'error'), code: (e && e.code) || null, files: Array.isArray(e && e.files) ? e.files.map(String) : [] }));
23
+ (Array.isArray(list) ? list : []).map((e) =>
24
+ typeof e === 'string'
25
+ ? { migration: null, message: e }
26
+ : {
27
+ migration: (e && (e.migration || e.name || e.version || e.file)) || null,
28
+ message: String((e && (e.message || e.error)) || 'error'),
29
+ code: (e && e.code) || null,
30
+ files: Array.isArray(e && e.files) ? e.files.map(String) : [],
31
+ // migrations_missing : versions (toujours) et missing (version, nom, fichier, date ; poad.io avec push.sh du 04/12/2026)
32
+ ...(Array.isArray(e && e.versions) ? { versions: e.versions.map(String) } : {}),
33
+ ...(Array.isArray(e && e.missing) ? { missing: e.missing.filter((m) => m && m.version).map((m) => ({ version: String(m.version), name: m.name || null, file: m.file || null, applied_at: m.applied_at || null })) } : {}),
34
+ },
35
+ );
36
+
37
+ const when = (at) => (typeof at === 'string' && at ? at.slice(0, 16).replace('T', ' ') + ' UTC' : null);
38
+
39
+ /** Lignes d'un refus de migrations (manquantes au dossier, hors d'ordre) avec la commande qui le lève. Pure. */
40
+ function refusalLines(e, { env, where, chalk }) {
41
+ const out = [];
42
+ if (e.code === 'migrations_missing') {
43
+ const list = e.missing && e.missing.length ? e.missing : (e.versions || []).map((v) => ({ version: v }));
44
+ out.push(` ${chalk.grey(`${list.length} migration(s) applied on ${env} and missing from poad/migrations:`)}`);
45
+ for (const m of list) out.push(` ${chalk.yellow(m.file || `${m.version} (name unknown)`)}${when(m.applied_at) ? chalk.grey(` applied ${when(m.applied_at)}`) : ''}`);
46
+ out.push(` ${chalk.grey('Bring them back, commit them, then deploy again:')} ${chalk.cyanBright(`poad migration pull${where}`)}`);
47
+ }
48
+ if (e.code === 'migrations_out_of_order') {
49
+ out.push(` ${chalk.grey(`Pending here, but older than the last migration applied on ${env}: they would run in a different order than locally. Nothing is forced; give them versions after the last one, in their order, with one command:`)}`);
50
+ out.push(` ${chalk.cyanBright(`poad migrate renumber --pending${where}`)}`);
51
+ if ((e.files || []).length) out.push(` ${chalk.grey(`(${(e.files || []).join(', ')}; one at a time: poad migrate renumber <version>${where})`)}`);
52
+ }
53
+ return out;
54
+ }
24
55
 
25
56
  /** Résultat d'un déploiement, ramené aux champs connus */
26
57
  function summarize(d = {}) {
@@ -125,6 +156,8 @@ module.exports = (args, raw) =>
125
156
  }
126
157
 
127
158
  const route = `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}`;
159
+ // --env des commandes proposées : omis quand poad deploy l'aurait aussi omis (production par défaut)
160
+ const where = env.source === 'option' || !env.production ? ` --env ${env.branch}` : '';
128
161
  const headers = {};
129
162
  if (sha) headers['x-poad-sha'] = sha;
130
163
  if (dryRun) headers['x-poad-dry-run'] = '1';
@@ -150,8 +183,9 @@ module.exports = (args, raw) =>
150
183
  for (const n of m.pending) out.log(` ${chalk.yellow('○')} ${n} ${chalk.grey(dryRun ? '(would be applied)' : '(pending)')}`);
151
184
  for (const e of m.errors) {
152
185
  out.log(` ${chalk.redBright('✕')} ${e.migration ? chalk.bold(e.migration) + ': ' : ''}${e.message}`);
153
- // Refus pour migrations destructives : lesquelles, et comment confirmer
186
+ // Refus : lesquelles ; migrations manquantes ou hors d'ordre : la commande qui lève le refus
154
187
  for (const f of e.files || []) out.log(` ${chalk.yellow(f)}`);
188
+ for (const l of refusalLines(e, { env: env.branch, where, chalk })) out.log(l);
155
189
  }
156
190
  for (const w of result.warnings || []) {
157
191
  out.log(` ${chalk.yellowBright('⚠')} ${w.message}`);
@@ -185,6 +219,9 @@ module.exports = (args, raw) =>
185
219
  skipped: b.skipped,
186
220
  ...result,
187
221
  dry_run: dryRun,
222
+ // Ce qui lève un refus de migrations (poad migration pull, poad migrate renumber)
223
+ missing_migrations: result.migrations.errors.filter((e) => e.code === 'migrations_missing').flatMap((e) => (e.missing && e.missing.length ? e.missing : (e.versions || []).map((v) => ({ version: v, name: null, file: null, applied_at: null })))),
224
+ fix: result.migrations.errors.flatMap((e) => (e.code === 'migrations_missing' ? [`poad migration pull${where}`] : e.code === 'migrations_out_of_order' ? [`poad migrate renumber --pending${where}`, ...(e.files || []).map((f) => `poad migrate renumber ${f.slice(0, 14)}${where}`)] : [])),
188
225
  large_references: large.map((f) => ({ path: `poad/${f.rel}`, bytes: f.size, target: f.target })),
189
226
  references,
190
227
  });
@@ -192,3 +229,4 @@ module.exports = (args, raw) =>
192
229
  });
193
230
 
194
231
  module.exports.summarize = summarize;
232
+ module.exports.refusalLines = refusalLines;
package/project/logs.js CHANGED
@@ -37,7 +37,9 @@
37
37
  // poad logs data event=sync_pull device=<id> synchronisation d'une table synchronisée (engine 0.70+) :
38
38
  // sync_pull, sync_push (data), sync_purge (meta), avec table= et device=
39
39
  // poad logs transform model=ventes les transformations (engine 0.72+) : passages, modèles construits ou en
40
- // échec ; run=<id>, event=model_failed, trigger=deploy ; transform=<nom> = model=<nom>
40
+ // échec ; run=<id>, event=model_failed, trigger=deploy ; transform=<nom> = model=<nom> ;
41
+ // recalcul automatique (engine 0.73+) : trigger=source source=<nom>, trigger=cron,
42
+ // event=run_grouped (demandes réunies), event=schedule_tick
41
43
  // poad logs limit=500 nombre de lignes (100 par défaut)
42
44
  // poad logs -f | --follow suivi en direct
43
45
  // poad logs --json une ligne JSON par entrée (pour jq)
@@ -0,0 +1,227 @@
1
+ // poad migrate list [--env <nom>] [--project <id>] [--json]
2
+ // poad/migrations comparé à l'historique d'un environnement de poad.io : appliquée des deux côtés, en attente
3
+ // ici (le prochain poad deploy l'applique), manquante ici (poad migration pull), en attente là-haut (écrite
4
+ // sans être appliquée), conflit de version, modifiée depuis son application, hors d'ordre.
5
+ //
6
+ // poad migrate renumber <version|fichier> | --pending [--env <nom>] [--yes] [--json]
7
+ // --pending : toutes les migrations en attente plus anciennes que la dernière appliquée sur l'environnement (et
8
+ // les suivantes en attente), d'un coup, dans leur ordre d'origine.
9
+ // donne à une migration en attente une version après la dernière de poad.io et du dossier (le fichier est
10
+ // renommé, son contenu ne change pas). Jamais une migration appliquée sur un environnement de poad.io ; si elle
11
+ // l'est sur l'engine local seulement, son historique local suit (même transaction que le renommage).
12
+ //
13
+ // Lecture : GET v1/projects/:id/branches/:branch/migrations?sql=0 (liste sans SQL).
14
+ const FILE_RE = /^(\d{14})_([A-Za-z0-9_-]{1,120})\.sql$/;
15
+
16
+ const when = (at) => (typeof at === 'string' && at ? at.slice(0, 16).replace('T', ' ') + ' UTC' : '');
17
+
18
+ /**
19
+ * État de chaque version, dossier contre poad.io. Pure.
20
+ * local : [{ version, name, file, checksum }] ; remote : [{ version, name, file, checksum, applied_at, applied }]
21
+ */
22
+ function compare(local = [], remote = []) {
23
+ const here = new Map(local.map((l) => [l.version, l]));
24
+ const there = new Map(remote.filter((r) => r && r.version).map((r) => [r.version, r]));
25
+ const lastApplied = [...there.values()].filter((r) => r.applied !== false).map((r) => r.version).sort().pop() || '';
26
+ const versions = [...new Set([...here.keys(), ...there.keys()])].sort();
27
+ return versions.map((version) => {
28
+ const l = here.get(version);
29
+ const r = there.get(version);
30
+ const row = { version, name: (l && l.name) || (r && r.name) || null, file: (l && l.file) || (r && r.file) || null, applied_at: (r && r.applied_at) || null };
31
+ if (l && r && r.file && l.file !== r.file) return { ...row, state: 'conflict', remote_file: r.file };
32
+ if (l && r && r.applied !== false) return { ...row, state: r.checksum && l.checksum !== r.checksum ? 'changed' : 'applied' };
33
+ if (l && r) return { ...row, state: 'pending_both' };
34
+ if (l) return { ...row, state: version < lastApplied ? 'out_of_order' : 'pending' };
35
+ if (r.applied === false) return { ...row, state: 'remote_pending' };
36
+ return { ...row, state: 'missing' };
37
+ });
38
+ }
39
+
40
+ const LABEL = {
41
+ applied: ['✔', 'greenBright', 'applied on both sides'],
42
+ changed: ['!', 'yellowBright', 'applied, the file changed since (not replayed: write a new migration)'],
43
+ pending: ['○', 'cyanBright', 'pending here: the next poad deploy applies it'],
44
+ pending_both: ['○', 'cyanBright', 'pending here and written on poad.io, not applied yet'],
45
+ out_of_order: ['✕', 'redBright', 'pending here but older than the last one applied on poad.io: poad deploy refuses it'],
46
+ missing: ['✕', 'redBright', 'applied on poad.io, missing here: poad deploy refuses'],
47
+ remote_pending: ['↓', 'yellowBright', 'written on poad.io, not applied, missing here'],
48
+ conflict: ['✕', 'redBright', 'same version, another name on poad.io'],
49
+ };
50
+
51
+ /** Version suivante : maintenant, sinon juste après la plus grande prise. Pure (now passé). */
52
+ function nextVersion(taken, now = new Date()) {
53
+ let v = Number(now.toISOString().replace(/[-:T]/g, '').slice(0, 14));
54
+ const max = Math.max(0, ...[...taken].map(Number).filter(Number.isFinite));
55
+ if (v <= max) v = max + 1;
56
+ while (taken.has(String(v))) v += 1;
57
+ return String(v);
58
+ }
59
+
60
+ async function remoteList(api, id, branch) {
61
+ const got = await api.call('GET', `v1/projects/${api.enc(id)}/branches/${api.enc(branch)}/migrations?sql=0`, { what: 'migrations' });
62
+ return Array.isArray(got && got.migrations) ? got.migrations : [];
63
+ }
64
+
65
+ const list = (raw) =>
66
+ require('../utils/cloud/cli').run(raw, { values: ['env', 'project'] }, async ({ opts, positionals, out }) => {
67
+ const api = require('../utils/cloud/api');
68
+ const cli = require('../utils/cloud/cli');
69
+ const branches = require('../utils/cloud/branches');
70
+ const migrations = require('../utils/migrations');
71
+ const { chalk } = out;
72
+ if (positionals.length) throw api.usageError('Usage: poad migrate list [--env <name>] [--json]');
73
+ const root = cli.projectRoot();
74
+ if (!root) throw api.usageError('Not in a poad project folder: cd into one.');
75
+ const { id } = cli.targetProject(opts);
76
+ const env = await branches.resolve(id, { wanted: opts.env, root });
77
+ const where = env.source === 'option' || !env.production ? ` --env ${env.branch}` : '';
78
+ const rows = compare(migrations.files(root).list, await remoteList(api, id, env.branch));
79
+ const count = (s) => rows.filter((r) => r.state === s).length;
80
+
81
+ out.log(` ${chalk.bold('Migrations')} ${cli.rel(migrations.dir(root))} ↔ ${chalk.white(id)} ${env.production ? chalk.magenta.bold(`${env.branch} (production)`) : chalk.cyan.bold(env.branch)}`);
82
+ out.log(' ');
83
+ for (const r of rows) {
84
+ const [mark, color, text] = LABEL[r.state];
85
+ out.log(` ${chalk[color](mark)} ${r.file || r.version} ${chalk.grey(`${text}${r.applied_at && r.state !== 'pending' ? `, ${when(r.applied_at)}` : ''}${r.remote_file ? ` (${r.remote_file})` : ''}`)}`);
86
+ }
87
+ if (!rows.length) out.log(chalk.grey(' None, here or on poad.io.'));
88
+ out.log(' ');
89
+ if (count('missing') || count('remote_pending')) out.log(` ${chalk.cyanBright(`poad migration pull${where}`)} ${chalk.grey('brings the missing ones into the folder.')}`);
90
+ if (count('out_of_order')) out.log(` ${chalk.cyanBright(`poad migrate renumber --pending${where}`)} ${chalk.grey(`gives the ${count('out_of_order')} out-of-order one(s) versions after the last one, in their order.`)}`);
91
+ if (count('out_of_order') === 1) for (const r of rows.filter((x) => x.state === 'out_of_order')) out.log(` ${chalk.grey('or')} ${chalk.cyanBright(`poad migrate renumber ${r.version}${where}`)} ${chalk.grey(`for ${r.file} alone.`)}`);
92
+ if (count('pending') && !count('missing') && !count('out_of_order') && !count('conflict')) out.log(` ${chalk.cyanBright(`poad deploy${where}`)} ${chalk.grey(`applies the ${count('pending')} pending one(s).`)}`);
93
+ out.result({ project: id, env: env.branch, production: env.production, migrations: rows, counts: Object.fromEntries(Object.keys(LABEL).map((k) => [k, count(k)])) });
94
+ return 0;
95
+ });
96
+
97
+ /**
98
+ * Migrations à renuméroter d'un coup (--pending) : les locales en attente plus anciennes que la dernière appliquée
99
+ * sur l'environnement, et les suivantes en attente, pour que l'ordre d'origine reste celui de poad.io. Pure.
100
+ */
101
+ function pendingToRenumber(local = [], remote = []) {
102
+ const rows = compare(local, remote);
103
+ const first = rows.find((r) => r.state === 'out_of_order');
104
+ if (!first) return [];
105
+ const keep = new Set(rows.filter((r) => r.state === 'out_of_order' || (r.state === 'pending' && r.version > first.version)).map((r) => r.version));
106
+ return local.filter((l) => keep.has(l.version)).sort((a, b) => a.version.localeCompare(b.version));
107
+ }
108
+
109
+ const renumber = (raw) =>
110
+ require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['pending'] }, async ({ opts, positionals, out }) => {
111
+ const fs = require('fs');
112
+ const path = require('path');
113
+ const api = require('../utils/cloud/api');
114
+ const cli = require('../utils/cloud/cli');
115
+ const branches = require('../utils/cloud/branches');
116
+ const migrations = require('../utils/migrations');
117
+ const { chalk } = out;
118
+ const usage = 'Usage: poad migrate renumber <version|file> | --pending [--env <name>] [--yes] [--json]';
119
+ if (opts.pending ? positionals.length !== 0 : positionals.length !== 1) throw api.usageError(usage);
120
+ const root = cli.projectRoot();
121
+ if (!root) throw api.usageError('Not in a poad project folder: cd into one.');
122
+ const local = migrations.files(root).list;
123
+ let wantedList = null;
124
+ if (!opts.pending) {
125
+ const wanted = path.basename(positionals[0]);
126
+ const m = local.find((l) => l.version === wanted || l.file === wanted);
127
+ if (!m) throw api.usageError(`No migration "${wanted}" in ${cli.rel(migrations.dir(root))} (a version of 14 digits, or a file name).`);
128
+ wantedList = [m];
129
+ }
130
+ const { id } = cli.targetProject(opts);
131
+ const env = await branches.resolve(id, { wanted: opts.env, root });
132
+ const where = env.source === 'option' || !env.production ? ` --env ${env.branch}` : '';
133
+
134
+ // Appliquée nulle part sur poad.io : chaque environnement est lu ; un environnement illisible bloque
135
+ const all = await branches.list(id);
136
+ const taken = new Set(local.map((l) => l.version));
137
+ const remote = new Map();
138
+ for (const b of all) {
139
+ try {
140
+ remote.set(b.name, await remoteList(api, id, b.name));
141
+ } catch (err) {
142
+ throw new api.CloudError(`Cannot read the migrations of ${b.name} (${err.message}): nothing renamed. A migration is renumbered only once poad.io confirms it is applied nowhere; resume ${b.name} or try again.`, { code: 'environment_unreadable' });
143
+ }
144
+ }
145
+ // Seulement la cible fixe la version : après tout ce qui y est appliqué ou écrit
146
+ for (const r of remote.get(env.branch) || []) taken.add(r.version);
147
+ const ms = wantedList || pendingToRenumber(local, remote.get(env.branch) || []);
148
+ if (!ms.length) {
149
+ out.log(chalk.grey(` No pending migration older than the last one applied on ${env.branch}: nothing to renumber.`));
150
+ out.result({ project: id, env: env.branch, renamed: [] });
151
+ return 0;
152
+ }
153
+ for (const m of ms) {
154
+ for (const [name, rows] of remote) {
155
+ const there = rows.find((r) => r.version === m.version);
156
+ if (there && there.applied !== false) {
157
+ throw new api.CloudError(`${m.file} is already applied on ${name}${there.applied_at ? ` (${when(there.applied_at)})` : ''}: its version stays. Nothing renamed.`, { code: 'already_applied', exit: api.EXIT.failed });
158
+ }
159
+ }
160
+ }
161
+ // Versions successives, dans l'ordre d'origine
162
+ const plan = ms.map((m) => {
163
+ const version = nextVersion(taken);
164
+ taken.add(version);
165
+ const file = `${version}_${m.name}.sql`;
166
+ return { m, version, file, target: path.join(migrations.dir(root), file), localApplied: false };
167
+ });
168
+
169
+ // Engine local : appliquée là seulement, son historique suit le fichier
170
+ let client = null;
171
+ try {
172
+ const { readConfig } = require('../utils/config');
173
+ const { isDockerExist } = require('../utils/docker');
174
+ const config = readConfig(root);
175
+ if (await isDockerExist(config.project_uuid)) {
176
+ client = await migrations.connect(config);
177
+ for (const p of plan) {
178
+ const r = await client.query("select 1 from poad_migrations.history where version = $1 and to_regclass('poad_migrations.history') is not null", [p.m.version]).catch(() => ({ rows: [] }));
179
+ p.localApplied = r.rows.length > 0;
180
+ }
181
+ }
182
+ } catch {
183
+ client = null;
184
+ }
185
+ const anyLocal = plan.some((p) => p.localApplied);
186
+
187
+ out.log(` ${chalk.bold('Renumber')}${plan.length > 1 ? chalk.grey(` ${plan.length} migrations, in their original order`) : ''}`);
188
+ for (const p of plan) out.log(` ${p.m.file} → ${chalk.cyanBright(p.file)}${p.localApplied ? chalk.grey(' (local history follows)') : ''}`);
189
+ out.log(chalk.grey(` after the last migration of ${env.branch} and of the folder; applied on no environment of poad.io${anyLocal ? '; applied on the local engine: the local history follows' : ''}`));
190
+ const done = [];
191
+ try {
192
+ await cli.confirm(plan.length > 1 ? `Rename these ${plan.length} migrations?` : `Rename ${plan[0].m.file} to ${plan[0].file}?`, { yes: opts.yes, json: out.json });
193
+ for (const p of plan) if (fs.existsSync(p.target)) throw new api.CloudError(`${p.file} already exists: nothing renamed.`, { code: 'exists' });
194
+ if (anyLocal) await client.query('begin');
195
+ for (const p of plan) {
196
+ if (p.localApplied) await client.query('update poad_migrations.history set version = $1 where version = $2', [p.version, p.m.version]);
197
+ fs.renameSync(p.m.path, p.target);
198
+ done.push(p);
199
+ }
200
+ if (anyLocal) await client.query('commit');
201
+ if (client) {
202
+ for (const p of plan) {
203
+ await client
204
+ .query("insert into _logs.entries (ts, level, service, msg, attrs) values (now(), 'info', 'cli', 'migration renumbered', $1::jsonb)", [JSON.stringify({ event: 'migration_renumbered', from: p.m.version, to: p.version, migration: `poad/migrations/${p.file}`, env: env.branch, local_history: p.localApplied, pending: !!opts.pending })])
205
+ .catch(() => {});
206
+ }
207
+ }
208
+ } catch (err) {
209
+ for (const p of done.reverse()) {
210
+ try {
211
+ fs.renameSync(p.target, p.m.path);
212
+ } catch {}
213
+ }
214
+ if (client && anyLocal) await client.query('rollback').catch(() => {});
215
+ throw err;
216
+ } finally {
217
+ if (client) await client.end().catch(() => {});
218
+ }
219
+ for (const p of plan) out.log(`${chalk.greenBright('✔')} ${cli.rel(p.target)}`);
220
+ out.log(chalk.grey(` Commit ${plan.length > 1 ? 'them' : 'it'}, then "poad deploy${where}".`));
221
+ const renamed = plan.map((p) => ({ from: p.m.file, to: p.file, version: p.version, local_history: p.localApplied }));
222
+ if (opts.pending) out.result({ project: id, env: env.branch, renamed });
223
+ else out.result({ project: id, env: env.branch, ...renamed[0] });
224
+ return 0;
225
+ });
226
+
227
+ module.exports = { list, renumber, compare, nextVersion, pendingToRenumber, FILE_RE };
@@ -1,5 +1,16 @@
1
1
  // poad migrate : applique les migrations en attente de poad/migrations
2
- module.exports = async () => {
2
+ // poad migrate pull | list | renumber : poad/migrations face à poad.io (migration-pull.js, migrate-cloud.js)
3
+ module.exports = async (args, raw = []) => {
4
+ if (raw[0] === 'pull') return require('./migration-pull')(raw.slice(1));
5
+ if (raw[0] === 'list') {
6
+ // Projet non lié et sans --env / --project : l'engine local (poad migration list)
7
+ const cli = require('../utils/cloud/cli');
8
+ const root = cli.projectRoot();
9
+ const remote = raw.slice(1).some((w) => /^(--?)?(env|project)(=|$)/.test(w)) || (root && cli.linkedId(root));
10
+ if (!remote) return require('./migration')({ list: true }, ['list']);
11
+ return require('./migrate-cloud').list(raw.slice(1));
12
+ }
13
+ if (raw[0] === 'renumber') return require('./migrate-cloud').renumber(raw.slice(1));
3
14
  const chalk = require('chalk-v2');
4
15
  const { findPoadDir } = require('../utils/findpoad');
5
16
  const { isDockerExist } = require('../utils/docker');
@@ -0,0 +1,159 @@
1
+ // poad migration pull [--env <nom>] [--project <id>] [--yes] [--dry-run] [--json]
2
+ // (alias : poad migrate pull)
3
+ //
4
+ // Rapatrie dans poad/migrations les migrations d'un environnement de poad.io qui manquent au dossier : celles
5
+ // écrites là-haut par la console, le MCP ou l'assistant (appliquées, dans l'historique de la base), et celles
6
+ // écrites sans être appliquées (fichiers de /project/migrations de l'engine hébergé). poad deploy refuse tant
7
+ // qu'une migration appliquée manque au dossier (migrations_missing).
8
+ //
9
+ // GET v1/projects/:id/branches/:branch/migrations?sql=0 la liste (version, nom, date), sans SQL
10
+ // GET v1/projects/:id/branches/:branch/migrations?versions=a,b le SQL de celles qui manquent
11
+ //
12
+ // Chaque fichier garde son nom et sa version exacts (<version>_<nom>.sql) et son contenu exact (somme sha256 de
13
+ // l'historique vérifiée) ; jamais d'écrasement : une version déjà présente sous un autre nom est un conflit, dit
14
+ // et laissé tel quel. Journaux (sans SQL) : poad.io écrit event=migrations_pulled dans le puits du projet
15
+ // (poad logs cli event=migrations_pulled --env <nom>) et dans le sien.
16
+ //
17
+ // Codes de sortie : 0 rien à faire ou tout écrit, 5 une migration n'a pas pu être rapatriée (conflit, SQL
18
+ // introuvable là-haut), 4 confirmation manquante, 3 session, 2 usage, 1 autre erreur.
19
+ const FILE_RE = /^(\d{14})_([A-Za-z0-9_-]{1,120})\.sql$/;
20
+ const BATCH = 100;
21
+
22
+ /** Que faire de chaque migration de poad.io, d'après les fichiers du dossier. Pure. */
23
+ function planPull(remote = [], local = []) {
24
+ const byVersion = new Map(local.map((l) => [l.version, l]));
25
+ const plan = { pull: [], present: [], conflicts: [], unavailable: [] };
26
+ for (const m of remote) {
27
+ if (!m || typeof m.version !== 'string') continue;
28
+ const here = byVersion.get(m.version);
29
+ if (here && here.file === m.file) {
30
+ plan.present.push(m);
31
+ continue;
32
+ }
33
+ if (here) {
34
+ plan.conflicts.push({ ...m, local: here.file });
35
+ continue;
36
+ }
37
+ if (!m.file || !FILE_RE.test(m.file) || m.file.slice(0, 14) !== m.version) {
38
+ plan.unavailable.push({ ...m, problem: m.problem || 'invalid_name' });
39
+ continue;
40
+ }
41
+ if (m.problem) {
42
+ plan.unavailable.push(m);
43
+ continue;
44
+ }
45
+ plan.pull.push(m);
46
+ }
47
+ return plan;
48
+ }
49
+
50
+ const PROBLEMS = {
51
+ sql_unavailable: 'its SQL is not kept on poad.io (applied before engine 0.55, file lost)',
52
+ checksum_mismatch: 'the file on poad.io differs from what was applied',
53
+ invalid_name: 'its name is not <version>_<name>.sql',
54
+ };
55
+
56
+ const when = (at) => (typeof at === 'string' && at ? at.slice(0, 16).replace('T', ' ') + ' UTC' : null);
57
+
58
+ module.exports = (raw) =>
59
+ require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run'] }, async ({ opts, positionals, out }) => {
60
+ const fs = require('fs');
61
+ const path = require('path');
62
+ const crypto = require('crypto');
63
+ const api = require('../utils/cloud/api');
64
+ const cli = require('../utils/cloud/cli');
65
+ const branches = require('../utils/cloud/branches');
66
+ const migrations = require('../utils/migrations');
67
+ const { chalk } = out;
68
+
69
+ if (positionals.length) throw api.usageError(`poad migration pull: unexpected "${positionals[0]}". Usage: poad migration pull [--env <name>] [--yes] [--dry-run] [--json]`);
70
+ const root = cli.projectRoot();
71
+ if (!root) throw api.usageError('Not in a poad project folder: cd into one (the migrations are written to its poad/migrations).');
72
+ const { id } = cli.targetProject(opts);
73
+ const env = await branches.resolve(id, { wanted: opts.env, root });
74
+ const dir = migrations.dir(root);
75
+ const where = env.production && env.source !== 'option' ? '' : ` --env ${env.branch}`;
76
+ const route = `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/migrations`;
77
+
78
+ const listed = await api.call('GET', `${route}?sql=0`, { what: 'migrations' });
79
+ const remote = Array.isArray(listed && listed.migrations) ? listed.migrations : [];
80
+ const plan = planPull(remote, migrations.files(root).list);
81
+
82
+ out.log(` ${chalk.bold('Migrations of poad.io')} ${chalk.white(id)} → ${env.production ? chalk.magenta.bold(`${env.branch} (production)`) : chalk.cyan.bold(env.branch)}`);
83
+ out.log(chalk.grey(` ${remote.length} on poad.io, ${plan.present.length} already in ${cli.rel(dir)}`));
84
+ out.log(' ');
85
+ for (const m of plan.pull) out.log(` ${chalk.cyanBright('↓')} ${m.file}${chalk.grey(m.applied === false ? ' written on poad.io, not applied yet' : when(m.applied_at) ? ` applied ${when(m.applied_at)}` : '')}`);
86
+ for (const c of plan.conflicts) out.log(` ${chalk.redBright('✕')} ${c.file || c.version}: version ${c.version} is already used here by ${c.local}; nothing overwritten. Rename yours after the last migration of poad.io, then pull again.`);
87
+ for (const u of plan.unavailable) out.log(` ${chalk.redBright('✕')} ${u.file || u.version}: ${PROBLEMS[u.problem] || u.problem}. "poad db pull${where}" writes the real schema as a new migration instead.`);
88
+
89
+ const result = { project: id, env: env.branch, production: env.production, dir: cli.rel(dir), dry_run: Boolean(opts['dry-run']), written: [], present: plan.present.length, conflicts: plan.conflicts.map((c) => ({ version: c.version, file: c.file, local: c.local })), unavailable: plan.unavailable.map((u) => ({ version: u.version, file: u.file || null, problem: u.problem })) };
90
+ const failed = plan.conflicts.length + plan.unavailable.length > 0;
91
+
92
+ if (!plan.pull.length) {
93
+ if (!failed) out.log(`${chalk.greenBright('✔')} Nothing to pull: ${cli.rel(dir)} already has every migration of ${env.branch}.`);
94
+ out.log(' ');
95
+ out.result({ ...result, pull: [] });
96
+ return failed ? api.EXIT.failed : 0;
97
+ }
98
+ if (opts['dry-run']) {
99
+ out.log(' ');
100
+ out.log(`${chalk.greenBright('✔')} Dry run: ${plan.pull.length} migration(s) would be written; nothing changed.`);
101
+ out.log(' ');
102
+ out.result({ ...result, pull: plan.pull.map((m) => ({ version: m.version, file: m.file, applied: m.applied !== false, applied_at: m.applied_at || null })) });
103
+ return failed ? api.EXIT.failed : 0;
104
+ }
105
+ await cli.confirm(`Write ${plan.pull.length} migration(s) of ${env.branch} into ${cli.rel(dir)}?`, { yes: opts.yes, json: out.json });
106
+
107
+ fs.mkdirSync(dir, { recursive: true });
108
+ const wanted = new Map(plan.pull.map((m) => [m.version, m]));
109
+ const versions = [...wanted.keys()];
110
+ for (let i = 0; i < versions.length; i += BATCH) {
111
+ const got = await api.call('GET', `${route}?versions=${versions.slice(i, i + BATCH).join(',')}`, { what: 'migrations', timeout: 120000 });
112
+ for (const m of (got && got.migrations) || []) {
113
+ const asked = wanted.get(m && m.version);
114
+ if (!asked || m.file !== asked.file) continue;
115
+ wanted.delete(m.version);
116
+ if (m.problem || typeof m.sql !== 'string') {
117
+ result.unavailable.push({ version: m.version, file: m.file, problem: m.problem || 'sql_unavailable' });
118
+ out.log(` ${chalk.redBright('✕')} ${m.file}: ${PROBLEMS[m.problem || 'sql_unavailable']}.`);
119
+ continue;
120
+ }
121
+ // Le contenu exact de l'historique : sa somme fait foi
122
+ if (m.applied !== false && m.checksum && crypto.createHash('sha256').update(m.sql).digest('hex') !== m.checksum) {
123
+ result.unavailable.push({ version: m.version, file: m.file, problem: 'checksum_mismatch' });
124
+ out.log(` ${chalk.redBright('✕')} ${m.file}: ${PROBLEMS.checksum_mismatch}.`);
125
+ continue;
126
+ }
127
+ const target = path.join(dir, m.file);
128
+ try {
129
+ // wx : jamais d'écrasement, même d'un fichier apparu entre-temps
130
+ fs.writeFileSync(target, m.sql, { flag: 'wx' });
131
+ } catch (err) {
132
+ if (err.code !== 'EEXIST') throw err;
133
+ result.conflicts.push({ version: m.version, file: m.file, local: m.file });
134
+ out.log(` ${chalk.redBright('✕')} ${m.file}: already exists, left as it is.`);
135
+ continue;
136
+ }
137
+ result.written.push({ version: m.version, file: m.file, applied: m.applied !== false, applied_at: m.applied_at || null });
138
+ }
139
+ }
140
+ for (const [version, m] of wanted) {
141
+ result.unavailable.push({ version, file: m.file, problem: 'not_returned' });
142
+ out.log(` ${chalk.redBright('✕')} ${m.file}: not returned by poad.io, try again.`);
143
+ }
144
+
145
+ out.log(' ');
146
+ if (result.written.length) {
147
+ out.log(`${chalk.greenBright('✔')} ${result.written.length} migration(s) written to ${cli.rel(dir)}:`);
148
+ for (const w of result.written) out.log(` ${w.file}`);
149
+ out.log(chalk.grey(` Commit them (git add ${cli.rel(dir)} && git commit), then "poad deploy${where}".`));
150
+ if (result.written.some((w) => !w.applied)) out.log(chalk.grey(' Those not applied yet on poad.io are applied by that deploy.'));
151
+ }
152
+ const bad = result.conflicts.length + result.unavailable.length;
153
+ if (bad) out.log(chalk.redBright(` ${bad} migration(s) not pulled: poad deploy keeps refusing until they are in the folder.`));
154
+ out.log(' ');
155
+ out.result(result);
156
+ return bad ? api.EXIT.failed : 0;
157
+ });
158
+
159
+ module.exports.planPull = planPull;
@@ -1,7 +1,12 @@
1
1
  // poad migration new <nom> crée poad/migrations/<horodatage>_<nom>.sql
2
2
  // poad migration list migrations appliquées et en attente
3
3
  // (poad migrate applique celles en attente)
4
- module.exports = async (args = {}) => {
4
+ module.exports = async (args = {}, raw = []) => {
5
+ // poad migration pull : les migrations de poad.io qui manquent au dossier (migration-pull.js)
6
+ if (raw[0] === 'pull') return require('./migration-pull')(raw.slice(1));
7
+ // list --env / --project : le dossier face à poad.io (sans : l'engine local, plus bas)
8
+ if (raw[0] === 'list' && raw.slice(1).some((w) => /^(--?)?(env|project)(=|$)/.test(w))) return require('./migrate-cloud').list(raw.slice(1));
9
+ if (raw[0] === 'renumber') return require('./migrate-cloud').renumber(raw.slice(1));
5
10
  const chalk = require('chalk-v2');
6
11
  const path = require('path');
7
12
  const { findPoadDir } = require('../utils/findpoad');
@@ -58,5 +63,5 @@ module.exports = async (args = {}) => {
58
63
  return;
59
64
  }
60
65
 
61
- console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad migration new <name>')} | ${chalk.cyanBright('poad migration list')} | ${chalk.cyanBright('poad migrate')}`);
66
+ console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad migration new <name>')} | ${chalk.cyanBright('poad migration list [--env <name>]')} | ${chalk.cyanBright('poad migration pull [--env <name>]')} | ${chalk.cyanBright('poad migrate renumber <version> | --pending')} | ${chalk.cyanBright('poad migrate')}`);
62
67
  };
@@ -1,4 +1,5 @@
1
- // poad transform ls modèles (poad/transforms/<nom>.sql), état, dernier passage
1
+ // poad transform ls modèles (poad/transforms/<nom>.sql), état, dernier passage ; horaire
2
+ // (schedule:, fuseau), prochain passage, sources suivies (engine 0.73.0+)
2
3
  // poad transform new <nom> [--table|--view] [--from <table>] crée poad/transforms/<nom>.sql avec un en-tête minimal
3
4
  // poad transform check relit tous les modèles : en-têtes, requêtes, graphe, cycles ; ne change rien
4
5
  // poad transform run [<sélecteur>…] [--changed] [--detach] lance un passage et le suit (tout par défaut) ;
@@ -52,6 +53,25 @@ const modelLines = (m, chalk) => {
52
53
  else out.push(` ${chalk.redBright(r.status)} ${r.error ? `${r.error.message}${r.error.line ? chalk.grey(` (${m.file}:${r.error.line})`) : ''}` : ''}`);
53
54
  if (m.stale && r && r.status === 'ok') out.push(chalk.yellowBright(' changed since its last build: poad transform run ' + m.name));
54
55
  if (m.upstream && m.upstream.length) out.push(chalk.grey(` reads ${m.upstream.join(', ')}`));
56
+ for (const line of autoLines(m, chalk)) out.push(line);
57
+ return out;
58
+ };
59
+
60
+ /** Quand dire une échéance : « in 4 min », « in 3 h », « in 2 d ». Pure. */
61
+ const until = (iso, now = Date.now()) => {
62
+ const s = Math.max(0, Math.round((new Date(iso).getTime() - now) / 1000));
63
+ return s < 60 ? 'in less than a minute' : s < 3600 ? `in ${Math.round(s / 60)} min` : s < 86400 ? `in ${Math.round(s / 3600)} h` : `in ${Math.round(s / 86400)} d`;
64
+ };
65
+
66
+ /**
67
+ * Recalcul automatique d'un modèle (engine 0.73.0) : horaire et prochain passage, sources dont la synchronisation
68
+ * le recalcule. Rien pour un engine plus ancien (champs absents). Pure (chalk passé, now pour les tests).
69
+ */
70
+ const autoLines = (m, chalk, now = Date.now()) => {
71
+ const out = [];
72
+ if (m.schedule) out.push(chalk.grey(` schedule ${m.schedule} (${m.timezone || 'UTC'})${m.next_run ? `, next run ${new Date(m.next_run).toLocaleString()} (${until(m.next_run, now)})` : ''}`));
73
+ if (m.after_sources === false) out.push(chalk.grey(' not recomputed after sources (after_sources: false)'));
74
+ else if (Array.isArray(m.sources) && m.sources.length) out.push(chalk.grey(` recomputed after source${m.sources.length > 1 ? 's' : ''} ${m.sources.join(', ')}`));
55
75
  return out;
56
76
  };
57
77
 
@@ -351,4 +371,4 @@ const main = async (args = {}, raw, deps = {}) => {
351
371
  };
352
372
 
353
373
  module.exports = (args, raw) => main(args, raw);
354
- Object.assign(module.exports, { main, supportsTransforms, newModelText, modelLines, graphLines, runModelLine, NAME_RE, SELECTOR_RE });
374
+ Object.assign(module.exports, { main, supportsTransforms, newModelText, modelLines, graphLines, runModelLine, autoLines, until, NAME_RE, SELECTOR_RE });
@@ -96,8 +96,17 @@ function fakeCloud(t, behaviour = {}) {
96
96
  return send(res, 200, { removed: branch });
97
97
  }
98
98
  if (req.method === 'POST' && (m[2] === '/clone' || m[2] === '/sync')) return send(res, 200, { name: branch, status: 'active', status_detail: 'copie depuis la production : measure', credentials_with_values: ['claude'] });
99
+ // Migrations de l'environnement (control/server.mjs, migrationsOfBranch) : ?sql=0 la liste, ?versions= le SQL
100
+ if (req.method === 'GET' && m[2] === '/migrations') {
101
+ const all = (behaviour.migrations && behaviour.migrations[branch]) || [];
102
+ const only = url.searchParams.get('versions');
103
+ const withSql = url.searchParams.get('sql') !== '0';
104
+ const list = all.filter((x) => !only || only.split(',').includes(x.version)).map(({ sql, ...x }) => (withSql && sql !== undefined ? { ...x, sql } : x));
105
+ return send(res, 200, { project: id, branch, migrations: list });
106
+ }
99
107
  if (req.method === 'POST' && m[2] === '/deploy') {
100
108
  const dry = req.headers['x-poad-dry-run'] === '1';
109
+ if (behaviour.refuse) return send(res, 200, { deploy_id: 'dr', outcome: 'refused', dry_run: dry, migrations_applied: [], migrations_pending: [], errors: [behaviour.refuse] });
101
110
  if (behaviour.async) {
102
111
  state.deploys.d1 = 0;
103
112
  // La forme réelle de poad.io (control/server.mjs, deployView) : outcome, migrations_applied…
@@ -617,3 +626,204 @@ test('options : valeur manquante et option inconnue -> code 2', async (t) => {
617
626
  assert.strictEqual(jsonOf(u).error.code, 'usage');
618
627
  });
619
628
 
629
+
630
+ // --- Migrations écrites sur poad.io : deploy refusé, migration pull, migrate list, migrate renumber ------------
631
+
632
+ const sha256 = (s) => require('crypto').createHash('sha256').update(s).digest('hex');
633
+ const INIT_SQL = 'create table todo (id serial primary key);\n';
634
+ const NOTES_SQL = '-- ajoute_notes\n-- Écrite par la console poad.\n\ncreate table notes (id int);\n';
635
+ const IDX_SQL = 'create index on notes (id);\n';
636
+ const remoteMigrations = () => ({
637
+ main: [
638
+ { version: '20261101000000', name: 'init', file: '20261101000000_init.sql', checksum: sha256(INIT_SQL), applied_at: '2026-11-01T00:00:00Z', applied: true, source: 'history', sql: INIT_SQL },
639
+ { version: '20261203101500', name: 'ajoute_notes', file: '20261203101500_ajoute_notes.sql', checksum: sha256(NOTES_SQL), applied_at: '2026-12-03T10:15:00Z', applied: true, source: 'history', sql: NOTES_SQL },
640
+ { version: '20261204080000', name: 'index_notes', file: '20261204080000_index_notes.sql', checksum: null, applied_at: null, applied: false, source: 'folder', sql: IDX_SQL },
641
+ ],
642
+ dev: [{ version: '20261101000000', name: 'init', file: '20261101000000_init.sql', checksum: sha256(INIT_SQL), applied_at: '2026-11-01T00:00:00Z', applied: true, source: 'history', sql: INIT_SQL }],
643
+ });
644
+
645
+ test('deploy refusé (migrations manquantes) : lesquelles, avec nom et date, et la commande ; --dry-run --json garde versions et missing', async (t) => {
646
+ const box = sandbox(t);
647
+ const refuse = {
648
+ code: 'migrations_missing',
649
+ message: 'migrations applied on poad.io are missing from the folder: bring them back with poad migration pull, commit them, then deploy again',
650
+ versions: ['20261203101500'],
651
+ missing: [{ version: '20261203101500', name: 'ajoute_notes', file: '20261203101500_ajoute_notes.sql', applied_at: '2026-12-03T10:15:00Z' }],
652
+ };
653
+ const cloud = await fakeCloud(t, { refuse });
654
+ await login(box, cloud);
655
+ await poad(box, cloud.api, ['link', PID]);
656
+ const dry = await poad(box, cloud.api, ['deploy', '--dry-run']);
657
+ assert.strictEqual(dry.status, 5, dry.all);
658
+ assert.match(dry.stdout, /20261203101500_ajoute_notes\.sql\s+applied 2026-12-03 10:15 UTC/);
659
+ assert.match(dry.stdout, /poad migration pull(?! --env)/);
660
+ const j = await poad(box, cloud.api, ['deploy', '--dry-run', '--json', '--env', 'main']);
661
+ const o = jsonOf(j);
662
+ assert.deepStrictEqual(o.migrations.errors[0].versions, ['20261203101500']);
663
+ assert.strictEqual(o.migrations.errors[0].missing[0].file, '20261203101500_ajoute_notes.sql');
664
+ assert.deepStrictEqual(o.missing_migrations.map((m) => m.version), ['20261203101500']);
665
+ assert.deepStrictEqual(o.fix, ['poad migration pull --env main']);
666
+ // poad.io d'avant (versions seules) : listées quand même
667
+ const old = await fakeCloud(t, { refuse: { code: 'migrations_missing', message: 'missing', versions: ['20261203101500'] } });
668
+ await login(box, old);
669
+ const r = await poad(box, old.api, ['deploy', '--env', 'dev']);
670
+ assert.match(r.stdout, /20261203101500 \(name unknown\)/);
671
+ assert.match(r.stdout, /poad migration pull --env dev/);
672
+ });
673
+
674
+ test('deploy refusé (hors d’ordre) : la renumérotation proposée, rien de forcé', async (t) => {
675
+ const box = sandbox(t);
676
+ const cloud = await fakeCloud(t, { refuse: { code: 'migrations_out_of_order', message: 'pending migrations are older than the last applied one: rename them after it', files: ['20261101000000_init.sql'] } });
677
+ await login(box, cloud);
678
+ await poad(box, cloud.api, ['link', PID]);
679
+ const r = await poad(box, cloud.api, ['deploy', '--env', 'dev', '--json']);
680
+ assert.strictEqual(r.status, 5, r.all);
681
+ assert.deepStrictEqual(jsonOf(r).fix, ['poad migrate renumber --pending --env dev', 'poad migrate renumber 20261101000000 --env dev']);
682
+ const text = await poad(box, cloud.api, ['deploy', '--env', 'dev']);
683
+ assert.match(text.stdout, /poad migrate renumber --pending --env dev/);
684
+ assert.ok(text.stdout.indexOf('renumber --pending') < text.stdout.indexOf('one at a time'), 'la commande unique en premier');
685
+ assert.ok(!cloud.requests.some((q) => q.headers['x-poad-force']), 'aucun forçage');
686
+ });
687
+
688
+ test('migration pull : nom, version et contenu exacts, jamais d’écrasement, conflit dit (code 5) ; migrate pull alias', async (t) => {
689
+ const box = sandbox(t);
690
+ const cloud = await fakeCloud(t, { migrations: remoteMigrations() });
691
+ await login(box, cloud);
692
+ await poad(box, cloud.api, ['link', PID]);
693
+ const mdir = path.join(box.poad, 'migrations');
694
+
695
+ const dry = await poad(box, cloud.api, ['migration', 'pull', '--dry-run', '--json']);
696
+ assert.strictEqual(dry.status, 0, dry.all);
697
+ assert.deepStrictEqual(jsonOf(dry).pull.map((m) => m.file), ['20261203101500_ajoute_notes.sql', '20261204080000_index_notes.sql']);
698
+ assert.deepStrictEqual(fs.readdirSync(mdir), ['20261101000000_init.sql']);
699
+
700
+ // Hors terminal sans --yes : rien d'écrit
701
+ const ask = await poad(box, cloud.api, ['migration', 'pull']);
702
+ assert.strictEqual(ask.status, 4, ask.all);
703
+ assert.match(ask.stdout, /↓ 20261203101500_ajoute_notes\.sql\s+applied 2026-12-03 10:15 UTC/);
704
+ assert.match(ask.stdout, /↓ 20261204080000_index_notes\.sql\s+written on poad\.io, not applied yet/);
705
+
706
+ const r = await poad(box, cloud.api, ['migrate', 'pull', '--yes', '--json']);
707
+ assert.strictEqual(r.status, 0, r.all);
708
+ const o = jsonOf(r);
709
+ assert.deepStrictEqual(o.written.map((w) => w.file), ['20261203101500_ajoute_notes.sql', '20261204080000_index_notes.sql']);
710
+ assert.strictEqual(fs.readFileSync(path.join(mdir, '20261203101500_ajoute_notes.sql'), 'utf8'), NOTES_SQL);
711
+ assert.strictEqual(fs.readFileSync(path.join(mdir, '20261204080000_index_notes.sql'), 'utf8'), IDX_SQL);
712
+ const reqs = cloud.requests.filter((q) => q.route.endsWith('/migrations'));
713
+ assert.ok(reqs.every((q) => q.route === `v1/projects/${PID}/branches/main/migrations`));
714
+ assert.ok(reqs.some((q) => q.query.versions === '20261203101500,20261204080000'));
715
+ assert.ok(!r.all.includes(TOKEN));
716
+
717
+ const again = await poad(box, cloud.api, ['migration', 'pull', '--yes']);
718
+ assert.strictEqual(again.status, 0, again.all);
719
+ assert.match(again.stdout, /Nothing to pull/);
720
+
721
+ // Une version déjà prise ici sous un autre nom : conflit, rien d'écrasé
722
+ fs.rmSync(path.join(mdir, '20261203101500_ajoute_notes.sql'));
723
+ fs.writeFileSync(path.join(mdir, '20261203101500_mien.sql'), 'select 1;\n');
724
+ const c = await poad(box, cloud.api, ['migration', 'pull', '--yes', '--json']);
725
+ assert.strictEqual(c.status, 5, c.all);
726
+ assert.deepStrictEqual(jsonOf(c).conflicts, [{ version: '20261203101500', file: '20261203101500_ajoute_notes.sql', local: '20261203101500_mien.sql' }]);
727
+ assert.strictEqual(fs.readFileSync(path.join(mdir, '20261203101500_mien.sql'), 'utf8'), 'select 1;\n');
728
+ assert.ok(!fs.existsSync(path.join(mdir, '20261203101500_ajoute_notes.sql')));
729
+ });
730
+
731
+ test('migration pull : SQL introuvable ou somme fausse là-haut, refusé (code 5) avec poad db pull en recours', async (t) => {
732
+ const box = sandbox(t);
733
+ const m = remoteMigrations();
734
+ m.main[1] = { ...m.main[1], sql: 'tampered;\n' };
735
+ m.main.push({ version: '20261204090000', name: 'perdue', file: '20261204090000_perdue.sql', checksum: 'x', applied_at: '2026-12-04T09:00:00Z', applied: true, source: null, problem: 'sql_unavailable' });
736
+ const cloud = await fakeCloud(t, { migrations: m });
737
+ await login(box, cloud);
738
+ await poad(box, cloud.api, ['link', PID]);
739
+ const r = await poad(box, cloud.api, ['migration', 'pull', '--yes', '--json']);
740
+ assert.strictEqual(r.status, 5, r.all);
741
+ const o = jsonOf(r);
742
+ assert.deepStrictEqual(o.written.map((w) => w.file), ['20261204080000_index_notes.sql']);
743
+ assert.deepStrictEqual(o.unavailable.map((u) => [u.version, u.problem]).sort(), [['20261203101500', 'checksum_mismatch'], ['20261204090000', 'sql_unavailable']]);
744
+ assert.ok(!fs.existsSync(path.join(box.poad, 'migrations', '20261203101500_ajoute_notes.sql')));
745
+ const text = await poad(box, cloud.api, ['migration', 'pull', '--yes']);
746
+ assert.match(text.stdout, /poad db pull/);
747
+ });
748
+
749
+ test('migrate list : dossier face à poad.io (appliquée, en attente, manquante, hors d’ordre) ; migrate renumber', async (t) => {
750
+ const box = sandbox(t);
751
+ const cloud = await fakeCloud(t, { migrations: remoteMigrations() });
752
+ await login(box, cloud);
753
+ await poad(box, cloud.api, ['link', PID]);
754
+ const mdir = path.join(box.poad, 'migrations');
755
+ fs.writeFileSync(path.join(mdir, '20261202000000_vieille.sql'), 'select 2;\n');
756
+ fs.writeFileSync(path.join(mdir, '20991231000000_future.sql'), 'select 3;\n');
757
+ const r = await poad(box, cloud.api, ['migrate', 'list', '--json']);
758
+ assert.strictEqual(r.status, 0, r.all);
759
+ const states = Object.fromEntries(jsonOf(r).migrations.map((m) => [m.version, m.state]));
760
+ assert.deepStrictEqual(states, { 20261101000000: 'applied', 20261202000000: 'out_of_order', 20261203101500: 'missing', 20261204080000: 'remote_pending', 20991231000000: 'pending' });
761
+ assert.strictEqual(jsonOf(r).migrations.find((m) => m.version === '20261203101500').applied_at, '2026-12-03T10:15:00Z');
762
+ const text = await poad(box, cloud.api, ['migration', 'list', '--env', 'main']);
763
+ assert.match(text.stdout, /poad migration pull --env main/);
764
+ assert.match(text.stdout, /poad migrate renumber --pending --env main/);
765
+ assert.match(text.stdout, /poad migrate renumber 20261202000000 --env main/);
766
+
767
+ // Appliquée sur un environnement : jamais renumérotée
768
+ const applied = await poad(box, cloud.api, ['migrate', 'renumber', '20261101000000', '--yes']);
769
+ assert.strictEqual(applied.status, 5, applied.all);
770
+ assert.match(applied.stderr, /already applied on main/);
771
+ assert.ok(fs.existsSync(path.join(mdir, '20261101000000_init.sql')));
772
+
773
+ const ren = await poad(box, cloud.api, ['migrate', 'renumber', '20261202000000_vieille.sql', '--yes', '--json']);
774
+ assert.strictEqual(ren.status, 0, ren.all);
775
+ const o = jsonOf(ren);
776
+ assert.strictEqual(o.from, '20261202000000_vieille.sql');
777
+ assert.ok(o.version > '20991231000000', `après la dernière du dossier et de poad.io : ${o.version}`);
778
+ assert.strictEqual(fs.readFileSync(path.join(mdir, o.to), 'utf8'), 'select 2;\n');
779
+ assert.ok(!fs.existsSync(path.join(mdir, '20261202000000_vieille.sql')));
780
+ const unknown = await poad(box, cloud.api, ['migrate', 'renumber', '20200101000000', '--yes']);
781
+ assert.strictEqual(unknown.status, 2, unknown.all);
782
+ });
783
+
784
+ test('migrate renumber --pending : toutes les hors d’ordre d’un coup, dans l’ordre d’origine, les suivantes en attente aussi', async (t) => {
785
+ const box = sandbox(t);
786
+ const cloud = await fakeCloud(t, { migrations: remoteMigrations() });
787
+ await login(box, cloud);
788
+ await poad(box, cloud.api, ['link', PID]);
789
+ const mdir = path.join(box.poad, 'migrations');
790
+ // Le dossier a déjà les migrations de poad.io (pull) ; trois locales écrites avant la dernière appliquée, une après
791
+ fs.writeFileSync(path.join(mdir, '20261203101500_ajoute_notes.sql'), NOTES_SQL);
792
+ fs.writeFileSync(path.join(mdir, '20261201000000_a.sql'), 'select 1;\n');
793
+ fs.writeFileSync(path.join(mdir, '20261202000000_b.sql'), 'select 2;\n');
794
+ fs.writeFileSync(path.join(mdir, '20261203000000_c.sql'), 'select 3;\n');
795
+ fs.writeFileSync(path.join(mdir, '20261204090000_d.sql'), 'select 4;\n');
796
+
797
+ const usage = await poad(box, cloud.api, ['migrate', 'renumber', '--pending', '20261201000000', '--yes']);
798
+ assert.strictEqual(usage.status, 2, usage.all);
799
+ const ask = await poad(box, cloud.api, ['migrate', 'renumber', '--pending']);
800
+ assert.strictEqual(ask.status, 4, ask.all);
801
+ assert.ok(fs.existsSync(path.join(mdir, '20261201000000_a.sql')), 'rien de renommé sans confirmation');
802
+
803
+ const r = await poad(box, cloud.api, ['migrate', 'renumber', '--pending', '--env', 'main', '--yes', '--json']);
804
+ assert.strictEqual(r.status, 0, r.all);
805
+ const o = jsonOf(r);
806
+ assert.deepStrictEqual(o.renamed.map((x) => x.from), ['20261201000000_a.sql', '20261202000000_b.sql', '20261203000000_c.sql', '20261204090000_d.sql']);
807
+ const v = o.renamed.map((x) => x.version);
808
+ assert.deepStrictEqual([...v].sort(), v, 'ordre d’origine gardé');
809
+ assert.strictEqual(new Set(v).size, 4);
810
+ assert.ok(v[0] > '20261204080000', `après la dernière de poad.io : ${v[0]}`);
811
+ assert.deepStrictEqual(o.renamed.map((x) => fs.readFileSync(path.join(mdir, x.to), 'utf8')), ['select 1;\n', 'select 2;\n', 'select 3;\n', 'select 4;\n']);
812
+ for (const f of ['20261201000000_a.sql', '20261202000000_b.sql', '20261203000000_c.sql', '20261204090000_d.sql']) assert.ok(!fs.existsSync(path.join(mdir, f)));
813
+ assert.ok(fs.existsSync(path.join(mdir, '20261101000000_init.sql')) && fs.existsSync(path.join(mdir, '20261203101500_ajoute_notes.sql')), 'les appliquées ne bougent pas');
814
+
815
+ const list = await poad(box, cloud.api, ['migrate', 'list', '--json']);
816
+ assert.strictEqual(jsonOf(list).counts.out_of_order, 0);
817
+ const again = await poad(box, cloud.api, ['migrate', 'renumber', '--pending', '--yes', '--json']);
818
+ assert.strictEqual(again.status, 0, again.all);
819
+ assert.deepStrictEqual(jsonOf(again).renamed, []);
820
+ });
821
+
822
+ test('pendingToRenumber : pure', () => {
823
+ const { pendingToRenumber } = require('../project/migrate-cloud');
824
+ const l = (v) => ({ version: v, name: 'm' + v.slice(-2), file: `${v}_m.sql` });
825
+ const remote = [{ version: '20261110000000', applied: true }];
826
+ assert.deepStrictEqual(pendingToRenumber([l('20261111000000')], remote), []);
827
+ assert.deepStrictEqual(pendingToRenumber([l('20261109000000'), l('20261101000000'), l('20261111000000')], remote).map((m) => m.version), ['20261101000000', '20261109000000', '20261111000000']);
828
+ assert.deepStrictEqual(pendingToRenumber([l('20261101000000')], []), []);
829
+ });
@@ -175,3 +175,18 @@ test('poad start : un dossier sans .sql ne demande rien à l’engine', (t) => {
175
175
  fs.writeFileSync(path.join(poadDir, 'transforms', 'a.sql'), 'select 1');
176
176
  assert.strictEqual(hasModels(root), true);
177
177
  });
178
+
179
+ test('ls : horaire, prochain passage, sources suivies (engine 0.73)', () => {
180
+ const chalk = { bold: (x) => x, grey: (x) => x, greenBright: (x) => x, redBright: (x) => x, yellowBright: (x) => x, cyan: (x) => x };
181
+ const now = Date.parse('2026-12-04T10:00:00Z');
182
+ const lines = transform.autoLines({ schedule: '*/5 * * * *', timezone: 'Europe/Paris', next_run: '2026-12-04T10:05:00Z', after_sources: true, sources: ['commandes'] }, chalk, now);
183
+ assert.match(lines[0], /^ {2}schedule \*\/5 \* \* \* \* \(Europe\/Paris\), next run .* \(in 5 min\)$/);
184
+ assert.strictEqual(lines[1], ' recomputed after source commandes');
185
+ assert.deepStrictEqual(transform.autoLines({ schedule: null, after_sources: false, sources: [] }, chalk, now), [' not recomputed after sources (after_sources: false)']);
186
+ // engine 0.72 : rien
187
+ assert.deepStrictEqual(transform.autoLines({ name: 'x' }, chalk, now), []);
188
+ assert.strictEqual(transform.until('2026-12-04T13:00:00Z', now), 'in 3 h');
189
+ // dans la sortie de ls
190
+ const m = { ...LIST.models[0], schedule: '0 4 * * *', timezone: 'UTC', next_run: '2026-12-05T04:00:00Z', sources: ['commandes', 'magasins'] };
191
+ assert.ok(transform.modelLines(m, chalk).some((l) => l.includes('recomputed after sources commandes, magasins')));
192
+ });
@@ -328,7 +328,7 @@ const sheets = {
328
328
  ],
329
329
  },
330
330
  migrate: {
331
- usage: ['poad migrate', 'poad migrate --force-reference', 'poad migrate --json'],
331
+ usage: ['poad migrate', 'poad migrate --force-reference', 'poad migrate --json', 'poad migrate list [--env <name>] [--json]', 'poad migrate pull [--env <name>] [--yes] [--dry-run] [--json]', 'poad migrate renumber <version|file> [--env <name>] [--yes] [--json]', 'poad migrate renumber --pending [--env <name>] [--yes] [--json]'],
332
332
  text: [
333
333
  'Apply pending migrations of poad/migrations and named queries of poad/queries, then the reference tables of poad/reference (the file is the source of truth).',
334
334
  'Then warns (never blocks) about functions and views granted to anon or authenticated that the API does not serve them (403 not_exposed: SECURITY DEFINER functions, views without security_invoker, materialized views), each with its fix; the ones a migration just created also go to the log sink (poad logs cli event=api_exposure).',
@@ -336,15 +336,20 @@ const sheets = {
336
336
  options: [
337
337
  ['--force-reference', 'also apply a reference file that would remove many rows: an empty file for a table that has rows, or more than 20% of its rows (refused otherwise, nothing removed)'],
338
338
  ['--json', 'one JSON object: applied, failed, pending, api_exposure (items with reason, roles, fix, created), unprotected tables'],
339
+ ['list', 'poad/migrations against an environment of poad.io (--env, else the git branch, else main; the local engine when the project is not linked): applied on both sides, pending here, missing here, written on poad.io without being applied, same version under another name, changed since applied, older than the last one applied (poad deploy refuses it); with version, name and date'],
340
+ ['pull', 'same as poad migration pull'],
341
+ ['renumber <version>', 'give a pending migration a version after the last one of the environment and of the folder (the file is renamed, its SQL is unchanged) when poad deploy refuses it as out of order. Refused when it is applied on any environment of poad.io; applied on the local engine only: the local history follows. Logs: poad logs cli event=migration_renumbered'],
342
+ ['renumber --pending', 'renumber at once, in their original order, every pending migration older than the last one applied on the environment (and the pending ones after it, so the order stays): what poad deploy proposes first when it refuses the order'],
339
343
  ],
340
344
  },
341
345
  migration: {
342
- usage: ['poad migration new <name>', 'poad migration list'],
346
+ usage: ['poad migration new <name>', 'poad migration list [--env <name>]', 'poad migration pull [--env <name>] [--yes] [--dry-run] [--json]'],
343
347
  options: [
344
348
  ['new <name>', 'create poad/migrations/<timestamp>_<name>.sql'],
345
- ['list', 'applied and pending migrations'],
349
+ ['list', 'applied and pending migrations of the local engine; with --env <name>: against poad.io (as poad migrate list)'],
350
+ ['pull', 'write into poad/migrations the migrations of a poad.io environment missing from the folder (--env, else the git branch, else main): those written there by the console, the MCP or the assistant, applied (their exact SQL from the migration history) or not yet applied. Each keeps its exact version, name and content (sha256 of the history checked); an existing file is never overwritten: a version already used here under another name is a conflict, said and left alone. Then commit them and poad deploy. Exit code 5 when one could not be pulled'],
346
351
  ],
347
- notes: ['poad migrate applies the pending ones (poad start does it too).'],
352
+ notes: ['poad migrate applies the pending ones (poad start does it too).', 'poad deploy refuses while a migration applied on poad.io is missing from the folder: it lists them (version, name, date) and gives the poad migration pull command, --dry-run included.', 'Logs, never any SQL: poad logs cli event=migrations_pulled --env <name> (written by poad.io: versions and files).'],
348
353
  },
349
354
  kc: {
350
355
  usage: ['poad kc', 'poad kc export'],